Annotation of gforth/doc/gforth.ds, revision 1.211
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.65 anton 2372: creates a word @code{v2} and reserves 20 uninitialized cells; the
1.211 ! anton 2373: address pushed by @code{v2} points to the start of these 20 cells.
! 2374: You can use address arithmetic to access these cells:
1.48 anton 2375:
2376: @example
2377: 3 v2 5 cells + !
1.65 anton 2378: v2 20 cells dump
1.48 anton 2379: @end example
2380:
2381: You can reserve and initialize memory with @code{,}:
2382:
2383: @example
2384: create v3
2385: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2386: v3 @@ .
2387: v3 cell+ @@ .
2388: v3 2 cells + @@ .
1.65 anton 2389: v3 5 cells dump
1.48 anton 2390: @end example
2391:
1.141 anton 2392: @quotation Assignment
1.48 anton 2393: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2394: @code{u} cells, with the first of these cells at @code{addr}, the next
2395: one at @code{addr cell+} etc.
1.141 anton 2396: @end quotation
1.48 anton 2397:
2398: You can also reserve memory without creating a new word:
2399:
2400: @example
1.60 anton 2401: here 10 cells allot .
2402: here .
1.48 anton 2403: @end example
2404:
1.211 ! anton 2405: The first @code{here} pushes the start address of the memory area, the
! 2406: second @code{here} the address after the dictionary area. You should
! 2407: store the start address somewhere, or you will have a hard time
! 2408: finding the memory area again.
1.48 anton 2409:
2410: @code{Allot} manages dictionary memory. The dictionary memory contains
2411: the system's data structures for words etc. on Gforth and most other
2412: Forth systems. It is managed like a stack: You can free the memory that
2413: you have just @code{allot}ed with
2414:
2415: @example
2416: -10 cells allot
1.60 anton 2417: here .
1.48 anton 2418: @end example
2419:
2420: Note that you cannot do this if you have created a new word in the
2421: meantime (because then your @code{allot}ed memory is no longer on the
2422: top of the dictionary ``stack'').
2423:
1.211 ! anton 2424: Revisiting the @code{create} examples, where does @code{allot} get the
! 2425: address from? It is the current dictinary pointer, that you can read
! 2426: with @code{here}. And the @code{create}d word produces exactly that
! 2427: address (but keeps it):
! 2428:
! 2429: @example
! 2430: create v2a here . v2a .
! 2431: 20 cells allot here . v2a .
! 2432: @end example
! 2433:
1.48 anton 2434: Alternatively, you can use @code{allocate} and @code{free} which allow
2435: freeing memory in any order:
2436:
2437: @example
2438: 10 cells allocate throw .s
2439: 20 cells allocate throw .s
2440: swap
2441: free throw
2442: free throw
2443: @end example
2444:
2445: The @code{throw}s deal with errors (e.g., out of memory).
2446:
1.65 anton 2447: And there is also a
2448: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2449: garbage collector}, which eliminates the need to @code{free} memory
2450: explicitly.
1.48 anton 2451:
1.66 anton 2452: Reference: @ref{Memory}.
2453:
1.48 anton 2454:
2455: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2456: @section Characters and Strings
1.66 anton 2457: @cindex strings tutorial
2458: @cindex characters tutorial
1.48 anton 2459:
2460: On the stack characters take up a cell, like numbers. In memory they
2461: have their own size (one 8-bit byte on most systems), and therefore
2462: require their own words for memory access:
2463:
2464: @example
2465: create v4
2466: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2467: v4 4 chars + c@@ .
1.65 anton 2468: v4 5 chars dump
1.48 anton 2469: @end example
2470:
2471: The preferred representation of strings on the stack is @code{addr
2472: u-count}, where @code{addr} is the address of the first character and
2473: @code{u-count} is the number of characters in the string.
2474:
2475: @example
2476: v4 5 type
2477: @end example
2478:
2479: You get a string constant with
2480:
2481: @example
2482: s" hello, world" .s
2483: type
2484: @end example
2485:
2486: Make sure you have a space between @code{s"} and the string; @code{s"}
2487: is a normal Forth word and must be delimited with white space (try what
2488: happens when you remove the space).
2489:
2490: However, this interpretive use of @code{s"} is quite restricted: the
2491: string exists only until the next call of @code{s"} (some Forth systems
2492: keep more than one of these strings, but usually they still have a
1.62 crook 2493: limited lifetime).
1.48 anton 2494:
2495: @example
2496: s" hello," s" world" .s
2497: type
2498: type
2499: @end example
2500:
1.62 crook 2501: You can also use @code{s"} in a definition, and the resulting
2502: strings then live forever (well, for as long as the definition):
1.48 anton 2503:
2504: @example
2505: : foo s" hello," s" world" ;
2506: foo .s
2507: type
2508: type
2509: @end example
2510:
1.141 anton 2511: @quotation Assignment
1.48 anton 2512: @code{Emit ( c -- )} types @code{c} as character (not a number).
2513: Implement @code{type ( addr u -- )}.
1.141 anton 2514: @end quotation
1.48 anton 2515:
1.66 anton 2516: Reference: @ref{Memory Blocks}.
2517:
2518:
1.190 anton 2519: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2520: @section Alignment
1.66 anton 2521: @cindex alignment tutorial
2522: @cindex memory alignment tutorial
1.48 anton 2523:
2524: On many processors cells have to be aligned in memory, if you want to
2525: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2526: not require alignment, access to aligned cells is faster).
1.48 anton 2527:
2528: @code{Create} aligns @code{here} (i.e., the place where the next
2529: allocation will occur, and that the @code{create}d word points to).
2530: Likewise, the memory produced by @code{allocate} starts at an aligned
2531: address. Adding a number of @code{cells} to an aligned address produces
2532: another aligned address.
2533:
2534: However, address arithmetic involving @code{char+} and @code{chars} can
2535: create an address that is not cell-aligned. @code{Aligned ( addr --
2536: a-addr )} produces the next aligned address:
2537:
2538: @example
1.50 anton 2539: v3 char+ aligned .s @@ .
2540: v3 char+ .s @@ .
1.48 anton 2541: @end example
2542:
2543: Similarly, @code{align} advances @code{here} to the next aligned
2544: address:
2545:
2546: @example
2547: create v5 97 c,
2548: here .
2549: align here .
2550: 1000 ,
2551: @end example
2552:
2553: Note that you should use aligned addresses even if your processor does
2554: not require them, if you want your program to be portable.
2555:
1.66 anton 2556: Reference: @ref{Address arithmetic}.
2557:
1.190 anton 2558: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2559: @section Floating Point
2560: @cindex floating point tutorial
2561: @cindex FP tutorial
2562:
2563: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2564: might expect, but there are a few things worth noting:
2565:
2566: The first point is not specific to Forth, but so important and yet not
2567: universally known that I mention it here: FP numbers are not reals.
2568: Many properties (e.g., arithmetic laws) that reals have and that one
2569: expects of all kinds of numbers do not hold for FP numbers. If you
2570: want to use FP computations, you should learn about their problems and
2571: how to avoid them; a good starting point is @cite{David Goldberg,
2572: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2573: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2574: Computing Surveys 23(1):5@minus{}48, March 1991}.
2575:
2576: In Forth source code literal FP numbers need an exponent, e.g.,
1.210 anton 2577: @code{1e0}; this can also be written shorter as @code{1e}, longer as
2578: @code{+1.0e+0}, and many variations in between. The reason for this is
2579: that, for historical reasons, Forth interprets a decimal point alone
2580: (e.g., @code{1.}) as indicating a double-cell integer. Examples:
2581:
2582: @example
2583: 2e 2e f+ f.
2584: @end example
2585:
2586: Another requirement for literal FP numbers is that the current base is
1.190 anton 2587: decimal; with a hex base @code{1e} is interpreted as an integer.
2588:
2589: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2590: ANS Forth system may implement the FP stack on the data stack, but
2591: virtually all systems implement a separate FP stack; and programming
2592: in a way that accommodates all models is so cumbersome that nobody
2593: does it.} One advantage of this model is that cells are not in the
2594: way when accessing FP values, and vice versa. Forth has a set of
2595: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2596: frot} and (non-standard) @code{fnip ftuck fpick}.
2597:
2598: FP arithmetic words are prefixed with @code{F}. There is the usual
2599: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2600: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2601: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2602: computation results are usually inaccurate, so exact comparison is
2603: usually a mistake, and one should use approximate comparison.
2604: Unfortunately, @code{f~}, the standard word for that purpose, is not
2605: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2606: well.
2607:
2608: And of course there are words for accessing FP numbers in memory
2609: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2610: faligned}). There are also variants of these words with an @code{sf}
2611: and @code{df} prefix for accessing IEEE format single-precision and
2612: double-precision numbers in memory; their main purpose is for
2613: accessing external FP data (e.g., that has been read from or will be
2614: written to a file).
2615:
2616: Here is an example of a dot-product word and its use:
2617:
2618: @example
2619: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2620: >r swap 2swap swap 0e r> 0 ?DO
2621: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2622: LOOP
2623: 2drop 2drop ;
1.48 anton 2624:
1.190 anton 2625: create v 1.23e f, 4.56e f, 7.89e f,
2626:
2627: v 1 floats v 1 floats 3 v* f.
2628: @end example
2629:
2630: @quotation Assignment
2631: Write a program to solve a quadratic equation. Then read @cite{Henry
2632: G. Baker,
2633: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2634: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2635: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2636: program. Finally, find a test case where the original and the
2637: improved version produce different results.
2638: @end quotation
2639:
2640: Reference: @ref{Floating Point}; @ref{Floating point stack};
2641: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2642: arithmetic}.
2643:
2644: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84 pazsan 2645: @section Files
2646: @cindex files tutorial
2647:
2648: This section gives a short introduction into how to use files inside
2649: Forth. It's broken up into five easy steps:
2650:
2651: @enumerate 1
2652: @item Opened an ASCII text file for input
2653: @item Opened a file for output
2654: @item Read input file until string matched (or some other condition matched)
2655: @item Wrote some lines from input ( modified or not) to output
2656: @item Closed the files.
2657: @end enumerate
2658:
1.153 anton 2659: Reference: @ref{General files}.
2660:
1.84 pazsan 2661: @subsection Open file for input
2662:
2663: @example
2664: s" foo.in" r/o open-file throw Value fd-in
2665: @end example
2666:
2667: @subsection Create file for output
2668:
2669: @example
2670: s" foo.out" w/o create-file throw Value fd-out
2671: @end example
2672:
2673: The available file modes are r/o for read-only access, r/w for
2674: read-write access, and w/o for write-only access. You could open both
2675: files with r/w, too, if you like. All file words return error codes; for
2676: most applications, it's best to pass there error codes with @code{throw}
2677: to the outer error handler.
2678:
2679: If you want words for opening and assigning, define them as follows:
2680:
2681: @example
2682: 0 Value fd-in
2683: 0 Value fd-out
2684: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2685: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2686: @end example
2687:
2688: Usage example:
2689:
2690: @example
2691: s" foo.in" open-input
2692: s" foo.out" open-output
2693: @end example
2694:
2695: @subsection Scan file for a particular line
2696:
2697: @example
2698: 256 Constant max-line
2699: Create line-buffer max-line 2 + allot
2700:
2701: : scan-file ( addr u -- )
2702: begin
2703: line-buffer max-line fd-in read-line throw
2704: while
2705: >r 2dup line-buffer r> compare 0=
2706: until
2707: else
2708: drop
2709: then
2710: 2drop ;
2711: @end example
2712:
2713: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2714: the buffer at addr, and returns the number of bytes read, a flag that is
2715: false when the end of file is reached, and an error code.
1.84 pazsan 2716:
2717: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2718: returns zero if both strings are equal. It returns a positive number if
2719: the first string is lexically greater, a negative if the second string
2720: is lexically greater.
2721:
2722: We haven't seen this loop here; it has two exits. Since the @code{while}
2723: exits with the number of bytes read on the stack, we have to clean up
2724: that separately; that's after the @code{else}.
2725:
2726: Usage example:
2727:
2728: @example
2729: s" The text I search is here" scan-file
2730: @end example
2731:
2732: @subsection Copy input to output
2733:
2734: @example
2735: : copy-file ( -- )
2736: begin
2737: line-buffer max-line fd-in read-line throw
2738: while
1.194 anton 2739: line-buffer swap fd-out write-line throw
1.84 pazsan 2740: repeat ;
2741: @end example
1.194 anton 2742: @c !! does not handle long lines, no newline at end of file
1.84 pazsan 2743:
2744: @subsection Close files
2745:
2746: @example
2747: fd-in close-file throw
2748: fd-out close-file throw
2749: @end example
2750:
2751: Likewise, you can put that into definitions, too:
2752:
2753: @example
2754: : close-input ( -- ) fd-in close-file throw ;
2755: : close-output ( -- ) fd-out close-file throw ;
2756: @end example
2757:
1.141 anton 2758: @quotation Assignment
1.84 pazsan 2759: How could you modify @code{copy-file} so that it copies until a second line is
2760: matched? Can you write a program that extracts a section of a text file,
2761: given the line that starts and the line that terminates that section?
1.141 anton 2762: @end quotation
1.84 pazsan 2763:
2764: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2765: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2766: @cindex semantics tutorial
2767: @cindex interpretation semantics tutorial
2768: @cindex compilation semantics tutorial
2769: @cindex immediate, tutorial
1.48 anton 2770:
2771: When a word is compiled, it behaves differently from being interpreted.
2772: E.g., consider @code{+}:
2773:
2774: @example
2775: 1 2 + .
2776: : foo + ;
2777: @end example
2778:
2779: These two behaviours are known as compilation and interpretation
2780: semantics. For normal words (e.g., @code{+}), the compilation semantics
2781: is to append the interpretation semantics to the currently defined word
2782: (@code{foo} in the example above). I.e., when @code{foo} is executed
2783: later, the interpretation semantics of @code{+} (i.e., adding two
2784: numbers) will be performed.
2785:
2786: However, there are words with non-default compilation semantics, e.g.,
2787: the control-flow words like @code{if}. You can use @code{immediate} to
2788: change the compilation semantics of the last defined word to be equal to
2789: the interpretation semantics:
2790:
2791: @example
2792: : [FOO] ( -- )
2793: 5 . ; immediate
2794:
2795: [FOO]
2796: : bar ( -- )
2797: [FOO] ;
2798: bar
2799: see bar
2800: @end example
2801:
1.198 anton 2802: Two conventions to mark words with non-default compilation semantics are
1.48 anton 2803: names with brackets (more frequently used) and to write them all in
2804: upper case (less frequently used).
2805:
2806: In Gforth (and many other systems) you can also remove the
2807: interpretation semantics with @code{compile-only} (the compilation
2808: semantics is derived from the original interpretation semantics):
2809:
2810: @example
2811: : flip ( -- )
2812: 6 . ; compile-only \ but not immediate
2813: flip
2814:
2815: : flop ( -- )
2816: flip ;
2817: flop
2818: @end example
2819:
2820: In this example the interpretation semantics of @code{flop} is equal to
2821: the original interpretation semantics of @code{flip}.
2822:
2823: The text interpreter has two states: in interpret state, it performs the
2824: interpretation semantics of words it encounters; in compile state, it
2825: performs the compilation semantics of these words.
2826:
2827: Among other things, @code{:} switches into compile state, and @code{;}
2828: switches back to interpret state. They contain the factors @code{]}
2829: (switch to compile state) and @code{[} (switch to interpret state), that
2830: do nothing but switch the state.
2831:
2832: @example
2833: : xxx ( -- )
2834: [ 5 . ]
2835: ;
2836:
2837: xxx
2838: see xxx
2839: @end example
2840:
2841: These brackets are also the source of the naming convention mentioned
2842: above.
2843:
1.66 anton 2844: Reference: @ref{Interpretation and Compilation Semantics}.
2845:
1.48 anton 2846:
2847: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2848: @section Execution Tokens
1.66 anton 2849: @cindex execution tokens tutorial
2850: @cindex XT tutorial
1.48 anton 2851:
2852: @code{' word} gives you the execution token (XT) of a word. The XT is a
2853: cell representing the interpretation semantics of a word. You can
2854: execute this semantics with @code{execute}:
2855:
2856: @example
2857: ' + .s
2858: 1 2 rot execute .
2859: @end example
2860:
2861: The XT is similar to a function pointer in C. However, parameter
2862: passing through the stack makes it a little more flexible:
2863:
2864: @example
2865: : map-array ( ... addr u xt -- ... )
1.50 anton 2866: \ executes xt ( ... x -- ... ) for every element of the array starting
2867: \ at addr and containing u elements
1.48 anton 2868: @{ xt @}
2869: cells over + swap ?do
1.50 anton 2870: i @@ xt execute
1.48 anton 2871: 1 cells +loop ;
2872:
2873: create a 3 , 4 , 2 , -1 , 4 ,
2874: a 5 ' . map-array .s
2875: 0 a 5 ' + map-array .
2876: s" max-n" environment? drop .s
2877: a 5 ' min map-array .
2878: @end example
2879:
2880: You can use map-array with the XTs of words that consume one element
2881: more than they produce. In theory you can also use it with other XTs,
2882: but the stack effect then depends on the size of the array, which is
2883: hard to understand.
2884:
1.51 pazsan 2885: Since XTs are cell-sized, you can store them in memory and manipulate
2886: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2887: word with @code{compile,}:
2888:
2889: @example
2890: : foo1 ( n1 n2 -- n )
2891: [ ' + compile, ] ;
2892: see foo
2893: @end example
2894:
2895: This is non-standard, because @code{compile,} has no compilation
2896: semantics in the standard, but it works in good Forth systems. For the
2897: broken ones, use
2898:
2899: @example
2900: : [compile,] compile, ; immediate
2901:
2902: : foo1 ( n1 n2 -- n )
2903: [ ' + ] [compile,] ;
2904: see foo
2905: @end example
2906:
2907: @code{'} is a word with default compilation semantics; it parses the
2908: next word when its interpretation semantics are executed, not during
2909: compilation:
2910:
2911: @example
2912: : foo ( -- xt )
2913: ' ;
2914: see foo
2915: : bar ( ... "word" -- ... )
2916: ' execute ;
2917: see bar
1.60 anton 2918: 1 2 bar + .
1.48 anton 2919: @end example
2920:
2921: You often want to parse a word during compilation and compile its XT so
2922: it will be pushed on the stack at run-time. @code{[']} does this:
2923:
2924: @example
2925: : xt-+ ( -- xt )
2926: ['] + ;
2927: see xt-+
2928: 1 2 xt-+ execute .
2929: @end example
2930:
2931: Many programmers tend to see @code{'} and the word it parses as one
2932: unit, and expect it to behave like @code{[']} when compiled, and are
2933: confused by the actual behaviour. If you are, just remember that the
2934: Forth system just takes @code{'} as one unit and has no idea that it is
2935: a parsing word (attempts to convenience programmers in this issue have
2936: usually resulted in even worse pitfalls, see
1.66 anton 2937: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2938: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2939:
2940: Note that the state of the interpreter does not come into play when
1.51 pazsan 2941: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2942: compile state, it still gives you the interpretation semantics. And
2943: whatever that state is, @code{execute} performs the semantics
1.66 anton 2944: represented by the XT (i.e., for XTs produced with @code{'} the
2945: interpretation semantics).
2946:
2947: Reference: @ref{Tokens for Words}.
1.48 anton 2948:
2949:
2950: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2951: @section Exceptions
1.66 anton 2952: @cindex exceptions tutorial
1.48 anton 2953:
2954: @code{throw ( n -- )} causes an exception unless n is zero.
2955:
2956: @example
2957: 100 throw .s
2958: 0 throw .s
2959: @end example
2960:
2961: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2962: it catches exceptions and pushes the number of the exception on the
2963: stack (or 0, if the xt executed without exception). If there was an
2964: exception, the stacks have the same depth as when entering @code{catch}:
2965:
2966: @example
2967: .s
2968: 3 0 ' / catch .s
2969: 3 2 ' / catch .s
2970: @end example
2971:
1.141 anton 2972: @quotation Assignment
1.48 anton 2973: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2974: @end quotation
1.48 anton 2975:
2976: @code{Throw} always jumps to the dynamically next enclosing
2977: @code{catch}, even if it has to leave several call levels to achieve
2978: this:
2979:
2980: @example
2981: : foo 100 throw ;
2982: : foo1 foo ." after foo" ;
1.51 pazsan 2983: : bar ['] foo1 catch ;
1.60 anton 2984: bar .
1.48 anton 2985: @end example
2986:
2987: It is often important to restore a value upon leaving a definition, even
2988: if the definition is left through an exception. You can ensure this
2989: like this:
2990:
2991: @example
2992: : ...
2993: save-x
1.51 pazsan 2994: ['] word-changing-x catch ( ... n )
1.48 anton 2995: restore-x
2996: ( ... n ) throw ;
2997: @end example
2998:
1.172 anton 2999: However, this is still not safe against, e.g., the user pressing
3000: @kbd{Ctrl-C} when execution is between the @code{catch} and
3001: @code{restore-x}.
3002:
3003: Gforth provides an alternative exception handling syntax that is safe
3004: against such cases: @code{try ... restore ... endtry}. If the code
3005: between @code{try} and @code{endtry} has an exception, the stack
3006: depths are restored, the exception number is pushed on the stack, and
3007: the execution continues right after @code{restore}.
1.48 anton 3008:
1.172 anton 3009: The safer equivalent to the restoration code above is
1.48 anton 3010:
3011: @example
3012: : ...
3013: save-x
3014: try
1.92 anton 3015: word-changing-x 0
1.172 anton 3016: restore
3017: restore-x
3018: endtry
1.48 anton 3019: throw ;
3020: @end example
3021:
1.66 anton 3022: Reference: @ref{Exception Handling}.
3023:
1.48 anton 3024:
3025: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3026: @section Defining Words
1.66 anton 3027: @cindex defining words tutorial
3028: @cindex does> tutorial
3029: @cindex create...does> tutorial
3030:
3031: @c before semantics?
1.48 anton 3032:
3033: @code{:}, @code{create}, and @code{variable} are definition words: They
3034: define other words. @code{Constant} is another definition word:
3035:
3036: @example
3037: 5 constant foo
3038: foo .
3039: @end example
3040:
3041: You can also use the prefixes @code{2} (double-cell) and @code{f}
3042: (floating point) with @code{variable} and @code{constant}.
3043:
3044: You can also define your own defining words. E.g.:
3045:
3046: @example
3047: : variable ( "name" -- )
3048: create 0 , ;
3049: @end example
3050:
3051: You can also define defining words that create words that do something
3052: other than just producing their address:
3053:
3054: @example
3055: : constant ( n "name" -- )
3056: create ,
3057: does> ( -- n )
1.50 anton 3058: ( addr ) @@ ;
1.48 anton 3059:
3060: 5 constant foo
3061: foo .
3062: @end example
3063:
3064: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3065: @code{does>} replaces @code{;}, but it also does something else: It
3066: changes the last defined word such that it pushes the address of the
3067: body of the word and then performs the code after the @code{does>}
3068: whenever it is called.
3069:
3070: In the example above, @code{constant} uses @code{,} to store 5 into the
3071: body of @code{foo}. When @code{foo} executes, it pushes the address of
3072: the body onto the stack, then (in the code after the @code{does>})
3073: fetches the 5 from there.
3074:
3075: The stack comment near the @code{does>} reflects the stack effect of the
3076: defined word, not the stack effect of the code after the @code{does>}
3077: (the difference is that the code expects the address of the body that
3078: the stack comment does not show).
3079:
3080: You can use these definition words to do factoring in cases that involve
3081: (other) definition words. E.g., a field offset is always added to an
3082: address. Instead of defining
3083:
3084: @example
3085: 2 cells constant offset-field1
3086: @end example
3087:
3088: and using this like
3089:
3090: @example
3091: ( addr ) offset-field1 +
3092: @end example
3093:
3094: you can define a definition word
3095:
3096: @example
3097: : simple-field ( n "name" -- )
3098: create ,
3099: does> ( n1 -- n1+n )
1.50 anton 3100: ( addr ) @@ + ;
1.48 anton 3101: @end example
1.21 crook 3102:
1.48 anton 3103: Definition and use of field offsets now look like this:
1.21 crook 3104:
1.48 anton 3105: @example
3106: 2 cells simple-field field1
1.60 anton 3107: create mystruct 4 cells allot
3108: mystruct .s field1 .s drop
1.48 anton 3109: @end example
1.21 crook 3110:
1.48 anton 3111: If you want to do something with the word without performing the code
3112: after the @code{does>}, you can access the body of a @code{create}d word
3113: with @code{>body ( xt -- addr )}:
1.21 crook 3114:
1.48 anton 3115: @example
3116: : value ( n "name" -- )
3117: create ,
3118: does> ( -- n1 )
1.50 anton 3119: @@ ;
1.48 anton 3120: : to ( n "name" -- )
3121: ' >body ! ;
1.21 crook 3122:
1.48 anton 3123: 5 value foo
3124: foo .
3125: 7 to foo
3126: foo .
3127: @end example
1.21 crook 3128:
1.141 anton 3129: @quotation Assignment
1.48 anton 3130: Define @code{defer ( "name" -- )}, which creates a word that stores an
3131: XT (at the start the XT of @code{abort}), and upon execution
3132: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3133: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3134: recursion is one application of @code{defer}.
1.141 anton 3135: @end quotation
1.29 crook 3136:
1.66 anton 3137: Reference: @ref{User-defined Defining Words}.
3138:
3139:
1.48 anton 3140: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3141: @section Arrays and Records
1.66 anton 3142: @cindex arrays tutorial
3143: @cindex records tutorial
3144: @cindex structs tutorial
1.29 crook 3145:
1.48 anton 3146: Forth has no standard words for defining data structures such as arrays
3147: and records (structs in C terminology), but you can build them yourself
3148: based on address arithmetic. You can also define words for defining
3149: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3150:
1.48 anton 3151: One of the first projects a Forth newcomer sets out upon when learning
3152: about defining words is an array defining word (possibly for
3153: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3154: learn something from it. However, don't be disappointed when you later
3155: learn that you have little use for these words (inappropriate use would
1.198 anton 3156: be even worse). I have not found a set of useful array words yet;
1.48 anton 3157: the needs are just too diverse, and named, global arrays (the result of
3158: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3159: consider how to pass them as parameters). Another such project is a set
3160: of words to help dealing with strings.
1.29 crook 3161:
1.48 anton 3162: On the other hand, there is a useful set of record words, and it has
3163: been defined in @file{compat/struct.fs}; these words are predefined in
3164: Gforth. They are explained in depth elsewhere in this manual (see
3165: @pxref{Structures}). The @code{simple-field} example above is
3166: simplified variant of fields in this package.
1.21 crook 3167:
3168:
1.48 anton 3169: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3170: @section @code{POSTPONE}
1.66 anton 3171: @cindex postpone tutorial
1.21 crook 3172:
1.48 anton 3173: You can compile the compilation semantics (instead of compiling the
3174: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3175:
1.48 anton 3176: @example
3177: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3178: POSTPONE + ; immediate
1.48 anton 3179: : foo ( n1 n2 -- n )
3180: MY-+ ;
3181: 1 2 foo .
3182: see foo
3183: @end example
1.21 crook 3184:
1.48 anton 3185: During the definition of @code{foo} the text interpreter performs the
3186: compilation semantics of @code{MY-+}, which performs the compilation
3187: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3188:
3189: This example also displays separate stack comments for the compilation
3190: semantics and for the stack effect of the compiled code. For words with
3191: default compilation semantics these stack effects are usually not
3192: displayed; the stack effect of the compilation semantics is always
3193: @code{( -- )} for these words, the stack effect for the compiled code is
3194: the stack effect of the interpretation semantics.
3195:
3196: Note that the state of the interpreter does not come into play when
3197: performing the compilation semantics in this way. You can also perform
3198: it interpretively, e.g.:
3199:
3200: @example
3201: : foo2 ( n1 n2 -- n )
3202: [ MY-+ ] ;
3203: 1 2 foo .
3204: see foo
3205: @end example
1.21 crook 3206:
1.48 anton 3207: However, there are some broken Forth systems where this does not always
1.62 crook 3208: work, and therefore this practice was been declared non-standard in
1.48 anton 3209: 1999.
3210: @c !! repair.fs
3211:
3212: Here is another example for using @code{POSTPONE}:
1.44 crook 3213:
1.48 anton 3214: @example
3215: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3216: POSTPONE negate POSTPONE + ; immediate compile-only
3217: : bar ( n1 n2 -- n )
3218: MY-- ;
3219: 2 1 bar .
3220: see bar
3221: @end example
1.21 crook 3222:
1.48 anton 3223: You can define @code{ENDIF} in this way:
1.21 crook 3224:
1.48 anton 3225: @example
3226: : ENDIF ( Compilation: orig -- )
3227: POSTPONE then ; immediate
3228: @end example
1.21 crook 3229:
1.141 anton 3230: @quotation Assignment
1.48 anton 3231: Write @code{MY-2DUP} that has compilation semantics equivalent to
3232: @code{2dup}, but compiles @code{over over}.
1.141 anton 3233: @end quotation
1.29 crook 3234:
1.66 anton 3235: @c !! @xref{Macros} for reference
3236:
3237:
1.48 anton 3238: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3239: @section @code{Literal}
1.66 anton 3240: @cindex literal tutorial
1.29 crook 3241:
1.48 anton 3242: You cannot @code{POSTPONE} numbers:
1.21 crook 3243:
1.48 anton 3244: @example
3245: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3246: @end example
3247:
1.48 anton 3248: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3249:
1.48 anton 3250: @example
3251: : [FOO] ( compilation: --; run-time: -- n )
3252: 500 POSTPONE literal ; immediate
1.29 crook 3253:
1.60 anton 3254: : flip [FOO] ;
1.48 anton 3255: flip .
3256: see flip
3257: @end example
1.29 crook 3258:
1.48 anton 3259: @code{LITERAL} consumes a number at compile-time (when it's compilation
3260: semantics are executed) and pushes it at run-time (when the code it
3261: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3262: number computed at compile time into the current word:
1.29 crook 3263:
1.48 anton 3264: @example
3265: : bar ( -- n )
3266: [ 2 2 + ] literal ;
3267: see bar
3268: @end example
1.29 crook 3269:
1.141 anton 3270: @quotation Assignment
1.48 anton 3271: Write @code{]L} which allows writing the example above as @code{: bar (
3272: -- n ) [ 2 2 + ]L ;}
1.141 anton 3273: @end quotation
1.48 anton 3274:
1.66 anton 3275: @c !! @xref{Macros} for reference
3276:
1.48 anton 3277:
3278: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3279: @section Advanced macros
1.66 anton 3280: @cindex macros, advanced tutorial
3281: @cindex run-time code generation, tutorial
1.48 anton 3282:
1.66 anton 3283: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3284: Execution Tokens}. It frequently performs @code{execute}, a relatively
3285: expensive operation in some Forth implementations. You can use
1.48 anton 3286: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3287: and produce a word that contains the word to be performed directly:
3288:
3289: @c use ]] ... [[
3290: @example
3291: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3292: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3293: \ array beginning at addr and containing u elements
3294: @{ xt @}
3295: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3296: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3297: 1 cells POSTPONE literal POSTPONE +loop ;
3298:
3299: : sum-array ( addr u -- n )
3300: 0 rot rot [ ' + compile-map-array ] ;
3301: see sum-array
3302: a 5 sum-array .
3303: @end example
3304:
3305: You can use the full power of Forth for generating the code; here's an
3306: example where the code is generated in a loop:
3307:
3308: @example
3309: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3310: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3311: POSTPONE tuck POSTPONE @@
1.48 anton 3312: POSTPONE literal POSTPONE * POSTPONE +
3313: POSTPONE swap POSTPONE cell+ ;
3314:
3315: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3316: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3317: 0 postpone literal postpone swap
3318: [ ' compile-vmul-step compile-map-array ]
3319: postpone drop ;
3320: see compile-vmul
3321:
3322: : a-vmul ( addr -- n )
1.51 pazsan 3323: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3324: [ a 5 compile-vmul ] ;
3325: see a-vmul
3326: a a-vmul .
3327: @end example
3328:
3329: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3330: also use @code{map-array} instead (try it now!).
1.48 anton 3331:
3332: You can use this technique for efficient multiplication of large
3333: matrices. In matrix multiplication, you multiply every line of one
3334: matrix with every column of the other matrix. You can generate the code
3335: for one line once, and use it for every column. The only downside of
3336: this technique is that it is cumbersome to recover the memory consumed
3337: by the generated code when you are done (and in more complicated cases
3338: it is not possible portably).
3339:
1.66 anton 3340: @c !! @xref{Macros} for reference
3341:
3342:
1.48 anton 3343: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3344: @section Compilation Tokens
1.66 anton 3345: @cindex compilation tokens, tutorial
3346: @cindex CT, tutorial
1.48 anton 3347:
3348: This section is Gforth-specific. You can skip it.
3349:
3350: @code{' word compile,} compiles the interpretation semantics. For words
3351: with default compilation semantics this is the same as performing the
3352: compilation semantics. To represent the compilation semantics of other
3353: words (e.g., words like @code{if} that have no interpretation
3354: semantics), Gforth has the concept of a compilation token (CT,
3355: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3356: You can perform the compilation semantics represented by a CT with
3357: @code{execute}:
1.29 crook 3358:
1.48 anton 3359: @example
3360: : foo2 ( n1 n2 -- n )
3361: [ comp' + execute ] ;
3362: see foo
3363: @end example
1.29 crook 3364:
1.48 anton 3365: You can compile the compilation semantics represented by a CT with
3366: @code{postpone,}:
1.30 anton 3367:
1.48 anton 3368: @example
3369: : foo3 ( -- )
3370: [ comp' + postpone, ] ;
3371: see foo3
3372: @end example
1.30 anton 3373:
1.51 pazsan 3374: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3375: @code{comp'} is particularly useful for words that have no
3376: interpretation semantics:
1.29 crook 3377:
1.30 anton 3378: @example
1.48 anton 3379: ' if
1.60 anton 3380: comp' if .s 2drop
1.30 anton 3381: @end example
3382:
1.66 anton 3383: Reference: @ref{Tokens for Words}.
3384:
1.29 crook 3385:
1.48 anton 3386: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3387: @section Wordlists and Search Order
1.66 anton 3388: @cindex wordlists tutorial
3389: @cindex search order, tutorial
1.48 anton 3390:
3391: The dictionary is not just a memory area that allows you to allocate
3392: memory with @code{allot}, it also contains the Forth words, arranged in
3393: several wordlists. When searching for a word in a wordlist,
3394: conceptually you start searching at the youngest and proceed towards
3395: older words (in reality most systems nowadays use hash-tables); i.e., if
3396: you define a word with the same name as an older word, the new word
3397: shadows the older word.
3398:
3399: Which wordlists are searched in which order is determined by the search
3400: order. You can display the search order with @code{order}. It displays
3401: first the search order, starting with the wordlist searched first, then
3402: it displays the wordlist that will contain newly defined words.
1.21 crook 3403:
1.48 anton 3404: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3405:
1.48 anton 3406: @example
3407: wordlist constant mywords
3408: @end example
1.21 crook 3409:
1.48 anton 3410: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3411: defined words (the @emph{current} wordlist):
1.21 crook 3412:
1.48 anton 3413: @example
3414: mywords set-current
3415: order
3416: @end example
1.26 crook 3417:
1.48 anton 3418: Gforth does not display a name for the wordlist in @code{mywords}
3419: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3420:
1.48 anton 3421: You can get the current wordlist with @code{get-current ( -- wid)}. If
3422: you want to put something into a specific wordlist without overall
3423: effect on the current wordlist, this typically looks like this:
1.21 crook 3424:
1.48 anton 3425: @example
3426: get-current mywords set-current ( wid )
3427: create someword
3428: ( wid ) set-current
3429: @end example
1.21 crook 3430:
1.48 anton 3431: You can write the search order with @code{set-order ( wid1 .. widn n --
3432: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3433: searched wordlist is topmost.
1.21 crook 3434:
1.48 anton 3435: @example
3436: get-order mywords swap 1+ set-order
3437: order
3438: @end example
1.21 crook 3439:
1.48 anton 3440: Yes, the order of wordlists in the output of @code{order} is reversed
3441: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3442:
1.141 anton 3443: @quotation Assignment
1.48 anton 3444: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3445: wordlist to the search order. Define @code{previous ( -- )}, which
3446: removes the first searched wordlist from the search order. Experiment
3447: with boundary conditions (you will see some crashes or situations that
3448: are hard or impossible to leave).
1.141 anton 3449: @end quotation
1.21 crook 3450:
1.48 anton 3451: The search order is a powerful foundation for providing features similar
3452: to Modula-2 modules and C++ namespaces. However, trying to modularize
3453: programs in this way has disadvantages for debugging and reuse/factoring
3454: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3455: though). These disadvantages are not so clear in other
1.82 anton 3456: languages/programming environments, because these languages are not so
1.48 anton 3457: strong in debugging and reuse.
1.21 crook 3458:
1.66 anton 3459: @c !! example
3460:
3461: Reference: @ref{Word Lists}.
1.21 crook 3462:
1.29 crook 3463: @c ******************************************************************
1.48 anton 3464: @node Introduction, Words, Tutorial, Top
1.29 crook 3465: @comment node-name, next, previous, up
3466: @chapter An Introduction to ANS Forth
3467: @cindex Forth - an introduction
1.21 crook 3468:
1.83 anton 3469: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3470: that it is slower-paced in its examples, but uses them to dive deep into
3471: explaining Forth internals (not covered by the Tutorial). Apart from
3472: that, this chapter covers far less material. It is suitable for reading
3473: without using a computer.
3474:
1.29 crook 3475: The primary purpose of this manual is to document Gforth. However, since
3476: Forth is not a widely-known language and there is a lack of up-to-date
3477: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3478: material. For other sources of Forth-related
3479: information, see @ref{Forth-related information}.
1.21 crook 3480:
1.29 crook 3481: The examples in this section should work on any ANS Forth; the
3482: output shown was produced using Gforth. Each example attempts to
3483: reproduce the exact output that Gforth produces. If you try out the
3484: examples (and you should), what you should type is shown @kbd{like this}
3485: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3486: that, where the example shows @key{RET} it means that you should
1.29 crook 3487: press the ``carriage return'' key. Unfortunately, some output formats for
3488: this manual cannot show the difference between @kbd{this} and
3489: @code{this} which will make trying out the examples harder (but not
3490: impossible).
1.21 crook 3491:
1.29 crook 3492: Forth is an unusual language. It provides an interactive development
3493: environment which includes both an interpreter and compiler. Forth
3494: programming style encourages you to break a problem down into many
3495: @cindex factoring
3496: small fragments (@dfn{factoring}), and then to develop and test each
3497: fragment interactively. Forth advocates assert that breaking the
3498: edit-compile-test cycle used by conventional programming languages can
3499: lead to great productivity improvements.
1.21 crook 3500:
1.29 crook 3501: @menu
1.67 anton 3502: * Introducing the Text Interpreter::
3503: * Stacks and Postfix notation::
3504: * Your first definition::
3505: * How does that work?::
3506: * Forth is written in Forth::
3507: * Review - elements of a Forth system::
3508: * Where to go next::
3509: * Exercises::
1.29 crook 3510: @end menu
1.21 crook 3511:
1.29 crook 3512: @comment ----------------------------------------------
3513: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3514: @section Introducing the Text Interpreter
3515: @cindex text interpreter
3516: @cindex outer interpreter
1.21 crook 3517:
1.30 anton 3518: @c IMO this is too detailed and the pace is too slow for
3519: @c an introduction. If you know German, take a look at
3520: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3521: @c to see how I do it - anton
3522:
1.44 crook 3523: @c nac-> Where I have accepted your comments 100% and modified the text
3524: @c accordingly, I have deleted your comments. Elsewhere I have added a
3525: @c response like this to attempt to rationalise what I have done. Of
3526: @c course, this is a very clumsy mechanism for something that would be
3527: @c done far more efficiently over a beer. Please delete any dialogue
3528: @c you consider closed.
3529:
1.29 crook 3530: When you invoke the Forth image, you will see a startup banner printed
3531: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3532: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3533: its command line interpreter, which is called the @dfn{Text Interpreter}
3534: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3535: about the text interpreter as you read through this chapter, for more
3536: detail @pxref{The Text Interpreter}).
1.21 crook 3537:
1.29 crook 3538: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3539: input. Type a number and press the @key{RET} key:
1.21 crook 3540:
1.26 crook 3541: @example
1.30 anton 3542: @kbd{45@key{RET}} ok
1.26 crook 3543: @end example
1.21 crook 3544:
1.29 crook 3545: Rather than give you a prompt to invite you to input something, the text
3546: interpreter prints a status message @i{after} it has processed a line
3547: of input. The status message in this case (``@code{ ok}'' followed by
3548: carriage-return) indicates that the text interpreter was able to process
3549: all of your input successfully. Now type something illegal:
3550:
3551: @example
1.30 anton 3552: @kbd{qwer341@key{RET}}
1.134 anton 3553: *the terminal*:2: Undefined word
3554: >>>qwer341<<<
3555: Backtrace:
3556: $2A95B42A20 throw
3557: $2A95B57FB8 no.extensions
1.29 crook 3558: @end example
1.23 crook 3559:
1.134 anton 3560: The exact text, other than the ``Undefined word'' may differ slightly
3561: on your system, but the effect is the same; when the text interpreter
1.29 crook 3562: detects an error, it discards any remaining text on a line, resets
1.134 anton 3563: certain internal state and prints an error message. For a detailed
3564: description of error messages see @ref{Error messages}.
1.23 crook 3565:
1.29 crook 3566: The text interpreter waits for you to press carriage-return, and then
3567: processes your input line. Starting at the beginning of the line, it
3568: breaks the line into groups of characters separated by spaces. For each
3569: group of characters in turn, it makes two attempts to do something:
1.23 crook 3570:
1.29 crook 3571: @itemize @bullet
3572: @item
1.44 crook 3573: @cindex name dictionary
1.29 crook 3574: It tries to treat it as a command. It does this by searching a @dfn{name
3575: dictionary}. If the group of characters matches an entry in the name
3576: dictionary, the name dictionary provides the text interpreter with
3577: information that allows the text interpreter perform some actions. In
3578: Forth jargon, we say that the group
3579: @cindex word
3580: @cindex definition
3581: @cindex execution token
3582: @cindex xt
3583: of characters names a @dfn{word}, that the dictionary search returns an
3584: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3585: word, and that the text interpreter executes the xt. Often, the terms
3586: @dfn{word} and @dfn{definition} are used interchangeably.
3587: @item
3588: If the text interpreter fails to find a match in the name dictionary, it
3589: tries to treat the group of characters as a number in the current number
3590: base (when you start up Forth, the current number base is base 10). If
3591: the group of characters legitimately represents a number, the text
3592: interpreter pushes the number onto a stack (we'll learn more about that
3593: in the next section).
3594: @end itemize
1.23 crook 3595:
1.29 crook 3596: If the text interpreter is unable to do either of these things with any
3597: group of characters, it discards the group of characters and the rest of
3598: the line, then prints an error message. If the text interpreter reaches
3599: the end of the line without error, it prints the status message ``@code{ ok}''
3600: followed by carriage-return.
1.21 crook 3601:
1.29 crook 3602: This is the simplest command we can give to the text interpreter:
1.23 crook 3603:
3604: @example
1.30 anton 3605: @key{RET} ok
1.23 crook 3606: @end example
1.21 crook 3607:
1.29 crook 3608: The text interpreter did everything we asked it to do (nothing) without
3609: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3610: command:
1.21 crook 3611:
1.23 crook 3612: @example
1.30 anton 3613: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3614: *the terminal*:3: Undefined word
3615: 12 dup >>>fred<<< dup
3616: Backtrace:
3617: $2A95B42A20 throw
3618: $2A95B57FB8 no.extensions
1.23 crook 3619: @end example
1.21 crook 3620:
1.29 crook 3621: When you press the carriage-return key, the text interpreter starts to
3622: work its way along the line:
1.21 crook 3623:
1.29 crook 3624: @itemize @bullet
3625: @item
3626: When it gets to the space after the @code{2}, it takes the group of
3627: characters @code{12} and looks them up in the name
3628: dictionary@footnote{We can't tell if it found them or not, but assume
3629: for now that it did not}. There is no match for this group of characters
3630: in the name dictionary, so it tries to treat them as a number. It is
3631: able to do this successfully, so it puts the number, 12, ``on the stack''
3632: (whatever that means).
3633: @item
3634: The text interpreter resumes scanning the line and gets the next group
3635: of characters, @code{dup}. It looks it up in the name dictionary and
3636: (you'll have to take my word for this) finds it, and executes the word
3637: @code{dup} (whatever that means).
3638: @item
3639: Once again, the text interpreter resumes scanning the line and gets the
3640: group of characters @code{fred}. It looks them up in the name
3641: dictionary, but can't find them. It tries to treat them as a number, but
3642: they don't represent any legal number.
3643: @end itemize
1.21 crook 3644:
1.29 crook 3645: At this point, the text interpreter gives up and prints an error
3646: message. The error message shows exactly how far the text interpreter
3647: got in processing the line. In particular, it shows that the text
3648: interpreter made no attempt to do anything with the final character
3649: group, @code{dup}, even though we have good reason to believe that the
3650: text interpreter would have no problem looking that word up and
3651: executing it a second time.
1.21 crook 3652:
3653:
1.29 crook 3654: @comment ----------------------------------------------
3655: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3656: @section Stacks, postfix notation and parameter passing
3657: @cindex text interpreter
3658: @cindex outer interpreter
1.21 crook 3659:
1.29 crook 3660: In procedural programming languages (like C and Pascal), the
3661: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3662: functions or procedures are called with @dfn{explicit parameters}. For
3663: example, in C we might write:
1.21 crook 3664:
1.23 crook 3665: @example
1.29 crook 3666: total = total + new_volume(length,height,depth);
1.23 crook 3667: @end example
1.21 crook 3668:
1.23 crook 3669: @noindent
1.29 crook 3670: where new_volume is a function-call to another piece of code, and total,
3671: length, height and depth are all variables. length, height and depth are
3672: parameters to the function-call.
1.21 crook 3673:
1.29 crook 3674: In Forth, the equivalent of the function or procedure is the
3675: @dfn{definition} and parameters are implicitly passed between
3676: definitions using a shared stack that is visible to the
3677: programmer. Although Forth does support variables, the existence of the
3678: stack means that they are used far less often than in most other
3679: programming languages. When the text interpreter encounters a number, it
3680: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3681: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3682: used for any operation is implied unambiguously by the operation being
3683: performed. The stack used for all integer operations is called the @dfn{data
3684: stack} and, since this is the stack used most commonly, references to
3685: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3686:
1.29 crook 3687: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3688:
1.23 crook 3689: @example
1.30 anton 3690: @kbd{1 2 3@key{RET}} ok
1.23 crook 3691: @end example
1.21 crook 3692:
1.29 crook 3693: Then this instructs the text interpreter to placed three numbers on the
3694: (data) stack. An analogy for the behaviour of the stack is to take a
3695: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3696: the table. The 3 was the last card onto the pile (``last-in'') and if
3697: you take a card off the pile then, unless you're prepared to fiddle a
3698: bit, the card that you take off will be the 3 (``first-out''). The
3699: number that will be first-out of the stack is called the @dfn{top of
3700: stack}, which
3701: @cindex TOS definition
3702: is often abbreviated to @dfn{TOS}.
1.21 crook 3703:
1.29 crook 3704: To understand how parameters are passed in Forth, consider the
3705: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3706: be surprised to learn that this definition performs addition. More
3707: precisely, it adds two number together and produces a result. Where does
3708: it get the two numbers from? It takes the top two numbers off the
3709: stack. Where does it place the result? On the stack. You can act-out the
3710: behaviour of @code{+} with your playing cards like this:
1.21 crook 3711:
3712: @itemize @bullet
3713: @item
1.29 crook 3714: Pick up two cards from the stack on the table
1.21 crook 3715: @item
1.29 crook 3716: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3717: numbers''
1.21 crook 3718: @item
1.29 crook 3719: Decide that the answer is 5
1.21 crook 3720: @item
1.29 crook 3721: Shuffle the two cards back into the pack and find a 5
1.21 crook 3722: @item
1.29 crook 3723: Put a 5 on the remaining ace that's on the table.
1.21 crook 3724: @end itemize
3725:
1.29 crook 3726: If you don't have a pack of cards handy but you do have Forth running,
3727: you can use the definition @code{.s} to show the current state of the stack,
3728: without affecting the stack. Type:
1.21 crook 3729:
3730: @example
1.124 anton 3731: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3732: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3733: @end example
3734:
1.124 anton 3735: The text interpreter looks up the word @code{clearstacks} and executes
3736: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3737: left on it by earlier examples. The text interpreter pushes each of the
3738: three numbers in turn onto the stack. Finally, the text interpreter
3739: looks up the word @code{.s} and executes it. The effect of executing
3740: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3741: followed by a list of all the items on the stack; the item on the far
3742: right-hand side is the TOS.
1.21 crook 3743:
1.29 crook 3744: You can now type:
1.21 crook 3745:
1.29 crook 3746: @example
1.30 anton 3747: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3748: @end example
1.21 crook 3749:
1.29 crook 3750: @noindent
3751: which is correct; there are now 2 items on the stack and the result of
3752: the addition is 5.
1.23 crook 3753:
1.29 crook 3754: If you're playing with cards, try doing a second addition: pick up the
3755: two cards, work out that their sum is 6, shuffle them into the pack,
3756: look for a 6 and place that on the table. You now have just one item on
3757: the stack. What happens if you try to do a third addition? Pick up the
3758: first card, pick up the second card -- ah! There is no second card. This
3759: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3760: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3761: Underflow or an Invalid Memory Address error).
1.23 crook 3762:
1.29 crook 3763: The opposite situation to a stack underflow is a @dfn{stack overflow},
3764: which simply accepts that there is a finite amount of storage space
3765: reserved for the stack. To stretch the playing card analogy, if you had
3766: enough packs of cards and you piled the cards up on the table, you would
3767: eventually be unable to add another card; you'd hit the ceiling. Gforth
3768: allows you to set the maximum size of the stacks. In general, the only
3769: time that you will get a stack overflow is because a definition has a
3770: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3771:
1.29 crook 3772: There's one final use for the playing card analogy. If you model your
3773: stack using a pack of playing cards, the maximum number of items on
3774: your stack will be 52 (I assume you didn't use the Joker). The maximum
3775: @i{value} of any item on the stack is 13 (the King). In fact, the only
3776: possible numbers are positive integer numbers 1 through 13; you can't
3777: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3778: think about some of the cards, you can accommodate different
3779: numbers. For example, you could think of the Jack as representing 0,
3780: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3781: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3782: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3783:
1.29 crook 3784: In that analogy, the limit was the amount of information that a single
3785: stack entry could hold, and Forth has a similar limit. In Forth, the
3786: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3787: implementation dependent and affects the maximum value that a stack
3788: entry can hold. A Standard Forth provides a cell size of at least
3789: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3790:
1.29 crook 3791: Forth does not do any type checking for you, so you are free to
3792: manipulate and combine stack items in any way you wish. A convenient way
3793: of treating stack items is as 2's complement signed integers, and that
3794: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3795:
1.29 crook 3796: @example
1.30 anton 3797: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3798: @end example
1.21 crook 3799:
1.29 crook 3800: If you use numbers and definitions like @code{+} in order to turn Forth
3801: into a great big pocket calculator, you will realise that it's rather
3802: different from a normal calculator. Rather than typing 2 + 3 = you had
3803: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3804: result). The terminology used to describe this difference is to say that
3805: your calculator uses @dfn{Infix Notation} (parameters and operators are
3806: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3807: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3808:
1.29 crook 3809: Whilst postfix notation might look confusing to begin with, it has
3810: several important advantages:
1.21 crook 3811:
1.23 crook 3812: @itemize @bullet
3813: @item
1.29 crook 3814: it is unambiguous
1.23 crook 3815: @item
1.29 crook 3816: it is more concise
1.23 crook 3817: @item
1.29 crook 3818: it fits naturally with a stack-based system
1.23 crook 3819: @end itemize
1.21 crook 3820:
1.29 crook 3821: To examine these claims in more detail, consider these sums:
1.21 crook 3822:
1.29 crook 3823: @example
3824: 6 + 5 * 4 =
3825: 4 * 5 + 6 =
3826: @end example
1.21 crook 3827:
1.29 crook 3828: If you're just learning maths or your maths is very rusty, you will
3829: probably come up with the answer 44 for the first and 26 for the
3830: second. If you are a bit of a whizz at maths you will remember the
3831: @i{convention} that multiplication takes precendence over addition, and
3832: you'd come up with the answer 26 both times. To explain the answer 26
3833: to someone who got the answer 44, you'd probably rewrite the first sum
3834: like this:
1.21 crook 3835:
1.29 crook 3836: @example
3837: 6 + (5 * 4) =
3838: @end example
1.21 crook 3839:
1.29 crook 3840: If what you really wanted was to perform the addition before the
3841: multiplication, you would have to use parentheses to force it.
1.21 crook 3842:
1.29 crook 3843: If you did the first two sums on a pocket calculator you would probably
3844: get the right answers, unless you were very cautious and entered them using
3845: these keystroke sequences:
1.21 crook 3846:
1.29 crook 3847: 6 + 5 = * 4 =
3848: 4 * 5 = + 6 =
1.21 crook 3849:
1.29 crook 3850: Postfix notation is unambiguous because the order that the operators
3851: are applied is always explicit; that also means that parentheses are
3852: never required. The operators are @i{active} (the act of quoting the
3853: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3854:
1.29 crook 3855: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3856: equivalent ways:
1.26 crook 3857:
3858: @example
1.29 crook 3859: 6 5 4 * + or:
3860: 5 4 * 6 +
1.26 crook 3861: @end example
1.23 crook 3862:
1.29 crook 3863: An important thing that you should notice about this notation is that
3864: the @i{order} of the numbers does not change; if you want to subtract
3865: 2 from 10 you type @code{10 2 -}.
1.1 anton 3866:
1.29 crook 3867: The reason that Forth uses postfix notation is very simple to explain: it
3868: makes the implementation extremely simple, and it follows naturally from
3869: using the stack as a mechanism for passing parameters. Another way of
3870: thinking about this is to realise that all Forth definitions are
3871: @i{active}; they execute as they are encountered by the text
3872: interpreter. The result of this is that the syntax of Forth is trivially
3873: simple.
1.1 anton 3874:
3875:
3876:
1.29 crook 3877: @comment ----------------------------------------------
3878: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3879: @section Your first Forth definition
3880: @cindex first definition
1.1 anton 3881:
1.29 crook 3882: Until now, the examples we've seen have been trivial; we've just been
3883: using Forth as a bigger-than-pocket calculator. Also, each calculation
3884: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3885: again@footnote{That's not quite true. If you press the up-arrow key on
3886: your keyboard you should be able to scroll back to any earlier command,
3887: edit it and re-enter it.} In this section we'll see how to add new
3888: words to Forth's vocabulary.
1.1 anton 3889:
1.29 crook 3890: The easiest way to create a new word is to use a @dfn{colon
3891: definition}. We'll define a few and try them out before worrying too
3892: much about how they work. Try typing in these examples; be careful to
3893: copy the spaces accurately:
1.1 anton 3894:
1.29 crook 3895: @example
3896: : add-two 2 + . ;
3897: : greet ." Hello and welcome" ;
3898: : demo 5 add-two ;
3899: @end example
1.1 anton 3900:
1.29 crook 3901: @noindent
3902: Now try them out:
1.1 anton 3903:
1.29 crook 3904: @example
1.30 anton 3905: @kbd{greet@key{RET}} Hello and welcome ok
3906: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3907: @kbd{4 add-two@key{RET}} 6 ok
3908: @kbd{demo@key{RET}} 7 ok
3909: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3910: @end example
1.1 anton 3911:
1.29 crook 3912: The first new thing that we've introduced here is the pair of words
3913: @code{:} and @code{;}. These are used to start and terminate a new
3914: definition, respectively. The first word after the @code{:} is the name
3915: for the new definition.
1.1 anton 3916:
1.29 crook 3917: As you can see from the examples, a definition is built up of words that
3918: have already been defined; Forth makes no distinction between
3919: definitions that existed when you started the system up, and those that
3920: you define yourself.
1.1 anton 3921:
1.29 crook 3922: The examples also introduce the words @code{.} (dot), @code{."}
3923: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3924: the stack and displays it. It's like @code{.s} except that it only
3925: displays the top item of the stack and it is destructive; after it has
3926: executed, the number is no longer on the stack. There is always one
3927: space printed after the number, and no spaces before it. Dot-quote
3928: defines a string (a sequence of characters) that will be printed when
3929: the word is executed. The string can contain any printable characters
3930: except @code{"}. A @code{"} has a special function; it is not a Forth
3931: word but it acts as a delimiter (the way that delimiters work is
3932: described in the next section). Finally, @code{dup} duplicates the value
3933: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3934:
1.29 crook 3935: We already know that the text interpreter searches through the
3936: dictionary to locate names. If you've followed the examples earlier, you
3937: will already have a definition called @code{add-two}. Lets try modifying
3938: it by typing in a new definition:
1.1 anton 3939:
1.29 crook 3940: @example
1.30 anton 3941: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3942: @end example
1.5 anton 3943:
1.29 crook 3944: Forth recognised that we were defining a word that already exists, and
3945: printed a message to warn us of that fact. Let's try out the new
3946: definition:
1.5 anton 3947:
1.29 crook 3948: @example
1.30 anton 3949: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3950: @end example
1.1 anton 3951:
1.29 crook 3952: @noindent
3953: All that we've actually done here, though, is to create a new
3954: definition, with a particular name. The fact that there was already a
3955: definition with the same name did not make any difference to the way
3956: that the new definition was created (except that Forth printed a warning
3957: message). The old definition of add-two still exists (try @code{demo}
3958: again to see that this is true). Any new definition will use the new
3959: definition of @code{add-two}, but old definitions continue to use the
3960: version that already existed at the time that they were @code{compiled}.
1.1 anton 3961:
1.29 crook 3962: Before you go on to the next section, try defining and redefining some
3963: words of your own.
1.1 anton 3964:
1.29 crook 3965: @comment ----------------------------------------------
3966: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3967: @section How does that work?
3968: @cindex parsing words
1.1 anton 3969:
1.30 anton 3970: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3971:
3972: @c Is it a good idea to talk about the interpretation semantics of a
3973: @c number? We don't have an xt to go along with it. - anton
3974:
3975: @c Now that I have eliminated execution semantics, I wonder if it would not
3976: @c be better to keep them (or add run-time semantics), to make it easier to
3977: @c explain what compilation semantics usually does. - anton
3978:
1.44 crook 3979: @c nac-> I removed the term ``default compilation sematics'' from the
3980: @c introductory chapter. Removing ``execution semantics'' was making
3981: @c everything simpler to explain, then I think the use of this term made
3982: @c everything more complex again. I replaced it with ``default
3983: @c semantics'' (which is used elsewhere in the manual) by which I mean
3984: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3985: @c flag set''.
3986:
3987: @c anton: I have eliminated default semantics (except in one place where it
3988: @c means "default interpretation and compilation semantics"), because it
3989: @c makes no sense in the presence of combined words. I reverted to
3990: @c "execution semantics" where necessary.
3991:
3992: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3993: @c section (and, unusually for me, I think I even made it shorter!). See
3994: @c what you think -- I know I have not addressed your primary concern
3995: @c that it is too heavy-going for an introduction. From what I understood
3996: @c of your course notes it looks as though they might be a good framework.
3997: @c Things that I've tried to capture here are some things that came as a
3998: @c great revelation here when I first understood them. Also, I like the
3999: @c fact that a very simple code example shows up almost all of the issues
4000: @c that you need to understand to see how Forth works. That's unique and
4001: @c worthwhile to emphasise.
4002:
1.83 anton 4003: @c anton: I think it's a good idea to present the details, especially those
4004: @c that you found to be a revelation, and probably the tutorial tries to be
4005: @c too superficial and does not get some of the things across that make
4006: @c Forth special. I do believe that most of the time these things should
4007: @c be discussed at the end of a section or in separate sections instead of
4008: @c in the middle of a section (e.g., the stuff you added in "User-defined
4009: @c defining words" leads in a completely different direction from the rest
4010: @c of the section).
4011:
1.29 crook 4012: Now we're going to take another look at the definition of @code{add-two}
4013: from the previous section. From our knowledge of the way that the text
4014: interpreter works, we would have expected this result when we tried to
4015: define @code{add-two}:
1.21 crook 4016:
1.29 crook 4017: @example
1.44 crook 4018: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 4019: *the terminal*:4: Undefined word
4020: : >>>add-two<<< 2 + . ;
1.29 crook 4021: @end example
1.28 crook 4022:
1.29 crook 4023: The reason that this didn't happen is bound up in the way that @code{:}
4024: works. The word @code{:} does two special things. The first special
4025: thing that it does prevents the text interpreter from ever seeing the
4026: characters @code{add-two}. The text interpreter uses a variable called
4027: @cindex modifying >IN
1.44 crook 4028: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 4029: input line. When it encounters the word @code{:} it behaves in exactly
4030: the same way as it does for any other word; it looks it up in the name
4031: dictionary, finds its xt and executes it. When @code{:} executes, it
4032: looks at the input buffer, finds the word @code{add-two} and advances the
4033: value of @code{>IN} to point past it. It then does some other stuff
4034: associated with creating the new definition (including creating an entry
4035: for @code{add-two} in the name dictionary). When the execution of @code{:}
4036: completes, control returns to the text interpreter, which is oblivious
4037: to the fact that it has been tricked into ignoring part of the input
4038: line.
1.21 crook 4039:
1.29 crook 4040: @cindex parsing words
4041: Words like @code{:} -- words that advance the value of @code{>IN} and so
4042: prevent the text interpreter from acting on the whole of the input line
4043: -- are called @dfn{parsing words}.
1.21 crook 4044:
1.29 crook 4045: @cindex @code{state} - effect on the text interpreter
4046: @cindex text interpreter - effect of state
4047: The second special thing that @code{:} does is change the value of a
4048: variable called @code{state}, which affects the way that the text
4049: interpreter behaves. When Gforth starts up, @code{state} has the value
4050: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4051: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4052: the text interpreter is said to be @dfn{compiling}.
4053:
4054: In this example, the text interpreter is compiling when it processes the
4055: string ``@code{2 + . ;}''. It still breaks the string down into
4056: character sequences in the same way. However, instead of pushing the
4057: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4058: into the definition of @code{add-two} that will make the number @code{2} get
4059: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4060: the behaviours of @code{+} and @code{.} are also compiled into the
4061: definition.
4062:
4063: One category of words don't get compiled. These so-called @dfn{immediate
4064: words} get executed (performed @i{now}) regardless of whether the text
4065: interpreter is interpreting or compiling. The word @code{;} is an
4066: immediate word. Rather than being compiled into the definition, it
4067: executes. Its effect is to terminate the current definition, which
4068: includes changing the value of @code{state} back to 0.
4069:
4070: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4071: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4072: definition.
1.28 crook 4073:
1.30 anton 4074: In Forth, every word or number can be described in terms of two
1.29 crook 4075: properties:
1.28 crook 4076:
4077: @itemize @bullet
4078: @item
1.29 crook 4079: @cindex interpretation semantics
1.44 crook 4080: Its @dfn{interpretation semantics} describe how it will behave when the
4081: text interpreter encounters it in @dfn{interpret} state. The
4082: interpretation semantics of a word are represented by an @dfn{execution
4083: token}.
1.28 crook 4084: @item
1.29 crook 4085: @cindex compilation semantics
1.44 crook 4086: Its @dfn{compilation semantics} describe how it will behave when the
4087: text interpreter encounters it in @dfn{compile} state. The compilation
4088: semantics of a word are represented in an implementation-dependent way;
4089: Gforth uses a @dfn{compilation token}.
1.29 crook 4090: @end itemize
4091:
4092: @noindent
4093: Numbers are always treated in a fixed way:
4094:
4095: @itemize @bullet
1.28 crook 4096: @item
1.44 crook 4097: When the number is @dfn{interpreted}, its behaviour is to push the
4098: number onto the stack.
1.28 crook 4099: @item
1.30 anton 4100: When the number is @dfn{compiled}, a piece of code is appended to the
4101: current definition that pushes the number when it runs. (In other words,
4102: the compilation semantics of a number are to postpone its interpretation
4103: semantics until the run-time of the definition that it is being compiled
4104: into.)
1.29 crook 4105: @end itemize
4106:
1.44 crook 4107: Words don't behave in such a regular way, but most have @i{default
4108: semantics} which means that they behave like this:
1.29 crook 4109:
4110: @itemize @bullet
1.28 crook 4111: @item
1.30 anton 4112: The @dfn{interpretation semantics} of the word are to do something useful.
4113: @item
1.29 crook 4114: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4115: @dfn{interpretation semantics} to the current definition (so that its
4116: run-time behaviour is to do something useful).
1.28 crook 4117: @end itemize
4118:
1.30 anton 4119: @cindex immediate words
1.44 crook 4120: The actual behaviour of any particular word can be controlled by using
4121: the words @code{immediate} and @code{compile-only} when the word is
4122: defined. These words set flags in the name dictionary entry of the most
4123: recently defined word, and these flags are retrieved by the text
4124: interpreter when it finds the word in the name dictionary.
4125:
4126: A word that is marked as @dfn{immediate} has compilation semantics that
4127: are identical to its interpretation semantics. In other words, it
4128: behaves like this:
1.29 crook 4129:
4130: @itemize @bullet
4131: @item
1.30 anton 4132: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4133: @item
1.30 anton 4134: The @dfn{compilation semantics} of the word are to do something useful
4135: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4136: @end itemize
1.28 crook 4137:
1.44 crook 4138: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4139: performing the interpretation semantics of the word directly; an attempt
4140: to do so will generate an error. It is never necessary to use
4141: @code{compile-only} (and it is not even part of ANS Forth, though it is
4142: provided by many implementations) but it is good etiquette to apply it
4143: to a word that will not behave correctly (and might have unexpected
4144: side-effects) in interpret state. For example, it is only legal to use
4145: the conditional word @code{IF} within a definition. If you forget this
4146: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4147: @code{compile-only} allows the text interpreter to generate a helpful
4148: error message rather than subjecting you to the consequences of your
4149: folly.
4150:
1.29 crook 4151: This example shows the difference between an immediate and a
4152: non-immediate word:
1.28 crook 4153:
1.29 crook 4154: @example
4155: : show-state state @@ . ;
4156: : show-state-now show-state ; immediate
4157: : word1 show-state ;
4158: : word2 show-state-now ;
1.28 crook 4159: @end example
1.23 crook 4160:
1.29 crook 4161: The word @code{immediate} after the definition of @code{show-state-now}
4162: makes that word an immediate word. These definitions introduce a new
4163: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4164: variable, and leaves it on the stack. Therefore, the behaviour of
4165: @code{show-state} is to print a number that represents the current value
4166: of @code{state}.
1.28 crook 4167:
1.29 crook 4168: When you execute @code{word1}, it prints the number 0, indicating that
4169: the system is interpreting. When the text interpreter compiled the
4170: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4171: compilation semantics are to append its interpretation semantics to the
1.29 crook 4172: current definition. When you execute @code{word1}, it performs the
1.30 anton 4173: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4174: (and therefore @code{show-state}) are executed, the system is
4175: interpreting.
1.28 crook 4176:
1.30 anton 4177: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4178: you should have seen the number -1 printed, followed by ``@code{
4179: ok}''. When the text interpreter compiled the definition of
4180: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4181: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4182: semantics. It is executed straight away (even before the text
4183: interpreter has moved on to process another group of characters; the
4184: @code{;} in this example). The effect of executing it are to display the
4185: value of @code{state} @i{at the time that the definition of}
4186: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4187: system is compiling at this time. If you execute @code{word2} it does
4188: nothing at all.
1.28 crook 4189:
1.29 crook 4190: @cindex @code{."}, how it works
4191: Before leaving the subject of immediate words, consider the behaviour of
4192: @code{."} in the definition of @code{greet}, in the previous
4193: section. This word is both a parsing word and an immediate word. Notice
4194: that there is a space between @code{."} and the start of the text
4195: @code{Hello and welcome}, but that there is no space between the last
4196: letter of @code{welcome} and the @code{"} character. The reason for this
4197: is that @code{."} is a Forth word; it must have a space after it so that
4198: the text interpreter can identify it. The @code{"} is not a Forth word;
4199: it is a @dfn{delimiter}. The examples earlier show that, when the string
4200: is displayed, there is neither a space before the @code{H} nor after the
4201: @code{e}. Since @code{."} is an immediate word, it executes at the time
4202: that @code{greet} is defined. When it executes, its behaviour is to
4203: search forward in the input line looking for the delimiter. When it
4204: finds the delimiter, it updates @code{>IN} to point past the
4205: delimiter. It also compiles some magic code into the definition of
4206: @code{greet}; the xt of a run-time routine that prints a text string. It
4207: compiles the string @code{Hello and welcome} into memory so that it is
4208: available to be printed later. When the text interpreter gains control,
4209: the next word it finds in the input stream is @code{;} and so it
4210: terminates the definition of @code{greet}.
1.28 crook 4211:
4212:
4213: @comment ----------------------------------------------
1.29 crook 4214: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4215: @section Forth is written in Forth
4216: @cindex structure of Forth programs
4217:
4218: When you start up a Forth compiler, a large number of definitions
4219: already exist. In Forth, you develop a new application using bottom-up
4220: programming techniques to create new definitions that are defined in
4221: terms of existing definitions. As you create each definition you can
4222: test and debug it interactively.
4223:
4224: If you have tried out the examples in this section, you will probably
4225: have typed them in by hand; when you leave Gforth, your definitions will
4226: be lost. You can avoid this by using a text editor to enter Forth source
4227: code into a file, and then loading code from the file using
1.49 anton 4228: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4229: processed by the text interpreter, just as though you had typed it in by
4230: hand@footnote{Actually, there are some subtle differences -- see
4231: @ref{The Text Interpreter}.}.
4232:
4233: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4234: files for program entry (@pxref{Blocks}).
1.28 crook 4235:
1.29 crook 4236: In common with many, if not most, Forth compilers, most of Gforth is
4237: actually written in Forth. All of the @file{.fs} files in the
4238: installation directory@footnote{For example,
1.30 anton 4239: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4240: study to see examples of Forth programming.
1.28 crook 4241:
1.29 crook 4242: Gforth maintains a history file that records every line that you type to
4243: the text interpreter. This file is preserved between sessions, and is
4244: used to provide a command-line recall facility. If you enter long
4245: definitions by hand, you can use a text editor to paste them out of the
4246: history file into a Forth source file for reuse at a later time
1.49 anton 4247: (for more information @pxref{Command-line editing}).
1.28 crook 4248:
4249:
4250: @comment ----------------------------------------------
1.29 crook 4251: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4252: @section Review - elements of a Forth system
4253: @cindex elements of a Forth system
1.28 crook 4254:
1.29 crook 4255: To summarise this chapter:
1.28 crook 4256:
4257: @itemize @bullet
4258: @item
1.29 crook 4259: Forth programs use @dfn{factoring} to break a problem down into small
4260: fragments called @dfn{words} or @dfn{definitions}.
4261: @item
4262: Forth program development is an interactive process.
4263: @item
4264: The main command loop that accepts input, and controls both
4265: interpretation and compilation, is called the @dfn{text interpreter}
4266: (also known as the @dfn{outer interpreter}).
4267: @item
4268: Forth has a very simple syntax, consisting of words and numbers
4269: separated by spaces or carriage-return characters. Any additional syntax
4270: is imposed by @dfn{parsing words}.
4271: @item
4272: Forth uses a stack to pass parameters between words. As a result, it
4273: uses postfix notation.
4274: @item
4275: To use a word that has previously been defined, the text interpreter
4276: searches for the word in the @dfn{name dictionary}.
4277: @item
1.30 anton 4278: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4279: @item
1.29 crook 4280: The text interpreter uses the value of @code{state} to select between
4281: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4282: semantics} of a word that it encounters.
1.28 crook 4283: @item
1.30 anton 4284: The relationship between the @dfn{interpretation semantics} and
4285: @dfn{compilation semantics} for a word
1.29 crook 4286: depend upon the way in which the word was defined (for example, whether
4287: it is an @dfn{immediate} word).
1.28 crook 4288: @item
1.29 crook 4289: Forth definitions can be implemented in Forth (called @dfn{high-level
4290: definitions}) or in some other way (usually a lower-level language and
4291: as a result often called @dfn{low-level definitions}, @dfn{code
4292: definitions} or @dfn{primitives}).
1.28 crook 4293: @item
1.29 crook 4294: Many Forth systems are implemented mainly in Forth.
1.28 crook 4295: @end itemize
4296:
4297:
1.29 crook 4298: @comment ----------------------------------------------
1.48 anton 4299: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4300: @section Where To Go Next
4301: @cindex where to go next
1.28 crook 4302:
1.29 crook 4303: Amazing as it may seem, if you have read (and understood) this far, you
4304: know almost all the fundamentals about the inner workings of a Forth
4305: system. You certainly know enough to be able to read and understand the
4306: rest of this manual and the ANS Forth document, to learn more about the
4307: facilities that Forth in general and Gforth in particular provide. Even
4308: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4309: However, that's not a good idea just yet... better to try writing some
1.29 crook 4310: programs in Gforth.
1.28 crook 4311:
1.29 crook 4312: Forth has such a rich vocabulary that it can be hard to know where to
4313: start in learning it. This section suggests a few sets of words that are
4314: enough to write small but useful programs. Use the word index in this
4315: document to learn more about each word, then try it out and try to write
4316: small definitions using it. Start by experimenting with these words:
1.28 crook 4317:
4318: @itemize @bullet
4319: @item
1.29 crook 4320: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4321: @item
4322: Comparison: @code{MIN MAX =}
4323: @item
4324: Logic: @code{AND OR XOR NOT}
4325: @item
4326: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4327: @item
1.29 crook 4328: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4329: @item
1.29 crook 4330: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4331: @item
1.29 crook 4332: Defining words: @code{: ; CREATE}
1.28 crook 4333: @item
1.29 crook 4334: Memory allocation words: @code{ALLOT ,}
1.28 crook 4335: @item
1.29 crook 4336: Tools: @code{SEE WORDS .S MARKER}
4337: @end itemize
4338:
4339: When you have mastered those, go on to:
4340:
4341: @itemize @bullet
1.28 crook 4342: @item
1.29 crook 4343: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4344: @item
1.29 crook 4345: Memory access: @code{@@ !}
1.28 crook 4346: @end itemize
1.23 crook 4347:
1.29 crook 4348: When you have mastered these, there's nothing for it but to read through
4349: the whole of this manual and find out what you've missed.
4350:
4351: @comment ----------------------------------------------
1.48 anton 4352: @node Exercises, , Where to go next, Introduction
1.29 crook 4353: @section Exercises
4354: @cindex exercises
4355:
4356: TODO: provide a set of programming excercises linked into the stuff done
4357: already and into other sections of the manual. Provide solutions to all
4358: the exercises in a .fs file in the distribution.
4359:
4360: @c Get some inspiration from Starting Forth and Kelly&Spies.
4361:
4362: @c excercises:
4363: @c 1. take inches and convert to feet and inches.
4364: @c 2. take temperature and convert from fahrenheight to celcius;
4365: @c may need to care about symmetric vs floored??
4366: @c 3. take input line and do character substitution
4367: @c to encipher or decipher
4368: @c 4. as above but work on a file for in and out
4369: @c 5. take input line and convert to pig-latin
4370: @c
4371: @c thing of sets of things to exercise then come up with
4372: @c problems that need those things.
4373:
4374:
1.26 crook 4375: @c ******************************************************************
1.29 crook 4376: @node Words, Error messages, Introduction, Top
1.1 anton 4377: @chapter Forth Words
1.26 crook 4378: @cindex words
1.1 anton 4379:
4380: @menu
4381: * Notation::
1.65 anton 4382: * Case insensitivity::
4383: * Comments::
4384: * Boolean Flags::
1.1 anton 4385: * Arithmetic::
4386: * Stack Manipulation::
1.5 anton 4387: * Memory::
1.1 anton 4388: * Control Structures::
4389: * Defining Words::
1.65 anton 4390: * Interpretation and Compilation Semantics::
1.47 crook 4391: * Tokens for Words::
1.81 anton 4392: * Compiling words::
1.65 anton 4393: * The Text Interpreter::
1.111 anton 4394: * The Input Stream::
1.65 anton 4395: * Word Lists::
4396: * Environmental Queries::
1.12 anton 4397: * Files::
4398: * Blocks::
4399: * Other I/O::
1.121 anton 4400: * OS command line arguments::
1.78 anton 4401: * Locals::
4402: * Structures::
4403: * Object-oriented Forth::
1.12 anton 4404: * Programming Tools::
1.150 anton 4405: * C Interface::
1.12 anton 4406: * Assembler and Code Words::
4407: * Threading Words::
1.65 anton 4408: * Passing Commands to the OS::
4409: * Keeping track of Time::
4410: * Miscellaneous Words::
1.1 anton 4411: @end menu
4412:
1.65 anton 4413: @node Notation, Case insensitivity, Words, Words
1.1 anton 4414: @section Notation
4415: @cindex notation of glossary entries
4416: @cindex format of glossary entries
4417: @cindex glossary notation format
4418: @cindex word glossary entry format
4419:
4420: The Forth words are described in this section in the glossary notation
1.67 anton 4421: that has become a de-facto standard for Forth texts:
1.1 anton 4422:
4423: @format
1.29 crook 4424: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4425: @end format
1.29 crook 4426: @i{Description}
1.1 anton 4427:
4428: @table @var
4429: @item word
1.28 crook 4430: The name of the word.
1.1 anton 4431:
4432: @item Stack effect
4433: @cindex stack effect
1.29 crook 4434: The stack effect is written in the notation @code{@i{before} --
4435: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4436: stack entries before and after the execution of the word. The rest of
4437: the stack is not touched by the word. The top of stack is rightmost,
4438: i.e., a stack sequence is written as it is typed in. Note that Gforth
4439: uses a separate floating point stack, but a unified stack
1.29 crook 4440: notation. Also, return stack effects are not shown in @i{stack
4441: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4442: the type and/or the function of the item. See below for a discussion of
4443: the types.
4444:
4445: All words have two stack effects: A compile-time stack effect and a
4446: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4447: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4448: this standard behaviour, or the word does other unusual things at
4449: compile time, both stack effects are shown; otherwise only the run-time
4450: stack effect is shown.
4451:
1.211 ! anton 4452: Also note that in code templates or examples there can be comments in
! 4453: parentheses that display the stack picture at this point; there is no
! 4454: @code{--} in these places, because there is no before-after situation.
! 4455:
1.1 anton 4456: @cindex pronounciation of words
4457: @item pronunciation
4458: How the word is pronounced.
4459:
4460: @cindex wordset
1.67 anton 4461: @cindex environment wordset
1.1 anton 4462: @item wordset
1.21 crook 4463: The ANS Forth standard is divided into several word sets. A standard
4464: system need not support all of them. Therefore, in theory, the fewer
4465: word sets your program uses the more portable it will be. However, we
4466: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4467: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4468: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4469: describes words that will work in future releases of Gforth;
4470: @code{gforth-internal} words are more volatile. Environmental query
4471: strings are also displayed like words; you can recognize them by the
1.21 crook 4472: @code{environment} in the word set field.
1.1 anton 4473:
4474: @item Description
4475: A description of the behaviour of the word.
4476: @end table
4477:
4478: @cindex types of stack items
4479: @cindex stack item types
4480: The type of a stack item is specified by the character(s) the name
4481: starts with:
4482:
4483: @table @code
4484: @item f
4485: @cindex @code{f}, stack item type
4486: Boolean flags, i.e. @code{false} or @code{true}.
4487: @item c
4488: @cindex @code{c}, stack item type
4489: Char
4490: @item w
4491: @cindex @code{w}, stack item type
4492: Cell, can contain an integer or an address
4493: @item n
4494: @cindex @code{n}, stack item type
4495: signed integer
4496: @item u
4497: @cindex @code{u}, stack item type
4498: unsigned integer
4499: @item d
4500: @cindex @code{d}, stack item type
4501: double sized signed integer
4502: @item ud
4503: @cindex @code{ud}, stack item type
4504: double sized unsigned integer
4505: @item r
4506: @cindex @code{r}, stack item type
4507: Float (on the FP stack)
1.21 crook 4508: @item a-
1.1 anton 4509: @cindex @code{a_}, stack item type
4510: Cell-aligned address
1.21 crook 4511: @item c-
1.1 anton 4512: @cindex @code{c_}, stack item type
4513: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4514: @item f-
1.1 anton 4515: @cindex @code{f_}, stack item type
4516: Float-aligned address
1.21 crook 4517: @item df-
1.1 anton 4518: @cindex @code{df_}, stack item type
4519: Address aligned for IEEE double precision float
1.21 crook 4520: @item sf-
1.1 anton 4521: @cindex @code{sf_}, stack item type
4522: Address aligned for IEEE single precision float
4523: @item xt
4524: @cindex @code{xt}, stack item type
4525: Execution token, same size as Cell
4526: @item wid
4527: @cindex @code{wid}, stack item type
1.21 crook 4528: Word list ID, same size as Cell
1.68 anton 4529: @item ior, wior
4530: @cindex ior type description
4531: @cindex wior type description
4532: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4533: @item f83name
4534: @cindex @code{f83name}, stack item type
4535: Pointer to a name structure
4536: @item "
4537: @cindex @code{"}, stack item type
1.12 anton 4538: string in the input stream (not on the stack). The terminating character
4539: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4540: quotes.
4541: @end table
4542:
1.65 anton 4543: @comment ----------------------------------------------
4544: @node Case insensitivity, Comments, Notation, Words
4545: @section Case insensitivity
4546: @cindex case sensitivity
4547: @cindex upper and lower case
4548:
4549: Gforth is case-insensitive; you can enter definitions and invoke
4550: Standard words using upper, lower or mixed case (however,
4551: @pxref{core-idef, Implementation-defined options, Implementation-defined
4552: options}).
4553:
4554: ANS Forth only @i{requires} implementations to recognise Standard words
4555: when they are typed entirely in upper case. Therefore, a Standard
4556: program must use upper case for all Standard words. You can use whatever
4557: case you like for words that you define, but in a Standard program you
4558: have to use the words in the same case that you defined them.
4559:
4560: Gforth supports case sensitivity through @code{table}s (case-sensitive
4561: wordlists, @pxref{Word Lists}).
4562:
4563: Two people have asked how to convert Gforth to be case-sensitive; while
4564: we think this is a bad idea, you can change all wordlists into tables
4565: like this:
4566:
4567: @example
4568: ' table-find forth-wordlist wordlist-map @ !
4569: @end example
4570:
4571: Note that you now have to type the predefined words in the same case
4572: that we defined them, which are varying. You may want to convert them
4573: to your favourite case before doing this operation (I won't explain how,
4574: because if you are even contemplating doing this, you'd better have
4575: enough knowledge of Forth systems to know this already).
4576:
4577: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4578: @section Comments
1.26 crook 4579: @cindex comments
1.21 crook 4580:
1.29 crook 4581: Forth supports two styles of comment; the traditional @i{in-line} comment,
4582: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4583:
1.44 crook 4584:
1.23 crook 4585: doc-(
1.21 crook 4586: doc-\
1.23 crook 4587: doc-\G
1.21 crook 4588:
1.44 crook 4589:
1.21 crook 4590: @node Boolean Flags, Arithmetic, Comments, Words
4591: @section Boolean Flags
1.26 crook 4592: @cindex Boolean flags
1.21 crook 4593:
4594: A Boolean flag is cell-sized. A cell with all bits clear represents the
4595: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4596: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4597: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4598: @c on and off to Memory?
4599: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4600:
1.21 crook 4601: doc-true
4602: doc-false
1.29 crook 4603: doc-on
4604: doc-off
1.21 crook 4605:
1.44 crook 4606:
1.21 crook 4607: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4608: @section Arithmetic
4609: @cindex arithmetic words
4610:
4611: @cindex division with potentially negative operands
4612: Forth arithmetic is not checked, i.e., you will not hear about integer
4613: overflow on addition or multiplication, you may hear about division by
4614: zero if you are lucky. The operator is written after the operands, but
4615: the operands are still in the original order. I.e., the infix @code{2-1}
4616: corresponds to @code{2 1 -}. Forth offers a variety of division
4617: operators. If you perform division with potentially negative operands,
4618: you do not want to use @code{/} or @code{/mod} with its undefined
4619: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4620: former, @pxref{Mixed precision}).
1.26 crook 4621: @comment TODO discuss the different division forms and the std approach
1.1 anton 4622:
4623: @menu
4624: * Single precision::
1.67 anton 4625: * Double precision:: Double-cell integer arithmetic
1.1 anton 4626: * Bitwise operations::
1.67 anton 4627: * Numeric comparison::
1.29 crook 4628: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4629: * Floating Point::
4630: @end menu
4631:
1.67 anton 4632: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4633: @subsection Single precision
4634: @cindex single precision arithmetic words
4635:
1.67 anton 4636: @c !! cell undefined
4637:
4638: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4639: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4640: treat them. For the rules used by the text interpreter for recognising
4641: single-precision integers see @ref{Number Conversion}.
1.21 crook 4642:
1.67 anton 4643: These words are all defined for signed operands, but some of them also
4644: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4645: @code{*}.
1.44 crook 4646:
1.1 anton 4647: doc-+
1.21 crook 4648: doc-1+
1.128 anton 4649: doc-under+
1.1 anton 4650: doc--
1.21 crook 4651: doc-1-
1.1 anton 4652: doc-*
4653: doc-/
4654: doc-mod
4655: doc-/mod
4656: doc-negate
4657: doc-abs
4658: doc-min
4659: doc-max
1.27 crook 4660: doc-floored
1.1 anton 4661:
1.44 crook 4662:
1.67 anton 4663: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4664: @subsection Double precision
4665: @cindex double precision arithmetic words
4666:
1.49 anton 4667: For the rules used by the text interpreter for
4668: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4669:
4670: A double precision number is represented by a cell pair, with the most
1.67 anton 4671: significant cell at the TOS. It is trivial to convert an unsigned single
4672: to a double: simply push a @code{0} onto the TOS. Since numbers are
4673: represented by Gforth using 2's complement arithmetic, converting a
4674: signed single to a (signed) double requires sign-extension across the
4675: most significant cell. This can be achieved using @code{s>d}. The moral
4676: of the story is that you cannot convert a number without knowing whether
4677: it represents an unsigned or a signed number.
1.21 crook 4678:
1.67 anton 4679: These words are all defined for signed operands, but some of them also
4680: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4681:
1.21 crook 4682: doc-s>d
1.67 anton 4683: doc-d>s
1.21 crook 4684: doc-d+
4685: doc-d-
4686: doc-dnegate
4687: doc-dabs
4688: doc-dmin
4689: doc-dmax
4690:
1.44 crook 4691:
1.67 anton 4692: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4693: @subsection Bitwise operations
4694: @cindex bitwise operation words
4695:
4696:
4697: doc-and
4698: doc-or
4699: doc-xor
4700: doc-invert
4701: doc-lshift
4702: doc-rshift
4703: doc-2*
4704: doc-d2*
4705: doc-2/
4706: doc-d2/
4707:
4708:
4709: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4710: @subsection Numeric comparison
4711: @cindex numeric comparison words
4712:
1.67 anton 4713: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4714: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4715:
1.28 crook 4716: doc-<
4717: doc-<=
4718: doc-<>
4719: doc-=
4720: doc->
4721: doc->=
4722:
1.21 crook 4723: doc-0<
1.23 crook 4724: doc-0<=
1.21 crook 4725: doc-0<>
4726: doc-0=
1.23 crook 4727: doc-0>
4728: doc-0>=
1.28 crook 4729:
4730: doc-u<
4731: doc-u<=
1.44 crook 4732: @c u<> and u= exist but are the same as <> and =
1.31 anton 4733: @c doc-u<>
4734: @c doc-u=
1.28 crook 4735: doc-u>
4736: doc-u>=
4737:
4738: doc-within
4739:
4740: doc-d<
4741: doc-d<=
4742: doc-d<>
4743: doc-d=
4744: doc-d>
4745: doc-d>=
1.23 crook 4746:
1.21 crook 4747: doc-d0<
1.23 crook 4748: doc-d0<=
4749: doc-d0<>
1.21 crook 4750: doc-d0=
1.23 crook 4751: doc-d0>
4752: doc-d0>=
4753:
1.21 crook 4754: doc-du<
1.28 crook 4755: doc-du<=
1.44 crook 4756: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4757: @c doc-du<>
4758: @c doc-du=
1.28 crook 4759: doc-du>
4760: doc-du>=
1.1 anton 4761:
1.44 crook 4762:
1.21 crook 4763: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4764: @subsection Mixed precision
4765: @cindex mixed precision arithmetic words
4766:
1.44 crook 4767:
1.1 anton 4768: doc-m+
4769: doc-*/
4770: doc-*/mod
4771: doc-m*
4772: doc-um*
4773: doc-m*/
4774: doc-um/mod
4775: doc-fm/mod
4776: doc-sm/rem
4777:
1.44 crook 4778:
1.21 crook 4779: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4780: @subsection Floating Point
4781: @cindex floating point arithmetic words
4782:
1.49 anton 4783: For the rules used by the text interpreter for
4784: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4785:
1.67 anton 4786: Gforth has a separate floating point stack, but the documentation uses
4787: the unified notation.@footnote{It's easy to generate the separate
4788: notation from that by just separating the floating-point numbers out:
4789: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4790: r3 )}.}
1.1 anton 4791:
4792: @cindex floating-point arithmetic, pitfalls
4793: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4794: unwary (e.g., floating point addition is not associative) and even a
4795: few for the wary. You should not use them unless you know what you are
4796: doing or you don't care that the results you get are totally bogus. If
4797: you want to learn about the problems of floating point numbers (and
4798: how to avoid them), you might start with @cite{David Goldberg,
4799: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4800: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4801: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4802:
1.44 crook 4803:
1.21 crook 4804: doc-d>f
4805: doc-f>d
1.1 anton 4806: doc-f+
4807: doc-f-
4808: doc-f*
4809: doc-f/
4810: doc-fnegate
4811: doc-fabs
4812: doc-fmax
4813: doc-fmin
4814: doc-floor
4815: doc-fround
4816: doc-f**
4817: doc-fsqrt
4818: doc-fexp
4819: doc-fexpm1
4820: doc-fln
4821: doc-flnp1
4822: doc-flog
4823: doc-falog
1.32 anton 4824: doc-f2*
4825: doc-f2/
4826: doc-1/f
4827: doc-precision
4828: doc-set-precision
4829:
4830: @cindex angles in trigonometric operations
4831: @cindex trigonometric operations
4832: Angles in floating point operations are given in radians (a full circle
4833: has 2 pi radians).
4834:
1.1 anton 4835: doc-fsin
4836: doc-fcos
4837: doc-fsincos
4838: doc-ftan
4839: doc-fasin
4840: doc-facos
4841: doc-fatan
4842: doc-fatan2
4843: doc-fsinh
4844: doc-fcosh
4845: doc-ftanh
4846: doc-fasinh
4847: doc-facosh
4848: doc-fatanh
1.21 crook 4849: doc-pi
1.28 crook 4850:
1.32 anton 4851: @cindex equality of floats
4852: @cindex floating-point comparisons
1.31 anton 4853: One particular problem with floating-point arithmetic is that comparison
4854: for equality often fails when you would expect it to succeed. For this
4855: reason approximate equality is often preferred (but you still have to
1.67 anton 4856: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4857: differently from what you might expect. The comparison words are:
1.31 anton 4858:
4859: doc-f~rel
4860: doc-f~abs
1.68 anton 4861: doc-f~
1.31 anton 4862: doc-f=
4863: doc-f<>
4864:
4865: doc-f<
4866: doc-f<=
4867: doc-f>
4868: doc-f>=
4869:
1.21 crook 4870: doc-f0<
1.28 crook 4871: doc-f0<=
4872: doc-f0<>
1.21 crook 4873: doc-f0=
1.28 crook 4874: doc-f0>
4875: doc-f0>=
4876:
1.1 anton 4877:
4878: @node Stack Manipulation, Memory, Arithmetic, Words
4879: @section Stack Manipulation
4880: @cindex stack manipulation words
4881:
4882: @cindex floating-point stack in the standard
1.21 crook 4883: Gforth maintains a number of separate stacks:
4884:
1.29 crook 4885: @cindex data stack
4886: @cindex parameter stack
1.21 crook 4887: @itemize @bullet
4888: @item
1.29 crook 4889: A data stack (also known as the @dfn{parameter stack}) -- for
4890: characters, cells, addresses, and double cells.
1.21 crook 4891:
1.29 crook 4892: @cindex floating-point stack
1.21 crook 4893: @item
1.44 crook 4894: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4895:
1.29 crook 4896: @cindex return stack
1.21 crook 4897: @item
1.44 crook 4898: A return stack -- for holding the return addresses of colon
1.32 anton 4899: definitions and other (non-FP) data.
1.21 crook 4900:
1.29 crook 4901: @cindex locals stack
1.21 crook 4902: @item
1.44 crook 4903: A locals stack -- for holding local variables.
1.21 crook 4904: @end itemize
4905:
1.1 anton 4906: @menu
4907: * Data stack::
4908: * Floating point stack::
4909: * Return stack::
4910: * Locals stack::
4911: * Stack pointer manipulation::
4912: @end menu
4913:
4914: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4915: @subsection Data stack
4916: @cindex data stack manipulation words
4917: @cindex stack manipulations words, data stack
4918:
1.44 crook 4919:
1.1 anton 4920: doc-drop
4921: doc-nip
4922: doc-dup
4923: doc-over
4924: doc-tuck
4925: doc-swap
1.21 crook 4926: doc-pick
1.1 anton 4927: doc-rot
4928: doc--rot
4929: doc-?dup
4930: doc-roll
4931: doc-2drop
4932: doc-2nip
4933: doc-2dup
4934: doc-2over
4935: doc-2tuck
4936: doc-2swap
4937: doc-2rot
4938:
1.44 crook 4939:
1.1 anton 4940: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4941: @subsection Floating point stack
4942: @cindex floating-point stack manipulation words
4943: @cindex stack manipulation words, floating-point stack
4944:
1.32 anton 4945: Whilst every sane Forth has a separate floating-point stack, it is not
4946: strictly required; an ANS Forth system could theoretically keep
4947: floating-point numbers on the data stack. As an additional difficulty,
4948: you don't know how many cells a floating-point number takes. It is
4949: reportedly possible to write words in a way that they work also for a
4950: unified stack model, but we do not recommend trying it. Instead, just
4951: say that your program has an environmental dependency on a separate
4952: floating-point stack.
4953:
4954: doc-floating-stack
4955:
1.1 anton 4956: doc-fdrop
4957: doc-fnip
4958: doc-fdup
4959: doc-fover
4960: doc-ftuck
4961: doc-fswap
1.21 crook 4962: doc-fpick
1.1 anton 4963: doc-frot
4964:
1.44 crook 4965:
1.1 anton 4966: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4967: @subsection Return stack
4968: @cindex return stack manipulation words
4969: @cindex stack manipulation words, return stack
4970:
1.32 anton 4971: @cindex return stack and locals
4972: @cindex locals and return stack
4973: A Forth system is allowed to keep local variables on the
4974: return stack. This is reasonable, as local variables usually eliminate
4975: the need to use the return stack explicitly. So, if you want to produce
4976: a standard compliant program and you are using local variables in a
4977: word, forget about return stack manipulations in that word (refer to the
4978: standard document for the exact rules).
4979:
1.1 anton 4980: doc->r
4981: doc-r>
4982: doc-r@
4983: doc-rdrop
4984: doc-2>r
4985: doc-2r>
4986: doc-2r@
4987: doc-2rdrop
4988:
1.44 crook 4989:
1.1 anton 4990: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4991: @subsection Locals stack
4992:
1.78 anton 4993: Gforth uses an extra locals stack. It is described, along with the
4994: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4995:
1.1 anton 4996: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4997: @subsection Stack pointer manipulation
4998: @cindex stack pointer manipulation words
4999:
1.44 crook 5000: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 5001: doc-sp0
1.1 anton 5002: doc-sp@
5003: doc-sp!
1.21 crook 5004: doc-fp0
1.1 anton 5005: doc-fp@
5006: doc-fp!
1.21 crook 5007: doc-rp0
1.1 anton 5008: doc-rp@
5009: doc-rp!
1.21 crook 5010: doc-lp0
1.1 anton 5011: doc-lp@
5012: doc-lp!
5013:
1.44 crook 5014:
1.1 anton 5015: @node Memory, Control Structures, Stack Manipulation, Words
5016: @section Memory
1.26 crook 5017: @cindex memory words
1.1 anton 5018:
1.32 anton 5019: @menu
5020: * Memory model::
5021: * Dictionary allocation::
5022: * Heap Allocation::
5023: * Memory Access::
5024: * Address arithmetic::
5025: * Memory Blocks::
5026: @end menu
5027:
1.67 anton 5028: In addition to the standard Forth memory allocation words, there is also
5029: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5030: garbage collector}.
5031:
1.32 anton 5032: @node Memory model, Dictionary allocation, Memory, Memory
5033: @subsection ANS Forth and Gforth memory models
5034:
5035: @c The ANS Forth description is a mess (e.g., is the heap part of
5036: @c the dictionary?), so let's not stick to closely with it.
5037:
1.67 anton 5038: ANS Forth considers a Forth system as consisting of several address
5039: spaces, of which only @dfn{data space} is managed and accessible with
5040: the memory words. Memory not necessarily in data space includes the
5041: stacks, the code (called code space) and the headers (called name
5042: space). In Gforth everything is in data space, but the code for the
5043: primitives is usually read-only.
1.32 anton 5044:
5045: Data space is divided into a number of areas: The (data space portion of
5046: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5047: refer to the search data structure embodied in word lists and headers,
5048: because it is used for looking up names, just as you would in a
5049: conventional dictionary.}, the heap, and a number of system-allocated
5050: buffers.
5051:
1.68 anton 5052: @cindex address arithmetic restrictions, ANS vs. Gforth
5053: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5054: In ANS Forth data space is also divided into contiguous regions. You
5055: can only use address arithmetic within a contiguous region, not between
5056: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5057: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5058: allocation}).
5059:
5060: Gforth provides one big address space, and address arithmetic can be
5061: performed between any addresses. However, in the dictionary headers or
5062: code are interleaved with data, so almost the only contiguous data space
5063: regions there are those described by ANS Forth as contiguous; but you
5064: can be sure that the dictionary is allocated towards increasing
5065: addresses even between contiguous regions. The memory order of
5066: allocations in the heap is platform-dependent (and possibly different
5067: from one run to the next).
5068:
1.27 crook 5069:
1.32 anton 5070: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5071: @subsection Dictionary allocation
1.27 crook 5072: @cindex reserving data space
5073: @cindex data space - reserving some
5074:
1.32 anton 5075: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5076: you want to deallocate X, you also deallocate everything
5077: allocated after X.
5078:
1.68 anton 5079: @cindex contiguous regions in dictionary allocation
1.32 anton 5080: The allocations using the words below are contiguous and grow the region
5081: towards increasing addresses. Other words that allocate dictionary
5082: memory of any kind (i.e., defining words including @code{:noname}) end
5083: the contiguous region and start a new one.
5084:
5085: In ANS Forth only @code{create}d words are guaranteed to produce an
5086: address that is the start of the following contiguous region. In
5087: particular, the cell allocated by @code{variable} is not guaranteed to
5088: be contiguous with following @code{allot}ed memory.
5089:
5090: You can deallocate memory by using @code{allot} with a negative argument
5091: (with some restrictions, see @code{allot}). For larger deallocations use
5092: @code{marker}.
1.27 crook 5093:
1.29 crook 5094:
1.27 crook 5095: doc-here
5096: doc-unused
5097: doc-allot
5098: doc-c,
1.29 crook 5099: doc-f,
1.27 crook 5100: doc-,
5101: doc-2,
5102:
1.32 anton 5103: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5104: course you should allocate memory in an aligned way, too. I.e., before
5105: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5106: The words below align @code{here} if it is not already. Basically it is
5107: only already aligned for a type, if the last allocation was a multiple
5108: of the size of this type and if @code{here} was aligned for this type
5109: before.
5110:
5111: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5112: ANS Forth (@code{maxalign}ed in Gforth).
5113:
5114: doc-align
5115: doc-falign
5116: doc-sfalign
5117: doc-dfalign
5118: doc-maxalign
5119: doc-cfalign
5120:
5121:
5122: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5123: @subsection Heap allocation
5124: @cindex heap allocation
5125: @cindex dynamic allocation of memory
5126: @cindex memory-allocation word set
5127:
1.68 anton 5128: @cindex contiguous regions and heap allocation
1.32 anton 5129: Heap allocation supports deallocation of allocated memory in any
5130: order. Dictionary allocation is not affected by it (i.e., it does not
5131: end a contiguous region). In Gforth, these words are implemented using
5132: the standard C library calls malloc(), free() and resize().
5133:
1.68 anton 5134: The memory region produced by one invocation of @code{allocate} or
5135: @code{resize} is internally contiguous. There is no contiguity between
5136: such a region and any other region (including others allocated from the
5137: heap).
5138:
1.32 anton 5139: doc-allocate
5140: doc-free
5141: doc-resize
5142:
1.27 crook 5143:
1.32 anton 5144: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5145: @subsection Memory Access
5146: @cindex memory access words
5147:
5148: doc-@
5149: doc-!
5150: doc-+!
5151: doc-c@
5152: doc-c!
5153: doc-2@
5154: doc-2!
5155: doc-f@
5156: doc-f!
5157: doc-sf@
5158: doc-sf!
5159: doc-df@
5160: doc-df!
1.144 anton 5161: doc-sw@
5162: doc-uw@
5163: doc-w!
5164: doc-sl@
5165: doc-ul@
5166: doc-l!
1.68 anton 5167:
1.32 anton 5168: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5169: @subsection Address arithmetic
1.1 anton 5170: @cindex address arithmetic words
5171:
1.67 anton 5172: Address arithmetic is the foundation on which you can build data
5173: structures like arrays, records (@pxref{Structures}) and objects
5174: (@pxref{Object-oriented Forth}).
1.32 anton 5175:
1.68 anton 5176: @cindex address unit
5177: @cindex au (address unit)
1.1 anton 5178: ANS Forth does not specify the sizes of the data types. Instead, it
5179: offers a number of words for computing sizes and doing address
1.29 crook 5180: arithmetic. Address arithmetic is performed in terms of address units
5181: (aus); on most systems the address unit is one byte. Note that a
5182: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5183: platforms where it is a noop, it compiles to nothing).
1.1 anton 5184:
1.67 anton 5185: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5186: you have the address of a cell, perform @code{1 cells +}, and you will
5187: have the address of the next cell.
5188:
1.68 anton 5189: @cindex contiguous regions and address arithmetic
1.67 anton 5190: In ANS Forth you can perform address arithmetic only within a contiguous
5191: region, i.e., if you have an address into one region, you can only add
5192: and subtract such that the result is still within the region; you can
5193: only subtract or compare addresses from within the same contiguous
5194: region. Reasons: several contiguous regions can be arranged in memory
5195: in any way; on segmented systems addresses may have unusual
5196: representations, such that address arithmetic only works within a
5197: region. Gforth provides a few more guarantees (linear address space,
5198: dictionary grows upwards), but in general I have found it easy to stay
5199: within contiguous regions (exception: computing and comparing to the
5200: address just beyond the end of an array).
5201:
1.1 anton 5202: @cindex alignment of addresses for types
5203: ANS Forth also defines words for aligning addresses for specific
5204: types. Many computers require that accesses to specific data types
5205: must only occur at specific addresses; e.g., that cells may only be
5206: accessed at addresses divisible by 4. Even if a machine allows unaligned
5207: accesses, it can usually perform aligned accesses faster.
5208:
5209: For the performance-conscious: alignment operations are usually only
5210: necessary during the definition of a data structure, not during the
5211: (more frequent) accesses to it.
5212:
5213: ANS Forth defines no words for character-aligning addresses. This is not
5214: an oversight, but reflects the fact that addresses that are not
5215: char-aligned have no use in the standard and therefore will not be
5216: created.
5217:
5218: @cindex @code{CREATE} and alignment
1.29 crook 5219: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5220: are cell-aligned; in addition, Gforth guarantees that these addresses
5221: are aligned for all purposes.
5222:
1.26 crook 5223: Note that the ANS Forth word @code{char} has nothing to do with address
5224: arithmetic.
1.1 anton 5225:
1.44 crook 5226:
1.1 anton 5227: doc-chars
5228: doc-char+
5229: doc-cells
5230: doc-cell+
5231: doc-cell
5232: doc-aligned
5233: doc-floats
5234: doc-float+
5235: doc-float
5236: doc-faligned
5237: doc-sfloats
5238: doc-sfloat+
5239: doc-sfaligned
5240: doc-dfloats
5241: doc-dfloat+
5242: doc-dfaligned
5243: doc-maxaligned
5244: doc-cfaligned
5245: doc-address-unit-bits
1.145 anton 5246: doc-/w
5247: doc-/l
1.44 crook 5248:
1.32 anton 5249: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5250: @subsection Memory Blocks
5251: @cindex memory block words
1.27 crook 5252: @cindex character strings - moving and copying
5253:
1.49 anton 5254: Memory blocks often represent character strings; For ways of storing
5255: character strings in memory see @ref{String Formats}. For other
5256: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5257:
1.67 anton 5258: A few of these words work on address unit blocks. In that case, you
5259: usually have to insert @code{CHARS} before the word when working on
5260: character strings. Most words work on character blocks, and expect a
5261: char-aligned address.
5262:
5263: When copying characters between overlapping memory regions, use
5264: @code{chars move} or choose carefully between @code{cmove} and
5265: @code{cmove>}.
1.44 crook 5266:
1.1 anton 5267: doc-move
5268: doc-erase
5269: doc-cmove
5270: doc-cmove>
5271: doc-fill
5272: doc-blank
1.21 crook 5273: doc-compare
1.111 anton 5274: doc-str=
5275: doc-str<
5276: doc-string-prefix?
1.21 crook 5277: doc-search
1.27 crook 5278: doc--trailing
5279: doc-/string
1.82 anton 5280: doc-bounds
1.141 anton 5281: doc-pad
1.111 anton 5282:
1.27 crook 5283: @comment TODO examples
5284:
1.1 anton 5285:
1.26 crook 5286: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5287: @section Control Structures
5288: @cindex control structures
5289:
1.33 anton 5290: Control structures in Forth cannot be used interpretively, only in a
5291: colon definition@footnote{To be precise, they have no interpretation
5292: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5293: not like this limitation, but have not seen a satisfying way around it
5294: yet, although many schemes have been proposed.
1.1 anton 5295:
5296: @menu
1.33 anton 5297: * Selection:: IF ... ELSE ... ENDIF
5298: * Simple Loops:: BEGIN ...
1.29 crook 5299: * Counted Loops:: DO
1.67 anton 5300: * Arbitrary control structures::
5301: * Calls and returns::
1.1 anton 5302: * Exception Handling::
5303: @end menu
5304:
5305: @node Selection, Simple Loops, Control Structures, Control Structures
5306: @subsection Selection
5307: @cindex selection control structures
5308: @cindex control structures for selection
5309:
5310: @cindex @code{IF} control structure
5311: @example
1.29 crook 5312: @i{flag}
1.1 anton 5313: IF
1.29 crook 5314: @i{code}
1.1 anton 5315: ENDIF
5316: @end example
1.21 crook 5317: @noindent
1.33 anton 5318:
1.44 crook 5319: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5320: with any bit set represents truth) @i{code} is executed.
1.33 anton 5321:
1.1 anton 5322: @example
1.29 crook 5323: @i{flag}
1.1 anton 5324: IF
1.29 crook 5325: @i{code1}
1.1 anton 5326: ELSE
1.29 crook 5327: @i{code2}
1.1 anton 5328: ENDIF
5329: @end example
5330:
1.44 crook 5331: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5332: executed.
1.33 anton 5333:
1.1 anton 5334: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5335: standard, and @code{ENDIF} is not, although it is quite popular. We
5336: recommend using @code{ENDIF}, because it is less confusing for people
5337: who also know other languages (and is not prone to reinforcing negative
5338: prejudices against Forth in these people). Adding @code{ENDIF} to a
5339: system that only supplies @code{THEN} is simple:
5340: @example
1.82 anton 5341: : ENDIF POSTPONE then ; immediate
1.1 anton 5342: @end example
5343:
5344: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5345: (adv.)} has the following meanings:
5346: @quotation
5347: ... 2b: following next after in order ... 3d: as a necessary consequence
5348: (if you were there, then you saw them).
5349: @end quotation
5350: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5351: and many other programming languages has the meaning 3d.]
5352:
1.21 crook 5353: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5354: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5355: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5356: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5357: @file{compat/control.fs}.
5358:
5359: @cindex @code{CASE} control structure
5360: @example
1.29 crook 5361: @i{n}
1.1 anton 5362: CASE
1.29 crook 5363: @i{n1} OF @i{code1} ENDOF
5364: @i{n2} OF @i{code2} ENDOF
1.1 anton 5365: @dots{}
1.68 anton 5366: ( n ) @i{default-code} ( n )
1.131 anton 5367: ENDCASE ( )
1.1 anton 5368: @end example
5369:
1.211 ! anton 5370: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
! 5371: @i{ni} matches, the optional @i{default-code} is executed. The optional
! 5372: default case can be added by simply writing the code after the last
! 5373: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
! 5374: not consume it. The value @i{n} is consumed by this construction
! 5375: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
! 5376: matches). Example:
! 5377:
! 5378: @example
! 5379: : .spell ( n -- )
! 5380: case
! 5381: 0 of ." zero " endof
! 5382: 1 of ." one " endof
! 5383: 2 of ." two " endof
! 5384: dup .
! 5385: endcase ;
! 5386: @end example
1.1 anton 5387:
1.69 anton 5388: @progstyle
1.131 anton 5389: To keep the code understandable, you should ensure that you change the
5390: stack in the same way (wrt. number and types of stack items consumed
5391: and pushed) on all paths through a selection construct.
1.69 anton 5392:
1.1 anton 5393: @node Simple Loops, Counted Loops, Selection, Control Structures
5394: @subsection Simple Loops
5395: @cindex simple loops
5396: @cindex loops without count
5397:
5398: @cindex @code{WHILE} loop
5399: @example
5400: BEGIN
1.29 crook 5401: @i{code1}
5402: @i{flag}
1.1 anton 5403: WHILE
1.29 crook 5404: @i{code2}
1.1 anton 5405: REPEAT
5406: @end example
5407:
1.29 crook 5408: @i{code1} is executed and @i{flag} is computed. If it is true,
5409: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5410: false, execution continues after the @code{REPEAT}.
5411:
5412: @cindex @code{UNTIL} loop
5413: @example
5414: BEGIN
1.29 crook 5415: @i{code}
5416: @i{flag}
1.1 anton 5417: UNTIL
5418: @end example
5419:
1.29 crook 5420: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5421:
1.69 anton 5422: @progstyle
5423: To keep the code understandable, a complete iteration of the loop should
5424: not change the number and types of the items on the stacks.
5425:
1.1 anton 5426: @cindex endless loop
5427: @cindex loops, endless
5428: @example
5429: BEGIN
1.29 crook 5430: @i{code}
1.1 anton 5431: AGAIN
5432: @end example
5433:
5434: This is an endless loop.
5435:
5436: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5437: @subsection Counted Loops
5438: @cindex counted loops
5439: @cindex loops, counted
5440: @cindex @code{DO} loops
5441:
5442: The basic counted loop is:
5443: @example
1.29 crook 5444: @i{limit} @i{start}
1.1 anton 5445: ?DO
1.29 crook 5446: @i{body}
1.1 anton 5447: LOOP
5448: @end example
5449:
1.29 crook 5450: This performs one iteration for every integer, starting from @i{start}
5451: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5452: accessed with @code{i}. For example, the loop:
1.1 anton 5453: @example
5454: 10 0 ?DO
5455: i .
5456: LOOP
5457: @end example
1.21 crook 5458: @noindent
5459: prints @code{0 1 2 3 4 5 6 7 8 9}
5460:
1.1 anton 5461: The index of the innermost loop can be accessed with @code{i}, the index
5462: of the next loop with @code{j}, and the index of the third loop with
5463: @code{k}.
5464:
1.44 crook 5465:
1.1 anton 5466: doc-i
5467: doc-j
5468: doc-k
5469:
1.44 crook 5470:
1.1 anton 5471: The loop control data are kept on the return stack, so there are some
1.21 crook 5472: restrictions on mixing return stack accesses and counted loop words. In
5473: particuler, if you put values on the return stack outside the loop, you
5474: cannot read them inside the loop@footnote{well, not in a way that is
5475: portable.}. If you put values on the return stack within a loop, you
5476: have to remove them before the end of the loop and before accessing the
5477: index of the loop.
1.1 anton 5478:
5479: There are several variations on the counted loop:
5480:
1.21 crook 5481: @itemize @bullet
5482: @item
5483: @code{LEAVE} leaves the innermost counted loop immediately; execution
5484: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5485:
5486: @example
5487: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5488: @end example
5489: prints @code{0 1 2 3}
5490:
1.1 anton 5491:
1.21 crook 5492: @item
5493: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5494: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5495: return stack so @code{EXIT} can get to its return address. For example:
5496:
5497: @example
5498: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5499: @end example
5500: prints @code{0 1 2 3}
5501:
5502:
5503: @item
1.29 crook 5504: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5505: (and @code{LOOP} iterates until they become equal by wrap-around
5506: arithmetic). This behaviour is usually not what you want. Therefore,
5507: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5508: @code{?DO}), which do not enter the loop if @i{start} is greater than
5509: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5510: unsigned loop parameters.
5511:
1.21 crook 5512: @item
5513: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5514: the loop, independent of the loop parameters. Do not use @code{DO}, even
5515: if you know that the loop is entered in any case. Such knowledge tends
5516: to become invalid during maintenance of a program, and then the
5517: @code{DO} will make trouble.
5518:
5519: @item
1.29 crook 5520: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5521: index by @i{n} instead of by 1. The loop is terminated when the border
5522: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5523:
1.21 crook 5524: @example
5525: 4 0 +DO i . 2 +LOOP
5526: @end example
5527: @noindent
5528: prints @code{0 2}
5529:
5530: @example
5531: 4 1 +DO i . 2 +LOOP
5532: @end example
5533: @noindent
5534: prints @code{1 3}
1.1 anton 5535:
1.68 anton 5536: @item
1.1 anton 5537: @cindex negative increment for counted loops
5538: @cindex counted loops with negative increment
1.29 crook 5539: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5540:
1.21 crook 5541: @example
5542: -1 0 ?DO i . -1 +LOOP
5543: @end example
5544: @noindent
5545: prints @code{0 -1}
1.1 anton 5546:
1.21 crook 5547: @example
5548: 0 0 ?DO i . -1 +LOOP
5549: @end example
5550: prints nothing.
1.1 anton 5551:
1.29 crook 5552: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5553: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5554: index by @i{u} each iteration. The loop is terminated when the border
5555: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5556: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5557:
1.21 crook 5558: @example
5559: -2 0 -DO i . 1 -LOOP
5560: @end example
5561: @noindent
5562: prints @code{0 -1}
1.1 anton 5563:
1.21 crook 5564: @example
5565: -1 0 -DO i . 1 -LOOP
5566: @end example
5567: @noindent
5568: prints @code{0}
5569:
5570: @example
5571: 0 0 -DO i . 1 -LOOP
5572: @end example
5573: @noindent
5574: prints nothing.
1.1 anton 5575:
1.21 crook 5576: @end itemize
1.1 anton 5577:
5578: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5579: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5580: for these words that uses only standard words is provided in
5581: @file{compat/loops.fs}.
1.1 anton 5582:
5583:
5584: @cindex @code{FOR} loops
1.26 crook 5585: Another counted loop is:
1.1 anton 5586: @example
1.29 crook 5587: @i{n}
1.1 anton 5588: FOR
1.29 crook 5589: @i{body}
1.1 anton 5590: NEXT
5591: @end example
5592: This is the preferred loop of native code compiler writers who are too
1.26 crook 5593: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5594: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5595: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5596: Forth systems may behave differently, even if they support @code{FOR}
5597: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5598:
5599: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5600: @subsection Arbitrary control structures
5601: @cindex control structures, user-defined
5602:
5603: @cindex control-flow stack
5604: ANS Forth permits and supports using control structures in a non-nested
5605: way. Information about incomplete control structures is stored on the
5606: control-flow stack. This stack may be implemented on the Forth data
5607: stack, and this is what we have done in Gforth.
5608:
5609: @cindex @code{orig}, control-flow stack item
5610: @cindex @code{dest}, control-flow stack item
5611: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5612: entry represents a backward branch target. A few words are the basis for
5613: building any control structure possible (except control structures that
5614: need storage, like calls, coroutines, and backtracking).
5615:
1.44 crook 5616:
1.1 anton 5617: doc-if
5618: doc-ahead
5619: doc-then
5620: doc-begin
5621: doc-until
5622: doc-again
5623: doc-cs-pick
5624: doc-cs-roll
5625:
1.44 crook 5626:
1.21 crook 5627: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5628: manipulate the control-flow stack in a portable way. Without them, you
5629: would need to know how many stack items are occupied by a control-flow
5630: entry (many systems use one cell. In Gforth they currently take three,
5631: but this may change in the future).
5632:
1.1 anton 5633: Some standard control structure words are built from these words:
5634:
1.44 crook 5635:
1.1 anton 5636: doc-else
5637: doc-while
5638: doc-repeat
5639:
1.44 crook 5640:
5641: @noindent
1.1 anton 5642: Gforth adds some more control-structure words:
5643:
1.44 crook 5644:
1.1 anton 5645: doc-endif
5646: doc-?dup-if
5647: doc-?dup-0=-if
5648:
1.44 crook 5649:
5650: @noindent
1.1 anton 5651: Counted loop words constitute a separate group of words:
5652:
1.44 crook 5653:
1.1 anton 5654: doc-?do
5655: doc-+do
5656: doc-u+do
5657: doc--do
5658: doc-u-do
5659: doc-do
5660: doc-for
5661: doc-loop
5662: doc-+loop
5663: doc--loop
5664: doc-next
5665: doc-leave
5666: doc-?leave
5667: doc-unloop
5668: doc-done
5669:
1.44 crook 5670:
1.21 crook 5671: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5672: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5673: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5674: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5675: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5676: resolved (by using one of the loop-ending words or @code{DONE}).
5677:
1.44 crook 5678: @noindent
1.26 crook 5679: Another group of control structure words are:
1.1 anton 5680:
1.44 crook 5681:
1.1 anton 5682: doc-case
5683: doc-endcase
5684: doc-of
5685: doc-endof
5686:
1.44 crook 5687:
1.21 crook 5688: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5689: @code{CS-ROLL}.
1.1 anton 5690:
5691: @subsubsection Programming Style
1.47 crook 5692: @cindex control structures programming style
5693: @cindex programming style, arbitrary control structures
1.1 anton 5694:
5695: In order to ensure readability we recommend that you do not create
5696: arbitrary control structures directly, but define new control structure
5697: words for the control structure you want and use these words in your
1.26 crook 5698: program. For example, instead of writing:
1.1 anton 5699:
5700: @example
1.26 crook 5701: BEGIN
1.1 anton 5702: ...
1.26 crook 5703: IF [ 1 CS-ROLL ]
1.1 anton 5704: ...
1.26 crook 5705: AGAIN THEN
1.1 anton 5706: @end example
5707:
1.21 crook 5708: @noindent
1.1 anton 5709: we recommend defining control structure words, e.g.,
5710:
5711: @example
1.26 crook 5712: : WHILE ( DEST -- ORIG DEST )
5713: POSTPONE IF
5714: 1 CS-ROLL ; immediate
5715:
5716: : REPEAT ( orig dest -- )
5717: POSTPONE AGAIN
5718: POSTPONE THEN ; immediate
1.1 anton 5719: @end example
5720:
1.21 crook 5721: @noindent
1.1 anton 5722: and then using these to create the control structure:
5723:
5724: @example
1.26 crook 5725: BEGIN
1.1 anton 5726: ...
1.26 crook 5727: WHILE
1.1 anton 5728: ...
1.26 crook 5729: REPEAT
1.1 anton 5730: @end example
5731:
5732: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5733: @code{WHILE} are predefined, so in this example it would not be
5734: necessary to define them.
5735:
5736: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5737: @subsection Calls and returns
5738: @cindex calling a definition
5739: @cindex returning from a definition
5740:
1.3 anton 5741: @cindex recursive definitions
5742: A definition can be called simply be writing the name of the definition
1.26 crook 5743: to be called. Normally a definition is invisible during its own
1.3 anton 5744: definition. If you want to write a directly recursive definition, you
1.26 crook 5745: can use @code{recursive} to make the current definition visible, or
5746: @code{recurse} to call the current definition directly.
1.3 anton 5747:
1.44 crook 5748:
1.3 anton 5749: doc-recursive
5750: doc-recurse
5751:
1.44 crook 5752:
1.21 crook 5753: @comment TODO add example of the two recursion methods
1.12 anton 5754: @quotation
5755: @progstyle
5756: I prefer using @code{recursive} to @code{recurse}, because calling the
5757: definition by name is more descriptive (if the name is well-chosen) than
5758: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5759: implementation, it is much better to read (and think) ``now sort the
5760: partitions'' than to read ``now do a recursive call''.
5761: @end quotation
1.3 anton 5762:
1.29 crook 5763: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5764:
5765: @example
1.28 crook 5766: Defer foo
1.3 anton 5767:
5768: : bar ( ... -- ... )
5769: ... foo ... ;
5770:
5771: :noname ( ... -- ... )
5772: ... bar ... ;
5773: IS foo
5774: @end example
5775:
1.170 pazsan 5776: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5777:
1.26 crook 5778: The current definition returns control to the calling definition when
1.33 anton 5779: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5780:
5781: doc-exit
5782: doc-;s
5783:
1.44 crook 5784:
1.1 anton 5785: @node Exception Handling, , Calls and returns, Control Structures
5786: @subsection Exception Handling
1.26 crook 5787: @cindex exceptions
1.1 anton 5788:
1.68 anton 5789: @c quit is a very bad idea for error handling,
5790: @c because it does not translate into a THROW
5791: @c it also does not belong into this chapter
5792:
5793: If a word detects an error condition that it cannot handle, it can
5794: @code{throw} an exception. In the simplest case, this will terminate
5795: your program, and report an appropriate error.
1.21 crook 5796:
1.68 anton 5797: doc-throw
1.1 anton 5798:
1.69 anton 5799: @code{Throw} consumes a cell-sized error number on the stack. There are
5800: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5801: Gforth (and most other systems) you can use the iors produced by various
5802: words as error numbers (e.g., a typical use of @code{allocate} is
5803: @code{allocate throw}). Gforth also provides the word @code{exception}
5804: to define your own error numbers (with decent error reporting); an ANS
5805: Forth version of this word (but without the error messages) is available
5806: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5807: numbers (anything outside the range -4095..0), but won't get nice error
5808: messages, only numbers. For example, try:
5809:
5810: @example
1.69 anton 5811: -10 throw \ ANS defined
5812: -267 throw \ system defined
5813: s" my error" exception throw \ user defined
5814: 7 throw \ arbitrary number
1.68 anton 5815: @end example
5816:
5817: doc---exception-exception
1.1 anton 5818:
1.69 anton 5819: A common idiom to @code{THROW} a specific error if a flag is true is
5820: this:
5821:
5822: @example
5823: @code{( flag ) 0<> @i{errno} and throw}
5824: @end example
5825:
5826: Your program can provide exception handlers to catch exceptions. An
5827: exception handler can be used to correct the problem, or to clean up
5828: some data structures and just throw the exception to the next exception
5829: handler. Note that @code{throw} jumps to the dynamically innermost
5830: exception handler. The system's exception handler is outermost, and just
5831: prints an error and restarts command-line interpretation (or, in batch
5832: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5833:
1.68 anton 5834: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5835:
1.68 anton 5836: doc-catch
1.160 anton 5837: doc-nothrow
1.68 anton 5838:
5839: The most common use of exception handlers is to clean up the state when
5840: an error happens. E.g.,
1.1 anton 5841:
1.26 crook 5842: @example
1.68 anton 5843: base @ >r hex \ actually the hex should be inside foo, or we h
5844: ['] foo catch ( nerror|0 )
5845: r> base !
1.69 anton 5846: ( nerror|0 ) throw \ pass it on
1.26 crook 5847: @end example
1.1 anton 5848:
1.69 anton 5849: A use of @code{catch} for handling the error @code{myerror} might look
5850: like this:
1.44 crook 5851:
1.68 anton 5852: @example
1.69 anton 5853: ['] foo catch
5854: CASE
1.160 anton 5855: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5856: dup throw \ default: pass other errors on, do nothing on non-errors
5857: ENDCASE
1.68 anton 5858: @end example
1.44 crook 5859:
1.68 anton 5860: Having to wrap the code into a separate word is often cumbersome,
5861: therefore Gforth provides an alternative syntax:
1.1 anton 5862:
5863: @example
1.69 anton 5864: TRY
1.68 anton 5865: @i{code1}
1.172 anton 5866: IFERROR
5867: @i{code2}
5868: THEN
5869: @i{code3}
1.69 anton 5870: ENDTRY
1.1 anton 5871: @end example
5872:
1.172 anton 5873: This performs @i{code1}. If @i{code1} completes normally, execution
1.201 anton 5874: continues with @i{code3}. If there is an exception in @i{code1} or
5875: before @code{endtry}, the stacks are reset to the depth during
1.172 anton 5876: @code{try}, the throw value is pushed on the data stack, and execution
1.201 anton 5877: constinues at @i{code2}, and finally falls through to @i{code3}.
1.26 crook 5878:
1.68 anton 5879: doc-try
5880: doc-endtry
1.172 anton 5881: doc-iferror
5882:
5883: If you don't need @i{code2}, you can write @code{restore} instead of
5884: @code{iferror then}:
5885:
5886: @example
5887: TRY
5888: @i{code1}
5889: RESTORE
5890: @i{code3}
5891: ENDTRY
5892: @end example
1.26 crook 5893:
1.172 anton 5894: @cindex unwind-protect
1.69 anton 5895: The cleanup example from above in this syntax:
1.26 crook 5896:
1.68 anton 5897: @example
1.174 anton 5898: base @@ @{ oldbase @}
1.172 anton 5899: TRY
1.68 anton 5900: hex foo \ now the hex is placed correctly
1.69 anton 5901: 0 \ value for throw
1.172 anton 5902: RESTORE
5903: oldbase base !
5904: ENDTRY
5905: throw
1.1 anton 5906: @end example
5907:
1.172 anton 5908: An additional advantage of this variant is that an exception between
5909: @code{restore} and @code{endtry} (e.g., from the user pressing
5910: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5911: so the base will be restored under all circumstances.
5912:
5913: However, you have to ensure that this code does not cause an exception
5914: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5915: Moreover, you should also make sure that the stack contents needed by
5916: the @code{iferror}/@code{restore} code exist everywhere between
5917: @code{try} and @code{endtry}; in our example this is achived by
5918: putting the data in a local before the @code{try} (you cannot use the
5919: return stack because the exception frame (@i{sys1}) is in the way
5920: there).
5921:
5922: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5923:
5924: @cindex @code{recover} (old Gforth versions)
5925: If you do not want this exception-restarting behaviour, you achieve
5926: this as follows:
5927:
5928: @example
5929: TRY
5930: @i{code1}
5931: ENDTRY-IFERROR
5932: @i{code2}
5933: THEN
5934: @end example
5935:
5936: If there is an exception in @i{code1}, then @i{code2} is executed,
5937: otherwise execution continues behind the @code{then} (or in a possible
5938: @code{else} branch). This corresponds to the construct
5939:
5940: @example
5941: TRY
5942: @i{code1}
5943: RECOVER
5944: @i{code2}
5945: ENDTRY
5946: @end example
5947:
5948: in Gforth before version 0.7. So you can directly replace
5949: @code{recover}-using code; however, we recommend that you check if it
5950: would not be better to use one of the other @code{try} variants while
5951: you are at it.
5952:
1.173 anton 5953: To ease the transition, Gforth provides two compatibility files:
5954: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5955: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5956: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5957: ... endtry} syntax on new systems, so you can use that file as a
5958: stopgap to run old programs. Both files work on any system (they just
5959: do nothing if the system already has the syntax it implements), so you
5960: can unconditionally @code{require} one of these files, even if you use
5961: a mix old and new systems.
5962:
1.172 anton 5963: doc-restore
5964: doc-endtry-iferror
5965:
5966: Here's the error handling example:
1.1 anton 5967:
1.68 anton 5968: @example
1.69 anton 5969: TRY
1.68 anton 5970: foo
1.172 anton 5971: ENDTRY-IFERROR
1.69 anton 5972: CASE
1.160 anton 5973: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5974: throw \ pass other errors on
5975: ENDCASE
1.172 anton 5976: THEN
1.68 anton 5977: @end example
1.1 anton 5978:
1.69 anton 5979: @progstyle
5980: As usual, you should ensure that the stack depth is statically known at
5981: the end: either after the @code{throw} for passing on errors, or after
5982: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5983: selection construct for handling the error).
5984:
1.68 anton 5985: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5986: and you can provide an error message. @code{Abort} just produces an
5987: ``Aborted'' error.
1.1 anton 5988:
1.68 anton 5989: The problem with these words is that exception handlers cannot
5990: differentiate between different @code{abort"}s; they just look like
5991: @code{-2 throw} to them (the error message cannot be accessed by
5992: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5993: exception handlers.
1.44 crook 5994:
1.68 anton 5995: doc-abort"
1.26 crook 5996: doc-abort
1.29 crook 5997:
5998:
1.44 crook 5999:
1.29 crook 6000: @c -------------------------------------------------------------
1.47 crook 6001: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 6002: @section Defining Words
6003: @cindex defining words
6004:
1.47 crook 6005: Defining words are used to extend Forth by creating new entries in the dictionary.
6006:
1.29 crook 6007: @menu
1.67 anton 6008: * CREATE::
1.44 crook 6009: * Variables:: Variables and user variables
1.67 anton 6010: * Constants::
1.44 crook 6011: * Values:: Initialised variables
1.67 anton 6012: * Colon Definitions::
1.44 crook 6013: * Anonymous Definitions:: Definitions without names
1.69 anton 6014: * Supplying names:: Passing definition names as strings
1.67 anton 6015: * User-defined Defining Words::
1.170 pazsan 6016: * Deferred Words:: Allow forward references
1.67 anton 6017: * Aliases::
1.29 crook 6018: @end menu
6019:
1.44 crook 6020: @node CREATE, Variables, Defining Words, Defining Words
6021: @subsection @code{CREATE}
1.29 crook 6022: @cindex simple defining words
6023: @cindex defining words, simple
6024:
6025: Defining words are used to create new entries in the dictionary. The
6026: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6027: this:
6028:
6029: @example
6030: CREATE new-word1
6031: @end example
6032:
1.69 anton 6033: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6034: input stream (@code{new-word1} in our example). It generates a
6035: dictionary entry for @code{new-word1}. When @code{new-word1} is
6036: executed, all that it does is leave an address on the stack. The address
6037: represents the value of the data space pointer (@code{HERE}) at the time
6038: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6039: associating a name with the address of a region of memory.
1.29 crook 6040:
1.34 anton 6041: doc-create
6042:
1.69 anton 6043: Note that in ANS Forth guarantees only for @code{create} that its body
6044: is in dictionary data space (i.e., where @code{here}, @code{allot}
6045: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6046: @code{create}d words can be modified with @code{does>}
6047: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6048: can only be applied to @code{create}d words.
6049:
1.29 crook 6050: By extending this example to reserve some memory in data space, we end
1.69 anton 6051: up with something like a @i{variable}. Here are two different ways to do
6052: it:
1.29 crook 6053:
6054: @example
6055: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6056: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6057: @end example
6058:
6059: The variable can be examined and modified using @code{@@} (``fetch'') and
6060: @code{!} (``store'') like this:
6061:
6062: @example
6063: new-word2 @@ . \ get address, fetch from it and display
6064: 1234 new-word2 ! \ new value, get address, store to it
6065: @end example
6066:
1.44 crook 6067: @cindex arrays
6068: A similar mechanism can be used to create arrays. For example, an
6069: 80-character text input buffer:
1.29 crook 6070:
6071: @example
1.44 crook 6072: CREATE text-buf 80 chars allot
6073:
1.168 anton 6074: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6075: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6076: @end example
1.29 crook 6077:
1.44 crook 6078: You can build arbitrarily complex data structures by allocating
1.49 anton 6079: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6080: learn about some Gforth tools that make it easier,
1.49 anton 6081: @xref{Structures}.
1.44 crook 6082:
6083:
6084: @node Variables, Constants, CREATE, Defining Words
6085: @subsection Variables
6086: @cindex variables
6087:
6088: The previous section showed how a sequence of commands could be used to
6089: generate a variable. As a final refinement, the whole code sequence can
6090: be wrapped up in a defining word (pre-empting the subject of the next
6091: section), making it easier to create new variables:
6092:
6093: @example
6094: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6095: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6096:
6097: myvariableX foo \ variable foo starts off with an unknown value
6098: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6099:
6100: 45 3 * foo ! \ set foo to 135
6101: 1234 joe ! \ set joe to 1234
6102: 3 joe +! \ increment joe by 3.. to 1237
6103: @end example
6104:
6105: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6106: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6107: guarantee that a @code{Variable} is initialised when it is created
6108: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6109: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6110: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6111: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6112: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6113: store a boolean, you can use @code{on} and @code{off} to toggle its
6114: state.
1.29 crook 6115:
1.34 anton 6116: doc-variable
6117: doc-2variable
6118: doc-fvariable
6119:
1.29 crook 6120: @cindex user variables
6121: @cindex user space
6122: The defining word @code{User} behaves in the same way as @code{Variable}.
6123: The difference is that it reserves space in @i{user (data) space} rather
6124: than normal data space. In a Forth system that has a multi-tasker, each
6125: task has its own set of user variables.
6126:
1.34 anton 6127: doc-user
1.67 anton 6128: @c doc-udp
6129: @c doc-uallot
1.34 anton 6130:
1.29 crook 6131: @comment TODO is that stuff about user variables strictly correct? Is it
6132: @comment just terminal tasks that have user variables?
6133: @comment should document tasker.fs (with some examples) elsewhere
6134: @comment in this manual, then expand on user space and user variables.
6135:
1.44 crook 6136: @node Constants, Values, Variables, Defining Words
6137: @subsection Constants
6138: @cindex constants
6139:
6140: @code{Constant} allows you to declare a fixed value and refer to it by
6141: name. For example:
1.29 crook 6142:
6143: @example
6144: 12 Constant INCHES-PER-FOOT
6145: 3E+08 fconstant SPEED-O-LIGHT
6146: @end example
6147:
6148: A @code{Variable} can be both read and written, so its run-time
6149: behaviour is to supply an address through which its current value can be
6150: manipulated. In contrast, the value of a @code{Constant} cannot be
6151: changed once it has been declared@footnote{Well, often it can be -- but
6152: not in a Standard, portable way. It's safer to use a @code{Value} (read
6153: on).} so it's not necessary to supply the address -- it is more
6154: efficient to return the value of the constant directly. That's exactly
6155: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6156: the top of the stack (You can find one
6157: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6158:
1.69 anton 6159: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6160: double and floating-point constants, respectively.
6161:
1.34 anton 6162: doc-constant
6163: doc-2constant
6164: doc-fconstant
6165:
6166: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6167: @c nac-> How could that not be true in an ANS Forth? You can't define a
6168: @c constant, use it and then delete the definition of the constant..
1.69 anton 6169:
6170: @c anton->An ANS Forth system can compile a constant to a literal; On
6171: @c decompilation you would see only the number, just as if it had been used
6172: @c in the first place. The word will stay, of course, but it will only be
6173: @c used by the text interpreter (no run-time duties, except when it is
6174: @c POSTPONEd or somesuch).
6175:
6176: @c nac:
1.44 crook 6177: @c I agree that it's rather deep, but IMO it is an important difference
6178: @c relative to other programming languages.. often it's annoying: it
6179: @c certainly changes my programming style relative to C.
6180:
1.69 anton 6181: @c anton: In what way?
6182:
1.29 crook 6183: Constants in Forth behave differently from their equivalents in other
6184: programming languages. In other languages, a constant (such as an EQU in
6185: assembler or a #define in C) only exists at compile-time; in the
6186: executable program the constant has been translated into an absolute
6187: number and, unless you are using a symbolic debugger, it's impossible to
6188: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6189: an entry in the header space and remains there after the code that uses
6190: it has been defined. In fact, it must remain in the dictionary since it
6191: has run-time duties to perform. For example:
1.29 crook 6192:
6193: @example
6194: 12 Constant INCHES-PER-FOOT
6195: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6196: @end example
6197:
6198: @cindex in-lining of constants
6199: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6200: associated with the constant @code{INCHES-PER-FOOT}. If you use
6201: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6202: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6203: attempt to optimise constants by in-lining them where they are used. You
6204: can force Gforth to in-line a constant like this:
6205:
6206: @example
6207: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6208: @end example
6209:
6210: If you use @code{see} to decompile @i{this} version of
6211: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6212: longer present. To understand how this works, read
6213: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6214:
6215: In-lining constants in this way might improve execution time
6216: fractionally, and can ensure that a constant is now only referenced at
6217: compile-time. However, the definition of the constant still remains in
6218: the dictionary. Some Forth compilers provide a mechanism for controlling
6219: a second dictionary for holding transient words such that this second
6220: dictionary can be deleted later in order to recover memory
6221: space. However, there is no standard way of doing this.
6222:
6223:
1.44 crook 6224: @node Values, Colon Definitions, Constants, Defining Words
6225: @subsection Values
6226: @cindex values
1.34 anton 6227:
1.69 anton 6228: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6229: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6230: (not in ANS Forth) you can access (and change) a @code{value} also with
6231: @code{>body}.
6232:
6233: Here are some
6234: examples:
1.29 crook 6235:
6236: @example
1.69 anton 6237: 12 Value APPLES \ Define APPLES with an initial value of 12
6238: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6239: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6240: APPLES \ puts 35 on the top of the stack.
1.29 crook 6241: @end example
6242:
1.44 crook 6243: doc-value
6244: doc-to
1.29 crook 6245:
1.35 anton 6246:
1.69 anton 6247:
1.44 crook 6248: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6249: @subsection Colon Definitions
6250: @cindex colon definitions
1.35 anton 6251:
6252: @example
1.44 crook 6253: : name ( ... -- ... )
6254: word1 word2 word3 ;
1.29 crook 6255: @end example
6256:
1.44 crook 6257: @noindent
6258: Creates a word called @code{name} that, upon execution, executes
6259: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6260:
1.49 anton 6261: The explanation above is somewhat superficial. For simple examples of
6262: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6263: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6264: Compilation Semantics}.
1.29 crook 6265:
1.44 crook 6266: doc-:
6267: doc-;
1.1 anton 6268:
1.34 anton 6269:
1.69 anton 6270: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6271: @subsection Anonymous Definitions
6272: @cindex colon definitions
6273: @cindex defining words without name
1.34 anton 6274:
1.44 crook 6275: Sometimes you want to define an @dfn{anonymous word}; a word without a
6276: name. You can do this with:
1.1 anton 6277:
1.44 crook 6278: doc-:noname
1.1 anton 6279:
1.44 crook 6280: This leaves the execution token for the word on the stack after the
6281: closing @code{;}. Here's an example in which a deferred word is
6282: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6283:
1.29 crook 6284: @example
1.44 crook 6285: Defer deferred
6286: :noname ( ... -- ... )
6287: ... ;
6288: IS deferred
1.29 crook 6289: @end example
1.26 crook 6290:
1.44 crook 6291: @noindent
6292: Gforth provides an alternative way of doing this, using two separate
6293: words:
1.27 crook 6294:
1.44 crook 6295: doc-noname
6296: @cindex execution token of last defined word
1.116 anton 6297: doc-latestxt
1.1 anton 6298:
1.44 crook 6299: @noindent
6300: The previous example can be rewritten using @code{noname} and
1.116 anton 6301: @code{latestxt}:
1.1 anton 6302:
1.26 crook 6303: @example
1.44 crook 6304: Defer deferred
6305: noname : ( ... -- ... )
6306: ... ;
1.116 anton 6307: latestxt IS deferred
1.26 crook 6308: @end example
1.1 anton 6309:
1.29 crook 6310: @noindent
1.44 crook 6311: @code{noname} works with any defining word, not just @code{:}.
6312:
1.116 anton 6313: @code{latestxt} also works when the last word was not defined as
1.71 anton 6314: @code{noname}. It does not work for combined words, though. It also has
6315: the useful property that is is valid as soon as the header for a
6316: definition has been built. Thus:
1.44 crook 6317:
6318: @example
1.116 anton 6319: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6320: @end example
1.1 anton 6321:
1.44 crook 6322: @noindent
6323: prints 3 numbers; the last two are the same.
1.26 crook 6324:
1.69 anton 6325: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6326: @subsection Supplying the name of a defined word
6327: @cindex names for defined words
6328: @cindex defining words, name given in a string
6329:
6330: By default, a defining word takes the name for the defined word from the
6331: input stream. Sometimes you want to supply the name from a string. You
6332: can do this with:
6333:
6334: doc-nextname
6335:
6336: For example:
6337:
6338: @example
6339: s" foo" nextname create
6340: @end example
6341:
6342: @noindent
6343: is equivalent to:
6344:
6345: @example
6346: create foo
6347: @end example
6348:
6349: @noindent
6350: @code{nextname} works with any defining word.
6351:
1.1 anton 6352:
1.170 pazsan 6353: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6354: @subsection User-defined Defining Words
6355: @cindex user-defined defining words
6356: @cindex defining words, user-defined
1.1 anton 6357:
1.29 crook 6358: You can create a new defining word by wrapping defining-time code around
6359: an existing defining word and putting the sequence in a colon
1.69 anton 6360: definition.
6361:
6362: @c anton: This example is very complex and leads in a quite different
6363: @c direction from the CREATE-DOES> stuff that follows. It should probably
6364: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6365: @c subsection of Defining Words)
6366:
6367: For example, suppose that you have a word @code{stats} that
1.29 crook 6368: gathers statistics about colon definitions given the @i{xt} of the
6369: definition, and you want every colon definition in your application to
6370: make a call to @code{stats}. You can define and use a new version of
6371: @code{:} like this:
6372:
6373: @example
6374: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6375: ... ; \ other code
6376:
1.116 anton 6377: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6378:
6379: my: foo + - ;
6380: @end example
6381:
6382: When @code{foo} is defined using @code{my:} these steps occur:
6383:
6384: @itemize @bullet
6385: @item
6386: @code{my:} is executed.
6387: @item
6388: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6389: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6390: the input stream for a name, builds a dictionary header for the name
6391: @code{foo} and switches @code{state} from interpret to compile.
6392: @item
1.116 anton 6393: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6394: being defined -- @code{foo} -- onto the stack.
6395: @item
6396: The code that was produced by @code{postpone literal} is executed; this
6397: causes the value on the stack to be compiled as a literal in the code
6398: area of @code{foo}.
6399: @item
6400: The code @code{['] stats} compiles a literal into the definition of
6401: @code{my:}. When @code{compile,} is executed, that literal -- the
6402: execution token for @code{stats} -- is layed down in the code area of
6403: @code{foo} , following the literal@footnote{Strictly speaking, the
6404: mechanism that @code{compile,} uses to convert an @i{xt} into something
6405: in the code area is implementation-dependent. A threaded implementation
6406: might spit out the execution token directly whilst another
6407: implementation might spit out a native code sequence.}.
6408: @item
6409: At this point, the execution of @code{my:} is complete, and control
6410: returns to the text interpreter. The text interpreter is in compile
6411: state, so subsequent text @code{+ -} is compiled into the definition of
6412: @code{foo} and the @code{;} terminates the definition as always.
6413: @end itemize
6414:
6415: You can use @code{see} to decompile a word that was defined using
6416: @code{my:} and see how it is different from a normal @code{:}
6417: definition. For example:
6418:
6419: @example
6420: : bar + - ; \ like foo but using : rather than my:
6421: see bar
6422: : bar
6423: + - ;
6424: see foo
6425: : foo
6426: 107645672 stats + - ;
6427:
1.140 anton 6428: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6429: @end example
6430:
6431: You can use techniques like this to make new defining words in terms of
6432: @i{any} existing defining word.
1.1 anton 6433:
6434:
1.29 crook 6435: @cindex defining defining words
1.26 crook 6436: @cindex @code{CREATE} ... @code{DOES>}
6437: If you want the words defined with your defining words to behave
6438: differently from words defined with standard defining words, you can
6439: write your defining word like this:
1.1 anton 6440:
6441: @example
1.26 crook 6442: : def-word ( "name" -- )
1.29 crook 6443: CREATE @i{code1}
1.26 crook 6444: DOES> ( ... -- ... )
1.29 crook 6445: @i{code2} ;
1.26 crook 6446:
6447: def-word name
1.1 anton 6448: @end example
6449:
1.29 crook 6450: @cindex child words
6451: This fragment defines a @dfn{defining word} @code{def-word} and then
6452: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6453: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6454: is not executed at this time. The word @code{name} is sometimes called a
6455: @dfn{child} of @code{def-word}.
6456:
6457: When you execute @code{name}, the address of the body of @code{name} is
6458: put on the data stack and @i{code2} is executed (the address of the body
6459: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6460: @code{CREATE}, i.e., the address a @code{create}d word returns by
6461: default).
6462:
6463: @c anton:
6464: @c www.dictionary.com says:
6465: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6466: @c several generations of absence, usually caused by the chance
6467: @c recombination of genes. 2.An individual or a part that exhibits
6468: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6469: @c of previous behavior after a period of absence.
6470: @c
6471: @c Doesn't seem to fit.
1.29 crook 6472:
1.69 anton 6473: @c @cindex atavism in child words
1.33 anton 6474: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6475: similarly; they all have a common run-time behaviour determined by
6476: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6477: body of the child word. The structure of the data is common to all
6478: children of @code{def-word}, but the data values are specific -- and
6479: private -- to each child word. When a child word is executed, the
6480: address of its private data area is passed as a parameter on TOS to be
6481: used and manipulated@footnote{It is legitimate both to read and write to
6482: this data area.} by @i{code2}.
1.29 crook 6483:
6484: The two fragments of code that make up the defining words act (are
6485: executed) at two completely separate times:
1.1 anton 6486:
1.29 crook 6487: @itemize @bullet
6488: @item
6489: At @i{define time}, the defining word executes @i{code1} to generate a
6490: child word
6491: @item
6492: At @i{child execution time}, when a child word is invoked, @i{code2}
6493: is executed, using parameters (data) that are private and specific to
6494: the child word.
6495: @end itemize
6496:
1.44 crook 6497: Another way of understanding the behaviour of @code{def-word} and
6498: @code{name} is to say that, if you make the following definitions:
1.33 anton 6499: @example
6500: : def-word1 ( "name" -- )
6501: CREATE @i{code1} ;
6502:
6503: : action1 ( ... -- ... )
6504: @i{code2} ;
6505:
6506: def-word1 name1
6507: @end example
6508:
1.44 crook 6509: @noindent
6510: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6511:
1.29 crook 6512: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6513:
1.1 anton 6514: @example
1.29 crook 6515: : CONSTANT ( w "name" -- )
6516: CREATE ,
1.26 crook 6517: DOES> ( -- w )
6518: @@ ;
1.1 anton 6519: @end example
6520:
1.29 crook 6521: @comment There is a beautiful description of how this works and what
6522: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6523: @comment commentary on the Counting Fruits problem.
6524:
6525: When you create a constant with @code{5 CONSTANT five}, a set of
6526: define-time actions take place; first a new word @code{five} is created,
6527: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6528: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6529: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6530: no code of its own; it simply contains a data field and a pointer to the
6531: code that follows @code{DOES>} in its defining word. That makes words
6532: created in this way very compact.
6533:
6534: The final example in this section is intended to remind you that space
6535: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6536: both read and written by a Standard program@footnote{Exercise: use this
6537: example as a starting point for your own implementation of @code{Value}
6538: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6539: @code{[']}.}:
6540:
6541: @example
6542: : foo ( "name" -- )
6543: CREATE -1 ,
6544: DOES> ( -- )
1.33 anton 6545: @@ . ;
1.29 crook 6546:
6547: foo first-word
6548: foo second-word
6549:
6550: 123 ' first-word >BODY !
6551: @end example
6552:
6553: If @code{first-word} had been a @code{CREATE}d word, we could simply
6554: have executed it to get the address of its data field. However, since it
6555: was defined to have @code{DOES>} actions, its execution semantics are to
6556: perform those @code{DOES>} actions. To get the address of its data field
6557: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6558: translate the xt into the address of the data field. When you execute
6559: @code{first-word}, it will display @code{123}. When you execute
6560: @code{second-word} it will display @code{-1}.
1.26 crook 6561:
6562: @cindex stack effect of @code{DOES>}-parts
6563: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6564: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6565: the stack effect of the defined words, not the stack effect of the
6566: following code (the following code expects the address of the body on
6567: the top of stack, which is not reflected in the stack comment). This is
6568: the convention that I use and recommend (it clashes a bit with using
6569: locals declarations for stack effect specification, though).
1.1 anton 6570:
1.53 anton 6571: @menu
6572: * CREATE..DOES> applications::
6573: * CREATE..DOES> details::
1.63 anton 6574: * Advanced does> usage example::
1.155 anton 6575: * Const-does>::
1.53 anton 6576: @end menu
6577:
6578: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6579: @subsubsection Applications of @code{CREATE..DOES>}
6580: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6581:
1.26 crook 6582: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6583:
1.26 crook 6584: @cindex factoring similar colon definitions
6585: When you see a sequence of code occurring several times, and you can
6586: identify a meaning, you will factor it out as a colon definition. When
6587: you see similar colon definitions, you can factor them using
6588: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6589: that look very similar:
1.1 anton 6590: @example
1.26 crook 6591: : ori, ( reg-target reg-source n -- )
6592: 0 asm-reg-reg-imm ;
6593: : andi, ( reg-target reg-source n -- )
6594: 1 asm-reg-reg-imm ;
1.1 anton 6595: @end example
6596:
1.26 crook 6597: @noindent
6598: This could be factored with:
6599: @example
6600: : reg-reg-imm ( op-code -- )
6601: CREATE ,
6602: DOES> ( reg-target reg-source n -- )
6603: @@ asm-reg-reg-imm ;
6604:
6605: 0 reg-reg-imm ori,
6606: 1 reg-reg-imm andi,
6607: @end example
1.1 anton 6608:
1.26 crook 6609: @cindex currying
6610: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6611: supply a part of the parameters for a word (known as @dfn{currying} in
6612: the functional language community). E.g., @code{+} needs two
6613: parameters. Creating versions of @code{+} with one parameter fixed can
6614: be done like this:
1.82 anton 6615:
1.1 anton 6616: @example
1.82 anton 6617: : curry+ ( n1 "name" -- )
1.26 crook 6618: CREATE ,
6619: DOES> ( n2 -- n1+n2 )
6620: @@ + ;
6621:
6622: 3 curry+ 3+
6623: -2 curry+ 2-
1.1 anton 6624: @end example
6625:
1.91 anton 6626:
1.63 anton 6627: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6628: @subsubsection The gory details of @code{CREATE..DOES>}
6629: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6630:
1.26 crook 6631: doc-does>
1.1 anton 6632:
1.26 crook 6633: @cindex @code{DOES>} in a separate definition
6634: This means that you need not use @code{CREATE} and @code{DOES>} in the
6635: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6636: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6637: @example
6638: : does1
6639: DOES> ( ... -- ... )
1.44 crook 6640: ... ;
6641:
6642: : does2
6643: DOES> ( ... -- ... )
6644: ... ;
6645:
6646: : def-word ( ... -- ... )
6647: create ...
6648: IF
6649: does1
6650: ELSE
6651: does2
6652: ENDIF ;
6653: @end example
6654:
6655: In this example, the selection of whether to use @code{does1} or
1.69 anton 6656: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6657: @code{CREATE}d.
6658:
6659: @cindex @code{DOES>} in interpretation state
6660: In a standard program you can apply a @code{DOES>}-part only if the last
6661: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6662: will override the behaviour of the last word defined in any case. In a
6663: standard program, you can use @code{DOES>} only in a colon
6664: definition. In Gforth, you can also use it in interpretation state, in a
6665: kind of one-shot mode; for example:
6666: @example
6667: CREATE name ( ... -- ... )
6668: @i{initialization}
6669: DOES>
6670: @i{code} ;
6671: @end example
6672:
6673: @noindent
6674: is equivalent to the standard:
6675: @example
6676: :noname
6677: DOES>
6678: @i{code} ;
6679: CREATE name EXECUTE ( ... -- ... )
6680: @i{initialization}
6681: @end example
6682:
1.53 anton 6683: doc->body
6684:
1.152 pazsan 6685: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6686: @subsubsection Advanced does> usage example
6687:
6688: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6689: for disassembling instructions, that follow a very repetetive scheme:
6690:
6691: @example
6692: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6693: @var{entry-num} cells @var{table} + !
6694: @end example
6695:
6696: Of course, this inspires the idea to factor out the commonalities to
6697: allow a definition like
6698:
6699: @example
6700: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6701: @end example
6702:
6703: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6704: correlated. Moreover, before I wrote the disassembler, there already
6705: existed code that defines instructions like this:
1.63 anton 6706:
6707: @example
6708: @var{entry-num} @var{inst-format} @var{inst-name}
6709: @end example
6710:
6711: This code comes from the assembler and resides in
6712: @file{arch/mips/insts.fs}.
6713:
6714: So I had to define the @var{inst-format} words that performed the scheme
6715: above when executed. At first I chose to use run-time code-generation:
6716:
6717: @example
6718: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6719: :noname Postpone @var{disasm-operands}
6720: name Postpone sliteral Postpone type Postpone ;
6721: swap cells @var{table} + ! ;
6722: @end example
6723:
6724: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6725:
1.63 anton 6726: An alternative would have been to write this using
6727: @code{create}/@code{does>}:
6728:
6729: @example
6730: : @var{inst-format} ( entry-num "name" -- )
6731: here name string, ( entry-num c-addr ) \ parse and save "name"
6732: noname create , ( entry-num )
1.116 anton 6733: latestxt swap cells @var{table} + !
1.63 anton 6734: does> ( addr w -- )
6735: \ disassemble instruction w at addr
6736: @@ >r
6737: @var{disasm-operands}
6738: r> count type ;
6739: @end example
6740:
6741: Somehow the first solution is simpler, mainly because it's simpler to
6742: shift a string from definition-time to use-time with @code{sliteral}
6743: than with @code{string,} and friends.
6744:
6745: I wrote a lot of words following this scheme and soon thought about
6746: factoring out the commonalities among them. Note that this uses a
6747: two-level defining word, i.e., a word that defines ordinary defining
6748: words.
6749:
6750: This time a solution involving @code{postpone} and friends seemed more
6751: difficult (try it as an exercise), so I decided to use a
6752: @code{create}/@code{does>} word; since I was already at it, I also used
6753: @code{create}/@code{does>} for the lower level (try using
6754: @code{postpone} etc. as an exercise), resulting in the following
6755: definition:
6756:
6757: @example
6758: : define-format ( disasm-xt table-xt -- )
6759: \ define an instruction format that uses disasm-xt for
6760: \ disassembling and enters the defined instructions into table
6761: \ table-xt
6762: create 2,
6763: does> ( u "inst" -- )
6764: \ defines an anonymous word for disassembling instruction inst,
6765: \ and enters it as u-th entry into table-xt
6766: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6767: noname create 2, \ define anonymous word
1.116 anton 6768: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6769: does> ( addr w -- )
6770: \ disassemble instruction w at addr
6771: 2@@ >r ( addr w disasm-xt R: c-addr )
6772: execute ( R: c-addr ) \ disassemble operands
6773: r> count type ; \ print name
6774: @end example
6775:
6776: Note that the tables here (in contrast to above) do the @code{cells +}
6777: by themselves (that's why you have to pass an xt). This word is used in
6778: the following way:
6779:
6780: @example
6781: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6782: @end example
6783:
1.71 anton 6784: As shown above, the defined instruction format is then used like this:
6785:
6786: @example
6787: @var{entry-num} @var{inst-format} @var{inst-name}
6788: @end example
6789:
1.63 anton 6790: In terms of currying, this kind of two-level defining word provides the
6791: parameters in three stages: first @var{disasm-operands} and @var{table},
6792: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6793: the instruction to be disassembled.
6794:
6795: Of course this did not quite fit all the instruction format names used
6796: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6797: the parameters into the right form.
6798:
6799: If you have trouble following this section, don't worry. First, this is
6800: involved and takes time (and probably some playing around) to
6801: understand; second, this is the first two-level
6802: @code{create}/@code{does>} word I have written in seventeen years of
6803: Forth; and if I did not have @file{insts.fs} to start with, I may well
6804: have elected to use just a one-level defining word (with some repeating
6805: of parameters when using the defining word). So it is not necessary to
6806: understand this, but it may improve your understanding of Forth.
1.44 crook 6807:
6808:
1.152 pazsan 6809: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6810: @subsubsection @code{Const-does>}
6811:
6812: A frequent use of @code{create}...@code{does>} is for transferring some
6813: values from definition-time to run-time. Gforth supports this use with
6814:
6815: doc-const-does>
6816:
6817: A typical use of this word is:
6818:
6819: @example
6820: : curry+ ( n1 "name" -- )
6821: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6822: + ;
6823:
6824: 3 curry+ 3+
6825: @end example
6826:
6827: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6828: definition to run-time.
6829:
6830: The advantages of using @code{const-does>} are:
6831:
6832: @itemize
6833:
6834: @item
6835: You don't have to deal with storing and retrieving the values, i.e.,
6836: your program becomes more writable and readable.
6837:
6838: @item
6839: When using @code{does>}, you have to introduce a @code{@@} that cannot
6840: be optimized away (because you could change the data using
6841: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6842:
6843: @end itemize
6844:
6845: An ANS Forth implementation of @code{const-does>} is available in
6846: @file{compat/const-does.fs}.
6847:
6848:
1.170 pazsan 6849: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6850: @subsection Deferred Words
1.44 crook 6851: @cindex deferred words
6852:
6853: The defining word @code{Defer} allows you to define a word by name
6854: without defining its behaviour; the definition of its behaviour is
6855: deferred. Here are two situation where this can be useful:
6856:
6857: @itemize @bullet
6858: @item
6859: Where you want to allow the behaviour of a word to be altered later, and
6860: for all precompiled references to the word to change when its behaviour
6861: is changed.
6862: @item
6863: For mutual recursion; @xref{Calls and returns}.
6864: @end itemize
6865:
6866: In the following example, @code{foo} always invokes the version of
6867: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6868: always invokes the version that prints ``@code{Hello}''. There is no way
6869: of getting @code{foo} to use the later version without re-ordering the
6870: source code and recompiling it.
6871:
6872: @example
6873: : greet ." Good morning" ;
6874: : foo ... greet ... ;
6875: : greet ." Hello" ;
6876: : bar ... greet ... ;
6877: @end example
6878:
6879: This problem can be solved by defining @code{greet} as a @code{Defer}red
6880: word. The behaviour of a @code{Defer}red word can be defined and
6881: redefined at any time by using @code{IS} to associate the xt of a
6882: previously-defined word with it. The previous example becomes:
6883:
6884: @example
1.69 anton 6885: Defer greet ( -- )
1.44 crook 6886: : foo ... greet ... ;
6887: : bar ... greet ... ;
1.69 anton 6888: : greet1 ( -- ) ." Good morning" ;
6889: : greet2 ( -- ) ." Hello" ;
1.132 anton 6890: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6891: @end example
6892:
1.69 anton 6893: @progstyle
6894: You should write a stack comment for every deferred word, and put only
6895: XTs into deferred words that conform to this stack effect. Otherwise
6896: it's too difficult to use the deferred word.
6897:
1.44 crook 6898: A deferred word can be used to improve the statistics-gathering example
6899: from @ref{User-defined Defining Words}; rather than edit the
6900: application's source code to change every @code{:} to a @code{my:}, do
6901: this:
6902:
6903: @example
6904: : real: : ; \ retain access to the original
6905: defer : \ redefine as a deferred word
1.132 anton 6906: ' my: IS : \ use special version of :
1.44 crook 6907: \
6908: \ load application here
6909: \
1.132 anton 6910: ' real: IS : \ go back to the original
1.44 crook 6911: @end example
6912:
6913:
1.132 anton 6914: One thing to note is that @code{IS} has special compilation semantics,
6915: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6916:
6917: @example
6918: : set-greet ( xt -- )
1.132 anton 6919: IS greet ;
1.44 crook 6920:
6921: ' greet1 set-greet
6922: @end example
6923:
1.132 anton 6924: In situations where @code{IS} does not fit, use @code{defer!} instead.
6925:
1.69 anton 6926: A deferred word can only inherit execution semantics from the xt
6927: (because that is all that an xt can represent -- for more discussion of
6928: this @pxref{Tokens for Words}); by default it will have default
6929: interpretation and compilation semantics deriving from this execution
6930: semantics. However, you can change the interpretation and compilation
6931: semantics of the deferred word in the usual ways:
1.44 crook 6932:
6933: @example
1.132 anton 6934: : bar .... ; immediate
1.44 crook 6935: Defer fred immediate
6936: Defer jim
6937:
1.132 anton 6938: ' bar IS jim \ jim has default semantics
6939: ' bar IS fred \ fred is immediate
1.44 crook 6940: @end example
6941:
6942: doc-defer
1.132 anton 6943: doc-defer!
1.44 crook 6944: doc-is
1.132 anton 6945: doc-defer@
6946: doc-action-of
1.44 crook 6947: @comment TODO document these: what's defers [is]
6948: doc-defers
6949:
6950: @c Use @code{words-deferred} to see a list of deferred words.
6951:
1.132 anton 6952: Definitions of these words (except @code{defers}) in ANS Forth are
6953: provided in @file{compat/defer.fs}.
1.44 crook 6954:
6955:
1.170 pazsan 6956: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6957: @subsection Aliases
6958: @cindex aliases
1.1 anton 6959:
1.44 crook 6960: The defining word @code{Alias} allows you to define a word by name that
6961: has the same behaviour as some other word. Here are two situation where
6962: this can be useful:
1.1 anton 6963:
1.44 crook 6964: @itemize @bullet
6965: @item
6966: When you want access to a word's definition from a different word list
6967: (for an example of this, see the definition of the @code{Root} word list
6968: in the Gforth source).
6969: @item
6970: When you want to create a synonym; a definition that can be known by
6971: either of two names (for example, @code{THEN} and @code{ENDIF} are
6972: aliases).
6973: @end itemize
1.1 anton 6974:
1.69 anton 6975: Like deferred words, an alias has default compilation and interpretation
6976: semantics at the beginning (not the modifications of the other word),
6977: but you can change them in the usual ways (@code{immediate},
6978: @code{compile-only}). For example:
1.1 anton 6979:
6980: @example
1.44 crook 6981: : foo ... ; immediate
6982:
6983: ' foo Alias bar \ bar is not an immediate word
6984: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6985: @end example
6986:
1.44 crook 6987: Words that are aliases have the same xt, different headers in the
6988: dictionary, and consequently different name tokens (@pxref{Tokens for
6989: Words}) and possibly different immediate flags. An alias can only have
6990: default or immediate compilation semantics; you can define aliases for
6991: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6992:
1.44 crook 6993: doc-alias
1.1 anton 6994:
6995:
1.47 crook 6996: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6997: @section Interpretation and Compilation Semantics
1.26 crook 6998: @cindex semantics, interpretation and compilation
1.1 anton 6999:
1.71 anton 7000: @c !! state and ' are used without explanation
7001: @c example for immediate/compile-only? or is the tutorial enough
7002:
1.26 crook 7003: @cindex interpretation semantics
1.71 anton 7004: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 7005: interpreter does when it encounters the word in interpret state. It also
7006: appears in some other contexts, e.g., the execution token returned by
1.71 anton 7007: @code{' @i{word}} identifies the interpretation semantics of @i{word}
7008: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 7009: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 7010:
1.26 crook 7011: @cindex compilation semantics
1.71 anton 7012: The @dfn{compilation semantics} of a (named) word are what the text
7013: interpreter does when it encounters the word in compile state. It also
7014: appears in other contexts, e.g, @code{POSTPONE @i{word}}
7015: compiles@footnote{In standard terminology, ``appends to the current
7016: definition''.} the compilation semantics of @i{word}.
1.1 anton 7017:
1.26 crook 7018: @cindex execution semantics
7019: The standard also talks about @dfn{execution semantics}. They are used
7020: only for defining the interpretation and compilation semantics of many
7021: words. By default, the interpretation semantics of a word are to
7022: @code{execute} its execution semantics, and the compilation semantics of
7023: a word are to @code{compile,} its execution semantics.@footnote{In
7024: standard terminology: The default interpretation semantics are its
7025: execution semantics; the default compilation semantics are to append its
7026: execution semantics to the execution semantics of the current
7027: definition.}
7028:
1.71 anton 7029: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
7030: the text interpreter, ticked, or @code{postpone}d, so they have no
7031: interpretation or compilation semantics. Their behaviour is represented
7032: by their XT (@pxref{Tokens for Words}), and we call it execution
7033: semantics, too.
7034:
1.26 crook 7035: @comment TODO expand, make it co-operate with new sections on text interpreter.
7036:
7037: @cindex immediate words
7038: @cindex compile-only words
7039: You can change the semantics of the most-recently defined word:
7040:
1.44 crook 7041:
1.26 crook 7042: doc-immediate
7043: doc-compile-only
7044: doc-restrict
7045:
1.82 anton 7046: By convention, words with non-default compilation semantics (e.g.,
7047: immediate words) often have names surrounded with brackets (e.g.,
7048: @code{[']}, @pxref{Execution token}).
1.44 crook 7049:
1.26 crook 7050: Note that ticking (@code{'}) a compile-only word gives an error
7051: (``Interpreting a compile-only word'').
1.1 anton 7052:
1.47 crook 7053: @menu
1.67 anton 7054: * Combined words::
1.47 crook 7055: @end menu
1.44 crook 7056:
1.71 anton 7057:
1.48 anton 7058: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7059: @subsection Combined Words
7060: @cindex combined words
7061:
7062: Gforth allows you to define @dfn{combined words} -- words that have an
7063: arbitrary combination of interpretation and compilation semantics.
7064:
1.26 crook 7065: doc-interpret/compile:
1.1 anton 7066:
1.26 crook 7067: This feature was introduced for implementing @code{TO} and @code{S"}. I
7068: recommend that you do not define such words, as cute as they may be:
7069: they make it hard to get at both parts of the word in some contexts.
7070: E.g., assume you want to get an execution token for the compilation
7071: part. Instead, define two words, one that embodies the interpretation
7072: part, and one that embodies the compilation part. Once you have done
7073: that, you can define a combined word with @code{interpret/compile:} for
7074: the convenience of your users.
1.1 anton 7075:
1.26 crook 7076: You might try to use this feature to provide an optimizing
7077: implementation of the default compilation semantics of a word. For
7078: example, by defining:
1.1 anton 7079: @example
1.26 crook 7080: :noname
7081: foo bar ;
7082: :noname
7083: POSTPONE foo POSTPONE bar ;
1.29 crook 7084: interpret/compile: opti-foobar
1.1 anton 7085: @end example
1.26 crook 7086:
1.23 crook 7087: @noindent
1.26 crook 7088: as an optimizing version of:
7089:
1.1 anton 7090: @example
1.26 crook 7091: : foobar
7092: foo bar ;
1.1 anton 7093: @end example
7094:
1.26 crook 7095: Unfortunately, this does not work correctly with @code{[compile]},
7096: because @code{[compile]} assumes that the compilation semantics of all
7097: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7098: opti-foobar} would compile compilation semantics, whereas
7099: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7100:
1.26 crook 7101: @cindex state-smart words (are a bad idea)
1.82 anton 7102: @anchor{state-smartness}
1.29 crook 7103: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7104: by @code{interpret/compile:} (words are state-smart if they check
7105: @code{STATE} during execution). E.g., they would try to code
7106: @code{foobar} like this:
1.1 anton 7107:
1.26 crook 7108: @example
7109: : foobar
7110: STATE @@
7111: IF ( compilation state )
7112: POSTPONE foo POSTPONE bar
7113: ELSE
7114: foo bar
7115: ENDIF ; immediate
7116: @end example
1.1 anton 7117:
1.26 crook 7118: Although this works if @code{foobar} is only processed by the text
7119: interpreter, it does not work in other contexts (like @code{'} or
7120: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7121: for a state-smart word, not for the interpretation semantics of the
7122: original @code{foobar}; when you execute this execution token (directly
7123: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7124: state, the result will not be what you expected (i.e., it will not
7125: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7126: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7127: M. Anton Ertl,
7128: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7129: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7130:
1.26 crook 7131: @cindex defining words with arbitrary semantics combinations
7132: It is also possible to write defining words that define words with
7133: arbitrary combinations of interpretation and compilation semantics. In
7134: general, they look like this:
1.1 anton 7135:
1.26 crook 7136: @example
7137: : def-word
7138: create-interpret/compile
1.29 crook 7139: @i{code1}
1.26 crook 7140: interpretation>
1.29 crook 7141: @i{code2}
1.26 crook 7142: <interpretation
7143: compilation>
1.29 crook 7144: @i{code3}
1.26 crook 7145: <compilation ;
7146: @end example
1.1 anton 7147:
1.29 crook 7148: For a @i{word} defined with @code{def-word}, the interpretation
7149: semantics are to push the address of the body of @i{word} and perform
7150: @i{code2}, and the compilation semantics are to push the address of
7151: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7152: can also be defined like this (except that the defined constants don't
7153: behave correctly when @code{[compile]}d):
1.1 anton 7154:
1.26 crook 7155: @example
7156: : constant ( n "name" -- )
7157: create-interpret/compile
7158: ,
7159: interpretation> ( -- n )
7160: @@
7161: <interpretation
7162: compilation> ( compilation. -- ; run-time. -- n )
7163: @@ postpone literal
7164: <compilation ;
7165: @end example
1.1 anton 7166:
1.44 crook 7167:
1.26 crook 7168: doc-create-interpret/compile
7169: doc-interpretation>
7170: doc-<interpretation
7171: doc-compilation>
7172: doc-<compilation
1.1 anton 7173:
1.44 crook 7174:
1.29 crook 7175: Words defined with @code{interpret/compile:} and
1.26 crook 7176: @code{create-interpret/compile} have an extended header structure that
7177: differs from other words; however, unless you try to access them with
7178: plain address arithmetic, you should not notice this. Words for
7179: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7180: @code{'} @i{word} @code{>body} also gives you the body of a word created
7181: with @code{create-interpret/compile}.
1.1 anton 7182:
1.44 crook 7183:
1.47 crook 7184: @c -------------------------------------------------------------
1.81 anton 7185: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7186: @section Tokens for Words
7187: @cindex tokens for words
7188:
7189: This section describes the creation and use of tokens that represent
7190: words.
7191:
1.71 anton 7192: @menu
7193: * Execution token:: represents execution/interpretation semantics
7194: * Compilation token:: represents compilation semantics
7195: * Name token:: represents named words
7196: @end menu
1.47 crook 7197:
1.71 anton 7198: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7199: @subsection Execution token
1.47 crook 7200:
7201: @cindex xt
7202: @cindex execution token
1.71 anton 7203: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7204: You can use @code{execute} to invoke this behaviour.
1.47 crook 7205:
1.71 anton 7206: @cindex tick (')
7207: You can use @code{'} to get an execution token that represents the
7208: interpretation semantics of a named word:
1.47 crook 7209:
7210: @example
1.97 anton 7211: 5 ' . ( n xt )
7212: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7213: @end example
1.47 crook 7214:
1.71 anton 7215: doc-'
7216:
7217: @code{'} parses at run-time; there is also a word @code{[']} that parses
7218: when it is compiled, and compiles the resulting XT:
7219:
7220: @example
7221: : foo ['] . execute ;
7222: 5 foo
7223: : bar ' execute ; \ by contrast,
7224: 5 bar . \ ' parses "." when bar executes
7225: @end example
7226:
7227: doc-[']
7228:
7229: If you want the execution token of @i{word}, write @code{['] @i{word}}
7230: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7231: @code{'} and @code{[']} behave somewhat unusually by complaining about
7232: compile-only words (because these words have no interpretation
7233: semantics). You might get what you want by using @code{COMP' @i{word}
7234: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7235: token}).
7236:
1.116 anton 7237: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7238: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7239: for the only behaviour the word has (the execution semantics). For
1.116 anton 7240: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7241: would produce if the word was defined anonymously.
7242:
7243: @example
7244: :noname ." hello" ;
7245: execute
1.47 crook 7246: @end example
7247:
1.71 anton 7248: An XT occupies one cell and can be manipulated like any other cell.
7249:
1.47 crook 7250: @cindex code field address
7251: @cindex CFA
1.71 anton 7252: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7253: operations that produce or consume it). For old hands: In Gforth, the
7254: XT is implemented as a code field address (CFA).
7255:
7256: doc-execute
7257: doc-perform
7258:
7259: @node Compilation token, Name token, Execution token, Tokens for Words
7260: @subsection Compilation token
1.47 crook 7261:
7262: @cindex compilation token
1.71 anton 7263: @cindex CT (compilation token)
7264: Gforth represents the compilation semantics of a named word by a
1.47 crook 7265: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7266: @i{xt} is an execution token. The compilation semantics represented by
7267: the compilation token can be performed with @code{execute}, which
7268: consumes the whole compilation token, with an additional stack effect
7269: determined by the represented compilation semantics.
7270:
7271: At present, the @i{w} part of a compilation token is an execution token,
7272: and the @i{xt} part represents either @code{execute} or
7273: @code{compile,}@footnote{Depending upon the compilation semantics of the
7274: word. If the word has default compilation semantics, the @i{xt} will
7275: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7276: @i{xt} will represent @code{execute}.}. However, don't rely on that
7277: knowledge, unless necessary; future versions of Gforth may introduce
7278: unusual compilation tokens (e.g., a compilation token that represents
7279: the compilation semantics of a literal).
7280:
1.71 anton 7281: You can perform the compilation semantics represented by the compilation
7282: token with @code{execute}. You can compile the compilation semantics
7283: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7284: equivalent to @code{postpone @i{word}}.
7285:
7286: doc-[comp']
7287: doc-comp'
7288: doc-postpone,
7289:
7290: @node Name token, , Compilation token, Tokens for Words
7291: @subsection Name token
1.47 crook 7292:
7293: @cindex name token
1.116 anton 7294: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7295: token is an abstract data type that occurs as argument or result of the
7296: words below.
7297:
7298: @c !! put this elswhere?
1.47 crook 7299: @cindex name field address
7300: @cindex NFA
1.116 anton 7301: The closest thing to the nt in older Forth systems is the name field
7302: address (NFA), but there are significant differences: in older Forth
7303: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7304: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7305: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7306: is a link field in the structure identified by the name token, but
7307: searching usually uses a hash table external to these structures; the
7308: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7309: implemented as the address of that count field.
1.47 crook 7310:
7311: doc-find-name
1.116 anton 7312: doc-latest
7313: doc->name
1.47 crook 7314: doc-name>int
7315: doc-name?int
7316: doc-name>comp
7317: doc-name>string
1.109 anton 7318: doc-id.
7319: doc-.name
7320: doc-.id
1.47 crook 7321:
1.81 anton 7322: @c ----------------------------------------------------------
7323: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7324: @section Compiling words
7325: @cindex compiling words
7326: @cindex macros
7327:
7328: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7329: between compilation and run-time. E.g., you can run arbitrary code
7330: between defining words (or for computing data used by defining words
7331: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7332: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7333: running arbitrary code while compiling a colon definition (exception:
7334: you must not allot dictionary space).
7335:
7336: @menu
7337: * Literals:: Compiling data values
7338: * Macros:: Compiling words
7339: @end menu
7340:
7341: @node Literals, Macros, Compiling words, Compiling words
7342: @subsection Literals
7343: @cindex Literals
7344:
7345: The simplest and most frequent example is to compute a literal during
7346: compilation. E.g., the following definition prints an array of strings,
7347: one string per line:
7348:
7349: @example
7350: : .strings ( addr u -- ) \ gforth
7351: 2* cells bounds U+DO
7352: cr i 2@@ type
7353: 2 cells +LOOP ;
7354: @end example
1.81 anton 7355:
1.82 anton 7356: With a simple-minded compiler like Gforth's, this computes @code{2
7357: cells} on every loop iteration. You can compute this value once and for
7358: all at compile time and compile it into the definition like this:
7359:
7360: @example
7361: : .strings ( addr u -- ) \ gforth
7362: 2* cells bounds U+DO
7363: cr i 2@@ type
7364: [ 2 cells ] literal +LOOP ;
7365: @end example
7366:
7367: @code{[} switches the text interpreter to interpret state (you will get
7368: an @code{ok} prompt if you type this example interactively and insert a
7369: newline between @code{[} and @code{]}), so it performs the
7370: interpretation semantics of @code{2 cells}; this computes a number.
7371: @code{]} switches the text interpreter back into compile state. It then
7372: performs @code{Literal}'s compilation semantics, which are to compile
7373: this number into the current word. You can decompile the word with
7374: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7375:
1.82 anton 7376: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7377: *} in this way.
1.81 anton 7378:
1.82 anton 7379: doc-[
7380: doc-]
1.81 anton 7381: doc-literal
7382: doc-]L
1.82 anton 7383:
7384: There are also words for compiling other data types than single cells as
7385: literals:
7386:
1.81 anton 7387: doc-2literal
7388: doc-fliteral
1.82 anton 7389: doc-sliteral
7390:
7391: @cindex colon-sys, passing data across @code{:}
7392: @cindex @code{:}, passing data across
7393: You might be tempted to pass data from outside a colon definition to the
7394: inside on the data stack. This does not work, because @code{:} puhes a
7395: colon-sys, making stuff below unaccessible. E.g., this does not work:
7396:
7397: @example
7398: 5 : foo literal ; \ error: "unstructured"
7399: @end example
7400:
7401: Instead, you have to pass the value in some other way, e.g., through a
7402: variable:
7403:
7404: @example
7405: variable temp
7406: 5 temp !
7407: : foo [ temp @@ ] literal ;
7408: @end example
7409:
7410:
7411: @node Macros, , Literals, Compiling words
7412: @subsection Macros
7413: @cindex Macros
7414: @cindex compiling compilation semantics
7415:
7416: @code{Literal} and friends compile data values into the current
7417: definition. You can also write words that compile other words into the
7418: current definition. E.g.,
7419:
7420: @example
7421: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7422: POSTPONE + ;
7423:
7424: : foo ( n1 n2 -- n )
7425: [ compile-+ ] ;
7426: 1 2 foo .
7427: @end example
7428:
7429: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7430: What happens in this example? @code{Postpone} compiles the compilation
7431: semantics of @code{+} into @code{compile-+}; later the text interpreter
7432: executes @code{compile-+} and thus the compilation semantics of +, which
7433: compile (the execution semantics of) @code{+} into
7434: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7435: should only be executed in compile state, so this example is not
7436: guaranteed to work on all standard systems, but on any decent system it
7437: will work.}
7438:
7439: doc-postpone
7440:
7441: Compiling words like @code{compile-+} are usually immediate (or similar)
7442: so you do not have to switch to interpret state to execute them;
1.206 anton 7443: modifying the last example accordingly produces:
1.82 anton 7444:
7445: @example
7446: : [compile-+] ( compilation: --; interpretation: -- )
7447: \ compiled code: ( n1 n2 -- n )
7448: POSTPONE + ; immediate
7449:
7450: : foo ( n1 n2 -- n )
7451: [compile-+] ;
7452: 1 2 foo .
7453: @end example
7454:
1.206 anton 7455: You will occassionally find the need to POSTPONE several words;
7456: putting POSTPONE before each such word is cumbersome, so Gforth
7457: provides a more convenient syntax: @code{]] ... [[}. This
7458: allows us to write @code{[compile-+]} as:
7459:
7460: @example
7461: : [compile-+] ( compilation: --; interpretation: -- )
7462: ]] + [[ ; immediate
7463: @end example
7464:
7465: doc-]]
7466: doc-[[
7467:
7468: The unusual direction of the brackets indicates their function:
7469: @code{]]} switches from compilation to postponing (i.e., compilation
7470: of compilation), just like @code{]} switches from immediate execution
7471: (interpretation) to compilation. Conversely, @code{[[} switches from
7472: postponing to compilation, ananlogous to @code{[} which switches from
7473: compilation to immediate execution.
7474:
7475: The real advantage of @code{]] }...@code{ [[} becomes apparent when
7476: there are many words to POSTPONE. E.g., the word
7477: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
7478: written much shorter as follows:
7479:
7480: @example
7481: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
7482: \ at run-time, execute xt ( ... x -- ... ) for each element of the
7483: \ array beginning at addr and containing u elements
7484: @{ xt @}
7485: ]] cells over + swap ?do
7486: i @@ [[ xt compile,
7487: 1 cells ]]L +loop [[ ;
7488: @end example
7489:
7490: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
7491: There are also other shortcuts
7492:
7493: doc-]]L
7494: doc-]]2L
7495: doc-]]FL
7496: doc-]]SL
7497:
7498: Note that parsing words don't parse at postpone time; if you want to
7499: provide the parsed string right away, you have to switch back to
7500: compilation:
7501:
7502: @example
7503: ]] ... [[ s" some string" ]]2L ... [[
7504: ]] ... [[ ['] + ]]L ... [[
7505: @end example
7506:
7507: Definitions of @code{]]} and friends in ANS Forth are provided in
7508: @file{compat/macros.fs}.
7509:
1.82 anton 7510: Immediate compiling words are similar to macros in other languages (in
7511: particular, Lisp). The important differences to macros in, e.g., C are:
7512:
7513: @itemize @bullet
7514:
7515: @item
7516: You use the same language for defining and processing macros, not a
7517: separate preprocessing language and processor.
7518:
7519: @item
7520: Consequently, the full power of Forth is available in macro definitions.
7521: E.g., you can perform arbitrarily complex computations, or generate
7522: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7523: Tutorial}). This power is very useful when writing a parser generators
7524: or other code-generating software.
7525:
7526: @item
7527: Macros defined using @code{postpone} etc. deal with the language at a
7528: higher level than strings; name binding happens at macro definition
7529: time, so you can avoid the pitfalls of name collisions that can happen
7530: in C macros. Of course, Forth is a liberal language and also allows to
7531: shoot yourself in the foot with text-interpreted macros like
7532:
7533: @example
7534: : [compile-+] s" +" evaluate ; immediate
7535: @end example
7536:
7537: Apart from binding the name at macro use time, using @code{evaluate}
7538: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7539: @end itemize
7540:
7541: You may want the macro to compile a number into a word. The word to do
7542: it is @code{literal}, but you have to @code{postpone} it, so its
7543: compilation semantics take effect when the macro is executed, not when
7544: it is compiled:
7545:
7546: @example
7547: : [compile-5] ( -- ) \ compiled code: ( -- n )
7548: 5 POSTPONE literal ; immediate
7549:
7550: : foo [compile-5] ;
7551: foo .
7552: @end example
7553:
7554: You may want to pass parameters to a macro, that the macro should
7555: compile into the current definition. If the parameter is a number, then
7556: you can use @code{postpone literal} (similar for other values).
7557:
7558: If you want to pass a word that is to be compiled, the usual way is to
7559: pass an execution token and @code{compile,} it:
7560:
7561: @example
7562: : twice1 ( xt -- ) \ compiled code: ... -- ...
7563: dup compile, compile, ;
7564:
7565: : 2+ ( n1 -- n2 )
7566: [ ' 1+ twice1 ] ;
7567: @end example
7568:
7569: doc-compile,
7570:
7571: An alternative available in Gforth, that allows you to pass compile-only
7572: words as parameters is to use the compilation token (@pxref{Compilation
7573: token}). The same example in this technique:
7574:
7575: @example
7576: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7577: 2dup 2>r execute 2r> execute ;
7578:
7579: : 2+ ( n1 -- n2 )
7580: [ comp' 1+ twice ] ;
7581: @end example
7582:
7583: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7584: works even if the executed compilation semantics has an effect on the
7585: data stack.
7586:
7587: You can also define complete definitions with these words; this provides
7588: an alternative to using @code{does>} (@pxref{User-defined Defining
7589: Words}). E.g., instead of
7590:
7591: @example
7592: : curry+ ( n1 "name" -- )
7593: CREATE ,
7594: DOES> ( n2 -- n1+n2 )
7595: @@ + ;
7596: @end example
7597:
7598: you could define
7599:
7600: @example
7601: : curry+ ( n1 "name" -- )
7602: \ name execution: ( n2 -- n1+n2 )
7603: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7604:
1.82 anton 7605: -3 curry+ 3-
7606: see 3-
7607: @end example
1.81 anton 7608:
1.82 anton 7609: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7610: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7611:
1.82 anton 7612: This way of writing defining words is sometimes more, sometimes less
7613: convenient than using @code{does>} (@pxref{Advanced does> usage
7614: example}). One advantage of this method is that it can be optimized
7615: better, because the compiler knows that the value compiled with
7616: @code{literal} is fixed, whereas the data associated with a
7617: @code{create}d word can be changed.
1.47 crook 7618:
1.206 anton 7619: @c doc-[compile] !! not properly documented
7620:
1.26 crook 7621: @c ----------------------------------------------------------
1.111 anton 7622: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7623: @section The Text Interpreter
7624: @cindex interpreter - outer
7625: @cindex text interpreter
7626: @cindex outer interpreter
1.1 anton 7627:
1.34 anton 7628: @c Should we really describe all these ugly details? IMO the text
7629: @c interpreter should be much cleaner, but that may not be possible within
7630: @c ANS Forth. - anton
1.44 crook 7631: @c nac-> I wanted to explain how it works to show how you can exploit
7632: @c it in your own programs. When I was writing a cross-compiler, figuring out
7633: @c some of these gory details was very helpful to me. None of the textbooks
7634: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7635: @c seems to positively avoid going into too much detail for some of
7636: @c the internals.
1.34 anton 7637:
1.71 anton 7638: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7639: @c it is; for the ugly details, I would prefer another place. I wonder
7640: @c whether we should have a chapter before "Words" that describes some
7641: @c basic concepts referred to in words, and a chapter after "Words" that
7642: @c describes implementation details.
7643:
1.29 crook 7644: The text interpreter@footnote{This is an expanded version of the
7645: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7646: that processes input from the current input device. It is also called
7647: the outer interpreter, in contrast to the inner interpreter
7648: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7649: implementations.
1.27 crook 7650:
1.29 crook 7651: @cindex interpret state
7652: @cindex compile state
7653: The text interpreter operates in one of two states: @dfn{interpret
7654: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7655: aptly-named variable @code{state}.
1.29 crook 7656:
7657: This section starts by describing how the text interpreter behaves when
7658: it is in interpret state, processing input from the user input device --
7659: the keyboard. This is the mode that a Forth system is in after it starts
7660: up.
7661:
7662: @cindex input buffer
7663: @cindex terminal input buffer
7664: The text interpreter works from an area of memory called the @dfn{input
7665: buffer}@footnote{When the text interpreter is processing input from the
7666: keyboard, this area of memory is called the @dfn{terminal input buffer}
7667: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7668: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7669: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7670: leading spaces (called @dfn{delimiters}) then parses a string (a
7671: sequence of non-space characters) until it reaches either a space
7672: character or the end of the buffer. Having parsed a string, it makes two
7673: attempts to process it:
1.27 crook 7674:
1.29 crook 7675: @cindex dictionary
1.27 crook 7676: @itemize @bullet
7677: @item
1.29 crook 7678: It looks for the string in a @dfn{dictionary} of definitions. If the
7679: string is found, the string names a @dfn{definition} (also known as a
7680: @dfn{word}) and the dictionary search returns information that allows
7681: the text interpreter to perform the word's @dfn{interpretation
7682: semantics}. In most cases, this simply means that the word will be
7683: executed.
1.27 crook 7684: @item
7685: If the string is not found in the dictionary, the text interpreter
1.29 crook 7686: attempts to treat it as a number, using the rules described in
7687: @ref{Number Conversion}. If the string represents a legal number in the
7688: current radix, the number is pushed onto a parameter stack (the data
7689: stack for integers, the floating-point stack for floating-point
7690: numbers).
7691: @end itemize
7692:
7693: If both attempts fail, or if the word is found in the dictionary but has
7694: no interpretation semantics@footnote{This happens if the word was
7695: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7696: remainder of the input buffer, issues an error message and waits for
7697: more input. If one of the attempts succeeds, the text interpreter
7698: repeats the parsing process until the whole of the input buffer has been
7699: processed, at which point it prints the status message ``@code{ ok}''
7700: and waits for more input.
7701:
1.71 anton 7702: @c anton: this should be in the input stream subsection (or below it)
7703:
1.29 crook 7704: @cindex parse area
7705: The text interpreter keeps track of its position in the input buffer by
7706: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7707: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7708: of the input buffer. The region from offset @code{>IN @@} to the end of
7709: the input buffer is called the @dfn{parse area}@footnote{In other words,
7710: the text interpreter processes the contents of the input buffer by
7711: parsing strings from the parse area until the parse area is empty.}.
7712: This example shows how @code{>IN} changes as the text interpreter parses
7713: the input buffer:
7714:
7715: @example
7716: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7717: CR ." ->" TYPE ." <-" ; IMMEDIATE
7718:
7719: 1 2 3 remaining + remaining .
7720:
7721: : foo 1 2 3 remaining SWAP remaining ;
7722: @end example
7723:
7724: @noindent
7725: The result is:
7726:
7727: @example
7728: ->+ remaining .<-
7729: ->.<-5 ok
7730:
7731: ->SWAP remaining ;-<
7732: ->;<- ok
7733: @end example
7734:
7735: @cindex parsing words
7736: The value of @code{>IN} can also be modified by a word in the input
7737: buffer that is executed by the text interpreter. This means that a word
7738: can ``trick'' the text interpreter into either skipping a section of the
7739: input buffer@footnote{This is how parsing words work.} or into parsing a
7740: section twice. For example:
1.27 crook 7741:
1.29 crook 7742: @example
1.71 anton 7743: : lat ." <<foo>>" ;
7744: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7745: @end example
7746:
7747: @noindent
7748: When @code{flat} is executed, this output is produced@footnote{Exercise
7749: for the reader: what would happen if the @code{3} were replaced with
7750: @code{4}?}:
7751:
7752: @example
1.71 anton 7753: <<bar>><<foo>>
1.29 crook 7754: @end example
7755:
1.71 anton 7756: This technique can be used to work around some of the interoperability
7757: problems of parsing words. Of course, it's better to avoid parsing
7758: words where possible.
7759:
1.29 crook 7760: @noindent
7761: Two important notes about the behaviour of the text interpreter:
1.27 crook 7762:
7763: @itemize @bullet
7764: @item
7765: It processes each input string to completion before parsing additional
1.29 crook 7766: characters from the input buffer.
7767: @item
7768: It treats the input buffer as a read-only region (and so must your code).
7769: @end itemize
7770:
7771: @noindent
7772: When the text interpreter is in compile state, its behaviour changes in
7773: these ways:
7774:
7775: @itemize @bullet
7776: @item
7777: If a parsed string is found in the dictionary, the text interpreter will
7778: perform the word's @dfn{compilation semantics}. In most cases, this
7779: simply means that the execution semantics of the word will be appended
7780: to the current definition.
1.27 crook 7781: @item
1.29 crook 7782: When a number is encountered, it is compiled into the current definition
7783: (as a literal) rather than being pushed onto a parameter stack.
7784: @item
7785: If an error occurs, @code{state} is modified to put the text interpreter
7786: back into interpret state.
7787: @item
7788: Each time a line is entered from the keyboard, Gforth prints
7789: ``@code{ compiled}'' rather than `` @code{ok}''.
7790: @end itemize
7791:
7792: @cindex text interpreter - input sources
7793: When the text interpreter is using an input device other than the
7794: keyboard, its behaviour changes in these ways:
7795:
7796: @itemize @bullet
7797: @item
7798: When the parse area is empty, the text interpreter attempts to refill
7799: the input buffer from the input source. When the input source is
1.71 anton 7800: exhausted, the input source is set back to the previous input source.
1.29 crook 7801: @item
7802: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7803: time the parse area is emptied.
7804: @item
7805: If an error occurs, the input source is set back to the user input
7806: device.
1.27 crook 7807: @end itemize
1.21 crook 7808:
1.49 anton 7809: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7810:
1.26 crook 7811: doc->in
1.27 crook 7812: doc-source
7813:
1.26 crook 7814: doc-tib
7815: doc-#tib
1.1 anton 7816:
1.44 crook 7817:
1.26 crook 7818: @menu
1.67 anton 7819: * Input Sources::
7820: * Number Conversion::
7821: * Interpret/Compile states::
7822: * Interpreter Directives::
1.26 crook 7823: @end menu
1.1 anton 7824:
1.29 crook 7825: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7826: @subsection Input Sources
7827: @cindex input sources
7828: @cindex text interpreter - input sources
7829:
1.44 crook 7830: By default, the text interpreter processes input from the user input
1.29 crook 7831: device (the keyboard) when Forth starts up. The text interpreter can
7832: process input from any of these sources:
7833:
7834: @itemize @bullet
7835: @item
7836: The user input device -- the keyboard.
7837: @item
7838: A file, using the words described in @ref{Forth source files}.
7839: @item
7840: A block, using the words described in @ref{Blocks}.
7841: @item
7842: A text string, using @code{evaluate}.
7843: @end itemize
7844:
7845: A program can identify the current input device from the values of
7846: @code{source-id} and @code{blk}.
7847:
1.44 crook 7848:
1.29 crook 7849: doc-source-id
7850: doc-blk
7851:
7852: doc-save-input
7853: doc-restore-input
7854:
7855: doc-evaluate
1.111 anton 7856: doc-query
1.1 anton 7857:
1.29 crook 7858:
1.44 crook 7859:
1.29 crook 7860: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7861: @subsection Number Conversion
7862: @cindex number conversion
7863: @cindex double-cell numbers, input format
7864: @cindex input format for double-cell numbers
7865: @cindex single-cell numbers, input format
7866: @cindex input format for single-cell numbers
7867: @cindex floating-point numbers, input format
7868: @cindex input format for floating-point numbers
1.1 anton 7869:
1.29 crook 7870: This section describes the rules that the text interpreter uses when it
7871: tries to convert a string into a number.
1.1 anton 7872:
1.26 crook 7873: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7874: number base@footnote{For example, 0-9 when the number base is decimal or
7875: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7876:
1.26 crook 7877: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7878:
1.29 crook 7879: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7880: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7881:
1.26 crook 7882: Let * represent any number of instances of the previous character
7883: (including none).
1.1 anton 7884:
1.26 crook 7885: Let any other character represent itself.
1.1 anton 7886:
1.29 crook 7887: @noindent
1.26 crook 7888: Now, the conversion rules are:
1.21 crook 7889:
1.26 crook 7890: @itemize @bullet
7891: @item
7892: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7893: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7894: @item
7895: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7896: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7897: arithmetic. Examples are -45 -5681 -0
7898: @item
7899: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7900: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7901: (all three of these represent the same number).
1.26 crook 7902: @item
7903: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7904: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7905: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7906: -34.65 (all three of these represent the same number).
1.26 crook 7907: @item
1.29 crook 7908: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7909: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7910: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7911: number) +12.E-4
1.26 crook 7912: @end itemize
1.1 anton 7913:
1.174 anton 7914: By default, the number base used for integer number conversion is
7915: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7916: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7917: change @code{base} anywhere, make sure to save the old value and
7918: restore it afterwards; better yet, use @code{base-execute}, which does
7919: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7920: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7921:
1.29 crook 7922: doc-dpl
1.174 anton 7923: doc-base-execute
1.26 crook 7924: doc-base
7925: doc-hex
7926: doc-decimal
1.1 anton 7927:
1.26 crook 7928: @cindex '-prefix for character strings
7929: @cindex &-prefix for decimal numbers
1.133 anton 7930: @cindex #-prefix for decimal numbers
1.26 crook 7931: @cindex %-prefix for binary numbers
7932: @cindex $-prefix for hexadecimal numbers
1.133 anton 7933: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7934: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7935: prefix@footnote{Some Forth implementations provide a similar scheme by
7936: implementing @code{$} etc. as parsing words that process the subsequent
7937: number in the input stream and push it onto the stack. For example, see
7938: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7939: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7940: is required between the prefix and the number.} before the first digit
1.133 anton 7941: of an (integer) number. The following prefixes are supported:
1.1 anton 7942:
1.26 crook 7943: @itemize @bullet
7944: @item
1.35 anton 7945: @code{&} -- decimal
1.26 crook 7946: @item
1.133 anton 7947: @code{#} -- decimal
7948: @item
1.35 anton 7949: @code{%} -- binary
1.26 crook 7950: @item
1.35 anton 7951: @code{$} -- hexadecimal
1.26 crook 7952: @item
1.133 anton 7953: @code{0x} -- hexadecimal, if base<33.
7954: @item
7955: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7956: optional @code{'} may be present after the character.
1.26 crook 7957: @end itemize
1.1 anton 7958:
1.26 crook 7959: Here are some examples, with the equivalent decimal number shown after
7960: in braces:
1.1 anton 7961:
1.26 crook 7962: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7963: 'A (65),
7964: -'a' (-97),
1.26 crook 7965: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7966:
1.26 crook 7967: @cindex number conversion - traps for the unwary
1.29 crook 7968: @noindent
1.26 crook 7969: Number conversion has a number of traps for the unwary:
1.1 anton 7970:
1.26 crook 7971: @itemize @bullet
7972: @item
7973: You cannot determine the current number base using the code sequence
1.35 anton 7974: @code{base @@ .} -- the number base is always 10 in the current number
7975: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7976: @item
7977: If the number base is set to a value greater than 14 (for example,
7978: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7979: it to be intepreted as either a single-precision integer or a
7980: floating-point number (Gforth treats it as an integer). The ambiguity
7981: can be resolved by explicitly stating the sign of the mantissa and/or
7982: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7983: ambiguity arises; either representation will be treated as a
7984: floating-point number.
7985: @item
1.29 crook 7986: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7987: It is used to specify file types.
7988: @item
1.72 anton 7989: ANS Forth requires the @code{.} of a double-precision number to be the
7990: final character in the string. Gforth allows the @code{.} to be
7991: anywhere after the first digit.
1.26 crook 7992: @item
7993: The number conversion process does not check for overflow.
7994: @item
1.72 anton 7995: In an ANS Forth program @code{base} is required to be decimal when
7996: converting floating-point numbers. In Gforth, number conversion to
7997: floating-point numbers always uses base &10, irrespective of the value
7998: of @code{base}.
1.26 crook 7999: @end itemize
1.1 anton 8000:
1.49 anton 8001: You can read numbers into your programs with the words described in
1.181 anton 8002: @ref{Line input and conversion}.
1.1 anton 8003:
1.82 anton 8004: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 8005: @subsection Interpret/Compile states
8006: @cindex Interpret/Compile states
1.1 anton 8007:
1.29 crook 8008: A standard program is not permitted to change @code{state}
8009: explicitly. However, it can change @code{state} implicitly, using the
8010: words @code{[} and @code{]}. When @code{[} is executed it switches
8011: @code{state} to interpret state, and therefore the text interpreter
8012: starts interpreting. When @code{]} is executed it switches @code{state}
8013: to compile state and therefore the text interpreter starts
1.44 crook 8014: compiling. The most common usage for these words is for switching into
8015: interpret state and back from within a colon definition; this technique
1.49 anton 8016: can be used to compile a literal (for an example, @pxref{Literals}) or
8017: for conditional compilation (for an example, @pxref{Interpreter
8018: Directives}).
1.44 crook 8019:
1.35 anton 8020:
8021: @c This is a bad example: It's non-standard, and it's not necessary.
8022: @c However, I can't think of a good example for switching into compile
8023: @c state when there is no current word (@code{state}-smart words are not a
8024: @c good reason). So maybe we should use an example for switching into
8025: @c interpret @code{state} in a colon def. - anton
1.44 crook 8026: @c nac-> I agree. I started out by putting in the example, then realised
8027: @c that it was non-ANS, so wrote more words around it. I hope this
8028: @c re-written version is acceptable to you. I do want to keep the example
8029: @c as it is helpful for showing what is and what is not portable, particularly
8030: @c where it outlaws a style in common use.
8031:
1.72 anton 8032: @c anton: it's more important to show what's portable. After we have done
1.83 anton 8033: @c that, we can also show what's not. In any case, I have written a
8034: @c section Compiling Words which also deals with [ ].
1.35 anton 8035:
1.95 anton 8036: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 8037:
1.95 anton 8038: @c @code{[} and @code{]} also give you the ability to switch into compile
8039: @c state and back, but we cannot think of any useful Standard application
8040: @c for this ability. Pre-ANS Forth textbooks have examples like this:
8041:
8042: @c @example
8043: @c : AA ." this is A" ;
8044: @c : BB ." this is B" ;
8045: @c : CC ." this is C" ;
8046:
8047: @c create table ] aa bb cc [
8048:
8049: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
8050: @c cells table + @@ execute ;
8051: @c @end example
8052:
8053: @c This example builds a jump table; @code{0 go} will display ``@code{this
8054: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
8055: @c defining @code{table} like this:
8056:
8057: @c @example
8058: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
8059: @c @end example
8060:
8061: @c The problem with this code is that the definition of @code{table} is not
8062: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
8063: @c @i{may} work on systems where code space and data space co-incide, the
8064: @c Standard only allows data space to be assigned for a @code{CREATE}d
8065: @c word. In addition, the Standard only allows @code{@@} to access data
8066: @c space, whilst this example is using it to access code space. The only
8067: @c portable, Standard way to build this table is to build it in data space,
8068: @c like this:
8069:
8070: @c @example
8071: @c create table ' aa , ' bb , ' cc ,
8072: @c @end example
1.29 crook 8073:
1.95 anton 8074: @c doc-state
1.44 crook 8075:
1.29 crook 8076:
1.82 anton 8077: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 8078: @subsection Interpreter Directives
8079: @cindex interpreter directives
1.72 anton 8080: @cindex conditional compilation
1.1 anton 8081:
1.29 crook 8082: These words are usually used in interpret state; typically to control
8083: which parts of a source file are processed by the text
1.26 crook 8084: interpreter. There are only a few ANS Forth Standard words, but Gforth
8085: supplements these with a rich set of immediate control structure words
8086: to compensate for the fact that the non-immediate versions can only be
1.29 crook 8087: used in compile state (@pxref{Control Structures}). Typical usages:
8088:
8089: @example
1.72 anton 8090: FALSE Constant HAVE-ASSEMBLER
1.29 crook 8091: .
8092: .
1.72 anton 8093: HAVE-ASSEMBLER [IF]
1.29 crook 8094: : ASSEMBLER-FEATURE
8095: ...
8096: ;
8097: [ENDIF]
8098: .
8099: .
8100: : SEE
8101: ... \ general-purpose SEE code
1.72 anton 8102: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 8103: ... \ assembler-specific SEE code
8104: [ [ENDIF] ]
8105: ;
8106: @end example
1.1 anton 8107:
1.44 crook 8108:
1.26 crook 8109: doc-[IF]
8110: doc-[ELSE]
8111: doc-[THEN]
8112: doc-[ENDIF]
1.1 anton 8113:
1.26 crook 8114: doc-[IFDEF]
8115: doc-[IFUNDEF]
1.1 anton 8116:
1.26 crook 8117: doc-[?DO]
8118: doc-[DO]
8119: doc-[FOR]
8120: doc-[LOOP]
8121: doc-[+LOOP]
8122: doc-[NEXT]
1.1 anton 8123:
1.26 crook 8124: doc-[BEGIN]
8125: doc-[UNTIL]
8126: doc-[AGAIN]
8127: doc-[WHILE]
8128: doc-[REPEAT]
1.1 anton 8129:
1.27 crook 8130:
1.26 crook 8131: @c -------------------------------------------------------------
1.111 anton 8132: @node The Input Stream, Word Lists, The Text Interpreter, Words
8133: @section The Input Stream
8134: @cindex input stream
8135:
8136: @c !! integrate this better with the "Text Interpreter" section
8137: The text interpreter reads from the input stream, which can come from
8138: several sources (@pxref{Input Sources}). Some words, in particular
8139: defining words, but also words like @code{'}, read parameters from the
8140: input stream instead of from the stack.
8141:
8142: Such words are called parsing words, because they parse the input
8143: stream. Parsing words are hard to use in other words, because it is
8144: hard to pass program-generated parameters through the input stream.
8145: They also usually have an unintuitive combination of interpretation and
8146: compilation semantics when implemented naively, leading to various
8147: approaches that try to produce a more intuitive behaviour
8148: (@pxref{Combined words}).
8149:
8150: It should be obvious by now that parsing words are a bad idea. If you
8151: want to implement a parsing word for convenience, also provide a factor
8152: of the word that does not parse, but takes the parameters on the stack.
8153: To implement the parsing word on top if it, you can use the following
8154: words:
8155:
8156: @c anton: these belong in the input stream section
8157: doc-parse
1.138 anton 8158: doc-parse-name
1.111 anton 8159: doc-parse-word
8160: doc-name
8161: doc-word
8162: doc-refill
8163:
8164: Conversely, if you have the bad luck (or lack of foresight) to have to
8165: deal with parsing words without having such factors, how do you pass a
8166: string that is not in the input stream to it?
8167:
8168: doc-execute-parsing
8169:
1.146 anton 8170: A definition of this word in ANS Forth is provided in
8171: @file{compat/execute-parsing.fs}.
8172:
1.111 anton 8173: If you want to run a parsing word on a file, the following word should
8174: help:
8175:
8176: doc-execute-parsing-file
8177:
8178: @c -------------------------------------------------------------
8179: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8180: @section Word Lists
8181: @cindex word lists
1.32 anton 8182: @cindex header space
1.1 anton 8183:
1.36 anton 8184: A wordlist is a list of named words; you can add new words and look up
8185: words by name (and you can remove words in a restricted way with
8186: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8187:
8188: @cindex search order stack
8189: The text interpreter searches the wordlists present in the search order
8190: (a stack of wordlists), from the top to the bottom. Within each
8191: wordlist, the search starts conceptually at the newest word; i.e., if
8192: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8193:
1.26 crook 8194: @cindex compilation word list
1.36 anton 8195: New words are added to the @dfn{compilation wordlist} (aka current
8196: wordlist).
1.1 anton 8197:
1.36 anton 8198: @cindex wid
8199: A word list is identified by a cell-sized word list identifier (@i{wid})
8200: in much the same way as a file is identified by a file handle. The
8201: numerical value of the wid has no (portable) meaning, and might change
8202: from session to session.
1.1 anton 8203:
1.29 crook 8204: The ANS Forth ``Search order'' word set is intended to provide a set of
8205: low-level tools that allow various different schemes to be
1.74 anton 8206: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8207: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8208: Forth.
1.1 anton 8209:
1.27 crook 8210: @comment TODO: locals section refers to here, saying that every word list (aka
8211: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8212: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8213:
1.45 crook 8214: @comment TODO: document markers, reveal, tables, mappedwordlist
8215:
8216: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8217: @comment word from the source files, rather than some alias.
1.44 crook 8218:
1.26 crook 8219: doc-forth-wordlist
8220: doc-definitions
8221: doc-get-current
8222: doc-set-current
8223: doc-get-order
1.185 anton 8224: doc-set-order
1.26 crook 8225: doc-wordlist
1.30 anton 8226: doc-table
1.79 anton 8227: doc->order
1.36 anton 8228: doc-previous
1.26 crook 8229: doc-also
1.185 anton 8230: doc-forth
1.26 crook 8231: doc-only
1.185 anton 8232: doc-order
1.15 anton 8233:
1.26 crook 8234: doc-find
8235: doc-search-wordlist
1.15 anton 8236:
1.26 crook 8237: doc-words
8238: doc-vlist
1.44 crook 8239: @c doc-words-deferred
1.1 anton 8240:
1.74 anton 8241: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8242: doc-root
8243: doc-vocabulary
8244: doc-seal
8245: doc-vocs
8246: doc-current
8247: doc-context
1.1 anton 8248:
1.44 crook 8249:
1.26 crook 8250: @menu
1.75 anton 8251: * Vocabularies::
1.67 anton 8252: * Why use word lists?::
1.75 anton 8253: * Word list example::
1.26 crook 8254: @end menu
8255:
1.75 anton 8256: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8257: @subsection Vocabularies
8258: @cindex Vocabularies, detailed explanation
8259:
8260: Here is an example of creating and using a new wordlist using ANS
8261: Forth words:
8262:
8263: @example
8264: wordlist constant my-new-words-wordlist
8265: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8266:
8267: \ add it to the search order
8268: also my-new-words
8269:
8270: \ alternatively, add it to the search order and make it
8271: \ the compilation word list
8272: also my-new-words definitions
8273: \ type "order" to see the problem
8274: @end example
8275:
8276: The problem with this example is that @code{order} has no way to
8277: associate the name @code{my-new-words} with the wid of the word list (in
8278: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8279: that has no associated name). There is no Standard way of associating a
8280: name with a wid.
8281:
8282: In Gforth, this example can be re-coded using @code{vocabulary}, which
8283: associates a name with a wid:
8284:
8285: @example
8286: vocabulary my-new-words
8287:
8288: \ add it to the search order
8289: also my-new-words
8290:
8291: \ alternatively, add it to the search order and make it
8292: \ the compilation word list
8293: my-new-words definitions
8294: \ type "order" to see that the problem is solved
8295: @end example
8296:
8297:
8298: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8299: @subsection Why use word lists?
8300: @cindex word lists - why use them?
8301:
1.74 anton 8302: Here are some reasons why people use wordlists:
1.26 crook 8303:
8304: @itemize @bullet
1.74 anton 8305:
8306: @c anton: Gforth's hashing implementation makes the search speed
8307: @c independent from the number of words. But it is linear with the number
8308: @c of wordlists that have to be searched, so in effect using more wordlists
8309: @c actually slows down compilation.
8310:
8311: @c @item
8312: @c To improve compilation speed by reducing the number of header space
8313: @c entries that must be searched. This is achieved by creating a new
8314: @c word list that contains all of the definitions that are used in the
8315: @c definition of a Forth system but which would not usually be used by
8316: @c programs running on that system. That word list would be on the search
8317: @c list when the Forth system was compiled but would be removed from the
8318: @c search list for normal operation. This can be a useful technique for
8319: @c low-performance systems (for example, 8-bit processors in embedded
8320: @c systems) but is unlikely to be necessary in high-performance desktop
8321: @c systems.
8322:
1.26 crook 8323: @item
8324: To prevent a set of words from being used outside the context in which
8325: they are valid. Two classic examples of this are an integrated editor
8326: (all of the edit commands are defined in a separate word list; the
8327: search order is set to the editor word list when the editor is invoked;
8328: the old search order is restored when the editor is terminated) and an
8329: integrated assembler (the op-codes for the machine are defined in a
8330: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8331:
8332: @item
8333: To organize the words of an application or library into a user-visible
8334: set (in @code{forth-wordlist} or some other common wordlist) and a set
8335: of helper words used just for the implementation (hidden in a separate
1.75 anton 8336: wordlist). This keeps @code{words}' output smaller, separates
8337: implementation and interface, and reduces the chance of name conflicts
8338: within the common wordlist.
1.74 anton 8339:
1.26 crook 8340: @item
8341: To prevent a name-space clash between multiple definitions with the same
8342: name. For example, when building a cross-compiler you might have a word
8343: @code{IF} that generates conditional code for your target system. By
8344: placing this definition in a different word list you can control whether
8345: the host system's @code{IF} or the target system's @code{IF} get used in
8346: any particular context by controlling the order of the word lists on the
8347: search order stack.
1.74 anton 8348:
1.26 crook 8349: @end itemize
1.1 anton 8350:
1.74 anton 8351: The downsides of using wordlists are:
8352:
8353: @itemize
8354:
8355: @item
8356: Debugging becomes more cumbersome.
8357:
8358: @item
8359: Name conflicts worked around with wordlists are still there, and you
8360: have to arrange the search order carefully to get the desired results;
8361: if you forget to do that, you get hard-to-find errors (as in any case
8362: where you read the code differently from the compiler; @code{see} can
1.75 anton 8363: help seeing which of several possible words the name resolves to in such
8364: cases). @code{See} displays just the name of the words, not what
8365: wordlist they belong to, so it might be misleading. Using unique names
8366: is a better approach to avoid name conflicts.
1.74 anton 8367:
8368: @item
8369: You have to explicitly undo any changes to the search order. In many
8370: cases it would be more convenient if this happened implicitly. Gforth
8371: currently does not provide such a feature, but it may do so in the
8372: future.
8373: @end itemize
8374:
8375:
1.75 anton 8376: @node Word list example, , Why use word lists?, Word Lists
8377: @subsection Word list example
8378: @cindex word lists - example
1.1 anton 8379:
1.74 anton 8380: The following example is from the
8381: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8382: garbage collector} and uses wordlists to separate public words from
8383: helper words:
8384:
8385: @example
8386: get-current ( wid )
8387: vocabulary garbage-collector also garbage-collector definitions
8388: ... \ define helper words
8389: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8390: ... \ define the public (i.e., API) words
8391: \ they can refer to the helper words
8392: previous \ restore original search order (helper words become invisible)
8393: @end example
8394:
1.26 crook 8395: @c -------------------------------------------------------------
8396: @node Environmental Queries, Files, Word Lists, Words
8397: @section Environmental Queries
8398: @cindex environmental queries
1.21 crook 8399:
1.26 crook 8400: ANS Forth introduced the idea of ``environmental queries'' as a way
8401: for a program running on a system to determine certain characteristics of the system.
8402: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8403:
1.32 anton 8404: The Standard requires that the header space used for environmental queries
8405: be distinct from the header space used for definitions.
1.21 crook 8406:
1.26 crook 8407: Typically, environmental queries are supported by creating a set of
1.29 crook 8408: definitions in a word list that is @i{only} used during environmental
1.26 crook 8409: queries; that is what Gforth does. There is no Standard way of adding
8410: definitions to the set of recognised environmental queries, but any
8411: implementation that supports the loading of optional word sets must have
8412: some mechanism for doing this (after loading the word set, the
8413: associated environmental query string must return @code{true}). In
8414: Gforth, the word list used to honour environmental queries can be
8415: manipulated just like any other word list.
1.21 crook 8416:
1.44 crook 8417:
1.26 crook 8418: doc-environment?
8419: doc-environment-wordlist
1.21 crook 8420:
1.26 crook 8421: doc-gforth
8422: doc-os-class
1.21 crook 8423:
1.44 crook 8424:
1.26 crook 8425: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8426: returning two items on the stack, querying it using @code{environment?}
8427: will return an additional item; the @code{true} flag that shows that the
8428: string was recognised.
1.21 crook 8429:
1.26 crook 8430: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8431:
1.26 crook 8432: Here are some examples of using environmental queries:
1.21 crook 8433:
1.26 crook 8434: @example
8435: s" address-unit-bits" environment? 0=
8436: [IF]
8437: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8438: [ELSE]
8439: drop \ ensure balanced stack effect
1.26 crook 8440: [THEN]
1.21 crook 8441:
1.75 anton 8442: \ this might occur in the prelude of a standard program that uses THROW
8443: s" exception" environment? [IF]
8444: 0= [IF]
8445: : throw abort" exception thrown" ;
8446: [THEN]
8447: [ELSE] \ we don't know, so make sure
8448: : throw abort" exception thrown" ;
8449: [THEN]
1.21 crook 8450:
1.26 crook 8451: s" gforth" environment? [IF] .( Gforth version ) TYPE
8452: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8453:
8454: \ a program using v*
8455: s" gforth" environment? [IF]
8456: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8457: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8458: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8459: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8460: LOOP
8461: 2drop 2drop ;
8462: [THEN]
8463: [ELSE] \
8464: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8465: ...
8466: [THEN]
1.26 crook 8467: @end example
1.21 crook 8468:
1.26 crook 8469: Here is an example of adding a definition to the environment word list:
1.21 crook 8470:
1.26 crook 8471: @example
8472: get-current environment-wordlist set-current
8473: true constant block
8474: true constant block-ext
8475: set-current
8476: @end example
1.21 crook 8477:
1.26 crook 8478: You can see what definitions are in the environment word list like this:
1.21 crook 8479:
1.26 crook 8480: @example
1.79 anton 8481: environment-wordlist >order words previous
1.26 crook 8482: @end example
1.21 crook 8483:
8484:
1.26 crook 8485: @c -------------------------------------------------------------
8486: @node Files, Blocks, Environmental Queries, Words
8487: @section Files
1.28 crook 8488: @cindex files
8489: @cindex I/O - file-handling
1.21 crook 8490:
1.26 crook 8491: Gforth provides facilities for accessing files that are stored in the
8492: host operating system's file-system. Files that are processed by Gforth
8493: can be divided into two categories:
1.21 crook 8494:
1.23 crook 8495: @itemize @bullet
8496: @item
1.29 crook 8497: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8498: @item
1.29 crook 8499: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8500: @end itemize
8501:
8502: @menu
1.48 anton 8503: * Forth source files::
8504: * General files::
1.167 anton 8505: * Redirection::
1.48 anton 8506: * Search Paths::
1.26 crook 8507: @end menu
8508:
8509: @c -------------------------------------------------------------
8510: @node Forth source files, General files, Files, Files
8511: @subsection Forth source files
8512: @cindex including files
8513: @cindex Forth source files
1.21 crook 8514:
1.26 crook 8515: The simplest way to interpret the contents of a file is to use one of
8516: these two formats:
1.21 crook 8517:
1.26 crook 8518: @example
8519: include mysource.fs
8520: s" mysource.fs" included
8521: @end example
1.21 crook 8522:
1.75 anton 8523: You usually want to include a file only if it is not included already
1.26 crook 8524: (by, say, another source file). In that case, you can use one of these
1.45 crook 8525: three formats:
1.21 crook 8526:
1.26 crook 8527: @example
8528: require mysource.fs
8529: needs mysource.fs
8530: s" mysource.fs" required
8531: @end example
1.21 crook 8532:
1.26 crook 8533: @cindex stack effect of included files
8534: @cindex including files, stack effect
1.45 crook 8535: It is good practice to write your source files such that interpreting them
8536: does not change the stack. Source files designed in this way can be used with
1.26 crook 8537: @code{required} and friends without complications. For example:
1.21 crook 8538:
1.26 crook 8539: @example
1.75 anton 8540: 1024 require foo.fs drop
1.26 crook 8541: @end example
1.21 crook 8542:
1.75 anton 8543: Here you want to pass the argument 1024 (e.g., a buffer size) to
8544: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8545: ), which allows its use with @code{require}. Of course with such
8546: parameters to required files, you have to ensure that the first
8547: @code{require} fits for all uses (i.e., @code{require} it early in the
8548: master load file).
1.44 crook 8549:
1.26 crook 8550: doc-include-file
8551: doc-included
1.28 crook 8552: doc-included?
1.26 crook 8553: doc-include
8554: doc-required
8555: doc-require
8556: doc-needs
1.75 anton 8557: @c doc-init-included-files @c internal
8558: doc-sourcefilename
8559: doc-sourceline#
1.44 crook 8560:
1.26 crook 8561: A definition in ANS Forth for @code{required} is provided in
8562: @file{compat/required.fs}.
1.21 crook 8563:
1.26 crook 8564: @c -------------------------------------------------------------
1.167 anton 8565: @node General files, Redirection, Forth source files, Files
1.26 crook 8566: @subsection General files
8567: @cindex general files
8568: @cindex file-handling
1.21 crook 8569:
1.75 anton 8570: Files are opened/created by name and type. The following file access
8571: methods (FAMs) are recognised:
1.44 crook 8572:
1.75 anton 8573: @cindex fam (file access method)
1.26 crook 8574: doc-r/o
8575: doc-r/w
8576: doc-w/o
8577: doc-bin
1.1 anton 8578:
1.44 crook 8579:
1.26 crook 8580: When a file is opened/created, it returns a file identifier,
1.29 crook 8581: @i{wfileid} that is used for all other file commands. All file
8582: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8583: successful operation and an implementation-defined non-zero value in the
8584: case of an error.
1.21 crook 8585:
1.44 crook 8586:
1.26 crook 8587: doc-open-file
8588: doc-create-file
1.21 crook 8589:
1.26 crook 8590: doc-close-file
8591: doc-delete-file
8592: doc-rename-file
8593: doc-read-file
8594: doc-read-line
1.154 anton 8595: doc-key-file
8596: doc-key?-file
1.26 crook 8597: doc-write-file
8598: doc-write-line
8599: doc-emit-file
8600: doc-flush-file
1.21 crook 8601:
1.26 crook 8602: doc-file-status
8603: doc-file-position
8604: doc-reposition-file
8605: doc-file-size
8606: doc-resize-file
1.21 crook 8607:
1.93 anton 8608: doc-slurp-file
8609: doc-slurp-fid
1.112 anton 8610: doc-stdin
8611: doc-stdout
8612: doc-stderr
1.44 crook 8613:
1.26 crook 8614: @c ---------------------------------------------------------
1.167 anton 8615: @node Redirection, Search Paths, General files, Files
8616: @subsection Redirection
8617: @cindex Redirection
8618: @cindex Input Redirection
8619: @cindex Output Redirection
8620:
8621: You can redirect the output of @code{type} and @code{emit} and all the
8622: words that use them (all output words that don't have an explicit
1.174 anton 8623: target file) to an arbitrary file with the @code{outfile-execute},
8624: used like this:
1.167 anton 8625:
8626: @example
1.174 anton 8627: : some-warning ( n -- )
8628: cr ." warning# " . ;
8629:
1.167 anton 8630: : print-some-warning ( n -- )
1.174 anton 8631: ['] some-warning stderr outfile-execute ;
1.167 anton 8632: @end example
8633:
1.174 anton 8634: After @code{some-warning} is executed, the original output direction
8635: is restored; this construct is safe against exceptions. Similarly,
8636: there is @code{infile-execute} for redirecting the input of @code{key}
8637: and its users (any input word that does not take a file explicitly).
8638:
8639: doc-outfile-execute
8640: doc-infile-execute
1.167 anton 8641:
8642: If you do not want to redirect the input or output to a file, you can
8643: also make use of the fact that @code{key}, @code{emit} and @code{type}
8644: are deferred words (@pxref{Deferred Words}). However, in that case
8645: you have to worry about the restoration and the protection against
8646: exceptions yourself; also, note that for redirecting the output in
8647: this way, you have to redirect both @code{emit} and @code{type}.
8648:
8649: @c ---------------------------------------------------------
8650: @node Search Paths, , Redirection, Files
1.26 crook 8651: @subsection Search Paths
8652: @cindex path for @code{included}
8653: @cindex file search path
8654: @cindex @code{include} search path
8655: @cindex search path for files
1.21 crook 8656:
1.26 crook 8657: If you specify an absolute filename (i.e., a filename starting with
8658: @file{/} or @file{~}, or with @file{:} in the second position (as in
8659: @samp{C:...})) for @code{included} and friends, that file is included
8660: just as you would expect.
1.21 crook 8661:
1.75 anton 8662: If the filename starts with @file{./}, this refers to the directory that
8663: the present file was @code{included} from. This allows files to include
8664: other files relative to their own position (irrespective of the current
8665: working directory or the absolute position). This feature is essential
8666: for libraries consisting of several files, where a file may include
8667: other files from the library. It corresponds to @code{#include "..."}
8668: in C. If the current input source is not a file, @file{.} refers to the
8669: directory of the innermost file being included, or, if there is no file
8670: being included, to the current working directory.
8671:
8672: For relative filenames (not starting with @file{./}), Gforth uses a
8673: search path similar to Forth's search order (@pxref{Word Lists}). It
8674: tries to find the given filename in the directories present in the path,
8675: and includes the first one it finds. There are separate search paths for
8676: Forth source files and general files. If the search path contains the
8677: directory @file{.}, this refers to the directory of the current file, or
8678: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8679:
1.26 crook 8680: Use @file{~+} to refer to the current working directory (as in the
8681: @code{bash}).
1.1 anton 8682:
1.75 anton 8683: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8684:
1.48 anton 8685: @menu
1.75 anton 8686: * Source Search Paths::
1.48 anton 8687: * General Search Paths::
8688: @end menu
8689:
1.26 crook 8690: @c ---------------------------------------------------------
1.75 anton 8691: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8692: @subsubsection Source Search Paths
8693: @cindex search path control, source files
1.5 anton 8694:
1.26 crook 8695: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8696: Gforth}). You can display it and change it using @code{fpath} in
8697: combination with the general path handling words.
1.5 anton 8698:
1.75 anton 8699: doc-fpath
8700: @c the functionality of the following words is easily available through
8701: @c fpath and the general path words. The may go away.
8702: @c doc-.fpath
8703: @c doc-fpath+
8704: @c doc-fpath=
8705: @c doc-open-fpath-file
1.44 crook 8706:
8707: @noindent
1.26 crook 8708: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8709:
1.26 crook 8710: @example
1.75 anton 8711: fpath path= /usr/lib/forth/|./
1.26 crook 8712: require timer.fs
8713: @end example
1.5 anton 8714:
1.75 anton 8715:
1.26 crook 8716: @c ---------------------------------------------------------
1.75 anton 8717: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8718: @subsubsection General Search Paths
1.75 anton 8719: @cindex search path control, source files
1.5 anton 8720:
1.26 crook 8721: Your application may need to search files in several directories, like
8722: @code{included} does. To facilitate this, Gforth allows you to define
8723: and use your own search paths, by providing generic equivalents of the
8724: Forth search path words:
1.5 anton 8725:
1.75 anton 8726: doc-open-path-file
8727: doc-path-allot
8728: doc-clear-path
8729: doc-also-path
1.26 crook 8730: doc-.path
8731: doc-path+
8732: doc-path=
1.5 anton 8733:
1.75 anton 8734: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8735:
1.75 anton 8736: Here's an example of creating an empty search path:
8737: @c
1.26 crook 8738: @example
1.75 anton 8739: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8740: @end example
1.5 anton 8741:
1.26 crook 8742: @c -------------------------------------------------------------
8743: @node Blocks, Other I/O, Files, Words
8744: @section Blocks
1.28 crook 8745: @cindex I/O - blocks
8746: @cindex blocks
8747:
8748: When you run Gforth on a modern desk-top computer, it runs under the
8749: control of an operating system which provides certain services. One of
8750: these services is @var{file services}, which allows Forth source code
8751: and data to be stored in files and read into Gforth (@pxref{Files}).
8752:
8753: Traditionally, Forth has been an important programming language on
8754: systems where it has interfaced directly to the underlying hardware with
8755: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8756: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8757:
8758: A block is a 1024-byte data area, which can be used to hold data or
8759: Forth source code. No structure is imposed on the contents of the
8760: block. A block is identified by its number; blocks are numbered
8761: contiguously from 1 to an implementation-defined maximum.
8762:
8763: A typical system that used blocks but no operating system might use a
8764: single floppy-disk drive for mass storage, with the disks formatted to
8765: provide 256-byte sectors. Blocks would be implemented by assigning the
8766: first four sectors of the disk to block 1, the second four sectors to
8767: block 2 and so on, up to the limit of the capacity of the disk. The disk
8768: would not contain any file system information, just the set of blocks.
8769:
1.29 crook 8770: @cindex blocks file
1.28 crook 8771: On systems that do provide file services, blocks are typically
1.29 crook 8772: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8773: file}. The size of the blocks file will be an exact multiple of 1024
8774: bytes, corresponding to the number of blocks it contains. This is the
8775: mechanism that Gforth uses.
8776:
1.29 crook 8777: @cindex @file{blocks.fb}
1.75 anton 8778: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8779: having specified a blocks file, Gforth defaults to the blocks file
8780: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8781: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8782:
1.29 crook 8783: @cindex block buffers
1.28 crook 8784: When you read and write blocks under program control, Gforth uses a
1.29 crook 8785: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8786: not used when you use @code{load} to interpret the contents of a block.
8787:
1.75 anton 8788: The behaviour of the block buffers is analagous to that of a cache.
8789: Each block buffer has three states:
1.28 crook 8790:
8791: @itemize @bullet
8792: @item
8793: Unassigned
8794: @item
8795: Assigned-clean
8796: @item
8797: Assigned-dirty
8798: @end itemize
8799:
1.29 crook 8800: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8801: block, the block (specified by its block number) must be assigned to a
8802: block buffer.
8803:
8804: The assignment of a block to a block buffer is performed by @code{block}
8805: or @code{buffer}. Use @code{block} when you wish to modify the existing
8806: contents of a block. Use @code{buffer} when you don't care about the
8807: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8808: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8809: with the particular block is already stored in a block buffer due to an
8810: earlier @code{block} command, @code{buffer} will return that block
8811: buffer and the existing contents of the block will be
8812: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8813: block buffer for the block.}.
1.28 crook 8814:
1.47 crook 8815: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8816: @code{buffer}, that block buffer becomes the @i{current block
8817: buffer}. Data may only be manipulated (read or written) within the
8818: current block buffer.
1.47 crook 8819:
8820: When the contents of the current block buffer has been modified it is
1.48 anton 8821: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8822: either abandon the changes (by doing nothing) or mark the block as
8823: changed (assigned-dirty), using @code{update}. Using @code{update} does
8824: not change the blocks file; it simply changes a block buffer's state to
8825: @i{assigned-dirty}. The block will be written implicitly when it's
8826: buffer is needed for another block, or explicitly by @code{flush} or
8827: @code{save-buffers}.
8828:
8829: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8830: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8831: @code{flush}.
1.28 crook 8832:
1.29 crook 8833: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8834: algorithm to assign a block buffer to a block. That means that any
8835: particular block can only be assigned to one specific block buffer,
1.29 crook 8836: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8837: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8838: the new block immediately. If it is @i{assigned-dirty} its current
8839: contents are written back to the blocks file on disk before it is
1.28 crook 8840: allocated to the new block.
8841:
8842: Although no structure is imposed on the contents of a block, it is
8843: traditional to display the contents as 16 lines each of 64 characters. A
8844: block provides a single, continuous stream of input (for example, it
8845: acts as a single parse area) -- there are no end-of-line characters
8846: within a block, and no end-of-file character at the end of a
8847: block. There are two consequences of this:
1.26 crook 8848:
1.28 crook 8849: @itemize @bullet
8850: @item
8851: The last character of one line wraps straight into the first character
8852: of the following line
8853: @item
8854: The word @code{\} -- comment to end of line -- requires special
8855: treatment; in the context of a block it causes all characters until the
8856: end of the current 64-character ``line'' to be ignored.
8857: @end itemize
8858:
8859: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8860: the current blocks file will be extended to the appropriate size and the
1.28 crook 8861: block buffer will be initialised with spaces.
8862:
1.47 crook 8863: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8864: for details) but doesn't encourage the use of blocks; the mechanism is
8865: only provided for backward compatibility -- ANS Forth requires blocks to
8866: be available when files are.
1.28 crook 8867:
8868: Common techniques that are used when working with blocks include:
8869:
8870: @itemize @bullet
8871: @item
8872: A screen editor that allows you to edit blocks without leaving the Forth
8873: environment.
8874: @item
8875: Shadow screens; where every code block has an associated block
8876: containing comments (for example: code in odd block numbers, comments in
8877: even block numbers). Typically, the block editor provides a convenient
8878: mechanism to toggle between code and comments.
8879: @item
8880: Load blocks; a single block (typically block 1) contains a number of
8881: @code{thru} commands which @code{load} the whole of the application.
8882: @end itemize
1.26 crook 8883:
1.29 crook 8884: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8885: integrated into a Forth programming environment.
1.26 crook 8886:
8887: @comment TODO what about errors on open-blocks?
1.44 crook 8888:
1.26 crook 8889: doc-open-blocks
8890: doc-use
1.75 anton 8891: doc-block-offset
1.26 crook 8892: doc-get-block-fid
8893: doc-block-position
1.28 crook 8894:
1.75 anton 8895: doc-list
1.28 crook 8896: doc-scr
8897:
1.184 anton 8898: doc-block
1.28 crook 8899: doc-buffer
8900:
1.75 anton 8901: doc-empty-buffers
8902: doc-empty-buffer
1.26 crook 8903: doc-update
1.28 crook 8904: doc-updated?
1.26 crook 8905: doc-save-buffers
1.75 anton 8906: doc-save-buffer
1.26 crook 8907: doc-flush
1.28 crook 8908:
1.26 crook 8909: doc-load
8910: doc-thru
8911: doc-+load
8912: doc-+thru
1.45 crook 8913: doc---gforthman--->
1.26 crook 8914: doc-block-included
8915:
1.44 crook 8916:
1.26 crook 8917: @c -------------------------------------------------------------
1.126 pazsan 8918: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8919: @section Other I/O
1.28 crook 8920: @cindex I/O - keyboard and display
1.26 crook 8921:
8922: @menu
8923: * Simple numeric output:: Predefined formats
8924: * Formatted numeric output:: Formatted (pictured) output
8925: * String Formats:: How Forth stores strings in memory
1.67 anton 8926: * Displaying characters and strings:: Other stuff
1.175 anton 8927: * Terminal output:: Cursor positioning etc.
1.181 anton 8928: * Single-key input::
8929: * Line input and conversion::
1.112 anton 8930: * Pipes:: How to create your own pipes
1.149 pazsan 8931: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8932: @end menu
8933:
8934: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8935: @subsection Simple numeric output
1.28 crook 8936: @cindex numeric output - simple/free-format
1.5 anton 8937:
1.26 crook 8938: The simplest output functions are those that display numbers from the
8939: data or floating-point stacks. Floating-point output is always displayed
8940: using base 10. Numbers displayed from the data stack use the value stored
8941: in @code{base}.
1.5 anton 8942:
1.44 crook 8943:
1.26 crook 8944: doc-.
8945: doc-dec.
8946: doc-hex.
8947: doc-u.
8948: doc-.r
8949: doc-u.r
8950: doc-d.
8951: doc-ud.
8952: doc-d.r
8953: doc-ud.r
8954: doc-f.
8955: doc-fe.
8956: doc-fs.
1.111 anton 8957: doc-f.rdp
1.44 crook 8958:
1.26 crook 8959: Examples of printing the number 1234.5678E23 in the different floating-point output
8960: formats are shown below:
1.5 anton 8961:
8962: @example
1.26 crook 8963: f. 123456779999999000000000000.
8964: fe. 123.456779999999E24
8965: fs. 1.23456779999999E26
1.5 anton 8966: @end example
8967:
8968:
1.26 crook 8969: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8970: @subsection Formatted numeric output
1.28 crook 8971: @cindex formatted numeric output
1.26 crook 8972: @cindex pictured numeric output
1.28 crook 8973: @cindex numeric output - formatted
1.26 crook 8974:
1.29 crook 8975: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8976: output} for formatted printing of integers. In this technique, digits
8977: are extracted from the number (using the current output radix defined by
8978: @code{base}), converted to ASCII codes and appended to a string that is
8979: built in a scratch-pad area of memory (@pxref{core-idef,
8980: Implementation-defined options, Implementation-defined
8981: options}). Arbitrary characters can be appended to the string during the
8982: extraction process. The completed string is specified by an address
8983: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8984: under program control.
1.5 anton 8985:
1.75 anton 8986: All of the integer output words described in the previous section
8987: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8988: numeric output.
1.5 anton 8989:
1.47 crook 8990: Three important things to remember about pictured numeric output:
1.5 anton 8991:
1.26 crook 8992: @itemize @bullet
8993: @item
1.28 crook 8994: It always operates on double-precision numbers; to display a
1.49 anton 8995: single-precision number, convert it first (for ways of doing this
8996: @pxref{Double precision}).
1.26 crook 8997: @item
1.28 crook 8998: It always treats the double-precision number as though it were
8999: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 9000: @item
9001: The string is built up from right to left; least significant digit first.
9002: @end itemize
1.5 anton 9003:
1.44 crook 9004:
1.26 crook 9005: doc-<#
1.47 crook 9006: doc-<<#
1.26 crook 9007: doc-#
9008: doc-#s
9009: doc-hold
9010: doc-sign
9011: doc-#>
1.47 crook 9012: doc-#>>
1.5 anton 9013:
1.26 crook 9014: doc-represent
1.111 anton 9015: doc-f>str-rdp
9016: doc-f>buf-rdp
1.5 anton 9017:
1.44 crook 9018:
9019: @noindent
1.26 crook 9020: Here are some examples of using pictured numeric output:
1.5 anton 9021:
9022: @example
1.26 crook 9023: : my-u. ( u -- )
9024: \ Simplest use of pns.. behaves like Standard u.
9025: 0 \ convert to unsigned double
1.75 anton 9026: <<# \ start conversion
1.26 crook 9027: #s \ convert all digits
9028: #> \ complete conversion
1.75 anton 9029: TYPE SPACE \ display, with trailing space
9030: #>> ; \ release hold area
1.5 anton 9031:
1.26 crook 9032: : cents-only ( u -- )
9033: 0 \ convert to unsigned double
1.75 anton 9034: <<# \ start conversion
1.26 crook 9035: # # \ convert two least-significant digits
9036: #> \ complete conversion, discard other digits
1.75 anton 9037: TYPE SPACE \ display, with trailing space
9038: #>> ; \ release hold area
1.5 anton 9039:
1.26 crook 9040: : dollars-and-cents ( u -- )
9041: 0 \ convert to unsigned double
1.75 anton 9042: <<# \ start conversion
1.26 crook 9043: # # \ convert two least-significant digits
9044: [char] . hold \ insert decimal point
9045: #s \ convert remaining digits
9046: [char] $ hold \ append currency symbol
9047: #> \ complete conversion
1.75 anton 9048: TYPE SPACE \ display, with trailing space
9049: #>> ; \ release hold area
1.5 anton 9050:
1.26 crook 9051: : my-. ( n -- )
9052: \ handling negatives.. behaves like Standard .
9053: s>d \ convert to signed double
9054: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9055: <<# \ start conversion
1.26 crook 9056: #s \ convert all digits
9057: rot sign \ get at sign byte, append "-" if needed
9058: #> \ complete conversion
1.75 anton 9059: TYPE SPACE \ display, with trailing space
9060: #>> ; \ release hold area
1.5 anton 9061:
1.26 crook 9062: : account. ( n -- )
1.75 anton 9063: \ accountants don't like minus signs, they use parentheses
1.26 crook 9064: \ for negative numbers
9065: s>d \ convert to signed double
9066: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9067: <<# \ start conversion
1.26 crook 9068: 2 pick \ get copy of sign byte
9069: 0< IF [char] ) hold THEN \ right-most character of output
9070: #s \ convert all digits
9071: rot \ get at sign byte
9072: 0< IF [char] ( hold THEN
9073: #> \ complete conversion
1.75 anton 9074: TYPE SPACE \ display, with trailing space
9075: #>> ; \ release hold area
9076:
1.5 anton 9077: @end example
9078:
1.26 crook 9079: Here are some examples of using these words:
1.5 anton 9080:
9081: @example
1.26 crook 9082: 1 my-u. 1
9083: hex -1 my-u. decimal FFFFFFFF
9084: 1 cents-only 01
9085: 1234 cents-only 34
9086: 2 dollars-and-cents $0.02
9087: 1234 dollars-and-cents $12.34
9088: 123 my-. 123
9089: -123 my. -123
9090: 123 account. 123
9091: -456 account. (456)
1.5 anton 9092: @end example
9093:
9094:
1.26 crook 9095: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
9096: @subsection String Formats
1.27 crook 9097: @cindex strings - see character strings
9098: @cindex character strings - formats
1.28 crook 9099: @cindex I/O - see character strings
1.75 anton 9100: @cindex counted strings
9101:
9102: @c anton: this does not really belong here; maybe the memory section,
9103: @c or the principles chapter
1.26 crook 9104:
1.27 crook 9105: Forth commonly uses two different methods for representing character
9106: strings:
1.26 crook 9107:
9108: @itemize @bullet
9109: @item
9110: @cindex address of counted string
1.45 crook 9111: @cindex counted string
1.29 crook 9112: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9113: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9114: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9115: memory.
9116: @item
1.29 crook 9117: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9118: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9119: first byte of the string.
9120: @end itemize
9121:
9122: ANS Forth encourages the use of the second format when representing
1.75 anton 9123: strings.
1.26 crook 9124:
1.44 crook 9125:
1.26 crook 9126: doc-count
9127:
1.44 crook 9128:
1.49 anton 9129: For words that move, copy and search for strings see @ref{Memory
9130: Blocks}. For words that display characters and strings see
9131: @ref{Displaying characters and strings}.
1.26 crook 9132:
1.175 anton 9133: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9134: @subsection Displaying characters and strings
1.27 crook 9135: @cindex characters - compiling and displaying
9136: @cindex character strings - compiling and displaying
1.26 crook 9137:
9138: This section starts with a glossary of Forth words and ends with a set
9139: of examples.
9140:
9141: doc-bl
9142: doc-space
9143: doc-spaces
9144: doc-emit
9145: doc-toupper
9146: doc-."
9147: doc-.(
1.98 anton 9148: doc-.\"
1.26 crook 9149: doc-type
1.44 crook 9150: doc-typewhite
1.26 crook 9151: doc-cr
1.27 crook 9152: @cindex cursor control
1.26 crook 9153: doc-s"
1.98 anton 9154: doc-s\"
1.26 crook 9155: doc-c"
9156: doc-char
9157: doc-[char]
9158:
1.44 crook 9159:
9160: @noindent
1.26 crook 9161: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9162:
9163: @example
1.26 crook 9164: .( text-1)
9165: : my-word
9166: ." text-2" cr
9167: .( text-3)
9168: ;
9169:
9170: ." text-4"
9171:
9172: : my-char
9173: [char] ALPHABET emit
9174: char emit
9175: ;
1.5 anton 9176: @end example
9177:
1.26 crook 9178: When you load this code into Gforth, the following output is generated:
1.5 anton 9179:
1.26 crook 9180: @example
1.30 anton 9181: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9182: @end example
1.5 anton 9183:
1.26 crook 9184: @itemize @bullet
9185: @item
9186: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9187: is an immediate word; it behaves in the same way whether it is used inside
9188: or outside a colon definition.
9189: @item
9190: Message @code{text-4} is displayed because of Gforth's added interpretation
9191: semantics for @code{."}.
9192: @item
1.29 crook 9193: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9194: performs the compilation semantics for @code{."} within the definition of
9195: @code{my-word}.
9196: @end itemize
1.5 anton 9197:
1.26 crook 9198: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9199:
1.26 crook 9200: @example
1.30 anton 9201: @kbd{my-word @key{RET}} text-2
1.26 crook 9202: ok
1.30 anton 9203: @kbd{my-char fred @key{RET}} Af ok
9204: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9205: @end example
1.5 anton 9206:
9207: @itemize @bullet
9208: @item
1.26 crook 9209: Message @code{text-2} is displayed because of the run-time behaviour of
9210: @code{."}.
9211: @item
9212: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9213: on the stack at run-time. @code{emit} always displays the character
9214: when @code{my-char} is executed.
9215: @item
9216: @code{char} parses a string at run-time and the second @code{emit} displays
9217: the first character of the string.
1.5 anton 9218: @item
1.26 crook 9219: If you type @code{see my-char} you can see that @code{[char]} discarded
9220: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9221: definition of @code{my-char}.
1.5 anton 9222: @end itemize
9223:
9224:
1.181 anton 9225: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9226: @subsection Terminal output
9227: @cindex output to terminal
9228: @cindex terminal output
9229:
9230: If you are outputting to a terminal, you may want to control the
9231: positioning of the cursor:
9232: @cindex cursor positioning
9233:
9234: doc-at-xy
9235:
9236: In order to know where to position the cursor, it is often helpful to
9237: know the size of the screen:
9238: @cindex terminal size
9239:
9240: doc-form
9241:
9242: And sometimes you want to use:
9243: @cindex clear screen
9244:
9245: doc-page
9246:
9247: Note that on non-terminals you should use @code{12 emit}, not
9248: @code{page}, to get a form feed.
9249:
1.5 anton 9250:
1.181 anton 9251: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9252: @subsection Single-key input
9253: @cindex single-key input
9254: @cindex input, single-key
9255:
9256: If you want to get a single printable character, you can use
9257: @code{key}; to check whether a character is available for @code{key},
9258: you can use @code{key?}.
1.5 anton 9259:
1.181 anton 9260: doc-key
9261: doc-key?
1.27 crook 9262:
1.181 anton 9263: If you want to process a mix of printable and non-printable
9264: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9265: produces a keyboard event that you have to convert into a character
9266: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9267:
9268: Typical code for using EKEY looks like this:
9269:
9270: @example
9271: ekey ekey>char if ( c )
9272: ... \ do something with the character
9273: else ekey>fkey if ( key-id )
9274: case
9275: k-up of ... endof
9276: k-f1 of ... endof
9277: k-left k-shift-mask or k-ctrl-mask or of ... endof
9278: ...
9279: endcase
9280: else ( keyboard-event )
9281: drop \ just ignore an unknown keyboard event type
9282: then then
9283: @end example
1.44 crook 9284:
1.45 crook 9285: doc-ekey
1.141 anton 9286: doc-ekey>char
1.181 anton 9287: doc-ekey>fkey
1.45 crook 9288: doc-ekey?
1.141 anton 9289:
1.181 anton 9290: The key identifiers for cursor keys are:
1.141 anton 9291:
9292: doc-k-left
9293: doc-k-right
1.185 anton 9294: doc-k-up
9295: doc-k-down
9296: doc-k-home
9297: doc-k-end
1.141 anton 9298: doc-k-prior
9299: doc-k-next
9300: doc-k-insert
9301: doc-k-delete
9302:
1.181 anton 9303: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9304:
1.181 anton 9305: doc-k-f1
9306: doc-k-f2
9307: doc-k-f3
9308: doc-k-f4
9309: doc-k-f5
9310: doc-k-f6
9311: doc-k-f7
9312: doc-k-f8
9313: doc-k-f9
9314: doc-k-f10
9315: doc-k-f11
9316: doc-k-f12
9317:
9318: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9319:
9320: You can combine these key identifiers with masks for various shift keys:
9321:
9322: doc-k-shift-mask
9323: doc-k-ctrl-mask
9324: doc-k-alt-mask
9325:
9326: Note that, even if a Forth system has @code{ekey>fkey} and the key
9327: identifier words, the keys are not necessarily available or it may not
9328: necessarily be able to report all the keys and all the possible
9329: combinations with shift masks. Therefore, write your programs in such
9330: a way that they are still useful even if the keys and key combinations
9331: cannot be pressed or are not recognized.
9332:
9333: Examples: Older keyboards often do not have an F11 and F12 key. If
9334: you run Gforth in an xterm, the xterm catches a number of combinations
9335: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9336: Gforth currently does not recognize and report combinations with
9337: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9338: above would never be entered).
9339:
9340: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9341: you need the ANSI.SYS driver to get that behaviour); it works by
9342: recognizing the escape sequences that ANSI terminals send when such a
9343: key is pressed. If you have a terminal that sends other escape
9344: sequences, you will not get useful results on Gforth. Other Forth
9345: systems may work in a different way.
9346:
1.200 anton 9347: Gforth also provides a few words for outputting names of function
9348: keys:
9349:
9350: doc-fkey.
9351: doc-simple-fkey-string
9352:
1.181 anton 9353:
9354: @node Line input and conversion, Pipes, Single-key input, Other I/O
9355: @subsection Line input and conversion
9356: @cindex line input from terminal
9357: @cindex input, linewise from terminal
9358: @cindex convertin strings to numbers
9359: @cindex I/O - see input
9360:
9361: For ways of storing character strings in memory see @ref{String Formats}.
9362:
9363: @comment TODO examples for >number >float accept key key? pad parse word refill
9364: @comment then index them
1.141 anton 9365:
9366: Words for inputting one line from the keyboard:
9367:
9368: doc-accept
9369: doc-edit-line
9370:
9371: Conversion words:
9372:
1.143 anton 9373: doc-s>number?
9374: doc-s>unumber?
1.26 crook 9375: doc->number
9376: doc->float
1.143 anton 9377:
1.141 anton 9378:
1.27 crook 9379: @comment obsolescent words..
1.141 anton 9380: Obsolescent input and conversion words:
9381:
1.27 crook 9382: doc-convert
1.26 crook 9383: doc-expect
1.27 crook 9384: doc-span
1.5 anton 9385:
9386:
1.181 anton 9387: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9388: @subsection Pipes
9389: @cindex pipes, creating your own
9390:
9391: In addition to using Gforth in pipes created by other processes
9392: (@pxref{Gforth in pipes}), you can create your own pipe with
9393: @code{open-pipe}, and read from or write to it.
9394:
9395: doc-open-pipe
9396: doc-close-pipe
9397:
9398: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9399: you don't catch this exception, Gforth will catch it and exit, usually
9400: silently (@pxref{Gforth in pipes}). Since you probably do not want
9401: this, you should wrap a @code{catch} or @code{try} block around the code
9402: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9403: problem yourself, and then return to regular processing.
9404:
9405: doc-broken-pipe-error
9406:
1.155 anton 9407: @node Xchars and Unicode, , Pipes, Other I/O
9408: @subsection Xchars and Unicode
1.149 pazsan 9409:
1.188 pazsan 9410: ASCII is only appropriate for the English language. Most western
9411: languages however fit somewhat into the Forth frame, since a byte is
9412: sufficient to encode the few special characters in each (though not
9413: always the same encoding can be used; latin-1 is most widely used,
9414: though). For other languages, different char-sets have to be used,
9415: several of them variable-width. Most prominent representant is
9416: UTF-8. Let's call these extended characters xchars. The primitive
9417: fixed-size characters stored as bytes are called pchars in this
9418: section.
9419:
9420: The xchar words add a few data types:
9421:
9422: @itemize
9423:
9424: @item
9425: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9426: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9427: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9428: character set can be used.
9429:
9430: @item
9431: @var{xc-addr} is the address of an xchar in memory. Alignment
9432: requirements are the same as @var{c-addr}. The memory representation of an
9433: xchar differs from the stack representation, and depends on the
9434: encoding used. An xchar may use a variable number of pchars in memory.
9435:
9436: @item
9437: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9438: @var{xc-addr}, @var{u} pchars long.
9439:
9440: @end itemize
9441:
9442: doc-xc-size
9443: doc-x-size
9444: doc-xc@+
9445: doc-xc!+?
9446: doc-xchar+
9447: doc-xchar-
9448: doc-+x/string
9449: doc-x\string-
9450: doc--trailing-garbage
9451: doc-x-width
9452: doc-xkey
9453: doc-xemit
9454:
9455: There's a new environment query
9456:
9457: doc-xchar-encoding
1.112 anton 9458:
1.121 anton 9459: @node OS command line arguments, Locals, Other I/O, Words
9460: @section OS command line arguments
9461: @cindex OS command line arguments
9462: @cindex command line arguments, OS
9463: @cindex arguments, OS command line
9464:
9465: The usual way to pass arguments to Gforth programs on the command line
9466: is via the @option{-e} option, e.g.
9467:
9468: @example
9469: gforth -e "123 456" foo.fs -e bye
9470: @end example
9471:
9472: However, you may want to interpret the command-line arguments directly.
9473: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9474: through @code{next-arg}:
1.121 anton 9475:
1.123 anton 9476: doc-next-arg
1.121 anton 9477:
1.123 anton 9478: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9479:
9480: @example
9481: : echo ( -- )
1.122 anton 9482: begin
1.123 anton 9483: next-arg 2dup 0 0 d<> while
9484: type space
9485: repeat
9486: 2drop ;
1.121 anton 9487:
9488: echo cr bye
9489: @end example
9490:
9491: This can be invoked with
9492:
9493: @example
9494: gforth echo.fs hello world
9495: @end example
1.123 anton 9496:
9497: and it will print
9498:
9499: @example
9500: hello world
9501: @end example
9502:
9503: The next lower level of dealing with the OS command line are the
9504: following words:
9505:
9506: doc-arg
9507: doc-shift-args
9508:
9509: Finally, at the lowest level Gforth provides the following words:
9510:
9511: doc-argc
9512: doc-argv
1.121 anton 9513:
1.78 anton 9514: @c -------------------------------------------------------------
1.126 pazsan 9515: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9516: @section Locals
9517: @cindex locals
9518:
9519: Local variables can make Forth programming more enjoyable and Forth
9520: programs easier to read. Unfortunately, the locals of ANS Forth are
9521: laden with restrictions. Therefore, we provide not only the ANS Forth
9522: locals wordset, but also our own, more powerful locals wordset (we
9523: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9524:
1.78 anton 9525: The ideas in this section have also been published in M. Anton Ertl,
9526: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9527: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9528:
9529: @menu
1.78 anton 9530: * Gforth locals::
9531: * ANS Forth locals::
1.5 anton 9532: @end menu
9533:
1.78 anton 9534: @node Gforth locals, ANS Forth locals, Locals, Locals
9535: @subsection Gforth locals
9536: @cindex Gforth locals
9537: @cindex locals, Gforth style
1.5 anton 9538:
1.78 anton 9539: Locals can be defined with
1.44 crook 9540:
1.78 anton 9541: @example
9542: @{ local1 local2 ... -- comment @}
9543: @end example
9544: or
9545: @example
9546: @{ local1 local2 ... @}
9547: @end example
1.5 anton 9548:
1.78 anton 9549: E.g.,
9550: @example
9551: : max @{ n1 n2 -- n3 @}
9552: n1 n2 > if
9553: n1
9554: else
9555: n2
9556: endif ;
9557: @end example
1.44 crook 9558:
1.78 anton 9559: The similarity of locals definitions with stack comments is intended. A
9560: locals definition often replaces the stack comment of a word. The order
9561: of the locals corresponds to the order in a stack comment and everything
9562: after the @code{--} is really a comment.
1.77 anton 9563:
1.78 anton 9564: This similarity has one disadvantage: It is too easy to confuse locals
9565: declarations with stack comments, causing bugs and making them hard to
9566: find. However, this problem can be avoided by appropriate coding
9567: conventions: Do not use both notations in the same program. If you do,
9568: they should be distinguished using additional means, e.g. by position.
1.77 anton 9569:
1.78 anton 9570: @cindex types of locals
9571: @cindex locals types
9572: The name of the local may be preceded by a type specifier, e.g.,
9573: @code{F:} for a floating point value:
1.5 anton 9574:
1.78 anton 9575: @example
9576: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9577: \ complex multiplication
9578: Ar Br f* Ai Bi f* f-
9579: Ar Bi f* Ai Br f* f+ ;
9580: @end example
1.44 crook 9581:
1.78 anton 9582: @cindex flavours of locals
9583: @cindex locals flavours
9584: @cindex value-flavoured locals
9585: @cindex variable-flavoured locals
9586: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9587: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9588: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9589: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9590: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9591: produces its address (which becomes invalid when the variable's scope is
9592: left). E.g., the standard word @code{emit} can be defined in terms of
9593: @code{type} like this:
1.5 anton 9594:
1.78 anton 9595: @example
9596: : emit @{ C^ char* -- @}
9597: char* 1 type ;
9598: @end example
1.5 anton 9599:
1.78 anton 9600: @cindex default type of locals
9601: @cindex locals, default type
9602: A local without type specifier is a @code{W:} local. Both flavours of
9603: locals are initialized with values from the data or FP stack.
1.44 crook 9604:
1.78 anton 9605: Currently there is no way to define locals with user-defined data
9606: structures, but we are working on it.
1.5 anton 9607:
1.78 anton 9608: Gforth allows defining locals everywhere in a colon definition. This
9609: poses the following questions:
1.5 anton 9610:
1.78 anton 9611: @menu
9612: * Where are locals visible by name?::
9613: * How long do locals live?::
9614: * Locals programming style::
9615: * Locals implementation::
9616: @end menu
1.44 crook 9617:
1.78 anton 9618: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9619: @subsubsection Where are locals visible by name?
9620: @cindex locals visibility
9621: @cindex visibility of locals
9622: @cindex scope of locals
1.5 anton 9623:
1.78 anton 9624: Basically, the answer is that locals are visible where you would expect
9625: it in block-structured languages, and sometimes a little longer. If you
9626: want to restrict the scope of a local, enclose its definition in
9627: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9628:
9629:
1.78 anton 9630: doc-scope
9631: doc-endscope
1.5 anton 9632:
9633:
1.78 anton 9634: These words behave like control structure words, so you can use them
9635: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9636: arbitrary ways.
1.77 anton 9637:
1.78 anton 9638: If you want a more exact answer to the visibility question, here's the
9639: basic principle: A local is visible in all places that can only be
9640: reached through the definition of the local@footnote{In compiler
9641: construction terminology, all places dominated by the definition of the
9642: local.}. In other words, it is not visible in places that can be reached
9643: without going through the definition of the local. E.g., locals defined
9644: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9645: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9646: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9647:
1.78 anton 9648: The reasoning behind this solution is: We want to have the locals
9649: visible as long as it is meaningful. The user can always make the
9650: visibility shorter by using explicit scoping. In a place that can
9651: only be reached through the definition of a local, the meaning of a
9652: local name is clear. In other places it is not: How is the local
9653: initialized at the control flow path that does not contain the
9654: definition? Which local is meant, if the same name is defined twice in
9655: two independent control flow paths?
1.77 anton 9656:
1.78 anton 9657: This should be enough detail for nearly all users, so you can skip the
9658: rest of this section. If you really must know all the gory details and
9659: options, read on.
1.77 anton 9660:
1.78 anton 9661: In order to implement this rule, the compiler has to know which places
9662: are unreachable. It knows this automatically after @code{AHEAD},
9663: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9664: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9665: compiler that the control flow never reaches that place. If
9666: @code{UNREACHABLE} is not used where it could, the only consequence is
9667: that the visibility of some locals is more limited than the rule above
9668: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9669: lie to the compiler), buggy code will be produced.
1.77 anton 9670:
1.5 anton 9671:
1.78 anton 9672: doc-unreachable
1.5 anton 9673:
1.23 crook 9674:
1.78 anton 9675: Another problem with this rule is that at @code{BEGIN}, the compiler
9676: does not know which locals will be visible on the incoming
9677: back-edge. All problems discussed in the following are due to this
9678: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9679: loops as examples; the discussion also applies to @code{?DO} and other
9680: loops). Perhaps the most insidious example is:
1.26 crook 9681: @example
1.78 anton 9682: AHEAD
9683: BEGIN
9684: x
9685: [ 1 CS-ROLL ] THEN
9686: @{ x @}
9687: ...
9688: UNTIL
1.26 crook 9689: @end example
1.23 crook 9690:
1.78 anton 9691: This should be legal according to the visibility rule. The use of
9692: @code{x} can only be reached through the definition; but that appears
9693: textually below the use.
9694:
9695: From this example it is clear that the visibility rules cannot be fully
9696: implemented without major headaches. Our implementation treats common
9697: cases as advertised and the exceptions are treated in a safe way: The
9698: compiler makes a reasonable guess about the locals visible after a
9699: @code{BEGIN}; if it is too pessimistic, the
9700: user will get a spurious error about the local not being defined; if the
9701: compiler is too optimistic, it will notice this later and issue a
9702: warning. In the case above the compiler would complain about @code{x}
9703: being undefined at its use. You can see from the obscure examples in
9704: this section that it takes quite unusual control structures to get the
9705: compiler into trouble, and even then it will often do fine.
1.23 crook 9706:
1.78 anton 9707: If the @code{BEGIN} is reachable from above, the most optimistic guess
9708: is that all locals visible before the @code{BEGIN} will also be
9709: visible after the @code{BEGIN}. This guess is valid for all loops that
9710: are entered only through the @code{BEGIN}, in particular, for normal
9711: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9712: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9713: compiler. When the branch to the @code{BEGIN} is finally generated by
9714: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9715: warns the user if it was too optimistic:
1.26 crook 9716: @example
1.78 anton 9717: IF
9718: @{ x @}
9719: BEGIN
9720: \ x ?
9721: [ 1 cs-roll ] THEN
9722: ...
9723: UNTIL
1.26 crook 9724: @end example
1.23 crook 9725:
1.78 anton 9726: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9727: optimistically assumes that it lives until the @code{THEN}. It notices
9728: this difference when it compiles the @code{UNTIL} and issues a
9729: warning. The user can avoid the warning, and make sure that @code{x}
9730: is not used in the wrong area by using explicit scoping:
9731: @example
9732: IF
9733: SCOPE
9734: @{ x @}
9735: ENDSCOPE
9736: BEGIN
9737: [ 1 cs-roll ] THEN
9738: ...
9739: UNTIL
9740: @end example
1.23 crook 9741:
1.78 anton 9742: Since the guess is optimistic, there will be no spurious error messages
9743: about undefined locals.
1.44 crook 9744:
1.78 anton 9745: If the @code{BEGIN} is not reachable from above (e.g., after
9746: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9747: optimistic guess, as the locals visible after the @code{BEGIN} may be
9748: defined later. Therefore, the compiler assumes that no locals are
9749: visible after the @code{BEGIN}. However, the user can use
9750: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9751: visible at the BEGIN as at the point where the top control-flow stack
9752: item was created.
1.23 crook 9753:
1.44 crook 9754:
1.78 anton 9755: doc-assume-live
1.26 crook 9756:
1.23 crook 9757:
1.78 anton 9758: @noindent
9759: E.g.,
9760: @example
9761: @{ x @}
9762: AHEAD
9763: ASSUME-LIVE
9764: BEGIN
9765: x
9766: [ 1 CS-ROLL ] THEN
9767: ...
9768: UNTIL
9769: @end example
1.44 crook 9770:
1.78 anton 9771: Other cases where the locals are defined before the @code{BEGIN} can be
9772: handled by inserting an appropriate @code{CS-ROLL} before the
9773: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9774: behind the @code{ASSUME-LIVE}).
1.23 crook 9775:
1.78 anton 9776: Cases where locals are defined after the @code{BEGIN} (but should be
9777: visible immediately after the @code{BEGIN}) can only be handled by
9778: rearranging the loop. E.g., the ``most insidious'' example above can be
9779: arranged into:
9780: @example
9781: BEGIN
9782: @{ x @}
9783: ... 0=
9784: WHILE
9785: x
9786: REPEAT
9787: @end example
1.44 crook 9788:
1.78 anton 9789: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9790: @subsubsection How long do locals live?
9791: @cindex locals lifetime
9792: @cindex lifetime of locals
1.23 crook 9793:
1.78 anton 9794: The right answer for the lifetime question would be: A local lives at
9795: least as long as it can be accessed. For a value-flavoured local this
9796: means: until the end of its visibility. However, a variable-flavoured
9797: local could be accessed through its address far beyond its visibility
9798: scope. Ultimately, this would mean that such locals would have to be
9799: garbage collected. Since this entails un-Forth-like implementation
9800: complexities, I adopted the same cowardly solution as some other
9801: languages (e.g., C): The local lives only as long as it is visible;
9802: afterwards its address is invalid (and programs that access it
9803: afterwards are erroneous).
1.23 crook 9804:
1.78 anton 9805: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9806: @subsubsection Locals programming style
9807: @cindex locals programming style
9808: @cindex programming style, locals
1.23 crook 9809:
1.78 anton 9810: The freedom to define locals anywhere has the potential to change
9811: programming styles dramatically. In particular, the need to use the
9812: return stack for intermediate storage vanishes. Moreover, all stack
9813: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9814: determined arguments) can be eliminated: If the stack items are in the
9815: wrong order, just write a locals definition for all of them; then
9816: write the items in the order you want.
1.23 crook 9817:
1.78 anton 9818: This seems a little far-fetched and eliminating stack manipulations is
9819: unlikely to become a conscious programming objective. Still, the number
9820: of stack manipulations will be reduced dramatically if local variables
9821: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9822: a traditional implementation of @code{max}).
1.23 crook 9823:
1.78 anton 9824: This shows one potential benefit of locals: making Forth programs more
9825: readable. Of course, this benefit will only be realized if the
9826: programmers continue to honour the principle of factoring instead of
9827: using the added latitude to make the words longer.
1.23 crook 9828:
1.78 anton 9829: @cindex single-assignment style for locals
9830: Using @code{TO} can and should be avoided. Without @code{TO},
9831: every value-flavoured local has only a single assignment and many
9832: advantages of functional languages apply to Forth. I.e., programs are
9833: easier to analyse, to optimize and to read: It is clear from the
9834: definition what the local stands for, it does not turn into something
9835: different later.
1.23 crook 9836:
1.78 anton 9837: E.g., a definition using @code{TO} might look like this:
9838: @example
9839: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9840: u1 u2 min 0
9841: ?do
9842: addr1 c@@ addr2 c@@ -
9843: ?dup-if
9844: unloop exit
9845: then
9846: addr1 char+ TO addr1
9847: addr2 char+ TO addr2
9848: loop
9849: u1 u2 - ;
1.26 crook 9850: @end example
1.78 anton 9851: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9852: every loop iteration. @code{strcmp} is a typical example of the
9853: readability problems of using @code{TO}. When you start reading
9854: @code{strcmp}, you think that @code{addr1} refers to the start of the
9855: string. Only near the end of the loop you realize that it is something
9856: else.
1.23 crook 9857:
1.78 anton 9858: This can be avoided by defining two locals at the start of the loop that
9859: are initialized with the right value for the current iteration.
9860: @example
9861: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9862: addr1 addr2
9863: u1 u2 min 0
9864: ?do @{ s1 s2 @}
9865: s1 c@@ s2 c@@ -
9866: ?dup-if
9867: unloop exit
9868: then
9869: s1 char+ s2 char+
9870: loop
9871: 2drop
9872: u1 u2 - ;
9873: @end example
9874: Here it is clear from the start that @code{s1} has a different value
9875: in every loop iteration.
1.23 crook 9876:
1.78 anton 9877: @node Locals implementation, , Locals programming style, Gforth locals
9878: @subsubsection Locals implementation
9879: @cindex locals implementation
9880: @cindex implementation of locals
1.23 crook 9881:
1.78 anton 9882: @cindex locals stack
9883: Gforth uses an extra locals stack. The most compelling reason for
9884: this is that the return stack is not float-aligned; using an extra stack
9885: also eliminates the problems and restrictions of using the return stack
9886: as locals stack. Like the other stacks, the locals stack grows toward
9887: lower addresses. A few primitives allow an efficient implementation:
9888:
9889:
9890: doc-@local#
9891: doc-f@local#
9892: doc-laddr#
9893: doc-lp+!#
9894: doc-lp!
9895: doc->l
9896: doc-f>l
9897:
9898:
9899: In addition to these primitives, some specializations of these
9900: primitives for commonly occurring inline arguments are provided for
9901: efficiency reasons, e.g., @code{@@local0} as specialization of
9902: @code{@@local#} for the inline argument 0. The following compiling words
9903: compile the right specialized version, or the general version, as
9904: appropriate:
1.23 crook 9905:
1.5 anton 9906:
1.107 dvdkhlng 9907: @c doc-compile-@local
9908: @c doc-compile-f@local
1.78 anton 9909: doc-compile-lp+!
1.5 anton 9910:
9911:
1.78 anton 9912: Combinations of conditional branches and @code{lp+!#} like
9913: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9914: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9915:
1.78 anton 9916: A special area in the dictionary space is reserved for keeping the
9917: local variable names. @code{@{} switches the dictionary pointer to this
9918: area and @code{@}} switches it back and generates the locals
9919: initializing code. @code{W:} etc.@ are normal defining words. This
9920: special area is cleared at the start of every colon definition.
1.5 anton 9921:
1.78 anton 9922: @cindex word list for defining locals
9923: A special feature of Gforth's dictionary is used to implement the
9924: definition of locals without type specifiers: every word list (aka
9925: vocabulary) has its own methods for searching
9926: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9927: with a special search method: When it is searched for a word, it
9928: actually creates that word using @code{W:}. @code{@{} changes the search
9929: order to first search the word list containing @code{@}}, @code{W:} etc.,
9930: and then the word list for defining locals without type specifiers.
1.5 anton 9931:
1.78 anton 9932: The lifetime rules support a stack discipline within a colon
9933: definition: The lifetime of a local is either nested with other locals
9934: lifetimes or it does not overlap them.
1.23 crook 9935:
1.78 anton 9936: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9937: pointer manipulation is generated. Between control structure words
9938: locals definitions can push locals onto the locals stack. @code{AGAIN}
9939: is the simplest of the other three control flow words. It has to
9940: restore the locals stack depth of the corresponding @code{BEGIN}
9941: before branching. The code looks like this:
9942: @format
9943: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9944: @code{branch} <begin>
9945: @end format
1.26 crook 9946:
1.78 anton 9947: @code{UNTIL} is a little more complicated: If it branches back, it
9948: must adjust the stack just like @code{AGAIN}. But if it falls through,
9949: the locals stack must not be changed. The compiler generates the
9950: following code:
9951: @format
9952: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9953: @end format
9954: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9955:
1.78 anton 9956: @code{THEN} can produce somewhat inefficient code:
9957: @format
9958: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9959: <orig target>:
9960: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9961: @end format
9962: The second @code{lp+!#} adjusts the locals stack pointer from the
9963: level at the @i{orig} point to the level after the @code{THEN}. The
9964: first @code{lp+!#} adjusts the locals stack pointer from the current
9965: level to the level at the orig point, so the complete effect is an
9966: adjustment from the current level to the right level after the
9967: @code{THEN}.
1.26 crook 9968:
1.78 anton 9969: @cindex locals information on the control-flow stack
9970: @cindex control-flow stack items, locals information
9971: In a conventional Forth implementation a dest control-flow stack entry
9972: is just the target address and an orig entry is just the address to be
9973: patched. Our locals implementation adds a word list to every orig or dest
9974: item. It is the list of locals visible (or assumed visible) at the point
9975: described by the entry. Our implementation also adds a tag to identify
9976: the kind of entry, in particular to differentiate between live and dead
9977: (reachable and unreachable) orig entries.
1.26 crook 9978:
1.78 anton 9979: A few unusual operations have to be performed on locals word lists:
1.44 crook 9980:
1.5 anton 9981:
1.78 anton 9982: doc-common-list
9983: doc-sub-list?
9984: doc-list-size
1.52 anton 9985:
9986:
1.78 anton 9987: Several features of our locals word list implementation make these
9988: operations easy to implement: The locals word lists are organised as
9989: linked lists; the tails of these lists are shared, if the lists
9990: contain some of the same locals; and the address of a name is greater
9991: than the address of the names behind it in the list.
1.5 anton 9992:
1.78 anton 9993: Another important implementation detail is the variable
9994: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9995: determine if they can be reached directly or only through the branch
9996: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9997: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9998: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9999:
1.78 anton 10000: Counted loops are similar to other loops in most respects, but
10001: @code{LEAVE} requires special attention: It performs basically the same
10002: service as @code{AHEAD}, but it does not create a control-flow stack
10003: entry. Therefore the information has to be stored elsewhere;
10004: traditionally, the information was stored in the target fields of the
10005: branches created by the @code{LEAVE}s, by organizing these fields into a
10006: linked list. Unfortunately, this clever trick does not provide enough
10007: space for storing our extended control flow information. Therefore, we
10008: introduce another stack, the leave stack. It contains the control-flow
10009: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 10010:
1.78 anton 10011: Local names are kept until the end of the colon definition, even if
10012: they are no longer visible in any control-flow path. In a few cases
10013: this may lead to increased space needs for the locals name area, but
10014: usually less than reclaiming this space would cost in code size.
1.5 anton 10015:
1.44 crook 10016:
1.78 anton 10017: @node ANS Forth locals, , Gforth locals, Locals
10018: @subsection ANS Forth locals
10019: @cindex locals, ANS Forth style
1.5 anton 10020:
1.78 anton 10021: The ANS Forth locals wordset does not define a syntax for locals, but
10022: words that make it possible to define various syntaxes. One of the
10023: possible syntaxes is a subset of the syntax we used in the Gforth locals
10024: wordset, i.e.:
1.29 crook 10025:
10026: @example
1.78 anton 10027: @{ local1 local2 ... -- comment @}
10028: @end example
10029: @noindent
10030: or
10031: @example
10032: @{ local1 local2 ... @}
1.29 crook 10033: @end example
10034:
1.78 anton 10035: The order of the locals corresponds to the order in a stack comment. The
10036: restrictions are:
1.5 anton 10037:
1.78 anton 10038: @itemize @bullet
10039: @item
10040: Locals can only be cell-sized values (no type specifiers are allowed).
10041: @item
10042: Locals can be defined only outside control structures.
10043: @item
10044: Locals can interfere with explicit usage of the return stack. For the
10045: exact (and long) rules, see the standard. If you don't use return stack
10046: accessing words in a definition using locals, you will be all right. The
10047: purpose of this rule is to make locals implementation on the return
10048: stack easier.
10049: @item
10050: The whole definition must be in one line.
10051: @end itemize
1.5 anton 10052:
1.78 anton 10053: Locals defined in ANS Forth behave like @code{VALUE}s
10054: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10055: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 10056:
1.78 anton 10057: Since the syntax above is supported by Gforth directly, you need not do
10058: anything to use it. If you want to port a program using this syntax to
10059: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10060: syntax on the other system.
1.5 anton 10061:
1.78 anton 10062: Note that a syntax shown in the standard, section A.13 looks
10063: similar, but is quite different in having the order of locals
10064: reversed. Beware!
1.5 anton 10065:
1.78 anton 10066: The ANS Forth locals wordset itself consists of one word:
1.5 anton 10067:
1.78 anton 10068: doc-(local)
1.5 anton 10069:
1.78 anton 10070: The ANS Forth locals extension wordset defines a syntax using
10071: @code{locals|}, but it is so awful that we strongly recommend not to use
10072: it. We have implemented this syntax to make porting to Gforth easy, but
10073: do not document it here. The problem with this syntax is that the locals
10074: are defined in an order reversed with respect to the standard stack
10075: comment notation, making programs harder to read, and easier to misread
10076: and miswrite. The only merit of this syntax is that it is easy to
10077: implement using the ANS Forth locals wordset.
1.53 anton 10078:
10079:
1.78 anton 10080: @c ----------------------------------------------------------
10081: @node Structures, Object-oriented Forth, Locals, Words
10082: @section Structures
10083: @cindex structures
10084: @cindex records
1.53 anton 10085:
1.78 anton 10086: This section presents the structure package that comes with Gforth. A
10087: version of the package implemented in ANS Forth is available in
10088: @file{compat/struct.fs}. This package was inspired by a posting on
10089: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10090: possibly John Hayes). A version of this section has been published in
10091: M. Anton Ertl,
10092: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10093: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10094: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 10095:
1.78 anton 10096: @menu
10097: * Why explicit structure support?::
10098: * Structure Usage::
10099: * Structure Naming Convention::
10100: * Structure Implementation::
10101: * Structure Glossary::
1.183 anton 10102: * Forth200x Structures::
1.78 anton 10103: @end menu
1.55 anton 10104:
1.78 anton 10105: @node Why explicit structure support?, Structure Usage, Structures, Structures
10106: @subsection Why explicit structure support?
1.53 anton 10107:
1.78 anton 10108: @cindex address arithmetic for structures
10109: @cindex structures using address arithmetic
10110: If we want to use a structure containing several fields, we could simply
10111: reserve memory for it, and access the fields using address arithmetic
10112: (@pxref{Address arithmetic}). As an example, consider a structure with
10113: the following fields
1.57 anton 10114:
1.78 anton 10115: @table @code
10116: @item a
10117: is a float
10118: @item b
10119: is a cell
10120: @item c
10121: is a float
10122: @end table
1.57 anton 10123:
1.78 anton 10124: Given the (float-aligned) base address of the structure we get the
10125: address of the field
1.52 anton 10126:
1.78 anton 10127: @table @code
10128: @item a
10129: without doing anything further.
10130: @item b
10131: with @code{float+}
10132: @item c
10133: with @code{float+ cell+ faligned}
10134: @end table
1.52 anton 10135:
1.78 anton 10136: It is easy to see that this can become quite tiring.
1.52 anton 10137:
1.78 anton 10138: Moreover, it is not very readable, because seeing a
10139: @code{cell+} tells us neither which kind of structure is
10140: accessed nor what field is accessed; we have to somehow infer the kind
10141: of structure, and then look up in the documentation, which field of
10142: that structure corresponds to that offset.
1.53 anton 10143:
1.78 anton 10144: Finally, this kind of address arithmetic also causes maintenance
10145: troubles: If you add or delete a field somewhere in the middle of the
10146: structure, you have to find and change all computations for the fields
10147: afterwards.
1.52 anton 10148:
1.78 anton 10149: So, instead of using @code{cell+} and friends directly, how
10150: about storing the offsets in constants:
1.52 anton 10151:
1.78 anton 10152: @example
10153: 0 constant a-offset
10154: 0 float+ constant b-offset
10155: 0 float+ cell+ faligned c-offset
10156: @end example
1.64 pazsan 10157:
1.78 anton 10158: Now we can get the address of field @code{x} with @code{x-offset
10159: +}. This is much better in all respects. Of course, you still
10160: have to change all later offset definitions if you add a field. You can
10161: fix this by declaring the offsets in the following way:
1.57 anton 10162:
1.78 anton 10163: @example
10164: 0 constant a-offset
10165: a-offset float+ constant b-offset
10166: b-offset cell+ faligned constant c-offset
10167: @end example
1.57 anton 10168:
1.78 anton 10169: Since we always use the offsets with @code{+}, we could use a defining
10170: word @code{cfield} that includes the @code{+} in the action of the
10171: defined word:
1.64 pazsan 10172:
1.78 anton 10173: @example
10174: : cfield ( n "name" -- )
10175: create ,
10176: does> ( name execution: addr1 -- addr2 )
10177: @@ + ;
1.64 pazsan 10178:
1.78 anton 10179: 0 cfield a
10180: 0 a float+ cfield b
10181: 0 b cell+ faligned cfield c
10182: @end example
1.64 pazsan 10183:
1.78 anton 10184: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10185:
1.78 anton 10186: The structure field words now can be used quite nicely. However,
10187: their definition is still a bit cumbersome: We have to repeat the
10188: name, the information about size and alignment is distributed before
10189: and after the field definitions etc. The structure package presented
10190: here addresses these problems.
1.64 pazsan 10191:
1.78 anton 10192: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10193: @subsection Structure Usage
10194: @cindex structure usage
1.57 anton 10195:
1.78 anton 10196: @cindex @code{field} usage
10197: @cindex @code{struct} usage
10198: @cindex @code{end-struct} usage
10199: You can define a structure for a (data-less) linked list with:
1.57 anton 10200: @example
1.78 anton 10201: struct
10202: cell% field list-next
10203: end-struct list%
1.57 anton 10204: @end example
10205:
1.78 anton 10206: With the address of the list node on the stack, you can compute the
10207: address of the field that contains the address of the next node with
10208: @code{list-next}. E.g., you can determine the length of a list
10209: with:
1.57 anton 10210:
10211: @example
1.78 anton 10212: : list-length ( list -- n )
10213: \ "list" is a pointer to the first element of a linked list
10214: \ "n" is the length of the list
10215: 0 BEGIN ( list1 n1 )
10216: over
10217: WHILE ( list1 n1 )
10218: 1+ swap list-next @@ swap
10219: REPEAT
10220: nip ;
1.57 anton 10221: @end example
10222:
1.78 anton 10223: You can reserve memory for a list node in the dictionary with
10224: @code{list% %allot}, which leaves the address of the list node on the
10225: stack. For the equivalent allocation on the heap you can use @code{list%
10226: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10227: use @code{list% %allocate}). You can get the the size of a list
10228: node with @code{list% %size} and its alignment with @code{list%
10229: %alignment}.
10230:
10231: Note that in ANS Forth the body of a @code{create}d word is
10232: @code{aligned} but not necessarily @code{faligned};
10233: therefore, if you do a:
1.57 anton 10234:
10235: @example
1.78 anton 10236: create @emph{name} foo% %allot drop
1.57 anton 10237: @end example
10238:
1.78 anton 10239: @noindent
10240: then the memory alloted for @code{foo%} is guaranteed to start at the
10241: body of @code{@emph{name}} only if @code{foo%} contains only character,
10242: cell and double fields. Therefore, if your structure contains floats,
10243: better use
1.57 anton 10244:
10245: @example
1.78 anton 10246: foo% %allot constant @emph{name}
1.57 anton 10247: @end example
10248:
1.78 anton 10249: @cindex structures containing structures
10250: You can include a structure @code{foo%} as a field of
10251: another structure, like this:
1.65 anton 10252: @example
1.78 anton 10253: struct
10254: ...
10255: foo% field ...
10256: ...
10257: end-struct ...
1.65 anton 10258: @end example
1.52 anton 10259:
1.78 anton 10260: @cindex structure extension
10261: @cindex extended records
10262: Instead of starting with an empty structure, you can extend an
10263: existing structure. E.g., a plain linked list without data, as defined
10264: above, is hardly useful; You can extend it to a linked list of integers,
10265: like this:@footnote{This feature is also known as @emph{extended
10266: records}. It is the main innovation in the Oberon language; in other
10267: words, adding this feature to Modula-2 led Wirth to create a new
10268: language, write a new compiler etc. Adding this feature to Forth just
10269: required a few lines of code.}
1.52 anton 10270:
1.78 anton 10271: @example
10272: list%
10273: cell% field intlist-int
10274: end-struct intlist%
10275: @end example
1.55 anton 10276:
1.78 anton 10277: @code{intlist%} is a structure with two fields:
10278: @code{list-next} and @code{intlist-int}.
1.55 anton 10279:
1.78 anton 10280: @cindex structures containing arrays
10281: You can specify an array type containing @emph{n} elements of
10282: type @code{foo%} like this:
1.55 anton 10283:
10284: @example
1.78 anton 10285: foo% @emph{n} *
1.56 anton 10286: @end example
1.55 anton 10287:
1.78 anton 10288: You can use this array type in any place where you can use a normal
10289: type, e.g., when defining a @code{field}, or with
10290: @code{%allot}.
10291:
10292: @cindex first field optimization
10293: The first field is at the base address of a structure and the word for
10294: this field (e.g., @code{list-next}) actually does not change the address
10295: on the stack. You may be tempted to leave it away in the interest of
10296: run-time and space efficiency. This is not necessary, because the
10297: structure package optimizes this case: If you compile a first-field
10298: words, no code is generated. So, in the interest of readability and
10299: maintainability you should include the word for the field when accessing
10300: the field.
1.52 anton 10301:
10302:
1.78 anton 10303: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10304: @subsection Structure Naming Convention
10305: @cindex structure naming convention
1.52 anton 10306:
1.78 anton 10307: The field names that come to (my) mind are often quite generic, and,
10308: if used, would cause frequent name clashes. E.g., many structures
10309: probably contain a @code{counter} field. The structure names
10310: that come to (my) mind are often also the logical choice for the names
10311: of words that create such a structure.
1.52 anton 10312:
1.78 anton 10313: Therefore, I have adopted the following naming conventions:
1.52 anton 10314:
1.78 anton 10315: @itemize @bullet
10316: @cindex field naming convention
10317: @item
10318: The names of fields are of the form
10319: @code{@emph{struct}-@emph{field}}, where
10320: @code{@emph{struct}} is the basic name of the structure, and
10321: @code{@emph{field}} is the basic name of the field. You can
10322: think of field words as converting the (address of the)
10323: structure into the (address of the) field.
1.52 anton 10324:
1.78 anton 10325: @cindex structure naming convention
10326: @item
10327: The names of structures are of the form
10328: @code{@emph{struct}%}, where
10329: @code{@emph{struct}} is the basic name of the structure.
10330: @end itemize
1.52 anton 10331:
1.78 anton 10332: This naming convention does not work that well for fields of extended
10333: structures; e.g., the integer list structure has a field
10334: @code{intlist-int}, but has @code{list-next}, not
10335: @code{intlist-next}.
1.53 anton 10336:
1.78 anton 10337: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10338: @subsection Structure Implementation
10339: @cindex structure implementation
10340: @cindex implementation of structures
1.52 anton 10341:
1.78 anton 10342: The central idea in the implementation is to pass the data about the
10343: structure being built on the stack, not in some global
10344: variable. Everything else falls into place naturally once this design
10345: decision is made.
1.53 anton 10346:
1.78 anton 10347: The type description on the stack is of the form @emph{align
10348: size}. Keeping the size on the top-of-stack makes dealing with arrays
10349: very simple.
1.53 anton 10350:
1.78 anton 10351: @code{field} is a defining word that uses @code{Create}
10352: and @code{DOES>}. The body of the field contains the offset
10353: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10354:
10355: @example
1.78 anton 10356: @@ +
1.53 anton 10357: @end example
10358:
1.78 anton 10359: @noindent
10360: i.e., add the offset to the address, giving the stack effect
10361: @i{addr1 -- addr2} for a field.
10362:
10363: @cindex first field optimization, implementation
10364: This simple structure is slightly complicated by the optimization
10365: for fields with offset 0, which requires a different
10366: @code{DOES>}-part (because we cannot rely on there being
10367: something on the stack if such a field is invoked during
10368: compilation). Therefore, we put the different @code{DOES>}-parts
10369: in separate words, and decide which one to invoke based on the
10370: offset. For a zero offset, the field is basically a noop; it is
10371: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10372:
1.183 anton 10373: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10374: @subsection Structure Glossary
10375: @cindex structure glossary
1.53 anton 10376:
1.5 anton 10377:
1.78 anton 10378: doc-%align
10379: doc-%alignment
10380: doc-%alloc
10381: doc-%allocate
10382: doc-%allot
10383: doc-cell%
10384: doc-char%
10385: doc-dfloat%
10386: doc-double%
10387: doc-end-struct
10388: doc-field
10389: doc-float%
10390: doc-naligned
10391: doc-sfloat%
10392: doc-%size
10393: doc-struct
1.54 anton 10394:
10395:
1.183 anton 10396: @node Forth200x Structures, , Structure Glossary, Structures
10397: @subsection Forth200x Structures
10398: @cindex Structures in Forth200x
10399:
10400: The Forth 200x standard defines a slightly less convenient form of
10401: structures. In general (when using @code{field+}, you have to perform
10402: the alignment yourself, but there are a number of convenience words
10403: (e.g., @code{field:} that perform the alignment for you.
10404:
10405: A typical usage example is:
10406:
10407: @example
10408: 0
10409: field: s-a
10410: faligned 2 floats +field s-b
10411: constant s-struct
10412: @end example
10413:
10414: An alternative way of writing this structure is:
10415:
10416: @example
10417: begin-structure s-struct
10418: field: s-a
10419: faligned 2 floats +field s-b
10420: end-structure
10421: @end example
10422:
10423: doc-begin-structure
10424: doc-end-structure
10425: doc-+field
10426: doc-cfield:
10427: doc-field:
10428: doc-2field:
10429: doc-ffield:
10430: doc-sffield:
10431: doc-dffield:
10432:
1.26 crook 10433: @c -------------------------------------------------------------
1.78 anton 10434: @node Object-oriented Forth, Programming Tools, Structures, Words
10435: @section Object-oriented Forth
10436:
10437: Gforth comes with three packages for object-oriented programming:
10438: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10439: is preloaded, so you have to @code{include} them before use. The most
10440: important differences between these packages (and others) are discussed
10441: in @ref{Comparison with other object models}. All packages are written
10442: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10443:
1.78 anton 10444: @menu
10445: * Why object-oriented programming?::
10446: * Object-Oriented Terminology::
10447: * Objects::
10448: * OOF::
10449: * Mini-OOF::
10450: * Comparison with other object models::
10451: @end menu
1.5 anton 10452:
1.78 anton 10453: @c ----------------------------------------------------------------
10454: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10455: @subsection Why object-oriented programming?
10456: @cindex object-oriented programming motivation
10457: @cindex motivation for object-oriented programming
1.44 crook 10458:
1.78 anton 10459: Often we have to deal with several data structures (@emph{objects}),
10460: that have to be treated similarly in some respects, but differently in
10461: others. Graphical objects are the textbook example: circles, triangles,
10462: dinosaurs, icons, and others, and we may want to add more during program
10463: development. We want to apply some operations to any graphical object,
10464: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10465: has to do something different for every kind of object.
10466: @comment TODO add some other operations eg perimeter, area
10467: @comment and tie in to concrete examples later..
1.5 anton 10468:
1.78 anton 10469: We could implement @code{draw} as a big @code{CASE}
10470: control structure that executes the appropriate code depending on the
10471: kind of object to be drawn. This would be not be very elegant, and,
10472: moreover, we would have to change @code{draw} every time we add
10473: a new kind of graphical object (say, a spaceship).
1.44 crook 10474:
1.78 anton 10475: What we would rather do is: When defining spaceships, we would tell
10476: the system: ``Here's how you @code{draw} a spaceship; you figure
10477: out the rest''.
1.5 anton 10478:
1.78 anton 10479: This is the problem that all systems solve that (rightfully) call
10480: themselves object-oriented; the object-oriented packages presented here
10481: solve this problem (and not much else).
10482: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10483:
1.78 anton 10484: @c ------------------------------------------------------------------------
10485: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10486: @subsection Object-Oriented Terminology
10487: @cindex object-oriented terminology
10488: @cindex terminology for object-oriented programming
1.5 anton 10489:
1.78 anton 10490: This section is mainly for reference, so you don't have to understand
10491: all of it right away. The terminology is mainly Smalltalk-inspired. In
10492: short:
1.44 crook 10493:
1.78 anton 10494: @table @emph
10495: @cindex class
10496: @item class
10497: a data structure definition with some extras.
1.5 anton 10498:
1.78 anton 10499: @cindex object
10500: @item object
10501: an instance of the data structure described by the class definition.
1.5 anton 10502:
1.78 anton 10503: @cindex instance variables
10504: @item instance variables
10505: fields of the data structure.
1.5 anton 10506:
1.78 anton 10507: @cindex selector
10508: @cindex method selector
10509: @cindex virtual function
10510: @item selector
10511: (or @emph{method selector}) a word (e.g.,
10512: @code{draw}) that performs an operation on a variety of data
10513: structures (classes). A selector describes @emph{what} operation to
10514: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10515:
1.78 anton 10516: @cindex method
10517: @item method
10518: the concrete definition that performs the operation
10519: described by the selector for a specific class. A method specifies
10520: @emph{how} the operation is performed for a specific class.
1.5 anton 10521:
1.78 anton 10522: @cindex selector invocation
10523: @cindex message send
10524: @cindex invoking a selector
10525: @item selector invocation
10526: a call of a selector. One argument of the call (the TOS (top-of-stack))
10527: is used for determining which method is used. In Smalltalk terminology:
10528: a message (consisting of the selector and the other arguments) is sent
10529: to the object.
1.5 anton 10530:
1.78 anton 10531: @cindex receiving object
10532: @item receiving object
10533: the object used for determining the method executed by a selector
10534: invocation. In the @file{objects.fs} model, it is the object that is on
10535: the TOS when the selector is invoked. (@emph{Receiving} comes from
10536: the Smalltalk @emph{message} terminology.)
1.5 anton 10537:
1.78 anton 10538: @cindex child class
10539: @cindex parent class
10540: @cindex inheritance
10541: @item child class
10542: a class that has (@emph{inherits}) all properties (instance variables,
10543: selectors, methods) from a @emph{parent class}. In Smalltalk
10544: terminology: The subclass inherits from the superclass. In C++
10545: terminology: The derived class inherits from the base class.
1.5 anton 10546:
1.78 anton 10547: @end table
1.5 anton 10548:
1.78 anton 10549: @c If you wonder about the message sending terminology, it comes from
10550: @c a time when each object had it's own task and objects communicated via
10551: @c message passing; eventually the Smalltalk developers realized that
10552: @c they can do most things through simple (indirect) calls. They kept the
10553: @c terminology.
1.5 anton 10554:
1.78 anton 10555: @c --------------------------------------------------------------
10556: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10557: @subsection The @file{objects.fs} model
10558: @cindex objects
10559: @cindex object-oriented programming
1.26 crook 10560:
1.78 anton 10561: @cindex @file{objects.fs}
10562: @cindex @file{oof.fs}
1.26 crook 10563:
1.78 anton 10564: This section describes the @file{objects.fs} package. This material also
10565: has been published in M. Anton Ertl,
10566: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10567: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10568: 37--43.
10569: @c McKewan's and Zsoter's packages
1.26 crook 10570:
1.78 anton 10571: This section assumes that you have read @ref{Structures}.
1.5 anton 10572:
1.78 anton 10573: The techniques on which this model is based have been used to implement
10574: the parser generator, Gray, and have also been used in Gforth for
10575: implementing the various flavours of word lists (hashed or not,
10576: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10577:
10578:
1.26 crook 10579: @menu
1.78 anton 10580: * Properties of the Objects model::
10581: * Basic Objects Usage::
10582: * The Objects base class::
10583: * Creating objects::
10584: * Object-Oriented Programming Style::
10585: * Class Binding::
10586: * Method conveniences::
10587: * Classes and Scoping::
10588: * Dividing classes::
10589: * Object Interfaces::
10590: * Objects Implementation::
10591: * Objects Glossary::
1.26 crook 10592: @end menu
1.5 anton 10593:
1.78 anton 10594: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10595:
1.78 anton 10596: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10597: @subsubsection Properties of the @file{objects.fs} model
10598: @cindex @file{objects.fs} properties
1.5 anton 10599:
1.78 anton 10600: @itemize @bullet
10601: @item
10602: It is straightforward to pass objects on the stack. Passing
10603: selectors on the stack is a little less convenient, but possible.
1.44 crook 10604:
1.78 anton 10605: @item
10606: Objects are just data structures in memory, and are referenced by their
10607: address. You can create words for objects with normal defining words
10608: like @code{constant}. Likewise, there is no difference between instance
10609: variables that contain objects and those that contain other data.
1.5 anton 10610:
1.78 anton 10611: @item
10612: Late binding is efficient and easy to use.
1.44 crook 10613:
1.78 anton 10614: @item
10615: It avoids parsing, and thus avoids problems with state-smartness
10616: and reduced extensibility; for convenience there are a few parsing
10617: words, but they have non-parsing counterparts. There are also a few
10618: defining words that parse. This is hard to avoid, because all standard
10619: defining words parse (except @code{:noname}); however, such
10620: words are not as bad as many other parsing words, because they are not
10621: state-smart.
1.5 anton 10622:
1.78 anton 10623: @item
10624: It does not try to incorporate everything. It does a few things and does
10625: them well (IMO). In particular, this model was not designed to support
10626: information hiding (although it has features that may help); you can use
10627: a separate package for achieving this.
1.5 anton 10628:
1.78 anton 10629: @item
10630: It is layered; you don't have to learn and use all features to use this
10631: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10632: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10633: are optional and independent of each other.
1.5 anton 10634:
1.78 anton 10635: @item
10636: An implementation in ANS Forth is available.
1.5 anton 10637:
1.78 anton 10638: @end itemize
1.5 anton 10639:
1.44 crook 10640:
1.78 anton 10641: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10642: @subsubsection Basic @file{objects.fs} Usage
10643: @cindex basic objects usage
10644: @cindex objects, basic usage
1.5 anton 10645:
1.78 anton 10646: You can define a class for graphical objects like this:
1.44 crook 10647:
1.78 anton 10648: @cindex @code{class} usage
10649: @cindex @code{end-class} usage
10650: @cindex @code{selector} usage
1.5 anton 10651: @example
1.78 anton 10652: object class \ "object" is the parent class
10653: selector draw ( x y graphical -- )
10654: end-class graphical
10655: @end example
10656:
10657: This code defines a class @code{graphical} with an
10658: operation @code{draw}. We can perform the operation
10659: @code{draw} on any @code{graphical} object, e.g.:
10660:
10661: @example
10662: 100 100 t-rex draw
1.26 crook 10663: @end example
1.5 anton 10664:
1.78 anton 10665: @noindent
10666: where @code{t-rex} is a word (say, a constant) that produces a
10667: graphical object.
10668:
10669: @comment TODO add a 2nd operation eg perimeter.. and use for
10670: @comment a concrete example
1.5 anton 10671:
1.78 anton 10672: @cindex abstract class
10673: How do we create a graphical object? With the present definitions,
10674: we cannot create a useful graphical object. The class
10675: @code{graphical} describes graphical objects in general, but not
10676: any concrete graphical object type (C++ users would call it an
10677: @emph{abstract class}); e.g., there is no method for the selector
10678: @code{draw} in the class @code{graphical}.
1.5 anton 10679:
1.78 anton 10680: For concrete graphical objects, we define child classes of the
10681: class @code{graphical}, e.g.:
1.5 anton 10682:
1.78 anton 10683: @cindex @code{overrides} usage
10684: @cindex @code{field} usage in class definition
1.26 crook 10685: @example
1.78 anton 10686: graphical class \ "graphical" is the parent class
10687: cell% field circle-radius
1.5 anton 10688:
1.78 anton 10689: :noname ( x y circle -- )
10690: circle-radius @@ draw-circle ;
10691: overrides draw
1.5 anton 10692:
1.78 anton 10693: :noname ( n-radius circle -- )
10694: circle-radius ! ;
10695: overrides construct
1.5 anton 10696:
1.78 anton 10697: end-class circle
10698: @end example
1.44 crook 10699:
1.78 anton 10700: Here we define a class @code{circle} as a child of @code{graphical},
10701: with field @code{circle-radius} (which behaves just like a field
10702: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10703: for the selectors @code{draw} and @code{construct} (@code{construct} is
10704: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10705:
1.78 anton 10706: Now we can create a circle on the heap (i.e.,
10707: @code{allocate}d memory) with:
1.44 crook 10708:
1.78 anton 10709: @cindex @code{heap-new} usage
1.5 anton 10710: @example
1.78 anton 10711: 50 circle heap-new constant my-circle
1.5 anton 10712: @end example
10713:
1.78 anton 10714: @noindent
10715: @code{heap-new} invokes @code{construct}, thus
10716: initializing the field @code{circle-radius} with 50. We can draw
10717: this new circle at (100,100) with:
1.5 anton 10718:
10719: @example
1.78 anton 10720: 100 100 my-circle draw
1.5 anton 10721: @end example
10722:
1.78 anton 10723: @cindex selector invocation, restrictions
10724: @cindex class definition, restrictions
10725: Note: You can only invoke a selector if the object on the TOS
10726: (the receiving object) belongs to the class where the selector was
10727: defined or one of its descendents; e.g., you can invoke
10728: @code{draw} only for objects belonging to @code{graphical}
10729: or its descendents (e.g., @code{circle}). Immediately before
10730: @code{end-class}, the search order has to be the same as
10731: immediately after @code{class}.
10732:
10733: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10734: @subsubsection The @file{object.fs} base class
10735: @cindex @code{object} class
10736:
10737: When you define a class, you have to specify a parent class. So how do
10738: you start defining classes? There is one class available from the start:
10739: @code{object}. It is ancestor for all classes and so is the
10740: only class that has no parent. It has two selectors: @code{construct}
10741: and @code{print}.
10742:
10743: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10744: @subsubsection Creating objects
10745: @cindex creating objects
10746: @cindex object creation
10747: @cindex object allocation options
10748:
10749: @cindex @code{heap-new} discussion
10750: @cindex @code{dict-new} discussion
10751: @cindex @code{construct} discussion
10752: You can create and initialize an object of a class on the heap with
10753: @code{heap-new} ( ... class -- object ) and in the dictionary
10754: (allocation with @code{allot}) with @code{dict-new} (
10755: ... class -- object ). Both words invoke @code{construct}, which
10756: consumes the stack items indicated by "..." above.
10757:
10758: @cindex @code{init-object} discussion
10759: @cindex @code{class-inst-size} discussion
10760: If you want to allocate memory for an object yourself, you can get its
10761: alignment and size with @code{class-inst-size 2@@} ( class --
10762: align size ). Once you have memory for an object, you can initialize
10763: it with @code{init-object} ( ... class object -- );
10764: @code{construct} does only a part of the necessary work.
10765:
10766: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10767: @subsubsection Object-Oriented Programming Style
10768: @cindex object-oriented programming style
10769: @cindex programming style, object-oriented
1.5 anton 10770:
1.78 anton 10771: This section is not exhaustive.
1.5 anton 10772:
1.78 anton 10773: @cindex stack effects of selectors
10774: @cindex selectors and stack effects
10775: In general, it is a good idea to ensure that all methods for the
10776: same selector have the same stack effect: when you invoke a selector,
10777: you often have no idea which method will be invoked, so, unless all
10778: methods have the same stack effect, you will not know the stack effect
10779: of the selector invocation.
1.5 anton 10780:
1.78 anton 10781: One exception to this rule is methods for the selector
10782: @code{construct}. We know which method is invoked, because we
10783: specify the class to be constructed at the same place. Actually, I
10784: defined @code{construct} as a selector only to give the users a
10785: convenient way to specify initialization. The way it is used, a
10786: mechanism different from selector invocation would be more natural
10787: (but probably would take more code and more space to explain).
1.5 anton 10788:
1.78 anton 10789: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10790: @subsubsection Class Binding
10791: @cindex class binding
10792: @cindex early binding
1.5 anton 10793:
1.78 anton 10794: @cindex late binding
10795: Normal selector invocations determine the method at run-time depending
10796: on the class of the receiving object. This run-time selection is called
10797: @i{late binding}.
1.5 anton 10798:
1.78 anton 10799: Sometimes it's preferable to invoke a different method. For example,
10800: you might want to use the simple method for @code{print}ing
10801: @code{object}s instead of the possibly long-winded @code{print} method
10802: of the receiver class. You can achieve this by replacing the invocation
10803: of @code{print} with:
1.5 anton 10804:
1.78 anton 10805: @cindex @code{[bind]} usage
1.5 anton 10806: @example
1.78 anton 10807: [bind] object print
1.5 anton 10808: @end example
10809:
1.78 anton 10810: @noindent
10811: in compiled code or:
10812:
10813: @cindex @code{bind} usage
1.5 anton 10814: @example
1.78 anton 10815: bind object print
1.5 anton 10816: @end example
10817:
1.78 anton 10818: @cindex class binding, alternative to
10819: @noindent
10820: in interpreted code. Alternatively, you can define the method with a
10821: name (e.g., @code{print-object}), and then invoke it through the
10822: name. Class binding is just a (often more convenient) way to achieve
10823: the same effect; it avoids name clutter and allows you to invoke
10824: methods directly without naming them first.
1.5 anton 10825:
1.78 anton 10826: @cindex superclass binding
10827: @cindex parent class binding
10828: A frequent use of class binding is this: When we define a method
10829: for a selector, we often want the method to do what the selector does
10830: in the parent class, and a little more. There is a special word for
10831: this purpose: @code{[parent]}; @code{[parent]
10832: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10833: selector}}, where @code{@emph{parent}} is the parent
10834: class of the current class. E.g., a method definition might look like:
1.44 crook 10835:
1.78 anton 10836: @cindex @code{[parent]} usage
10837: @example
10838: :noname
10839: dup [parent] foo \ do parent's foo on the receiving object
10840: ... \ do some more
10841: ; overrides foo
10842: @end example
1.6 pazsan 10843:
1.78 anton 10844: @cindex class binding as optimization
10845: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10846: March 1997), Andrew McKewan presents class binding as an optimization
10847: technique. I recommend not using it for this purpose unless you are in
10848: an emergency. Late binding is pretty fast with this model anyway, so the
10849: benefit of using class binding is small; the cost of using class binding
10850: where it is not appropriate is reduced maintainability.
1.44 crook 10851:
1.78 anton 10852: While we are at programming style questions: You should bind
10853: selectors only to ancestor classes of the receiving object. E.g., say,
10854: you know that the receiving object is of class @code{foo} or its
10855: descendents; then you should bind only to @code{foo} and its
10856: ancestors.
1.12 anton 10857:
1.78 anton 10858: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10859: @subsubsection Method conveniences
10860: @cindex method conveniences
1.44 crook 10861:
1.78 anton 10862: In a method you usually access the receiving object pretty often. If
10863: you define the method as a plain colon definition (e.g., with
10864: @code{:noname}), you may have to do a lot of stack
10865: gymnastics. To avoid this, you can define the method with @code{m:
10866: ... ;m}. E.g., you could define the method for
10867: @code{draw}ing a @code{circle} with
1.6 pazsan 10868:
1.78 anton 10869: @cindex @code{this} usage
10870: @cindex @code{m:} usage
10871: @cindex @code{;m} usage
10872: @example
10873: m: ( x y circle -- )
10874: ( x y ) this circle-radius @@ draw-circle ;m
10875: @end example
1.6 pazsan 10876:
1.78 anton 10877: @cindex @code{exit} in @code{m: ... ;m}
10878: @cindex @code{exitm} discussion
10879: @cindex @code{catch} in @code{m: ... ;m}
10880: When this method is executed, the receiver object is removed from the
10881: stack; you can access it with @code{this} (admittedly, in this
10882: example the use of @code{m: ... ;m} offers no advantage). Note
10883: that I specify the stack effect for the whole method (i.e. including
10884: the receiver object), not just for the code between @code{m:}
10885: and @code{;m}. You cannot use @code{exit} in
10886: @code{m:...;m}; instead, use
10887: @code{exitm}.@footnote{Moreover, for any word that calls
10888: @code{catch} and was defined before loading
10889: @code{objects.fs}, you have to redefine it like I redefined
10890: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10891:
1.78 anton 10892: @cindex @code{inst-var} usage
10893: You will frequently use sequences of the form @code{this
10894: @emph{field}} (in the example above: @code{this
10895: circle-radius}). If you use the field only in this way, you can
10896: define it with @code{inst-var} and eliminate the
10897: @code{this} before the field name. E.g., the @code{circle}
10898: class above could also be defined with:
1.6 pazsan 10899:
1.78 anton 10900: @example
10901: graphical class
10902: cell% inst-var radius
1.6 pazsan 10903:
1.78 anton 10904: m: ( x y circle -- )
10905: radius @@ draw-circle ;m
10906: overrides draw
1.6 pazsan 10907:
1.78 anton 10908: m: ( n-radius circle -- )
10909: radius ! ;m
10910: overrides construct
1.6 pazsan 10911:
1.78 anton 10912: end-class circle
10913: @end example
1.6 pazsan 10914:
1.78 anton 10915: @code{radius} can only be used in @code{circle} and its
10916: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10917:
1.78 anton 10918: @cindex @code{inst-value} usage
10919: You can also define fields with @code{inst-value}, which is
10920: to @code{inst-var} what @code{value} is to
10921: @code{variable}. You can change the value of such a field with
10922: @code{[to-inst]}. E.g., we could also define the class
10923: @code{circle} like this:
1.44 crook 10924:
1.78 anton 10925: @example
10926: graphical class
10927: inst-value radius
1.6 pazsan 10928:
1.78 anton 10929: m: ( x y circle -- )
10930: radius draw-circle ;m
10931: overrides draw
1.44 crook 10932:
1.78 anton 10933: m: ( n-radius circle -- )
10934: [to-inst] radius ;m
10935: overrides construct
1.6 pazsan 10936:
1.78 anton 10937: end-class circle
10938: @end example
1.6 pazsan 10939:
1.78 anton 10940: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10941:
1.78 anton 10942: @c Finally, you can define named methods with @code{:m}. One use of this
10943: @c feature is the definition of words that occur only in one class and are
10944: @c not intended to be overridden, but which still need method context
10945: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10946: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10947:
10948:
1.78 anton 10949: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10950: @subsubsection Classes and Scoping
10951: @cindex classes and scoping
10952: @cindex scoping and classes
1.6 pazsan 10953:
1.78 anton 10954: Inheritance is frequent, unlike structure extension. This exacerbates
10955: the problem with the field name convention (@pxref{Structure Naming
10956: Convention}): One always has to remember in which class the field was
10957: originally defined; changing a part of the class structure would require
10958: changes for renaming in otherwise unaffected code.
1.6 pazsan 10959:
1.78 anton 10960: @cindex @code{inst-var} visibility
10961: @cindex @code{inst-value} visibility
10962: To solve this problem, I added a scoping mechanism (which was not in my
10963: original charter): A field defined with @code{inst-var} (or
10964: @code{inst-value}) is visible only in the class where it is defined and in
10965: the descendent classes of this class. Using such fields only makes
10966: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10967:
1.78 anton 10968: This scoping mechanism allows us to use the unadorned field name,
10969: because name clashes with unrelated words become much less likely.
1.6 pazsan 10970:
1.78 anton 10971: @cindex @code{protected} discussion
10972: @cindex @code{private} discussion
10973: Once we have this mechanism, we can also use it for controlling the
10974: visibility of other words: All words defined after
10975: @code{protected} are visible only in the current class and its
10976: descendents. @code{public} restores the compilation
10977: (i.e. @code{current}) word list that was in effect before. If you
10978: have several @code{protected}s without an intervening
10979: @code{public} or @code{set-current}, @code{public}
10980: will restore the compilation word list in effect before the first of
10981: these @code{protected}s.
1.6 pazsan 10982:
1.78 anton 10983: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10984: @subsubsection Dividing classes
10985: @cindex Dividing classes
10986: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10987:
1.78 anton 10988: You may want to do the definition of methods separate from the
10989: definition of the class, its selectors, fields, and instance variables,
10990: i.e., separate the implementation from the definition. You can do this
10991: in the following way:
1.6 pazsan 10992:
1.78 anton 10993: @example
10994: graphical class
10995: inst-value radius
10996: end-class circle
1.6 pazsan 10997:
1.78 anton 10998: ... \ do some other stuff
1.6 pazsan 10999:
1.78 anton 11000: circle methods \ now we are ready
1.44 crook 11001:
1.78 anton 11002: m: ( x y circle -- )
11003: radius draw-circle ;m
11004: overrides draw
1.6 pazsan 11005:
1.78 anton 11006: m: ( n-radius circle -- )
11007: [to-inst] radius ;m
11008: overrides construct
1.44 crook 11009:
1.78 anton 11010: end-methods
11011: @end example
1.7 pazsan 11012:
1.78 anton 11013: You can use several @code{methods}...@code{end-methods} sections. The
11014: only things you can do to the class in these sections are: defining
11015: methods, and overriding the class's selectors. You must not define new
11016: selectors or fields.
1.7 pazsan 11017:
1.78 anton 11018: Note that you often have to override a selector before using it. In
11019: particular, you usually have to override @code{construct} with a new
11020: method before you can invoke @code{heap-new} and friends. E.g., you
11021: must not create a circle before the @code{overrides construct} sequence
11022: in the example above.
1.7 pazsan 11023:
1.78 anton 11024: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
11025: @subsubsection Object Interfaces
11026: @cindex object interfaces
11027: @cindex interfaces for objects
1.7 pazsan 11028:
1.78 anton 11029: In this model you can only call selectors defined in the class of the
11030: receiving objects or in one of its ancestors. If you call a selector
11031: with a receiving object that is not in one of these classes, the
11032: result is undefined; if you are lucky, the program crashes
11033: immediately.
1.7 pazsan 11034:
1.78 anton 11035: @cindex selectors common to hardly-related classes
11036: Now consider the case when you want to have a selector (or several)
11037: available in two classes: You would have to add the selector to a
11038: common ancestor class, in the worst case to @code{object}. You
11039: may not want to do this, e.g., because someone else is responsible for
11040: this ancestor class.
1.7 pazsan 11041:
1.78 anton 11042: The solution for this problem is interfaces. An interface is a
11043: collection of selectors. If a class implements an interface, the
11044: selectors become available to the class and its descendents. A class
11045: can implement an unlimited number of interfaces. For the problem
11046: discussed above, we would define an interface for the selector(s), and
11047: both classes would implement the interface.
1.7 pazsan 11048:
1.78 anton 11049: As an example, consider an interface @code{storage} for
11050: writing objects to disk and getting them back, and a class
11051: @code{foo} that implements it. The code would look like this:
1.7 pazsan 11052:
1.78 anton 11053: @cindex @code{interface} usage
11054: @cindex @code{end-interface} usage
11055: @cindex @code{implementation} usage
11056: @example
11057: interface
11058: selector write ( file object -- )
11059: selector read1 ( file object -- )
11060: end-interface storage
1.13 pazsan 11061:
1.78 anton 11062: bar class
11063: storage implementation
1.13 pazsan 11064:
1.78 anton 11065: ... overrides write
11066: ... overrides read1
11067: ...
11068: end-class foo
11069: @end example
1.13 pazsan 11070:
1.78 anton 11071: @noindent
11072: (I would add a word @code{read} @i{( file -- object )} that uses
11073: @code{read1} internally, but that's beyond the point illustrated
11074: here.)
1.13 pazsan 11075:
1.78 anton 11076: Note that you cannot use @code{protected} in an interface; and
11077: of course you cannot define fields.
1.13 pazsan 11078:
1.78 anton 11079: In the Neon model, all selectors are available for all classes;
11080: therefore it does not need interfaces. The price you pay in this model
11081: is slower late binding, and therefore, added complexity to avoid late
11082: binding.
1.13 pazsan 11083:
1.78 anton 11084: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11085: @subsubsection @file{objects.fs} Implementation
11086: @cindex @file{objects.fs} implementation
1.13 pazsan 11087:
1.78 anton 11088: @cindex @code{object-map} discussion
11089: An object is a piece of memory, like one of the data structures
11090: described with @code{struct...end-struct}. It has a field
11091: @code{object-map} that points to the method map for the object's
11092: class.
1.13 pazsan 11093:
1.78 anton 11094: @cindex method map
11095: @cindex virtual function table
11096: The @emph{method map}@footnote{This is Self terminology; in C++
11097: terminology: virtual function table.} is an array that contains the
11098: execution tokens (@i{xt}s) of the methods for the object's class. Each
11099: selector contains an offset into a method map.
1.13 pazsan 11100:
1.78 anton 11101: @cindex @code{selector} implementation, class
11102: @code{selector} is a defining word that uses
11103: @code{CREATE} and @code{DOES>}. The body of the
11104: selector contains the offset; the @code{DOES>} action for a
11105: class selector is, basically:
1.8 pazsan 11106:
11107: @example
1.78 anton 11108: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 11109: @end example
11110:
1.78 anton 11111: Since @code{object-map} is the first field of the object, it
11112: does not generate any code. As you can see, calling a selector has a
11113: small, constant cost.
1.26 crook 11114:
1.78 anton 11115: @cindex @code{current-interface} discussion
11116: @cindex class implementation and representation
11117: A class is basically a @code{struct} combined with a method
11118: map. During the class definition the alignment and size of the class
11119: are passed on the stack, just as with @code{struct}s, so
11120: @code{field} can also be used for defining class
11121: fields. However, passing more items on the stack would be
11122: inconvenient, so @code{class} builds a data structure in memory,
11123: which is accessed through the variable
11124: @code{current-interface}. After its definition is complete, the
11125: class is represented on the stack by a pointer (e.g., as parameter for
11126: a child class definition).
1.26 crook 11127:
1.78 anton 11128: A new class starts off with the alignment and size of its parent,
11129: and a copy of the parent's method map. Defining new fields extends the
11130: size and alignment; likewise, defining new selectors extends the
11131: method map. @code{overrides} just stores a new @i{xt} in the method
11132: map at the offset given by the selector.
1.13 pazsan 11133:
1.78 anton 11134: @cindex class binding, implementation
11135: Class binding just gets the @i{xt} at the offset given by the selector
11136: from the class's method map and @code{compile,}s (in the case of
11137: @code{[bind]}) it.
1.13 pazsan 11138:
1.78 anton 11139: @cindex @code{this} implementation
11140: @cindex @code{catch} and @code{this}
11141: @cindex @code{this} and @code{catch}
11142: I implemented @code{this} as a @code{value}. At the
11143: start of an @code{m:...;m} method the old @code{this} is
11144: stored to the return stack and restored at the end; and the object on
11145: the TOS is stored @code{TO this}. This technique has one
11146: disadvantage: If the user does not leave the method via
11147: @code{;m}, but via @code{throw} or @code{exit},
11148: @code{this} is not restored (and @code{exit} may
11149: crash). To deal with the @code{throw} problem, I have redefined
11150: @code{catch} to save and restore @code{this}; the same
11151: should be done with any word that can catch an exception. As for
11152: @code{exit}, I simply forbid it (as a replacement, there is
11153: @code{exitm}).
1.13 pazsan 11154:
1.78 anton 11155: @cindex @code{inst-var} implementation
11156: @code{inst-var} is just the same as @code{field}, with
11157: a different @code{DOES>} action:
1.13 pazsan 11158: @example
1.78 anton 11159: @@ this +
1.8 pazsan 11160: @end example
1.78 anton 11161: Similar for @code{inst-value}.
1.8 pazsan 11162:
1.78 anton 11163: @cindex class scoping implementation
11164: Each class also has a word list that contains the words defined with
11165: @code{inst-var} and @code{inst-value}, and its protected
11166: words. It also has a pointer to its parent. @code{class} pushes
11167: the word lists of the class and all its ancestors onto the search order stack,
11168: and @code{end-class} drops them.
1.20 pazsan 11169:
1.78 anton 11170: @cindex interface implementation
11171: An interface is like a class without fields, parent and protected
11172: words; i.e., it just has a method map. If a class implements an
11173: interface, its method map contains a pointer to the method map of the
11174: interface. The positive offsets in the map are reserved for class
11175: methods, therefore interface map pointers have negative
11176: offsets. Interfaces have offsets that are unique throughout the
11177: system, unlike class selectors, whose offsets are only unique for the
11178: classes where the selector is available (invokable).
1.20 pazsan 11179:
1.78 anton 11180: This structure means that interface selectors have to perform one
11181: indirection more than class selectors to find their method. Their body
11182: contains the interface map pointer offset in the class method map, and
11183: the method offset in the interface method map. The
11184: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11185:
11186: @example
1.78 anton 11187: ( object selector-body )
11188: 2dup selector-interface @@ ( object selector-body object interface-offset )
11189: swap object-map @@ + @@ ( object selector-body map )
11190: swap selector-offset @@ + @@ execute
1.20 pazsan 11191: @end example
11192:
1.78 anton 11193: where @code{object-map} and @code{selector-offset} are
11194: first fields and generate no code.
1.20 pazsan 11195:
1.78 anton 11196: As a concrete example, consider the following code:
1.20 pazsan 11197:
11198: @example
1.78 anton 11199: interface
11200: selector if1sel1
11201: selector if1sel2
11202: end-interface if1
1.20 pazsan 11203:
1.78 anton 11204: object class
11205: if1 implementation
11206: selector cl1sel1
11207: cell% inst-var cl1iv1
1.20 pazsan 11208:
1.78 anton 11209: ' m1 overrides construct
11210: ' m2 overrides if1sel1
11211: ' m3 overrides if1sel2
11212: ' m4 overrides cl1sel2
11213: end-class cl1
1.20 pazsan 11214:
1.78 anton 11215: create obj1 object dict-new drop
11216: create obj2 cl1 dict-new drop
11217: @end example
1.20 pazsan 11218:
1.78 anton 11219: The data structure created by this code (including the data structure
11220: for @code{object}) is shown in the
11221: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11222: @comment TODO add this diagram..
1.20 pazsan 11223:
1.78 anton 11224: @node Objects Glossary, , Objects Implementation, Objects
11225: @subsubsection @file{objects.fs} Glossary
11226: @cindex @file{objects.fs} Glossary
1.20 pazsan 11227:
11228:
1.78 anton 11229: doc---objects-bind
11230: doc---objects-<bind>
11231: doc---objects-bind'
11232: doc---objects-[bind]
11233: doc---objects-class
11234: doc---objects-class->map
11235: doc---objects-class-inst-size
11236: doc---objects-class-override!
1.79 anton 11237: doc---objects-class-previous
11238: doc---objects-class>order
1.78 anton 11239: doc---objects-construct
11240: doc---objects-current'
11241: doc---objects-[current]
11242: doc---objects-current-interface
11243: doc---objects-dict-new
11244: doc---objects-end-class
11245: doc---objects-end-class-noname
11246: doc---objects-end-interface
11247: doc---objects-end-interface-noname
11248: doc---objects-end-methods
11249: doc---objects-exitm
11250: doc---objects-heap-new
11251: doc---objects-implementation
11252: doc---objects-init-object
11253: doc---objects-inst-value
11254: doc---objects-inst-var
11255: doc---objects-interface
11256: doc---objects-m:
11257: doc---objects-:m
11258: doc---objects-;m
11259: doc---objects-method
11260: doc---objects-methods
11261: doc---objects-object
11262: doc---objects-overrides
11263: doc---objects-[parent]
11264: doc---objects-print
11265: doc---objects-protected
11266: doc---objects-public
11267: doc---objects-selector
11268: doc---objects-this
11269: doc---objects-<to-inst>
11270: doc---objects-[to-inst]
11271: doc---objects-to-this
11272: doc---objects-xt-new
1.20 pazsan 11273:
11274:
1.78 anton 11275: @c -------------------------------------------------------------
11276: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11277: @subsection The @file{oof.fs} model
11278: @cindex oof
11279: @cindex object-oriented programming
1.20 pazsan 11280:
1.78 anton 11281: @cindex @file{objects.fs}
11282: @cindex @file{oof.fs}
1.20 pazsan 11283:
1.78 anton 11284: This section describes the @file{oof.fs} package.
1.20 pazsan 11285:
1.78 anton 11286: The package described in this section has been used in bigFORTH since 1991, and
11287: used for two large applications: a chromatographic system used to
11288: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11289:
1.78 anton 11290: You can find a description (in German) of @file{oof.fs} in @cite{Object
11291: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11292: 10(2), 1994.
1.20 pazsan 11293:
1.78 anton 11294: @menu
11295: * Properties of the OOF model::
11296: * Basic OOF Usage::
11297: * The OOF base class::
11298: * Class Declaration::
11299: * Class Implementation::
11300: @end menu
1.20 pazsan 11301:
1.78 anton 11302: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11303: @subsubsection Properties of the @file{oof.fs} model
11304: @cindex @file{oof.fs} properties
1.20 pazsan 11305:
1.78 anton 11306: @itemize @bullet
11307: @item
11308: This model combines object oriented programming with information
11309: hiding. It helps you writing large application, where scoping is
11310: necessary, because it provides class-oriented scoping.
1.20 pazsan 11311:
1.78 anton 11312: @item
11313: Named objects, object pointers, and object arrays can be created,
11314: selector invocation uses the ``object selector'' syntax. Selector invocation
11315: to objects and/or selectors on the stack is a bit less convenient, but
11316: possible.
1.44 crook 11317:
1.78 anton 11318: @item
11319: Selector invocation and instance variable usage of the active object is
11320: straightforward, since both make use of the active object.
1.44 crook 11321:
1.78 anton 11322: @item
11323: Late binding is efficient and easy to use.
1.20 pazsan 11324:
1.78 anton 11325: @item
11326: State-smart objects parse selectors. However, extensibility is provided
11327: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11328:
1.78 anton 11329: @item
11330: An implementation in ANS Forth is available.
1.20 pazsan 11331:
1.78 anton 11332: @end itemize
1.23 crook 11333:
11334:
1.78 anton 11335: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11336: @subsubsection Basic @file{oof.fs} Usage
11337: @cindex @file{oof.fs} usage
1.23 crook 11338:
1.78 anton 11339: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11340:
1.78 anton 11341: You can define a class for graphical objects like this:
1.23 crook 11342:
1.78 anton 11343: @cindex @code{class} usage
11344: @cindex @code{class;} usage
11345: @cindex @code{method} usage
11346: @example
11347: object class graphical \ "object" is the parent class
1.139 pazsan 11348: method draw ( x y -- )
1.78 anton 11349: class;
11350: @end example
1.23 crook 11351:
1.78 anton 11352: This code defines a class @code{graphical} with an
11353: operation @code{draw}. We can perform the operation
11354: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11355:
1.78 anton 11356: @example
11357: 100 100 t-rex draw
11358: @end example
1.23 crook 11359:
1.78 anton 11360: @noindent
11361: where @code{t-rex} is an object or object pointer, created with e.g.
11362: @code{graphical : t-rex}.
1.23 crook 11363:
1.78 anton 11364: @cindex abstract class
11365: How do we create a graphical object? With the present definitions,
11366: we cannot create a useful graphical object. The class
11367: @code{graphical} describes graphical objects in general, but not
11368: any concrete graphical object type (C++ users would call it an
11369: @emph{abstract class}); e.g., there is no method for the selector
11370: @code{draw} in the class @code{graphical}.
1.23 crook 11371:
1.78 anton 11372: For concrete graphical objects, we define child classes of the
11373: class @code{graphical}, e.g.:
1.23 crook 11374:
1.78 anton 11375: @example
11376: graphical class circle \ "graphical" is the parent class
11377: cell var circle-radius
11378: how:
11379: : draw ( x y -- )
11380: circle-radius @@ draw-circle ;
1.23 crook 11381:
1.139 pazsan 11382: : init ( n-radius -- )
1.78 anton 11383: circle-radius ! ;
11384: class;
11385: @end example
1.1 anton 11386:
1.78 anton 11387: Here we define a class @code{circle} as a child of @code{graphical},
11388: with a field @code{circle-radius}; it defines new methods for the
11389: selectors @code{draw} and @code{init} (@code{init} is defined in
11390: @code{object}, the parent class of @code{graphical}).
1.1 anton 11391:
1.78 anton 11392: Now we can create a circle in the dictionary with:
1.1 anton 11393:
1.78 anton 11394: @example
11395: 50 circle : my-circle
11396: @end example
1.21 crook 11397:
1.78 anton 11398: @noindent
11399: @code{:} invokes @code{init}, thus initializing the field
11400: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11401: with:
1.1 anton 11402:
1.78 anton 11403: @example
11404: 100 100 my-circle draw
11405: @end example
1.1 anton 11406:
1.78 anton 11407: @cindex selector invocation, restrictions
11408: @cindex class definition, restrictions
11409: Note: You can only invoke a selector if the receiving object belongs to
11410: the class where the selector was defined or one of its descendents;
11411: e.g., you can invoke @code{draw} only for objects belonging to
11412: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11413: mechanism will check if you try to invoke a selector that is not
11414: defined in this class hierarchy, so you'll get an error at compilation
11415: time.
1.1 anton 11416:
11417:
1.78 anton 11418: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11419: @subsubsection The @file{oof.fs} base class
11420: @cindex @file{oof.fs} base class
1.1 anton 11421:
1.78 anton 11422: When you define a class, you have to specify a parent class. So how do
11423: you start defining classes? There is one class available from the start:
11424: @code{object}. You have to use it as ancestor for all classes. It is the
11425: only class that has no parent. Classes are also objects, except that
11426: they don't have instance variables; class manipulation such as
11427: inheritance or changing definitions of a class is handled through
11428: selectors of the class @code{object}.
1.1 anton 11429:
1.78 anton 11430: @code{object} provides a number of selectors:
1.1 anton 11431:
1.78 anton 11432: @itemize @bullet
11433: @item
11434: @code{class} for subclassing, @code{definitions} to add definitions
11435: later on, and @code{class?} to get type informations (is the class a
11436: subclass of the class passed on the stack?).
1.1 anton 11437:
1.78 anton 11438: doc---object-class
11439: doc---object-definitions
11440: doc---object-class?
1.1 anton 11441:
11442:
1.26 crook 11443: @item
1.78 anton 11444: @code{init} and @code{dispose} as constructor and destructor of the
11445: object. @code{init} is invocated after the object's memory is allocated,
11446: while @code{dispose} also handles deallocation. Thus if you redefine
11447: @code{dispose}, you have to call the parent's dispose with @code{super
11448: dispose}, too.
11449:
11450: doc---object-init
11451: doc---object-dispose
11452:
1.1 anton 11453:
1.26 crook 11454: @item
1.78 anton 11455: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11456: @code{[]} to create named and unnamed objects and object arrays or
11457: object pointers.
11458:
11459: doc---object-new
11460: doc---object-new[]
11461: doc---object-:
11462: doc---object-ptr
11463: doc---object-asptr
11464: doc---object-[]
11465:
1.1 anton 11466:
1.26 crook 11467: @item
1.78 anton 11468: @code{::} and @code{super} for explicit scoping. You should use explicit
11469: scoping only for super classes or classes with the same set of instance
11470: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11471:
1.78 anton 11472: doc---object-::
11473: doc---object-super
1.21 crook 11474:
11475:
1.26 crook 11476: @item
1.78 anton 11477: @code{self} to get the address of the object
1.21 crook 11478:
1.78 anton 11479: doc---object-self
1.21 crook 11480:
11481:
1.78 anton 11482: @item
11483: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11484: pointers and instance defers.
1.21 crook 11485:
1.78 anton 11486: doc---object-bind
11487: doc---object-bound
11488: doc---object-link
11489: doc---object-is
1.21 crook 11490:
11491:
1.78 anton 11492: @item
11493: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11494: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11495:
1.78 anton 11496: doc---object-'
11497: doc---object-postpone
1.21 crook 11498:
11499:
1.78 anton 11500: @item
11501: @code{with} and @code{endwith} to select the active object from the
11502: stack, and enable its scope. Using @code{with} and @code{endwith}
11503: also allows you to create code using selector @code{postpone} without being
11504: trapped by the state-smart objects.
1.21 crook 11505:
1.78 anton 11506: doc---object-with
11507: doc---object-endwith
1.21 crook 11508:
11509:
1.78 anton 11510: @end itemize
1.21 crook 11511:
1.78 anton 11512: @node Class Declaration, Class Implementation, The OOF base class, OOF
11513: @subsubsection Class Declaration
11514: @cindex class declaration
1.21 crook 11515:
1.78 anton 11516: @itemize @bullet
11517: @item
11518: Instance variables
1.21 crook 11519:
1.78 anton 11520: doc---oof-var
1.21 crook 11521:
11522:
1.78 anton 11523: @item
11524: Object pointers
1.21 crook 11525:
1.78 anton 11526: doc---oof-ptr
11527: doc---oof-asptr
1.21 crook 11528:
11529:
1.78 anton 11530: @item
11531: Instance defers
1.21 crook 11532:
1.78 anton 11533: doc---oof-defer
1.21 crook 11534:
11535:
1.78 anton 11536: @item
11537: Method selectors
1.21 crook 11538:
1.78 anton 11539: doc---oof-early
11540: doc---oof-method
1.21 crook 11541:
11542:
1.78 anton 11543: @item
11544: Class-wide variables
1.21 crook 11545:
1.78 anton 11546: doc---oof-static
1.21 crook 11547:
11548:
1.78 anton 11549: @item
11550: End declaration
1.1 anton 11551:
1.78 anton 11552: doc---oof-how:
11553: doc---oof-class;
1.21 crook 11554:
11555:
1.78 anton 11556: @end itemize
1.21 crook 11557:
1.78 anton 11558: @c -------------------------------------------------------------
11559: @node Class Implementation, , Class Declaration, OOF
11560: @subsubsection Class Implementation
11561: @cindex class implementation
1.21 crook 11562:
1.78 anton 11563: @c -------------------------------------------------------------
11564: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11565: @subsection The @file{mini-oof.fs} model
11566: @cindex mini-oof
1.21 crook 11567:
1.78 anton 11568: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11569: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11570: and reduces to the bare minimum of features. This is based on a posting
11571: of Bernd Paysan in comp.lang.forth.
1.21 crook 11572:
1.78 anton 11573: @menu
11574: * Basic Mini-OOF Usage::
11575: * Mini-OOF Example::
11576: * Mini-OOF Implementation::
11577: @end menu
1.21 crook 11578:
1.78 anton 11579: @c -------------------------------------------------------------
11580: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11581: @subsubsection Basic @file{mini-oof.fs} Usage
11582: @cindex mini-oof usage
1.21 crook 11583:
1.78 anton 11584: There is a base class (@code{class}, which allocates one cell for the
11585: object pointer) plus seven other words: to define a method, a variable,
11586: a class; to end a class, to resolve binding, to allocate an object and
11587: to compile a class method.
11588: @comment TODO better description of the last one
1.26 crook 11589:
1.21 crook 11590:
1.78 anton 11591: doc-object
11592: doc-method
11593: doc-var
11594: doc-class
11595: doc-end-class
11596: doc-defines
11597: doc-new
11598: doc-::
1.21 crook 11599:
11600:
11601:
1.78 anton 11602: @c -------------------------------------------------------------
11603: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11604: @subsubsection Mini-OOF Example
11605: @cindex mini-oof example
1.1 anton 11606:
1.78 anton 11607: A short example shows how to use this package. This example, in slightly
11608: extended form, is supplied as @file{moof-exm.fs}
11609: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11610:
1.26 crook 11611: @example
1.78 anton 11612: object class
11613: method init
11614: method draw
11615: end-class graphical
1.26 crook 11616: @end example
1.20 pazsan 11617:
1.78 anton 11618: This code defines a class @code{graphical} with an
11619: operation @code{draw}. We can perform the operation
11620: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11621:
1.26 crook 11622: @example
1.78 anton 11623: 100 100 t-rex draw
1.26 crook 11624: @end example
1.12 anton 11625:
1.78 anton 11626: where @code{t-rex} is an object or object pointer, created with e.g.
11627: @code{graphical new Constant t-rex}.
1.12 anton 11628:
1.78 anton 11629: For concrete graphical objects, we define child classes of the
11630: class @code{graphical}, e.g.:
1.12 anton 11631:
1.26 crook 11632: @example
11633: graphical class
1.78 anton 11634: cell var circle-radius
11635: end-class circle \ "graphical" is the parent class
1.12 anton 11636:
1.78 anton 11637: :noname ( x y -- )
11638: circle-radius @@ draw-circle ; circle defines draw
11639: :noname ( r -- )
11640: circle-radius ! ; circle defines init
11641: @end example
1.12 anton 11642:
1.78 anton 11643: There is no implicit init method, so we have to define one. The creation
11644: code of the object now has to call init explicitely.
1.21 crook 11645:
1.78 anton 11646: @example
11647: circle new Constant my-circle
11648: 50 my-circle init
1.12 anton 11649: @end example
11650:
1.78 anton 11651: It is also possible to add a function to create named objects with
11652: automatic call of @code{init}, given that all objects have @code{init}
11653: on the same place:
1.38 anton 11654:
1.78 anton 11655: @example
11656: : new: ( .. o "name" -- )
11657: new dup Constant init ;
11658: 80 circle new: large-circle
11659: @end example
1.12 anton 11660:
1.78 anton 11661: We can draw this new circle at (100,100) with:
1.12 anton 11662:
1.78 anton 11663: @example
11664: 100 100 my-circle draw
11665: @end example
1.12 anton 11666:
1.78 anton 11667: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11668: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11669:
1.78 anton 11670: Object-oriented systems with late binding typically use a
11671: ``vtable''-approach: the first variable in each object is a pointer to a
11672: table, which contains the methods as function pointers. The vtable
11673: may also contain other information.
1.12 anton 11674:
1.79 anton 11675: So first, let's declare selectors:
1.37 anton 11676:
11677: @example
1.79 anton 11678: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11679: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11680: @end example
1.37 anton 11681:
1.79 anton 11682: During selector declaration, the number of selectors and instance
11683: variables is on the stack (in address units). @code{method} creates one
11684: selector and increments the selector number. To execute a selector, it
1.78 anton 11685: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11686: executes the method @i{xt} stored there. Each selector takes the object
11687: it is invoked with as top of stack parameter; it passes the parameters
11688: (including the object) unchanged to the appropriate method which should
1.78 anton 11689: consume that object.
1.37 anton 11690:
1.78 anton 11691: Now, we also have to declare instance variables
1.37 anton 11692:
1.78 anton 11693: @example
1.79 anton 11694: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11695: DOES> ( o -- addr ) @@ + ;
1.37 anton 11696: @end example
11697:
1.78 anton 11698: As before, a word is created with the current offset. Instance
11699: variables can have different sizes (cells, floats, doubles, chars), so
11700: all we do is take the size and add it to the offset. If your machine
11701: has alignment restrictions, put the proper @code{aligned} or
11702: @code{faligned} before the variable, to adjust the variable
11703: offset. That's why it is on the top of stack.
1.37 anton 11704:
1.78 anton 11705: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11706:
1.78 anton 11707: @example
11708: Create object 1 cells , 2 cells ,
1.79 anton 11709: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11710: @end example
1.12 anton 11711:
1.78 anton 11712: For inheritance, the vtable of the parent object has to be
11713: copied when a new, derived class is declared. This gives all the
11714: methods of the parent class, which can be overridden, though.
1.12 anton 11715:
1.78 anton 11716: @example
1.79 anton 11717: : end-class ( class selectors vars "name" -- )
1.78 anton 11718: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11719: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11720: @end example
1.12 anton 11721:
1.78 anton 11722: The first line creates the vtable, initialized with
11723: @code{noop}s. The second line is the inheritance mechanism, it
11724: copies the xts from the parent vtable.
1.12 anton 11725:
1.78 anton 11726: We still have no way to define new methods, let's do that now:
1.12 anton 11727:
1.26 crook 11728: @example
1.79 anton 11729: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11730: @end example
1.12 anton 11731:
1.78 anton 11732: To allocate a new object, we need a word, too:
1.12 anton 11733:
1.78 anton 11734: @example
11735: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11736: @end example
11737:
1.78 anton 11738: Sometimes derived classes want to access the method of the
11739: parent object. There are two ways to achieve this with Mini-OOF:
11740: first, you could use named words, and second, you could look up the
11741: vtable of the parent object.
1.12 anton 11742:
1.78 anton 11743: @example
11744: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11745: @end example
1.12 anton 11746:
11747:
1.78 anton 11748: Nothing can be more confusing than a good example, so here is
11749: one. First let's declare a text object (called
11750: @code{button}), that stores text and position:
1.12 anton 11751:
1.78 anton 11752: @example
11753: object class
11754: cell var text
11755: cell var len
11756: cell var x
11757: cell var y
11758: method init
11759: method draw
11760: end-class button
11761: @end example
1.12 anton 11762:
1.78 anton 11763: @noindent
11764: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11765:
1.26 crook 11766: @example
1.78 anton 11767: :noname ( o -- )
11768: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11769: button defines draw
11770: :noname ( addr u o -- )
11771: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11772: button defines init
1.26 crook 11773: @end example
1.12 anton 11774:
1.78 anton 11775: @noindent
11776: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11777: new data and no new selectors:
1.78 anton 11778:
11779: @example
11780: button class
11781: end-class bold-button
1.12 anton 11782:
1.78 anton 11783: : bold 27 emit ." [1m" ;
11784: : normal 27 emit ." [0m" ;
11785: @end example
1.1 anton 11786:
1.78 anton 11787: @noindent
11788: The class @code{bold-button} has a different draw method to
11789: @code{button}, but the new method is defined in terms of the draw method
11790: for @code{button}:
1.20 pazsan 11791:
1.78 anton 11792: @example
11793: :noname bold [ button :: draw ] normal ; bold-button defines draw
11794: @end example
1.21 crook 11795:
1.78 anton 11796: @noindent
1.79 anton 11797: Finally, create two objects and apply selectors:
1.21 crook 11798:
1.26 crook 11799: @example
1.78 anton 11800: button new Constant foo
11801: s" thin foo" foo init
11802: page
11803: foo draw
11804: bold-button new Constant bar
11805: s" fat bar" bar init
11806: 1 bar y !
11807: bar draw
1.26 crook 11808: @end example
1.21 crook 11809:
11810:
1.78 anton 11811: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11812: @subsection Comparison with other object models
11813: @cindex comparison of object models
11814: @cindex object models, comparison
11815:
11816: Many object-oriented Forth extensions have been proposed (@cite{A survey
11817: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11818: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11819: relation of the object models described here to two well-known and two
11820: closely-related (by the use of method maps) models. Andras Zsoter
11821: helped us with this section.
11822:
11823: @cindex Neon model
11824: The most popular model currently seems to be the Neon model (see
11825: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11826: 1997) by Andrew McKewan) but this model has a number of limitations
11827: @footnote{A longer version of this critique can be
11828: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11829: Dimensions, May 1997) by Anton Ertl.}:
11830:
11831: @itemize @bullet
11832: @item
11833: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11834: to pass objects on the stack.
1.21 crook 11835:
1.78 anton 11836: @item
11837: It requires that the selector parses the input stream (at
1.79 anton 11838: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11839: hard to find.
1.21 crook 11840:
1.78 anton 11841: @item
1.79 anton 11842: It allows using every selector on every object; this eliminates the
11843: need for interfaces, but makes it harder to create efficient
11844: implementations.
1.78 anton 11845: @end itemize
1.21 crook 11846:
1.78 anton 11847: @cindex Pountain's object-oriented model
11848: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11849: Press, London, 1987) by Dick Pountain. However, it is not really about
11850: object-oriented programming, because it hardly deals with late
11851: binding. Instead, it focuses on features like information hiding and
11852: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11853:
1.78 anton 11854: @cindex Zsoter's object-oriented model
1.79 anton 11855: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11856: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11857: describes a model that makes heavy use of an active object (like
11858: @code{this} in @file{objects.fs}): The active object is not only used
11859: for accessing all fields, but also specifies the receiving object of
11860: every selector invocation; you have to change the active object
11861: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11862: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11863: the method entry point is unnecessary with Zsoter's model, because the
11864: receiving object is the active object already. On the other hand, the
11865: explicit change is absolutely necessary in that model, because otherwise
11866: no one could ever change the active object. An ANS Forth implementation
11867: of this model is available through
11868: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11869:
1.78 anton 11870: @cindex @file{oof.fs}, differences to other models
11871: The @file{oof.fs} model combines information hiding and overloading
11872: resolution (by keeping names in various word lists) with object-oriented
11873: programming. It sets the active object implicitly on method entry, but
11874: also allows explicit changing (with @code{>o...o>} or with
11875: @code{with...endwith}). It uses parsing and state-smart objects and
11876: classes for resolving overloading and for early binding: the object or
11877: class parses the selector and determines the method from this. If the
11878: selector is not parsed by an object or class, it performs a call to the
11879: selector for the active object (late binding), like Zsoter's model.
11880: Fields are always accessed through the active object. The big
11881: disadvantage of this model is the parsing and the state-smartness, which
11882: reduces extensibility and increases the opportunities for subtle bugs;
11883: essentially, you are only safe if you never tick or @code{postpone} an
11884: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11885:
1.78 anton 11886: @cindex @file{mini-oof.fs}, differences to other models
11887: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11888: version of the @file{objects.fs} model, but syntactically it is a
11889: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11890:
11891:
1.78 anton 11892: @c -------------------------------------------------------------
1.150 anton 11893: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11894: @section Programming Tools
11895: @cindex programming tools
1.21 crook 11896:
1.78 anton 11897: @c !! move this and assembler down below OO stuff.
1.21 crook 11898:
1.78 anton 11899: @menu
1.150 anton 11900: * Examining:: Data and Code.
11901: * Forgetting words:: Usually before reloading.
1.78 anton 11902: * Debugging:: Simple and quick.
11903: * Assertions:: Making your programs self-checking.
11904: * Singlestep Debugger:: Executing your program word by word.
11905: @end menu
1.21 crook 11906:
1.78 anton 11907: @node Examining, Forgetting words, Programming Tools, Programming Tools
11908: @subsection Examining data and code
11909: @cindex examining data and code
11910: @cindex data examination
11911: @cindex code examination
1.44 crook 11912:
1.78 anton 11913: The following words inspect the stack non-destructively:
1.21 crook 11914:
1.78 anton 11915: doc-.s
11916: doc-f.s
1.158 anton 11917: doc-maxdepth-.s
1.44 crook 11918:
1.78 anton 11919: There is a word @code{.r} but it does @i{not} display the return stack!
11920: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11921:
1.78 anton 11922: doc-depth
11923: doc-fdepth
11924: doc-clearstack
1.124 anton 11925: doc-clearstacks
1.21 crook 11926:
1.78 anton 11927: The following words inspect memory.
1.21 crook 11928:
1.78 anton 11929: doc-?
11930: doc-dump
1.21 crook 11931:
1.78 anton 11932: And finally, @code{see} allows to inspect code:
1.21 crook 11933:
1.78 anton 11934: doc-see
11935: doc-xt-see
1.111 anton 11936: doc-simple-see
11937: doc-simple-see-range
1.182 anton 11938: doc-see-code
11939: doc-see-code-range
1.21 crook 11940:
1.78 anton 11941: @node Forgetting words, Debugging, Examining, Programming Tools
11942: @subsection Forgetting words
11943: @cindex words, forgetting
11944: @cindex forgeting words
1.21 crook 11945:
1.78 anton 11946: @c anton: other, maybe better places for this subsection: Defining Words;
11947: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11948:
1.78 anton 11949: Forth allows you to forget words (and everything that was alloted in the
11950: dictonary after them) in a LIFO manner.
1.21 crook 11951:
1.78 anton 11952: doc-marker
1.21 crook 11953:
1.78 anton 11954: The most common use of this feature is during progam development: when
11955: you change a source file, forget all the words it defined and load it
11956: again (since you also forget everything defined after the source file
11957: was loaded, you have to reload that, too). Note that effects like
11958: storing to variables and destroyed system words are not undone when you
11959: forget words. With a system like Gforth, that is fast enough at
11960: starting up and compiling, I find it more convenient to exit and restart
11961: Gforth, as this gives me a clean slate.
1.21 crook 11962:
1.78 anton 11963: Here's an example of using @code{marker} at the start of a source file
11964: that you are debugging; it ensures that you only ever have one copy of
11965: the file's definitions compiled at any time:
1.21 crook 11966:
1.78 anton 11967: @example
11968: [IFDEF] my-code
11969: my-code
11970: [ENDIF]
1.26 crook 11971:
1.78 anton 11972: marker my-code
11973: init-included-files
1.21 crook 11974:
1.78 anton 11975: \ .. definitions start here
11976: \ .
11977: \ .
11978: \ end
11979: @end example
1.21 crook 11980:
1.26 crook 11981:
1.78 anton 11982: @node Debugging, Assertions, Forgetting words, Programming Tools
11983: @subsection Debugging
11984: @cindex debugging
1.21 crook 11985:
1.78 anton 11986: Languages with a slow edit/compile/link/test development loop tend to
11987: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11988:
1.78 anton 11989: A much better (faster) way in fast-compiling languages is to add
11990: printing code at well-selected places, let the program run, look at
11991: the output, see where things went wrong, add more printing code, etc.,
11992: until the bug is found.
1.21 crook 11993:
1.78 anton 11994: The simple debugging aids provided in @file{debugs.fs}
11995: are meant to support this style of debugging.
1.21 crook 11996:
1.78 anton 11997: The word @code{~~} prints debugging information (by default the source
11998: location and the stack contents). It is easy to insert. If you use Emacs
11999: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
12000: query-replace them with nothing). The deferred words
1.101 anton 12001: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 12002: @code{~~}. The default source location output format works well with
12003: Emacs' compilation mode, so you can step through the program at the
12004: source level using @kbd{C-x `} (the advantage over a stepping debugger
12005: is that you can step in any direction and you know where the crash has
12006: happened or where the strange data has occurred).
1.21 crook 12007:
1.78 anton 12008: doc-~~
12009: doc-printdebugdata
1.101 anton 12010: doc-.debugline
1.203 anton 12011: doc-debug-fid
1.21 crook 12012:
1.106 anton 12013: @cindex filenames in @code{~~} output
12014: @code{~~} (and assertions) will usually print the wrong file name if a
12015: marker is executed in the same file after their occurance. They will
12016: print @samp{*somewhere*} as file name if a marker is executed in the
12017: same file before their occurance.
12018:
12019:
1.78 anton 12020: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
12021: @subsection Assertions
12022: @cindex assertions
1.21 crook 12023:
1.78 anton 12024: It is a good idea to make your programs self-checking, especially if you
12025: make an assumption that may become invalid during maintenance (for
12026: example, that a certain field of a data structure is never zero). Gforth
12027: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 12028:
12029: @example
1.78 anton 12030: assert( @i{flag} )
1.26 crook 12031: @end example
12032:
1.78 anton 12033: The code between @code{assert(} and @code{)} should compute a flag, that
12034: should be true if everything is alright and false otherwise. It should
12035: not change anything else on the stack. The overall stack effect of the
12036: assertion is @code{( -- )}. E.g.
1.21 crook 12037:
1.26 crook 12038: @example
1.78 anton 12039: assert( 1 1 + 2 = ) \ what we learn in school
12040: assert( dup 0<> ) \ assert that the top of stack is not zero
12041: assert( false ) \ this code should not be reached
1.21 crook 12042: @end example
12043:
1.78 anton 12044: The need for assertions is different at different times. During
12045: debugging, we want more checking, in production we sometimes care more
12046: for speed. Therefore, assertions can be turned off, i.e., the assertion
12047: becomes a comment. Depending on the importance of an assertion and the
12048: time it takes to check it, you may want to turn off some assertions and
12049: keep others turned on. Gforth provides several levels of assertions for
12050: this purpose:
12051:
12052:
12053: doc-assert0(
12054: doc-assert1(
12055: doc-assert2(
12056: doc-assert3(
12057: doc-assert(
12058: doc-)
1.21 crook 12059:
12060:
1.78 anton 12061: The variable @code{assert-level} specifies the highest assertions that
12062: are turned on. I.e., at the default @code{assert-level} of one,
12063: @code{assert0(} and @code{assert1(} assertions perform checking, while
12064: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 12065:
1.78 anton 12066: The value of @code{assert-level} is evaluated at compile-time, not at
12067: run-time. Therefore you cannot turn assertions on or off at run-time;
12068: you have to set the @code{assert-level} appropriately before compiling a
12069: piece of code. You can compile different pieces of code at different
12070: @code{assert-level}s (e.g., a trusted library at level 1 and
12071: newly-written code at level 3).
1.26 crook 12072:
12073:
1.78 anton 12074: doc-assert-level
1.26 crook 12075:
12076:
1.78 anton 12077: If an assertion fails, a message compatible with Emacs' compilation mode
12078: is produced and the execution is aborted (currently with @code{ABORT"}.
12079: If there is interest, we will introduce a special throw code. But if you
12080: intend to @code{catch} a specific condition, using @code{throw} is
12081: probably more appropriate than an assertion).
1.106 anton 12082:
12083: @cindex filenames in assertion output
12084: Assertions (and @code{~~}) will usually print the wrong file name if a
12085: marker is executed in the same file after their occurance. They will
12086: print @samp{*somewhere*} as file name if a marker is executed in the
12087: same file before their occurance.
1.44 crook 12088:
1.78 anton 12089: Definitions in ANS Forth for these assertion words are provided
12090: in @file{compat/assert.fs}.
1.26 crook 12091:
1.44 crook 12092:
1.78 anton 12093: @node Singlestep Debugger, , Assertions, Programming Tools
12094: @subsection Singlestep Debugger
12095: @cindex singlestep Debugger
12096: @cindex debugging Singlestep
1.44 crook 12097:
1.189 anton 12098: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 12099:
1.78 anton 12100: When you create a new word there's often the need to check whether it
12101: behaves correctly or not. You can do this by typing @code{dbg
12102: badword}. A debug session might look like this:
1.26 crook 12103:
1.78 anton 12104: @example
12105: : badword 0 DO i . LOOP ; ok
12106: 2 dbg badword
12107: : badword
12108: Scanning code...
1.44 crook 12109:
1.78 anton 12110: Nesting debugger ready!
1.44 crook 12111:
1.78 anton 12112: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
12113: 400D4740 8049F68 DO -> [ 0 ]
12114: 400D4744 804A0C8 i -> [ 1 ] 00000
12115: 400D4748 400C5E60 . -> 0 [ 0 ]
12116: 400D474C 8049D0C LOOP -> [ 0 ]
12117: 400D4744 804A0C8 i -> [ 1 ] 00001
12118: 400D4748 400C5E60 . -> 1 [ 0 ]
12119: 400D474C 8049D0C LOOP -> [ 0 ]
12120: 400D4758 804B384 ; -> ok
12121: @end example
1.21 crook 12122:
1.78 anton 12123: Each line displayed is one step. You always have to hit return to
12124: execute the next word that is displayed. If you don't want to execute
12125: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12126: an overview what keys are available:
1.44 crook 12127:
1.78 anton 12128: @table @i
1.44 crook 12129:
1.78 anton 12130: @item @key{RET}
12131: Next; Execute the next word.
1.21 crook 12132:
1.78 anton 12133: @item n
12134: Nest; Single step through next word.
1.44 crook 12135:
1.78 anton 12136: @item u
12137: Unnest; Stop debugging and execute rest of word. If we got to this word
12138: with nest, continue debugging with the calling word.
1.44 crook 12139:
1.78 anton 12140: @item d
12141: Done; Stop debugging and execute rest.
1.21 crook 12142:
1.78 anton 12143: @item s
12144: Stop; Abort immediately.
1.44 crook 12145:
1.78 anton 12146: @end table
1.44 crook 12147:
1.78 anton 12148: Debugging large application with this mechanism is very difficult, because
12149: you have to nest very deeply into the program before the interesting part
12150: begins. This takes a lot of time.
1.26 crook 12151:
1.78 anton 12152: To do it more directly put a @code{BREAK:} command into your source code.
12153: When program execution reaches @code{BREAK:} the single step debugger is
12154: invoked and you have all the features described above.
1.44 crook 12155:
1.78 anton 12156: If you have more than one part to debug it is useful to know where the
12157: program has stopped at the moment. You can do this by the
12158: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12159: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12160:
1.26 crook 12161:
1.78 anton 12162: doc-dbg
12163: doc-break:
12164: doc-break"
1.44 crook 12165:
1.150 anton 12166: @c ------------------------------------------------------------
12167: @node C Interface, Assembler and Code Words, Programming Tools, Words
12168: @section C Interface
12169: @cindex C interface
12170: @cindex foreign language interface
12171: @cindex interface to C functions
12172:
1.178 anton 12173: Note that the C interface is not yet complete; callbacks are missing,
12174: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12175:
12176: @menu
12177: * Calling C Functions::
12178: * Declaring C Functions::
1.180 anton 12179: * Calling C function pointers::
1.196 anton 12180: * Defining library interfaces::
12181: * Declaring OS-level libraries::
1.150 anton 12182: * Callbacks::
1.178 anton 12183: * C interface internals::
1.155 anton 12184: * Low-Level C Interface Words::
1.150 anton 12185: @end menu
12186:
1.151 pazsan 12187: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12188: @subsection Calling C functions
1.155 anton 12189: @cindex C functions, calls to
12190: @cindex calling C functions
1.150 anton 12191:
1.151 pazsan 12192: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12193: can call it as follows: You push the arguments on the stack(s), and
12194: then call the word for the C function. The arguments have to be
12195: pushed in the same order as the arguments appear in the C
12196: documentation (i.e., the first argument is deepest on the stack).
12197: Integer and pointer arguments have to be pushed on the data stack,
12198: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12199: by the called C function.
1.150 anton 12200:
1.155 anton 12201: On returning from the C function, the return value, if any, resides on
12202: the appropriate stack: an integer return value is pushed on the data
12203: stack, an FP return value on the FP stack, and a void return value
12204: results in not pushing anything. Note that most C functions have a
12205: return value, even if that is often not used in C; in Forth, you have
12206: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12207:
1.177 anton 12208: The C interface automatically converts between the C type and the
12209: Forth type as necessary, on a best-effort basis (in some cases, there
12210: may be some loss).
1.150 anton 12211:
12212: As an example, consider the POSIX function @code{lseek()}:
12213:
12214: @example
12215: off_t lseek(int fd, off_t offset, int whence);
12216: @end example
12217:
12218: This function takes three integer arguments, and returns an integer
12219: argument, so a Forth call for setting the current file offset to the
12220: start of the file could look like this:
12221:
12222: @example
12223: fd @@ 0 SEEK_SET lseek -1 = if
12224: ... \ error handling
12225: then
12226: @end example
12227:
12228: You might be worried that an @code{off_t} does not fit into a cell, so
12229: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12230: of the return values. In that case, in your declaration of the
12231: function (@pxref{Declaring C Functions}) you should declare it to use
12232: double-cells for the off_t argument and return value, and maybe give
12233: the resulting Forth word a different name, like @code{dlseek}; the
12234: result could be called like this:
1.150 anton 12235:
12236: @example
12237: fd @@ 0. SEEK_SET dlseek -1. d= if
12238: ... \ error handling
12239: then
12240: @end example
12241:
12242: Passing and returning structs or unions is currently not supported by
12243: our interface@footnote{If you know the calling convention of your C
12244: compiler, you usually can call such functions in some way, but that
12245: way is usually not portable between platforms, and sometimes not even
12246: between C compilers.}.
12247:
1.177 anton 12248: Calling functions with a variable number of arguments (@emph{variadic}
12249: functions, e.g., @code{printf()}) is only supported by having you
12250: declare one function-calling word for each argument pattern, and
12251: calling the appropriate word for the desired pattern.
12252:
1.150 anton 12253:
1.155 anton 12254:
1.180 anton 12255: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12256: @subsection Declaring C Functions
1.155 anton 12257: @cindex C functions, declarations
12258: @cindex declaring C functions
1.150 anton 12259:
12260: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12261: it. The declaration consists of two parts:
12262:
12263: @table @b
12264:
12265: @item The C part
1.179 anton 12266: is the C declaration of the function, or more typically and portably,
12267: a C-style @code{#include} of a file that contains the declaration of
12268: the C function.
1.177 anton 12269:
12270: @item The Forth part
12271: declares the Forth types of the parameters and the Forth word name
12272: corresponding to the C function.
12273:
12274: @end table
12275:
12276: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12277: declarations are:
12278:
12279: @example
12280: \c #define _FILE_OFFSET_BITS 64
12281: \c #include <sys/types.h>
12282: \c #include <unistd.h>
12283: c-function lseek lseek n n n -- n
12284: c-function dlseek lseek n d n -- d
12285: @end example
12286:
1.178 anton 12287: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12288: of the line is ordinary C code. You can use as many lines of C
12289: declarations as you like, and they are visible for all further
12290: function declarations.
12291:
12292: The Forth part declares each interface word with @code{c-function},
12293: followed by the Forth name of the word, the C name of the called
12294: function, and the stack effect of the word. The stack effect contains
1.178 anton 12295: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12296: exactly one type for the return value. The possible types are:
12297:
12298: @table @code
12299:
12300: @item n
12301: single-cell integer
12302:
12303: @item a
12304: address (single-cell)
12305:
12306: @item d
12307: double-cell integer
12308:
12309: @item r
12310: floating-point value
12311:
12312: @item func
12313: C function pointer
12314:
12315: @item void
12316: no value (used as return type for void functions)
12317:
12318: @end table
12319:
12320: @cindex variadic C functions
12321:
12322: To deal with variadic C functions, you can declare one Forth word for
12323: every pattern you want to use, e.g.:
12324:
12325: @example
12326: \c #include <stdio.h>
12327: c-function printf-nr printf a n r -- n
12328: c-function printf-rn printf a r n -- n
12329: @end example
12330:
12331: Note that with C functions declared as variadic (or if you don't
12332: provide a prototype), the C interface has no C type to convert to, so
12333: no automatic conversion happens, which may lead to portability
12334: problems in some cases. In such cases you can perform the conversion
12335: explicitly on the C level, e.g., as follows:
12336:
12337: @example
1.178 anton 12338: \c #define printfll(s,ll) printf(s,(long long)ll)
12339: c-function printfll printfll a n -- n
1.177 anton 12340: @end example
12341:
12342: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12343: that casts (converts) the Forth single-cell integer into a
12344: C @code{long long} before calling @code{printf()}.
1.177 anton 12345:
12346: doc-\c
12347: doc-c-function
1.207 pazsan 12348: doc-c-value
12349: doc-c-variable
1.177 anton 12350:
12351: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12352: dynamic linking. If these features are not available, there are
12353: other, less convenient and less portable C interfaces in @file{lib.fs}
12354: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12355: mostly incompatible with each other and with the documented C
12356: interface; you can find some examples for the @file{lib.fs} interface
12357: in @file{lib.fs}.
1.177 anton 12358:
12359:
1.196 anton 12360: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180 anton 12361: @subsection Calling C function pointers from Forth
12362: @cindex C function pointers, calling from Forth
1.177 anton 12363:
1.180 anton 12364: If you come across a C function pointer (e.g., in some C-constructed
12365: structure) and want to call it from your Forth program, you can also
12366: use the features explained until now to achieve that, as follows:
1.150 anton 12367:
1.180 anton 12368: Let us assume that there is a C function pointer type @code{func1}
12369: defined in some header file @file{func1.h}, and you know that these
12370: functions take one integer argument and return an integer result; and
12371: you want to call functions through such pointers. Just define
1.155 anton 12372:
1.180 anton 12373: @example
12374: \c #include <func1.h>
12375: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12376: c-function call-func1 call_func1 n func -- n
12377: @end example
12378:
12379: and then you can call a function pointed to by, say @code{func1a} as
12380: follows:
12381:
12382: @example
12383: -5 func1a call-func1 .
12384: @end example
12385:
12386: In the C part, @code{call_func} is defined as a macro to avoid having
12387: to declare the exact parameter and return types, so the C compiler
12388: knows them from the declaration of @code{func1}.
12389:
12390: The Forth word @code{call-func1} is similar to @code{execute}, except
12391: that it takes a C @code{func1} pointer instead of a Forth execution
12392: token, and it is specific to @code{func1} pointers. For each type of
12393: function pointer you want to call from Forth, you have to define
12394: a separate calling word.
12395:
12396:
1.196 anton 12397: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12398: @subsection Defining library interfaces
12399: @cindex giving a name to a library interface
12400: @cindex library interface names
12401:
12402: You can give a name to a bunch of C function declarations (a library
12403: interface), as follows:
12404:
12405: @example
12406: c-library lseek-lib
12407: \c #define _FILE_OFFSET_BITS 64
12408: ...
12409: end-c-library
12410: @end example
12411:
1.202 anton 12412: The effect of giving such a name to the interface is that the names of
12413: the generated files will contain that name, and when you use the
12414: interface a second time, it will use the existing files instead of
12415: generating and compiling them again, saving you time. Note that even
12416: if you change the declarations, the old (stale) files will be used,
12417: probably leading to errors. So, during development of the
12418: declarations we recommend not using @code{c-library}. Normally these
12419: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12420: that directory you can get rid of stale files.
12421:
12422: Note that you should use @code{c-library} before everything else
12423: having anything to do with that library, as it resets some setup
12424: stuff. The idea is that the typical use is to put each
12425: @code{c-library}...@code{end-library} unit in its own file, and to be
12426: able to include these files in any order.
1.196 anton 12427:
12428: Note that the library name is not allocated in the dictionary and
12429: therefore does not shadow dictionary names. It is used in the file
12430: system, so you have to use naming conventions appropriate for file
12431: systems. Also, you must not call a function you declare after
12432: @code{c-library} before you perform @code{end-c-library}.
12433:
12434: A major benefit of these named library interfaces is that, once they
12435: are generated, the tools used to generated them (in particular, the C
12436: compiler and libtool) are no longer needed, so the interface can be
12437: used even on machines that do not have the tools installed.
12438:
12439: doc-c-library-name
12440: doc-c-library
12441: doc-end-c-library
12442:
12443:
12444: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12445: @subsection Declaring OS-level libraries
1.195 anton 12446: @cindex Shared libraries in C interface
12447: @cindex Dynamically linked libraries in C interface
12448: @cindex Libraries in C interface
12449:
1.196 anton 12450: For calling some C functions, you need to link with a specific
12451: OS-level library that contains that function. E.g., the @code{sin}
12452: function requires linking a special library by using the command line
12453: switch @code{-lm}. In our C iterface you do the equivalent thing by
12454: calling @code{add-lib} as follows:
1.195 anton 12455:
12456: @example
12457: clear-libs
12458: s" m" add-lib
12459: \c #include <math.h>
12460: c-function sin sin r -- r
12461: @end example
12462:
12463: First, you clear any libraries that may have been declared earlier
12464: (you don't need them for @code{sin}); then you add the @code{m}
12465: library (actually @code{libm.so} or somesuch) to the currently
12466: declared libraries; you can add as many as you need. Finally you
12467: declare the function as shown above. Typically you will use the same
12468: set of library declarations for many function declarations; you need
12469: to write only one set for that, right at the beginning.
12470:
1.196 anton 12471: Note that you must not call @code{clear-libs} inside
12472: @code{c-library...end-c-library}; however, @code{c-library} performs
12473: the function of @code{clear-libs}, so @code{clear-libs} is not
12474: necessary, and you usually want to put @code{add-lib} calls inside
12475: @code{c-library...end-c-library}.
12476:
1.195 anton 12477: doc-clear-libs
12478: doc-add-lib
12479:
12480:
1.196 anton 12481: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150 anton 12482: @subsection Callbacks
1.155 anton 12483: @cindex Callback functions written in Forth
12484: @cindex C function pointers to Forth words
12485:
1.177 anton 12486: Callbacks are not yet supported by the documented C interface. You
12487: can use the undocumented @file{lib.fs} interface for callbacks.
12488:
1.155 anton 12489: In some cases you have to pass a function pointer to a C function,
12490: i.e., the library wants to call back to your application (and the
12491: pointed-to function is called a callback function). You can pass the
12492: address of an existing C function (that you get with @code{lib-sym},
12493: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12494: function, you probably want to define the function as a Forth word.
12495:
12496: @c I don't understand the existing callback interface from the example - anton
12497:
1.165 anton 12498:
12499: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12500: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12501: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12502: @c > > C-Funktionsadresse auf dem TOS).
12503: @c >
12504: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12505: @c > gesehen habe, wozu das gut ist.
12506: @c
12507: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12508: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12509: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12510: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12511: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12512: @c demselben Prototyp.
12513:
12514:
1.178 anton 12515: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12516: @subsection How the C interface works
12517:
12518: The documented C interface works by generating a C code out of the
12519: declarations.
12520:
12521: In particular, for every Forth word declared with @code{c-function},
12522: it generates a wrapper function in C that takes the Forth data from
12523: the Forth stacks, and calls the target C function with these data as
12524: arguments. The C compiler then performs an implicit conversion
12525: between the Forth type from the stack, and the C type for the
12526: parameter, which is given by the C function prototype. After the C
12527: function returns, the return value is likewise implicitly converted to
12528: a Forth type and written back on the stack.
12529:
12530: The @code{\c} lines are literally included in the C code (but without
12531: the @code{\c}), and provide the necessary declarations so that the C
12532: compiler knows the C types and has enough information to perform the
12533: conversion.
12534:
12535: These wrapper functions are eventually compiled and dynamically linked
12536: into Gforth, and then they can be called.
12537:
1.195 anton 12538: The libraries added with @code{add-lib} are used in the compile
12539: command line to specify dependent libraries with @code{-l@var{lib}},
12540: causing these libraries to be dynamically linked when the wrapper
12541: function is linked.
12542:
1.177 anton 12543:
1.178 anton 12544: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12545: @subsection Low-Level C Interface Words
1.44 crook 12546:
1.155 anton 12547: doc-open-lib
12548: doc-lib-sym
1.196 anton 12549: doc-lib-error
1.177 anton 12550: doc-call-c
1.26 crook 12551:
1.78 anton 12552: @c -------------------------------------------------------------
1.150 anton 12553: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12554: @section Assembler and Code Words
12555: @cindex assembler
12556: @cindex code words
1.44 crook 12557:
1.78 anton 12558: @menu
12559: * Code and ;code::
12560: * Common Assembler:: Assembler Syntax
12561: * Common Disassembler::
12562: * 386 Assembler:: Deviations and special cases
12563: * Alpha Assembler:: Deviations and special cases
12564: * MIPS assembler:: Deviations and special cases
1.161 anton 12565: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 12566: * ARM Assembler:: Deviations and special cases
1.78 anton 12567: * Other assemblers:: How to write them
12568: @end menu
1.21 crook 12569:
1.78 anton 12570: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12571: @subsection @code{Code} and @code{;code}
1.26 crook 12572:
1.78 anton 12573: Gforth provides some words for defining primitives (words written in
12574: machine code), and for defining the machine-code equivalent of
12575: @code{DOES>}-based defining words. However, the machine-independent
12576: nature of Gforth poses a few problems: First of all, Gforth runs on
12577: several architectures, so it can provide no standard assembler. What's
12578: worse is that the register allocation not only depends on the processor,
12579: but also on the @code{gcc} version and options used.
1.44 crook 12580:
1.78 anton 12581: The words that Gforth offers encapsulate some system dependences (e.g.,
12582: the header structure), so a system-independent assembler may be used in
12583: Gforth. If you do not have an assembler, you can compile machine code
12584: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12585: because these words emit stuff in @i{data} space; it works because
12586: Gforth has unified code/data spaces. Assembler isn't likely to be
12587: portable anyway.}.
1.21 crook 12588:
1.44 crook 12589:
1.78 anton 12590: doc-assembler
12591: doc-init-asm
12592: doc-code
12593: doc-end-code
12594: doc-;code
12595: doc-flush-icache
1.44 crook 12596:
1.21 crook 12597:
1.78 anton 12598: If @code{flush-icache} does not work correctly, @code{code} words
12599: etc. will not work (reliably), either.
1.44 crook 12600:
1.78 anton 12601: The typical usage of these @code{code} words can be shown most easily by
12602: analogy to the equivalent high-level defining words:
1.44 crook 12603:
1.78 anton 12604: @example
12605: : foo code foo
12606: <high-level Forth words> <assembler>
12607: ; end-code
12608:
12609: : bar : bar
12610: <high-level Forth words> <high-level Forth words>
12611: CREATE CREATE
12612: <high-level Forth words> <high-level Forth words>
12613: DOES> ;code
12614: <high-level Forth words> <assembler>
12615: ; end-code
12616: @end example
1.21 crook 12617:
1.78 anton 12618: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12619:
1.78 anton 12620: @cindex registers of the inner interpreter
12621: In the assembly code you will want to refer to the inner interpreter's
12622: registers (e.g., the data stack pointer) and you may want to use other
12623: registers for temporary storage. Unfortunately, the register allocation
12624: is installation-dependent.
1.44 crook 12625:
1.78 anton 12626: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12627: (return stack pointer) may be in different places in @code{gforth} and
12628: @code{gforth-fast}, or different installations. This means that you
12629: cannot write a @code{NEXT} routine that works reliably on both versions
12630: or different installations; so for doing @code{NEXT}, I recommend
12631: jumping to @code{' noop >code-address}, which contains nothing but a
12632: @code{NEXT}.
1.21 crook 12633:
1.78 anton 12634: For general accesses to the inner interpreter's registers, the easiest
12635: solution is to use explicit register declarations (@pxref{Explicit Reg
12636: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12637: all of the inner interpreter's registers: You have to compile Gforth
12638: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12639: the appropriate declarations must be present in the @code{machine.h}
12640: file (see @code{mips.h} for an example; you can find a full list of all
12641: declarable register symbols with @code{grep register engine.c}). If you
12642: give explicit registers to all variables that are declared at the
12643: beginning of @code{engine()}, you should be able to use the other
12644: caller-saved registers for temporary storage. Alternatively, you can use
12645: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12646: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12647: reserve a register (however, this restriction on register allocation may
12648: slow Gforth significantly).
1.44 crook 12649:
1.78 anton 12650: If this solution is not viable (e.g., because @code{gcc} does not allow
12651: you to explicitly declare all the registers you need), you have to find
12652: out by looking at the code where the inner interpreter's registers
12653: reside and which registers can be used for temporary storage. You can
12654: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12655:
1.78 anton 12656: In any case, it is good practice to abstract your assembly code from the
12657: actual register allocation. E.g., if the data stack pointer resides in
12658: register @code{$17}, create an alias for this register called @code{sp},
12659: and use that in your assembly code.
1.21 crook 12660:
1.78 anton 12661: @cindex code words, portable
12662: Another option for implementing normal and defining words efficiently
12663: is to add the desired functionality to the source of Gforth. For normal
12664: words you just have to edit @file{primitives} (@pxref{Automatic
12665: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12666: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12667: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12668:
1.78 anton 12669: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12670: @subsection Common Assembler
1.44 crook 12671:
1.78 anton 12672: The assemblers in Gforth generally use a postfix syntax, i.e., the
12673: instruction name follows the operands.
1.21 crook 12674:
1.78 anton 12675: The operands are passed in the usual order (the same that is used in the
12676: manual of the architecture). Since they all are Forth words, they have
12677: to be separated by spaces; you can also use Forth words to compute the
12678: operands.
1.44 crook 12679:
1.78 anton 12680: The instruction names usually end with a @code{,}. This makes it easier
12681: to visually separate instructions if you put several of them on one
12682: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12683:
1.78 anton 12684: Registers are usually specified by number; e.g., (decimal) @code{11}
12685: specifies registers R11 and F11 on the Alpha architecture (which one,
12686: depends on the instruction). The usual names are also available, e.g.,
12687: @code{s2} for R11 on Alpha.
1.21 crook 12688:
1.78 anton 12689: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12690: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12691: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12692: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12693: conditions are specified in a way specific to each assembler.
1.1 anton 12694:
1.78 anton 12695: Note that the register assignments of the Gforth engine can change
12696: between Gforth versions, or even between different compilations of the
12697: same Gforth version (e.g., if you use a different GCC version). So if
12698: you want to refer to Gforth's registers (e.g., the stack pointer or
12699: TOS), I recommend defining your own words for refering to these
12700: registers, and using them later on; then you can easily adapt to a
12701: changed register assignment. The stability of the register assignment
12702: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12703:
1.100 anton 12704: The most common use of these registers is to dispatch to the next word
12705: (the @code{next} routine). A portable way to do this is to jump to
12706: @code{' noop >code-address} (of course, this is less efficient than
12707: integrating the @code{next} code and scheduling it well).
1.1 anton 12708:
1.96 anton 12709: Another difference between Gforth version is that the top of stack is
12710: kept in memory in @code{gforth} and, on most platforms, in a register in
12711: @code{gforth-fast}.
12712:
1.78 anton 12713: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12714: @subsection Common Disassembler
1.127 anton 12715: @cindex disassembler, general
12716: @cindex gdb disassembler
1.1 anton 12717:
1.78 anton 12718: You can disassemble a @code{code} word with @code{see}
12719: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12720:
1.127 anton 12721: doc-discode
1.44 crook 12722:
1.127 anton 12723: There are two kinds of disassembler for Gforth: The Forth disassembler
12724: (available on some CPUs) and the gdb disassembler (available on
12725: platforms with @command{gdb} and @command{mktemp}). If both are
12726: available, the Forth disassembler is used by default. If you prefer
12727: the gdb disassembler, say
12728:
12729: @example
12730: ' disasm-gdb is discode
12731: @end example
12732:
12733: If neither is available, @code{discode} performs @code{dump}.
12734:
12735: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12736: assembler (i.e., same syntax, etc.). It also includes additional
12737: information in comments. In particular, the address of the instruction
12738: is given in a comment before the instruction.
1.1 anton 12739:
1.127 anton 12740: The gdb disassembler produces output in the same format as the gdb
12741: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12742: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12743: the 386 and AMD64 architectures).
12744:
1.78 anton 12745: @code{See} may display more or less than the actual code of the word,
12746: because the recognition of the end of the code is unreliable. You can
1.127 anton 12747: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12748: the code word is not immediately followed by a named word. If you have
1.116 anton 12749: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12750: to ensure that the end is recognized.
1.21 crook 12751:
1.78 anton 12752: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12753: @subsection 386 Assembler
1.44 crook 12754:
1.78 anton 12755: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12756: available under GPL, and originally part of bigFORTH.
1.21 crook 12757:
1.78 anton 12758: The 386 disassembler included in Gforth was written by Andrew McKewan
12759: and is in the public domain.
1.21 crook 12760:
1.91 anton 12761: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12762:
1.78 anton 12763: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12764:
1.78 anton 12765: The assembler includes all instruction of the Athlon, i.e. 486 core
12766: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12767: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12768: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12769:
1.78 anton 12770: There are several prefixes to switch between different operation sizes,
12771: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12772: double-word accesses. Addressing modes can be switched with @code{.wa}
12773: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12774: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12775:
1.78 anton 12776: For floating point operations, the prefixes are @code{.fs} (IEEE
12777: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12778: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12779:
1.78 anton 12780: The MMX opcodes don't have size prefixes, they are spelled out like in
12781: the Intel assembler. Instead of move from and to memory, there are
12782: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12783:
1.78 anton 12784: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12785: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12786: e.g., @code{3 #}. Here are some examples of addressing modes in various
12787: syntaxes:
1.21 crook 12788:
1.26 crook 12789: @example
1.91 anton 12790: Gforth Intel (NASM) AT&T (gas) Name
12791: .w ax ax %ax register (16 bit)
12792: ax eax %eax register (32 bit)
12793: 3 # offset 3 $3 immediate
12794: 1000 #) byte ptr 1000 1000 displacement
12795: bx ) [ebx] (%ebx) base
12796: 100 di d) 100[edi] 100(%edi) base+displacement
12797: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12798: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12799: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12800: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12801: @end example
12802:
12803: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12804: @code{DI)} to enforce 32-bit displacement fields (useful for
12805: later patching).
1.21 crook 12806:
1.78 anton 12807: Some example of instructions are:
1.1 anton 12808:
12809: @example
1.78 anton 12810: ax bx mov \ move ebx,eax
12811: 3 # ax mov \ mov eax,3
1.137 pazsan 12812: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12813: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12814: .w ax bx mov \ mov bx,ax
1.1 anton 12815: @end example
12816:
1.78 anton 12817: The following forms are supported for binary instructions:
1.1 anton 12818:
12819: @example
1.78 anton 12820: <reg> <reg> <inst>
12821: <n> # <reg> <inst>
12822: <mem> <reg> <inst>
12823: <reg> <mem> <inst>
1.136 pazsan 12824: <n> # <mem> <inst>
1.1 anton 12825: @end example
12826:
1.136 pazsan 12827: The shift/rotate syntax is:
1.1 anton 12828:
1.26 crook 12829: @example
1.78 anton 12830: <reg/mem> 1 # shl \ shortens to shift without immediate
12831: <reg/mem> 4 # shl
12832: <reg/mem> cl shl
1.26 crook 12833: @end example
1.1 anton 12834:
1.78 anton 12835: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12836: the byte version.
1.1 anton 12837:
1.78 anton 12838: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12839: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12840: pc < >= <= >}. (Note that most of these words shadow some Forth words
12841: when @code{assembler} is in front of @code{forth} in the search path,
12842: e.g., in @code{code} words). Currently the control structure words use
12843: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12844: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12845:
1.78 anton 12846: Here is an example of a @code{code} word (assumes that the stack pointer
12847: is in esi and the TOS is in ebx):
1.21 crook 12848:
1.26 crook 12849: @example
1.78 anton 12850: code my+ ( n1 n2 -- n )
12851: 4 si D) bx add
12852: 4 # si add
12853: Next
12854: end-code
1.26 crook 12855: @end example
1.21 crook 12856:
1.161 anton 12857:
1.78 anton 12858: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12859: @subsection Alpha Assembler
1.21 crook 12860:
1.78 anton 12861: The Alpha assembler and disassembler were originally written by Bernd
12862: Thallner.
1.26 crook 12863:
1.78 anton 12864: The register names @code{a0}--@code{a5} are not available to avoid
12865: shadowing hex numbers.
1.2 jwilke 12866:
1.78 anton 12867: Immediate forms of arithmetic instructions are distinguished by a
12868: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12869: does not count as arithmetic instruction).
1.2 jwilke 12870:
1.78 anton 12871: You have to specify all operands to an instruction, even those that
12872: other assemblers consider optional, e.g., the destination register for
12873: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12874:
1.78 anton 12875: You can specify conditions for @code{if,} by removing the first @code{b}
12876: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12877:
1.26 crook 12878: @example
1.78 anton 12879: 11 fgt if, \ if F11>0e
12880: ...
12881: endif,
1.26 crook 12882: @end example
1.2 jwilke 12883:
1.78 anton 12884: @code{fbgt,} gives @code{fgt}.
12885:
1.161 anton 12886: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12887: @subsection MIPS assembler
1.2 jwilke 12888:
1.78 anton 12889: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12890:
1.78 anton 12891: Currently the assembler and disassembler only cover the MIPS-I
12892: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12893:
1.78 anton 12894: The register names @code{$a0}--@code{$a3} are not available to avoid
12895: shadowing hex numbers.
1.2 jwilke 12896:
1.78 anton 12897: Because there is no way to distinguish registers from immediate values,
12898: you have to explicitly use the immediate forms of instructions, i.e.,
12899: @code{addiu,}, not just @code{addu,} (@command{as} does this
12900: implicitly).
1.2 jwilke 12901:
1.78 anton 12902: If the architecture manual specifies several formats for the instruction
12903: (e.g., for @code{jalr,}), you usually have to use the one with more
12904: arguments (i.e., two for @code{jalr,}). When in doubt, see
12905: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12906:
1.78 anton 12907: Branches and jumps in the MIPS architecture have a delay slot. You have
12908: to fill it yourself (the simplest way is to use @code{nop,}), the
12909: assembler does not do it for you (unlike @command{as}). Even
12910: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12911: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12912: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12913:
1.78 anton 12914: Note that you must not put branches, jumps, or @code{li,} into the delay
12915: slot: @code{li,} may expand to several instructions, and control flow
12916: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12917:
1.78 anton 12918: For branches the argument specifying the target is a relative address;
12919: You have to add the address of the delay slot to get the absolute
12920: address.
1.1 anton 12921:
1.78 anton 12922: The MIPS architecture also has load delay slots and restrictions on
12923: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12924: yourself to satisfy these restrictions, the assembler does not do it for
12925: you.
1.1 anton 12926:
1.78 anton 12927: You can specify the conditions for @code{if,} etc. by taking a
12928: conditional branch and leaving away the @code{b} at the start and the
12929: @code{,} at the end. E.g.,
1.1 anton 12930:
1.26 crook 12931: @example
1.78 anton 12932: 4 5 eq if,
12933: ... \ do something if $4 equals $5
12934: then,
1.26 crook 12935: @end example
1.1 anton 12936:
1.161 anton 12937:
1.193 dvdkhlng 12938: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161 anton 12939: @subsection PowerPC assembler
12940:
1.162 anton 12941: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12942: Revucky.
12943:
1.162 anton 12944: This assembler does not follow the convention of ending mnemonic names
12945: with a ``,'', so some mnemonic names shadow regular Forth words (in
12946: particular: @code{and or xor fabs}); so if you want to use the Forth
12947: words, you have to make them visible first, e.g., with @code{also
12948: forth}.
12949:
1.161 anton 12950: Registers are referred to by their number, e.g., @code{9} means the
12951: integer register 9 or the FP register 9 (depending on the
12952: instruction).
12953:
12954: Because there is no way to distinguish registers from immediate values,
12955: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12956: @code{addi,}, not just @code{add,}.
1.161 anton 12957:
1.162 anton 12958: The assembler and disassembler usually support the most general form
1.161 anton 12959: of an instruction, but usually not the shorter forms (especially for
12960: branches).
12961:
12962:
1.193 dvdkhlng 12963: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12964: @subsection ARM Assembler
1.161 anton 12965:
1.193 dvdkhlng 12966: The ARM assembler included in Gforth was written from scratch by David
12967: Kuehling.
12968:
12969: The assembler includes all instruction of ARM architecture version 4,
12970: but does not (yet) have support for Thumb instructions. It also lacks
12971: support for any co-processors.
12972:
12973: The assembler uses a postfix syntax with the target operand specified
12974: last. For load/store instructions the last operand will be the
12975: register(s) to be loaded from/stored to.
12976:
12977: Registers are specified by their names @code{r0} through @code{r15},
12978: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12979: @code{fp} provided for convenience. Note that @code{ip} means intra
12980: procedure call scratch register (@code{r12}) and does not refer to the
12981: instruction pointer.
12982:
12983: Condition codes can be specified anywhere in the instruction, but will
12984: be most readable if specified just in front of the mnemonic. The 'S'
12985: flag is not a separate word, but encoded into instruction mnemonics,
12986: ie. just use @code{adds,} instead of @code{add,} if you want the
12987: status register to be updated.
12988:
12989: The following table lists the syntax of operands for general
12990: instructions:
12991:
12992: @example
12993: Gforth normal assembler description
12994: 123 # #123 immediate
12995: r12 r12 register
12996: r12 4 #LSL r12, LSL #4 shift left by immediate
12997: r12 r1 #LSL r12, LSL r1 shift left by register
12998: r12 4 #LSR r12, LSR #4 shift right by immediate
12999: r12 r1 #LSR r12, LSR r1 shift right by register
13000: r12 4 #ASR r12, ASR #4 arithmetic shift right
13001: r12 r1 #ASR r12, ASR r1 ... by register
13002: r12 4 #ROR r12, ROR #4 rotate right by immediate
13003: r12 r1 #ROR r12, ROR r1 ... by register
13004: r12 RRX r12, RRX rotate right with extend by 1
13005: @end example
13006:
13007: Memory operand syntax is listed in this table:
13008:
13009: @example
13010: Gforth normal assembler description
13011: r4 ] [r4] register
13012: r4 4 #] [r4, #+4] register with immediate offset
13013: r4 -4 #] [r4, #-4] with negative offset
13014: r4 r1 +] [r4, +r1] register with register offset
13015: r4 r1 -] [r4, -r1] with negated register offset
13016: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
13017: r4 4 #]! [r4, #+4]! immediate preincrement
13018: r4 r1 +]! [r4, +r1]! register preincrement
13019: r4 r1 -]! [r4, +r1]! register predecrement
13020: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
13021: r4 -4 ]# [r4], #-4 immediate postdecrement
13022: r4 r1 ]+ [r4], r1 register postincrement
13023: r4 r1 ]- [r4], -r1 register postdecrement
13024: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
13025: ' xyz >body [#] xyz PC-relative addressing
13026: @end example
13027:
13028: Register lists for load/store multiple instructions are started and
13029: terminated by using the words @code{@{} and @code{@}}
13030: respectivly. Between braces, register names can be listed one by one,
13031: or register ranges can be formed by using the postfix operator
13032: @code{r-r}. The @code{^} flag is not encoded in the register list
13033: operand, but instead directly encoded into the instruction mnemonic,
13034: ie. use @code{^ldm,} and @code{^stm,}.
13035:
13036: Addressing modes for load/store multiple are not encoded as
13037: instruction suffixes, but instead specified after the register that
13038: supplies the address. Use one of @code{DA}, @code{IA}, @code{DB},
13039: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
13040:
13041: The following table gives some examples:
13042:
13043: @example
13044: Gforth normal assembler
13045: @{ r0 r7 r8 @} r4 ia stm, stmia @{r0,r7,r8@}, r4
13046: @{ r0 r7 r8 @} r4 db! ldm, ldmdb @{r0,r7,r8@}, r4!
13047: @{ r0 r15 r-r @} sp ia! ^ldm, ldmfd @{r0-r15@}^, sp!
13048: @end example
13049:
13050: Conditions for control structure words are specified in front of a
13051: word:
13052:
13053: @example
13054: r1 r2 cmp, \ compare r1 and r2
13055: eq if, \ equal?
13056: ... \ code executed if r1 == r2
13057: then,
13058: @end example
13059:
13060: Here is an example of a @code{code} word (assumes that the stack
13061: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
13062: clobbered):
13063:
13064: @example
13065: code my+ ( n1 n2 -- n3 )
13066: r9 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
13067: r2 r3 r3 add, \ r3 = n2+n1
13068: r9 -4 #]! r3 str, \ push r3
13069: next,
13070: end-code
13071: @end example
13072:
13073: Look at @file{arch/arm/asm-example.fs} for more examples.
13074:
13075: @node Other assemblers, , ARM Assembler, Assembler and Code Words
1.78 anton 13076: @subsection Other assemblers
13077:
13078: If you want to contribute another assembler/disassembler, please contact
1.103 anton 13079: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13080: an assembler already. If you are writing them from scratch, please use
13081: a similar syntax style as the one we use (i.e., postfix, commas at the
13082: end of the instruction names, @pxref{Common Assembler}); make the output
13083: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 13084: similar to the style we used.
13085:
13086: Hints on implementation: The most important part is to have a good test
13087: suite that contains all instructions. Once you have that, the rest is
13088: easy. For actual coding you can take a look at
13089: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13090: the assembler and disassembler, avoiding redundancy and some potential
13091: bugs. You can also look at that file (and @pxref{Advanced does> usage
13092: example}) to get ideas how to factor a disassembler.
13093:
13094: Start with the disassembler, because it's easier to reuse data from the
13095: disassembler for the assembler than the other way round.
1.1 anton 13096:
1.78 anton 13097: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13098: how simple it can be.
1.1 anton 13099:
1.161 anton 13100:
13101:
13102:
1.78 anton 13103: @c -------------------------------------------------------------
13104: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13105: @section Threading Words
13106: @cindex threading words
1.1 anton 13107:
1.78 anton 13108: @cindex code address
13109: These words provide access to code addresses and other threading stuff
13110: in Gforth (and, possibly, other interpretive Forths). It more or less
13111: abstracts away the differences between direct and indirect threading
13112: (and, for direct threading, the machine dependences). However, at
13113: present this wordset is still incomplete. It is also pretty low-level;
13114: some day it will hopefully be made unnecessary by an internals wordset
13115: that abstracts implementation details away completely.
1.1 anton 13116:
1.78 anton 13117: The terminology used here stems from indirect threaded Forth systems; in
13118: such a system, the XT of a word is represented by the CFA (code field
13119: address) of a word; the CFA points to a cell that contains the code
13120: address. The code address is the address of some machine code that
13121: performs the run-time action of invoking the word (e.g., the
13122: @code{dovar:} routine pushes the address of the body of the word (a
13123: variable) on the stack
13124: ).
1.1 anton 13125:
1.78 anton 13126: @cindex code address
13127: @cindex code field address
13128: In an indirect threaded Forth, you can get the code address of @i{name}
13129: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13130: >code-address}, independent of the threading method.
1.1 anton 13131:
1.78 anton 13132: doc-threading-method
13133: doc->code-address
13134: doc-code-address!
1.1 anton 13135:
1.78 anton 13136: @cindex @code{does>}-handler
13137: @cindex @code{does>}-code
13138: For a word defined with @code{DOES>}, the code address usually points to
13139: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13140: routine (in Gforth on some platforms, it can also point to the dodoes
13141: routine itself). What you are typically interested in, though, is
13142: whether a word is a @code{DOES>}-defined word, and what Forth code it
13143: executes; @code{>does-code} tells you that.
1.1 anton 13144:
1.78 anton 13145: doc->does-code
1.1 anton 13146:
1.78 anton 13147: To create a @code{DOES>}-defined word with the following basic words,
13148: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13149: @code{/does-handler} aus behind you have to place your executable Forth
13150: code. Finally you have to create a word and modify its behaviour with
13151: @code{does-handler!}.
1.1 anton 13152:
1.78 anton 13153: doc-does-code!
13154: doc-does-handler!
13155: doc-/does-handler
1.1 anton 13156:
1.78 anton 13157: The code addresses produced by various defining words are produced by
13158: the following words:
1.1 anton 13159:
1.78 anton 13160: doc-docol:
13161: doc-docon:
13162: doc-dovar:
13163: doc-douser:
13164: doc-dodefer:
13165: doc-dofield:
1.1 anton 13166:
1.99 anton 13167: @cindex definer
13168: The following two words generalize @code{>code-address},
13169: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13170:
13171: doc->definer
13172: doc-definer!
13173:
1.26 crook 13174: @c -------------------------------------------------------------
1.78 anton 13175: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 13176: @section Passing Commands to the Operating System
13177: @cindex operating system - passing commands
13178: @cindex shell commands
13179:
13180: Gforth allows you to pass an arbitrary string to the host operating
13181: system shell (if such a thing exists) for execution.
13182:
13183: doc-sh
13184: doc-system
13185: doc-$?
1.23 crook 13186: doc-getenv
1.44 crook 13187:
1.26 crook 13188: @c -------------------------------------------------------------
1.47 crook 13189: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13190: @section Keeping track of Time
13191: @cindex time-related words
13192:
13193: doc-ms
13194: doc-time&date
1.79 anton 13195: doc-utime
13196: doc-cputime
1.47 crook 13197:
13198:
13199: @c -------------------------------------------------------------
13200: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 13201: @section Miscellaneous Words
13202: @cindex miscellaneous words
13203:
1.29 crook 13204: @comment TODO find homes for these
13205:
1.26 crook 13206: These section lists the ANS Forth words that are not documented
1.21 crook 13207: elsewhere in this manual. Ultimately, they all need proper homes.
13208:
1.68 anton 13209: doc-quit
1.44 crook 13210:
1.26 crook 13211: The following ANS Forth words are not currently supported by Gforth
1.27 crook 13212: (@pxref{ANS conformance}):
1.21 crook 13213:
13214: @code{EDITOR}
13215: @code{EMIT?}
13216: @code{FORGET}
13217:
1.24 anton 13218: @c ******************************************************************
13219: @node Error messages, Tools, Words, Top
13220: @chapter Error messages
13221: @cindex error messages
13222: @cindex backtrace
13223:
13224: A typical Gforth error message looks like this:
13225:
13226: @example
1.86 anton 13227: in file included from \evaluated string/:-1
1.24 anton 13228: in file included from ./yyy.fs:1
13229: ./xxx.fs:4: Invalid memory address
1.134 anton 13230: >>>bar<<<
1.79 anton 13231: Backtrace:
1.25 anton 13232: $400E664C @@
13233: $400E6664 foo
1.24 anton 13234: @end example
13235:
13236: The message identifying the error is @code{Invalid memory address}. The
13237: error happened when text-interpreting line 4 of the file
13238: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13239: word on the line where the error happened, is pointed out (with
1.134 anton 13240: @code{>>>} and @code{<<<}).
1.24 anton 13241:
13242: The file containing the error was included in line 1 of @file{./yyy.fs},
13243: and @file{yyy.fs} was included from a non-file (in this case, by giving
13244: @file{yyy.fs} as command-line parameter to Gforth).
13245:
13246: At the end of the error message you find a return stack dump that can be
13247: interpreted as a backtrace (possibly empty). On top you find the top of
13248: the return stack when the @code{throw} happened, and at the bottom you
13249: find the return stack entry just above the return stack of the topmost
13250: text interpreter.
13251:
13252: To the right of most return stack entries you see a guess for the word
13253: that pushed that return stack entry as its return address. This gives a
13254: backtrace. In our case we see that @code{bar} called @code{foo}, and
13255: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13256: address} exception).
13257:
13258: Note that the backtrace is not perfect: We don't know which return stack
13259: entries are return addresses (so we may get false positives); and in
13260: some cases (e.g., for @code{abort"}) we cannot determine from the return
13261: address the word that pushed the return address, so for some return
13262: addresses you see no names in the return stack dump.
1.25 anton 13263:
13264: @cindex @code{catch} and backtraces
13265: The return stack dump represents the return stack at the time when a
13266: specific @code{throw} was executed. In programs that make use of
13267: @code{catch}, it is not necessarily clear which @code{throw} should be
13268: used for the return stack dump (e.g., consider one @code{throw} that
13269: indicates an error, which is caught, and during recovery another error
1.160 anton 13270: happens; which @code{throw} should be used for the stack dump?).
13271: Gforth presents the return stack dump for the first @code{throw} after
13272: the last executed (not returned-to) @code{catch} or @code{nothrow};
13273: this works well in the usual case. To get the right backtrace, you
13274: usually want to insert @code{nothrow} or @code{['] false catch drop}
13275: after a @code{catch} if the error is not rethrown.
1.25 anton 13276:
13277: @cindex @code{gforth-fast} and backtraces
13278: @cindex @code{gforth-fast}, difference from @code{gforth}
13279: @cindex backtraces with @code{gforth-fast}
13280: @cindex return stack dump with @code{gforth-fast}
1.79 anton 13281: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 13282: from primitives (e.g., invalid memory address, stack empty etc.);
13283: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 13284: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 13285: exception caused by a primitive in @code{gforth-fast}, you will
13286: typically see no return stack dump at all; however, if the exception is
13287: caught by @code{catch} (e.g., for restoring some state), and then
13288: @code{throw}n again, the return stack dump will be for the first such
13289: @code{throw}.
1.2 jwilke 13290:
1.5 anton 13291: @c ******************************************************************
1.24 anton 13292: @node Tools, ANS conformance, Error messages, Top
1.1 anton 13293: @chapter Tools
13294:
13295: @menu
13296: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 13297: * Stack depth changes:: Where does this stack item come from?
1.1 anton 13298: @end menu
13299:
13300: See also @ref{Emacs and Gforth}.
13301:
1.126 pazsan 13302: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 13303: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13304: @cindex @file{ans-report.fs}
13305: @cindex report the words used in your program
13306: @cindex words used in your program
13307:
13308: If you want to label a Forth program as ANS Forth Program, you must
13309: document which wordsets the program uses; for extension wordsets, it is
13310: helpful to list the words the program requires from these wordsets
13311: (because Forth systems are allowed to provide only some words of them).
13312:
13313: The @file{ans-report.fs} tool makes it easy for you to determine which
13314: words from which wordset and which non-ANS words your application
13315: uses. You simply have to include @file{ans-report.fs} before loading the
13316: program you want to check. After loading your program, you can get the
13317: report with @code{print-ans-report}. A typical use is to run this as
13318: batch job like this:
13319: @example
13320: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13321: @end example
13322:
13323: The output looks like this (for @file{compat/control.fs}):
13324: @example
13325: The program uses the following words
13326: from CORE :
13327: : POSTPONE THEN ; immediate ?dup IF 0=
13328: from BLOCK-EXT :
13329: \
13330: from FILE :
13331: (
13332: @end example
13333:
13334: @subsection Caveats
13335:
13336: Note that @file{ans-report.fs} just checks which words are used, not whether
13337: they are used in an ANS Forth conforming way!
13338:
13339: Some words are defined in several wordsets in the
13340: standard. @file{ans-report.fs} reports them for only one of the
13341: wordsets, and not necessarily the one you expect. It depends on usage
13342: which wordset is the right one to specify. E.g., if you only use the
13343: compilation semantics of @code{S"}, it is a Core word; if you also use
13344: its interpretation semantics, it is a File word.
1.124 anton 13345:
13346:
1.127 anton 13347: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13348: @section Stack depth changes during interpretation
13349: @cindex @file{depth-changes.fs}
13350: @cindex depth changes during interpretation
13351: @cindex stack depth changes during interpretation
13352: @cindex items on the stack after interpretation
13353:
13354: Sometimes you notice that, after loading a file, there are items left
13355: on the stack. The tool @file{depth-changes.fs} helps you find out
13356: quickly where in the file these stack items are coming from.
13357:
13358: The simplest way of using @file{depth-changes.fs} is to include it
13359: before the file(s) you want to check, e.g.:
13360:
13361: @example
13362: gforth depth-changes.fs my-file.fs
13363: @end example
13364:
13365: This will compare the stack depths of the data and FP stack at every
13366: empty line (in interpretation state) against these depths at the last
13367: empty line (in interpretation state). If the depths are not equal,
13368: the position in the file and the stack contents are printed with
13369: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13370: change has occured in the paragraph of non-empty lines before the
13371: indicated line. It is a good idea to leave an empty line at the end
13372: of the file, so the last paragraph is checked, too.
13373:
13374: Checking only at empty lines usually works well, but sometimes you
13375: have big blocks of non-empty lines (e.g., when building a big table),
13376: and you want to know where in this block the stack depth changed. You
13377: can check all interpreted lines with
13378:
13379: @example
13380: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13381: @end example
13382:
13383: This checks the stack depth at every end-of-line. So the depth change
13384: occured in the line reported by the @code{~~} (not in the line
13385: before).
13386:
13387: Note that, while this offers better accuracy in indicating where the
13388: stack depth changes, it will often report many intentional stack depth
13389: changes (e.g., when an interpreted computation stretches across
13390: several lines). You can suppress the checking of some lines by
13391: putting backslashes at the end of these lines (not followed by white
13392: space), and using
13393:
13394: @example
13395: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13396: @end example
1.1 anton 13397:
13398: @c ******************************************************************
1.65 anton 13399: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13400: @chapter ANS conformance
13401: @cindex ANS conformance of Gforth
13402:
13403: To the best of our knowledge, Gforth is an
13404:
13405: ANS Forth System
13406: @itemize @bullet
13407: @item providing the Core Extensions word set
13408: @item providing the Block word set
13409: @item providing the Block Extensions word set
13410: @item providing the Double-Number word set
13411: @item providing the Double-Number Extensions word set
13412: @item providing the Exception word set
13413: @item providing the Exception Extensions word set
13414: @item providing the Facility word set
1.40 anton 13415: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13416: @item providing the File Access word set
13417: @item providing the File Access Extensions word set
13418: @item providing the Floating-Point word set
13419: @item providing the Floating-Point Extensions word set
13420: @item providing the Locals word set
13421: @item providing the Locals Extensions word set
13422: @item providing the Memory-Allocation word set
13423: @item providing the Memory-Allocation Extensions word set (that one's easy)
13424: @item providing the Programming-Tools word set
13425: @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
13426: @item providing the Search-Order word set
13427: @item providing the Search-Order Extensions word set
13428: @item providing the String word set
13429: @item providing the String Extensions word set (another easy one)
13430: @end itemize
13431:
1.118 anton 13432: Gforth has the following environmental restrictions:
13433:
13434: @cindex environmental restrictions
13435: @itemize @bullet
13436: @item
13437: While processing the OS command line, if an exception is not caught,
13438: Gforth exits with a non-zero exit code instyead of performing QUIT.
13439:
13440: @item
13441: When an @code{throw} is performed after a @code{query}, Gforth does not
13442: allways restore the input source specification in effect at the
13443: corresponding catch.
13444:
13445: @end itemize
13446:
13447:
1.1 anton 13448: @cindex system documentation
13449: In addition, ANS Forth systems are required to document certain
13450: implementation choices. This chapter tries to meet these
13451: requirements. In many cases it gives a way to ask the system for the
13452: information instead of providing the information directly, in
13453: particular, if the information depends on the processor, the operating
13454: system or the installation options chosen, or if they are likely to
13455: change during the maintenance of Gforth.
13456:
13457: @comment The framework for the rest has been taken from pfe.
13458:
13459: @menu
13460: * The Core Words::
13461: * The optional Block word set::
13462: * The optional Double Number word set::
13463: * The optional Exception word set::
13464: * The optional Facility word set::
13465: * The optional File-Access word set::
13466: * The optional Floating-Point word set::
13467: * The optional Locals word set::
13468: * The optional Memory-Allocation word set::
13469: * The optional Programming-Tools word set::
13470: * The optional Search-Order word set::
13471: @end menu
13472:
13473:
13474: @c =====================================================================
13475: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13476: @comment node-name, next, previous, up
13477: @section The Core Words
13478: @c =====================================================================
13479: @cindex core words, system documentation
13480: @cindex system documentation, core words
13481:
13482: @menu
13483: * core-idef:: Implementation Defined Options
13484: * core-ambcond:: Ambiguous Conditions
13485: * core-other:: Other System Documentation
13486: @end menu
13487:
13488: @c ---------------------------------------------------------------------
13489: @node core-idef, core-ambcond, The Core Words, The Core Words
13490: @subsection Implementation Defined Options
13491: @c ---------------------------------------------------------------------
13492: @cindex core words, implementation-defined options
13493: @cindex implementation-defined options, core words
13494:
13495:
13496: @table @i
13497: @item (Cell) aligned addresses:
13498: @cindex cell-aligned addresses
13499: @cindex aligned addresses
13500: processor-dependent. Gforth's alignment words perform natural alignment
13501: (e.g., an address aligned for a datum of size 8 is divisible by
13502: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13503:
13504: @item @code{EMIT} and non-graphic characters:
13505: @cindex @code{EMIT} and non-graphic characters
13506: @cindex non-graphic characters and @code{EMIT}
13507: The character is output using the C library function (actually, macro)
13508: @code{putc}.
13509:
13510: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13511: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13512: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13513: @cindex @code{ACCEPT}, editing
13514: @cindex @code{EXPECT}, editing
13515: This is modeled on the GNU readline library (@pxref{Readline
13516: Interaction, , Command Line Editing, readline, The GNU Readline
13517: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13518: producing a full word completion every time you type it (instead of
1.28 crook 13519: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13520:
13521: @item character set:
13522: @cindex character set
13523: The character set of your computer and display device. Gforth is
13524: 8-bit-clean (but some other component in your system may make trouble).
13525:
13526: @item Character-aligned address requirements:
13527: @cindex character-aligned address requirements
13528: installation-dependent. Currently a character is represented by a C
13529: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13530: (Comments on that requested).
13531:
13532: @item character-set extensions and matching of names:
13533: @cindex character-set extensions and matching of names
1.26 crook 13534: @cindex case-sensitivity for name lookup
13535: @cindex name lookup, case-sensitivity
13536: @cindex locale and case-sensitivity
1.21 crook 13537: Any character except the ASCII NUL character can be used in a
1.1 anton 13538: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13539: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13540: function is probably influenced by the locale. E.g., the @code{C} locale
13541: does not know about accents and umlauts, so they are matched
13542: case-sensitively in that locale. For portability reasons it is best to
13543: write programs such that they work in the @code{C} locale. Then one can
13544: use libraries written by a Polish programmer (who might use words
13545: containing ISO Latin-2 encoded characters) and by a French programmer
13546: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13547: funny results for some of the words (which ones, depends on the font you
13548: are using)). Also, the locale you prefer may not be available in other
13549: operating systems. Hopefully, Unicode will solve these problems one day.
13550:
13551: @item conditions under which control characters match a space delimiter:
13552: @cindex space delimiters
13553: @cindex control characters as delimiters
1.117 anton 13554: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13555: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13556: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13557: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13558: interpreter (aka text interpreter) by default, treats all white-space
13559: characters as delimiters.
13560:
1.26 crook 13561: @item format of the control-flow stack:
13562: @cindex control-flow stack, format
13563: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13564: stack item in cells is given by the constant @code{cs-item-size}. At the
13565: time of this writing, an item consists of a (pointer to a) locals list
13566: (third), an address in the code (second), and a tag for identifying the
13567: item (TOS). The following tags are used: @code{defstart},
13568: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13569: @code{scopestart}.
13570:
13571: @item conversion of digits > 35
13572: @cindex digits > 35
13573: The characters @code{[\]^_'} are the digits with the decimal value
13574: 36@minus{}41. There is no way to input many of the larger digits.
13575:
13576: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13577: @cindex @code{EXPECT}, display after end of input
13578: @cindex @code{ACCEPT}, display after end of input
13579: The cursor is moved to the end of the entered string. If the input is
13580: terminated using the @kbd{Return} key, a space is typed.
13581:
13582: @item exception abort sequence of @code{ABORT"}:
13583: @cindex exception abort sequence of @code{ABORT"}
13584: @cindex @code{ABORT"}, exception abort sequence
13585: The error string is stored into the variable @code{"error} and a
13586: @code{-2 throw} is performed.
13587:
13588: @item input line terminator:
13589: @cindex input line terminator
13590: @cindex line terminator on input
1.26 crook 13591: @cindex newline character on input
1.1 anton 13592: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13593: lines. One of these characters is typically produced when you type the
13594: @kbd{Enter} or @kbd{Return} key.
13595:
13596: @item maximum size of a counted string:
13597: @cindex maximum size of a counted string
13598: @cindex counted string, maximum size
13599: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13600: on all platforms, but this may change.
1.1 anton 13601:
13602: @item maximum size of a parsed string:
13603: @cindex maximum size of a parsed string
13604: @cindex parsed string, maximum size
13605: Given by the constant @code{/line}. Currently 255 characters.
13606:
13607: @item maximum size of a definition name, in characters:
13608: @cindex maximum size of a definition name, in characters
13609: @cindex name, maximum length
1.113 anton 13610: MAXU/8
1.1 anton 13611:
13612: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13613: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13614: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13615: MAXU/8
1.1 anton 13616:
13617: @item method of selecting the user input device:
13618: @cindex user input device, method of selecting
13619: The user input device is the standard input. There is currently no way to
13620: change it from within Gforth. However, the input can typically be
13621: redirected in the command line that starts Gforth.
13622:
13623: @item method of selecting the user output device:
13624: @cindex user output device, method of selecting
13625: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13626: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13627: output when the user output device is a terminal, otherwise the output
13628: is buffered.
1.1 anton 13629:
13630: @item methods of dictionary compilation:
13631: What are we expected to document here?
13632:
13633: @item number of bits in one address unit:
13634: @cindex number of bits in one address unit
13635: @cindex address unit, size in bits
13636: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13637: platforms.
1.1 anton 13638:
13639: @item number representation and arithmetic:
13640: @cindex number representation and arithmetic
1.79 anton 13641: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13642:
13643: @item ranges for integer types:
13644: @cindex ranges for integer types
13645: @cindex integer types, ranges
13646: Installation-dependent. Make environmental queries for @code{MAX-N},
13647: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13648: unsigned (and positive) types is 0. The lower bound for signed types on
13649: two's complement and one's complement machines machines can be computed
13650: by adding 1 to the upper bound.
13651:
13652: @item read-only data space regions:
13653: @cindex read-only data space regions
13654: @cindex data-space, read-only regions
13655: The whole Forth data space is writable.
13656:
13657: @item size of buffer at @code{WORD}:
13658: @cindex size of buffer at @code{WORD}
13659: @cindex @code{WORD} buffer size
13660: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13661: shared with the pictured numeric output string. If overwriting
13662: @code{PAD} is acceptable, it is as large as the remaining dictionary
13663: space, although only as much can be sensibly used as fits in a counted
13664: string.
13665:
13666: @item size of one cell in address units:
13667: @cindex cell size
13668: @code{1 cells .}.
13669:
13670: @item size of one character in address units:
13671: @cindex char size
1.79 anton 13672: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13673:
13674: @item size of the keyboard terminal buffer:
13675: @cindex size of the keyboard terminal buffer
13676: @cindex terminal buffer, size
13677: Varies. You can determine the size at a specific time using @code{lp@@
13678: tib - .}. It is shared with the locals stack and TIBs of files that
13679: include the current file. You can change the amount of space for TIBs
13680: and locals stack at Gforth startup with the command line option
13681: @code{-l}.
13682:
13683: @item size of the pictured numeric output buffer:
13684: @cindex size of the pictured numeric output buffer
13685: @cindex pictured numeric output buffer, size
13686: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13687: shared with @code{WORD}.
13688:
13689: @item size of the scratch area returned by @code{PAD}:
13690: @cindex size of the scratch area returned by @code{PAD}
13691: @cindex @code{PAD} size
13692: The remainder of dictionary space. @code{unused pad here - - .}.
13693:
13694: @item system case-sensitivity characteristics:
13695: @cindex case-sensitivity characteristics
1.26 crook 13696: Dictionary searches are case-insensitive (except in
1.1 anton 13697: @code{TABLE}s). However, as explained above under @i{character-set
13698: extensions}, the matching for non-ASCII characters is determined by the
13699: locale you are using. In the default @code{C} locale all non-ASCII
13700: characters are matched case-sensitively.
13701:
13702: @item system prompt:
13703: @cindex system prompt
13704: @cindex prompt
13705: @code{ ok} in interpret state, @code{ compiled} in compile state.
13706:
13707: @item division rounding:
13708: @cindex division rounding
1.166 anton 13709: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13710: division (with the default installation of Gforth). You can check
13711: this with @code{s" floored" environment? drop .}. If you write
13712: programs that need a specific division rounding, best use
13713: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13714:
13715: @item values of @code{STATE} when true:
13716: @cindex @code{STATE} values
13717: -1.
13718:
13719: @item values returned after arithmetic overflow:
13720: On two's complement machines, arithmetic is performed modulo
13721: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13722: arithmetic (with appropriate mapping for signed types). Division by
13723: zero typically results in a @code{-55 throw} (Floating-point
13724: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13725: division overflow can result in these throws, or in @code{-11 throw};
13726: in @code{gforth-fast} division overflow and divide by zero may also
13727: result in returning bogus results without producing an exception.
1.1 anton 13728:
13729: @item whether the current definition can be found after @t{DOES>}:
13730: @cindex @t{DOES>}, visibility of current definition
13731: No.
13732:
13733: @end table
13734:
13735: @c ---------------------------------------------------------------------
13736: @node core-ambcond, core-other, core-idef, The Core Words
13737: @subsection Ambiguous conditions
13738: @c ---------------------------------------------------------------------
13739: @cindex core words, ambiguous conditions
13740: @cindex ambiguous conditions, core words
13741:
13742: @table @i
13743:
13744: @item a name is neither a word nor a number:
13745: @cindex name not found
1.26 crook 13746: @cindex undefined word
1.80 anton 13747: @code{-13 throw} (Undefined word).
1.1 anton 13748:
13749: @item a definition name exceeds the maximum length allowed:
1.26 crook 13750: @cindex word name too long
1.1 anton 13751: @code{-19 throw} (Word name too long)
13752:
13753: @item addressing a region not inside the various data spaces of the forth system:
13754: @cindex Invalid memory address
1.32 anton 13755: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13756: typically readable. Accessing other addresses gives results dependent on
13757: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13758: address).
13759:
13760: @item argument type incompatible with parameter:
1.26 crook 13761: @cindex argument type mismatch
1.1 anton 13762: This is usually not caught. Some words perform checks, e.g., the control
13763: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13764: mismatch).
13765:
13766: @item attempting to obtain the execution token of a word with undefined execution semantics:
13767: @cindex Interpreting a compile-only word, for @code{'} etc.
13768: @cindex execution token of words with undefined execution semantics
13769: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13770: get an execution token for @code{compile-only-error} (which performs a
13771: @code{-14 throw} when executed).
13772:
13773: @item dividing by zero:
13774: @cindex dividing by zero
13775: @cindex floating point unidentified fault, integer division
1.80 anton 13776: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13777: zero); on other systems, this typically results in a @code{-55 throw}
13778: (Floating-point unidentified fault).
1.1 anton 13779:
13780: @item insufficient data stack or return stack space:
13781: @cindex insufficient data stack or return stack space
13782: @cindex stack overflow
1.26 crook 13783: @cindex address alignment exception, stack overflow
1.1 anton 13784: @cindex Invalid memory address, stack overflow
13785: Depending on the operating system, the installation, and the invocation
13786: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13787: it is not checked. If it is checked, you typically get a @code{-3 throw}
13788: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13789: throw} (Invalid memory address) (depending on the platform and how you
13790: achieved the overflow) as soon as the overflow happens. If it is not
13791: checked, overflows typically result in mysterious illegal memory
13792: accesses, producing @code{-9 throw} (Invalid memory address) or
13793: @code{-23 throw} (Address alignment exception); they might also destroy
13794: the internal data structure of @code{ALLOCATE} and friends, resulting in
13795: various errors in these words.
1.1 anton 13796:
13797: @item insufficient space for loop control parameters:
13798: @cindex insufficient space for loop control parameters
1.80 anton 13799: Like other return stack overflows.
1.1 anton 13800:
13801: @item insufficient space in the dictionary:
13802: @cindex insufficient space in the dictionary
13803: @cindex dictionary overflow
1.12 anton 13804: If you try to allot (either directly with @code{allot}, or indirectly
13805: with @code{,}, @code{create} etc.) more memory than available in the
13806: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13807: to access memory beyond the end of the dictionary, the results are
13808: similar to stack overflows.
1.1 anton 13809:
13810: @item interpreting a word with undefined interpretation semantics:
13811: @cindex interpreting a word with undefined interpretation semantics
13812: @cindex Interpreting a compile-only word
13813: For some words, we have defined interpretation semantics. For the
13814: others: @code{-14 throw} (Interpreting a compile-only word).
13815:
13816: @item modifying the contents of the input buffer or a string literal:
13817: @cindex modifying the contents of the input buffer or a string literal
13818: These are located in writable memory and can be modified.
13819:
13820: @item overflow of the pictured numeric output string:
13821: @cindex overflow of the pictured numeric output string
13822: @cindex pictured numeric output string, overflow
1.24 anton 13823: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13824:
13825: @item parsed string overflow:
13826: @cindex parsed string overflow
13827: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13828:
13829: @item producing a result out of range:
13830: @cindex result out of range
13831: On two's complement machines, arithmetic is performed modulo
13832: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13833: arithmetic (with appropriate mapping for signed types). Division by
13834: zero typically results in a @code{-10 throw} (divide by zero) or
13835: @code{-55 throw} (floating point unidentified fault). Overflow on
13836: division may result in these errors or in @code{-11 throw} (result out
13837: of range). @code{Gforth-fast} may silently produce bogus results on
13838: division overflow or division by zero. @code{Convert} and
1.24 anton 13839: @code{>number} currently overflow silently.
1.1 anton 13840:
13841: @item reading from an empty data or return stack:
13842: @cindex stack empty
13843: @cindex stack underflow
1.24 anton 13844: @cindex return stack underflow
1.1 anton 13845: The data stack is checked by the outer (aka text) interpreter after
13846: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13847: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13848: depending on operating system, installation, and invocation. If they are
13849: caught by a check, they typically result in @code{-4 throw} (Stack
13850: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13851: (Invalid memory address), depending on the platform and which stack
13852: underflows and by how much. Note that even if the system uses checking
13853: (through the MMU), your program may have to underflow by a significant
13854: number of stack items to trigger the reaction (the reason for this is
13855: that the MMU, and therefore the checking, works with a page-size
13856: granularity). If there is no checking, the symptoms resulting from an
13857: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13858: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13859: (Invalid memory address) and Illegal Instruction (typically @code{-260
13860: throw}).
1.1 anton 13861:
13862: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13863: @cindex unexpected end of the input buffer
13864: @cindex zero-length string as a name
13865: @cindex Attempt to use zero-length string as a name
13866: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13867: use zero-length string as a name). Words like @code{'} probably will not
13868: find what they search. Note that it is possible to create zero-length
13869: names with @code{nextname} (should it not?).
13870:
13871: @item @code{>IN} greater than input buffer:
13872: @cindex @code{>IN} greater than input buffer
13873: The next invocation of a parsing word returns a string with length 0.
13874:
13875: @item @code{RECURSE} appears after @code{DOES>}:
13876: @cindex @code{RECURSE} appears after @code{DOES>}
13877: Compiles a recursive call to the defining word, not to the defined word.
13878:
13879: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13880: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13881: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13882: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13883: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13884: the end of the file was reached), its source-id may be
13885: reused. Therefore, restoring an input source specification referencing a
13886: closed file may lead to unpredictable results instead of a @code{-12
13887: THROW}.
13888:
13889: In the future, Gforth may be able to restore input source specifications
13890: from other than the current input source.
13891:
13892: @item data space containing definitions gets de-allocated:
13893: @cindex data space containing definitions gets de-allocated
13894: Deallocation with @code{allot} is not checked. This typically results in
13895: memory access faults or execution of illegal instructions.
13896:
13897: @item data space read/write with incorrect alignment:
13898: @cindex data space read/write with incorrect alignment
13899: @cindex alignment faults
1.26 crook 13900: @cindex address alignment exception
1.1 anton 13901: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13902: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13903: alignment turned on, incorrect alignment results in a @code{-9 throw}
13904: (Invalid memory address). There are reportedly some processors with
1.12 anton 13905: alignment restrictions that do not report violations.
1.1 anton 13906:
13907: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13908: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13909: Like other alignment errors.
13910:
13911: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13912: Like other stack underflows.
13913:
13914: @item loop control parameters not available:
13915: @cindex loop control parameters not available
13916: Not checked. The counted loop words simply assume that the top of return
13917: stack items are loop control parameters and behave accordingly.
13918:
13919: @item most recent definition does not have a name (@code{IMMEDIATE}):
13920: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13921: @cindex last word was headerless
13922: @code{abort" last word was headerless"}.
13923:
13924: @item name not defined by @code{VALUE} used by @code{TO}:
13925: @cindex name not defined by @code{VALUE} used by @code{TO}
13926: @cindex @code{TO} on non-@code{VALUE}s
13927: @cindex Invalid name argument, @code{TO}
13928: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13929: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13930:
13931: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13932: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13933: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13934: @code{-13 throw} (Undefined word)
13935:
13936: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13937: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13938: Gforth behaves as if they were of the same type. I.e., you can predict
13939: the behaviour by interpreting all parameters as, e.g., signed.
13940:
13941: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13942: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13943: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13944: compilation semantics of @code{TO}.
13945:
13946: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13947: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13948: @cindex @code{WORD}, string overflow
13949: Not checked. The string will be ok, but the count will, of course,
13950: contain only the least significant bits of the length.
13951:
13952: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13953: @cindex @code{LSHIFT}, large shift counts
13954: @cindex @code{RSHIFT}, large shift counts
13955: Processor-dependent. Typical behaviours are returning 0 and using only
13956: the low bits of the shift count.
13957:
13958: @item word not defined via @code{CREATE}:
13959: @cindex @code{>BODY} of non-@code{CREATE}d words
13960: @code{>BODY} produces the PFA of the word no matter how it was defined.
13961:
13962: @cindex @code{DOES>} of non-@code{CREATE}d words
13963: @code{DOES>} changes the execution semantics of the last defined word no
13964: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13965: @code{CREATE , DOES>}.
13966:
13967: @item words improperly used outside @code{<#} and @code{#>}:
13968: Not checked. As usual, you can expect memory faults.
13969:
13970: @end table
13971:
13972:
13973: @c ---------------------------------------------------------------------
13974: @node core-other, , core-ambcond, The Core Words
13975: @subsection Other system documentation
13976: @c ---------------------------------------------------------------------
13977: @cindex other system documentation, core words
13978: @cindex core words, other system documentation
13979:
13980: @table @i
13981: @item nonstandard words using @code{PAD}:
13982: @cindex @code{PAD} use by nonstandard words
13983: None.
13984:
13985: @item operator's terminal facilities available:
13986: @cindex operator's terminal facilities available
1.80 anton 13987: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13988: and you can give commands to Gforth interactively. The actual facilities
13989: available depend on how you invoke Gforth.
13990:
13991: @item program data space available:
13992: @cindex program data space available
13993: @cindex data space available
13994: @code{UNUSED .} gives the remaining dictionary space. The total
13995: dictionary space can be specified with the @code{-m} switch
13996: (@pxref{Invoking Gforth}) when Gforth starts up.
13997:
13998: @item return stack space available:
13999: @cindex return stack space available
14000: You can compute the total return stack space in cells with
14001: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
14002: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
14003:
14004: @item stack space available:
14005: @cindex stack space available
14006: You can compute the total data stack space in cells with
14007: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
14008: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
14009:
14010: @item system dictionary space required, in address units:
14011: @cindex system dictionary space required, in address units
14012: Type @code{here forthstart - .} after startup. At the time of this
14013: writing, this gives 80080 (bytes) on a 32-bit system.
14014: @end table
14015:
14016:
14017: @c =====================================================================
14018: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
14019: @section The optional Block word set
14020: @c =====================================================================
14021: @cindex system documentation, block words
14022: @cindex block words, system documentation
14023:
14024: @menu
14025: * block-idef:: Implementation Defined Options
14026: * block-ambcond:: Ambiguous Conditions
14027: * block-other:: Other System Documentation
14028: @end menu
14029:
14030:
14031: @c ---------------------------------------------------------------------
14032: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14033: @subsection Implementation Defined Options
14034: @c ---------------------------------------------------------------------
14035: @cindex implementation-defined options, block words
14036: @cindex block words, implementation-defined options
14037:
14038: @table @i
14039: @item the format for display by @code{LIST}:
14040: @cindex @code{LIST} display format
14041: First the screen number is displayed, then 16 lines of 64 characters,
14042: each line preceded by the line number.
14043:
14044: @item the length of a line affected by @code{\}:
14045: @cindex length of a line affected by @code{\}
14046: @cindex @code{\}, line length in blocks
14047: 64 characters.
14048: @end table
14049:
14050:
14051: @c ---------------------------------------------------------------------
14052: @node block-ambcond, block-other, block-idef, The optional Block word set
14053: @subsection Ambiguous conditions
14054: @c ---------------------------------------------------------------------
14055: @cindex block words, ambiguous conditions
14056: @cindex ambiguous conditions, block words
14057:
14058: @table @i
14059: @item correct block read was not possible:
14060: @cindex block read not possible
14061: Typically results in a @code{throw} of some OS-derived value (between
14062: -512 and -2048). If the blocks file was just not long enough, blanks are
14063: supplied for the missing portion.
14064:
14065: @item I/O exception in block transfer:
14066: @cindex I/O exception in block transfer
14067: @cindex block transfer, I/O exception
14068: Typically results in a @code{throw} of some OS-derived value (between
14069: -512 and -2048).
14070:
14071: @item invalid block number:
14072: @cindex invalid block number
14073: @cindex block number invalid
14074: @code{-35 throw} (Invalid block number)
14075:
14076: @item a program directly alters the contents of @code{BLK}:
14077: @cindex @code{BLK}, altering @code{BLK}
14078: The input stream is switched to that other block, at the same
14079: position. If the storing to @code{BLK} happens when interpreting
14080: non-block input, the system will get quite confused when the block ends.
14081:
14082: @item no current block buffer for @code{UPDATE}:
14083: @cindex @code{UPDATE}, no current block buffer
14084: @code{UPDATE} has no effect.
14085:
14086: @end table
14087:
14088: @c ---------------------------------------------------------------------
14089: @node block-other, , block-ambcond, The optional Block word set
14090: @subsection Other system documentation
14091: @c ---------------------------------------------------------------------
14092: @cindex other system documentation, block words
14093: @cindex block words, other system documentation
14094:
14095: @table @i
14096: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14097: No restrictions (yet).
14098:
14099: @item the number of blocks available for source and data:
14100: depends on your disk space.
14101:
14102: @end table
14103:
14104:
14105: @c =====================================================================
14106: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14107: @section The optional Double Number word set
14108: @c =====================================================================
14109: @cindex system documentation, double words
14110: @cindex double words, system documentation
14111:
14112: @menu
14113: * double-ambcond:: Ambiguous Conditions
14114: @end menu
14115:
14116:
14117: @c ---------------------------------------------------------------------
14118: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
14119: @subsection Ambiguous conditions
14120: @c ---------------------------------------------------------------------
14121: @cindex double words, ambiguous conditions
14122: @cindex ambiguous conditions, double words
14123:
14124: @table @i
1.29 crook 14125: @item @i{d} outside of range of @i{n} in @code{D>S}:
14126: @cindex @code{D>S}, @i{d} out of range of @i{n}
14127: The least significant cell of @i{d} is produced.
1.1 anton 14128:
14129: @end table
14130:
14131:
14132: @c =====================================================================
14133: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14134: @section The optional Exception word set
14135: @c =====================================================================
14136: @cindex system documentation, exception words
14137: @cindex exception words, system documentation
14138:
14139: @menu
14140: * exception-idef:: Implementation Defined Options
14141: @end menu
14142:
14143:
14144: @c ---------------------------------------------------------------------
14145: @node exception-idef, , The optional Exception word set, The optional Exception word set
14146: @subsection Implementation Defined Options
14147: @c ---------------------------------------------------------------------
14148: @cindex implementation-defined options, exception words
14149: @cindex exception words, implementation-defined options
14150:
14151: @table @i
14152: @item @code{THROW}-codes used in the system:
14153: @cindex @code{THROW}-codes used in the system
14154: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 14155: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 14156: codes -512@minus{}-2047 are used for OS errors (for file and memory
14157: allocation operations). The mapping from OS error numbers to throw codes
14158: is -512@minus{}@code{errno}. One side effect of this mapping is that
14159: undefined OS errors produce a message with a strange number; e.g.,
14160: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14161: @end table
14162:
14163: @c =====================================================================
14164: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14165: @section The optional Facility word set
14166: @c =====================================================================
14167: @cindex system documentation, facility words
14168: @cindex facility words, system documentation
14169:
14170: @menu
14171: * facility-idef:: Implementation Defined Options
14172: * facility-ambcond:: Ambiguous Conditions
14173: @end menu
14174:
14175:
14176: @c ---------------------------------------------------------------------
14177: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14178: @subsection Implementation Defined Options
14179: @c ---------------------------------------------------------------------
14180: @cindex implementation-defined options, facility words
14181: @cindex facility words, implementation-defined options
14182:
14183: @table @i
14184: @item encoding of keyboard events (@code{EKEY}):
14185: @cindex keyboard events, encoding in @code{EKEY}
14186: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 14187: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 14188: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14189: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14190: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14191: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 14192:
1.1 anton 14193:
14194: @item duration of a system clock tick:
14195: @cindex duration of a system clock tick
14196: @cindex clock tick duration
14197: System dependent. With respect to @code{MS}, the time is specified in
14198: microseconds. How well the OS and the hardware implement this, is
14199: another question.
14200:
14201: @item repeatability to be expected from the execution of @code{MS}:
14202: @cindex repeatability to be expected from the execution of @code{MS}
14203: @cindex @code{MS}, repeatability to be expected
14204: System dependent. On Unix, a lot depends on load. If the system is
14205: lightly loaded, and the delay is short enough that Gforth does not get
14206: swapped out, the performance should be acceptable. Under MS-DOS and
14207: other single-tasking systems, it should be good.
14208:
14209: @end table
14210:
14211:
14212: @c ---------------------------------------------------------------------
14213: @node facility-ambcond, , facility-idef, The optional Facility word set
14214: @subsection Ambiguous conditions
14215: @c ---------------------------------------------------------------------
14216: @cindex facility words, ambiguous conditions
14217: @cindex ambiguous conditions, facility words
14218:
14219: @table @i
14220: @item @code{AT-XY} can't be performed on user output device:
14221: @cindex @code{AT-XY} can't be performed on user output device
14222: Largely terminal dependent. No range checks are done on the arguments.
14223: No errors are reported. You may see some garbage appearing, you may see
14224: simply nothing happen.
14225:
14226: @end table
14227:
14228:
14229: @c =====================================================================
14230: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14231: @section The optional File-Access word set
14232: @c =====================================================================
14233: @cindex system documentation, file words
14234: @cindex file words, system documentation
14235:
14236: @menu
14237: * file-idef:: Implementation Defined Options
14238: * file-ambcond:: Ambiguous Conditions
14239: @end menu
14240:
14241: @c ---------------------------------------------------------------------
14242: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14243: @subsection Implementation Defined Options
14244: @c ---------------------------------------------------------------------
14245: @cindex implementation-defined options, file words
14246: @cindex file words, implementation-defined options
14247:
14248: @table @i
14249: @item file access methods used:
14250: @cindex file access methods used
14251: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14252: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14253: @code{wb}): The file is cleared, if it exists, and created, if it does
14254: not (with both @code{open-file} and @code{create-file}). Under Unix
14255: @code{create-file} creates a file with 666 permissions modified by your
14256: umask.
14257:
14258: @item file exceptions:
14259: @cindex file exceptions
14260: The file words do not raise exceptions (except, perhaps, memory access
14261: faults when you pass illegal addresses or file-ids).
14262:
14263: @item file line terminator:
14264: @cindex file line terminator
14265: System-dependent. Gforth uses C's newline character as line
14266: terminator. What the actual character code(s) of this are is
14267: system-dependent.
14268:
14269: @item file name format:
14270: @cindex file name format
14271: System dependent. Gforth just uses the file name format of your OS.
14272:
14273: @item information returned by @code{FILE-STATUS}:
14274: @cindex @code{FILE-STATUS}, returned information
14275: @code{FILE-STATUS} returns the most powerful file access mode allowed
14276: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14277: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14278: along with the returned mode.
14279:
14280: @item input file state after an exception when including source:
14281: @cindex exception when including source
14282: All files that are left via the exception are closed.
14283:
1.29 crook 14284: @item @i{ior} values and meaning:
14285: @cindex @i{ior} values and meaning
1.68 anton 14286: @cindex @i{wior} values and meaning
1.29 crook 14287: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14288: intended as throw codes. They typically are in the range
14289: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14290: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14291:
14292: @item maximum depth of file input nesting:
14293: @cindex maximum depth of file input nesting
14294: @cindex file input nesting, maximum depth
14295: limited by the amount of return stack, locals/TIB stack, and the number
14296: of open files available. This should not give you troubles.
14297:
14298: @item maximum size of input line:
14299: @cindex maximum size of input line
14300: @cindex input line size, maximum
14301: @code{/line}. Currently 255.
14302:
14303: @item methods of mapping block ranges to files:
14304: @cindex mapping block ranges to files
14305: @cindex files containing blocks
14306: @cindex blocks in files
14307: By default, blocks are accessed in the file @file{blocks.fb} in the
14308: current working directory. The file can be switched with @code{USE}.
14309:
14310: @item number of string buffers provided by @code{S"}:
14311: @cindex @code{S"}, number of string buffers
14312: 1
14313:
14314: @item size of string buffer used by @code{S"}:
14315: @cindex @code{S"}, size of string buffer
14316: @code{/line}. currently 255.
14317:
14318: @end table
14319:
14320: @c ---------------------------------------------------------------------
14321: @node file-ambcond, , file-idef, The optional File-Access word set
14322: @subsection Ambiguous conditions
14323: @c ---------------------------------------------------------------------
14324: @cindex file words, ambiguous conditions
14325: @cindex ambiguous conditions, file words
14326:
14327: @table @i
14328: @item attempting to position a file outside its boundaries:
14329: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14330: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14331: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14332:
14333: @item attempting to read from file positions not yet written:
14334: @cindex reading from file positions not yet written
14335: End-of-file, i.e., zero characters are read and no error is reported.
14336:
1.29 crook 14337: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14338: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14339: An appropriate exception may be thrown, but a memory fault or other
14340: problem is more probable.
14341:
1.29 crook 14342: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14343: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14344: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14345: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14346: thrown.
14347:
14348: @item named file cannot be opened (@code{INCLUDED}):
14349: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14350: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14351:
14352: @item requesting an unmapped block number:
14353: @cindex unmapped block numbers
14354: There are no unmapped legal block numbers. On some operating systems,
14355: writing a block with a large number may overflow the file system and
14356: have an error message as consequence.
14357:
14358: @item using @code{source-id} when @code{blk} is non-zero:
14359: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14360: @code{source-id} performs its function. Typically it will give the id of
14361: the source which loaded the block. (Better ideas?)
14362:
14363: @end table
14364:
14365:
14366: @c =====================================================================
14367: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14368: @section The optional Floating-Point word set
14369: @c =====================================================================
14370: @cindex system documentation, floating-point words
14371: @cindex floating-point words, system documentation
14372:
14373: @menu
14374: * floating-idef:: Implementation Defined Options
14375: * floating-ambcond:: Ambiguous Conditions
14376: @end menu
14377:
14378:
14379: @c ---------------------------------------------------------------------
14380: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14381: @subsection Implementation Defined Options
14382: @c ---------------------------------------------------------------------
14383: @cindex implementation-defined options, floating-point words
14384: @cindex floating-point words, implementation-defined options
14385:
14386: @table @i
14387: @item format and range of floating point numbers:
14388: @cindex format and range of floating point numbers
14389: @cindex floating point numbers, format and range
14390: System-dependent; the @code{double} type of C.
14391:
1.29 crook 14392: @item results of @code{REPRESENT} when @i{float} is out of range:
14393: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14394: System dependent; @code{REPRESENT} is implemented using the C library
14395: function @code{ecvt()} and inherits its behaviour in this respect.
14396:
14397: @item rounding or truncation of floating-point numbers:
14398: @cindex rounding of floating-point numbers
14399: @cindex truncation of floating-point numbers
14400: @cindex floating-point numbers, rounding or truncation
14401: System dependent; the rounding behaviour is inherited from the hosting C
14402: compiler. IEEE-FP-based (i.e., most) systems by default round to
14403: nearest, and break ties by rounding to even (i.e., such that the last
14404: bit of the mantissa is 0).
14405:
14406: @item size of floating-point stack:
14407: @cindex floating-point stack size
14408: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14409: the floating-point stack (in floats). You can specify this on startup
14410: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14411:
14412: @item width of floating-point stack:
14413: @cindex floating-point stack width
14414: @code{1 floats}.
14415:
14416: @end table
14417:
14418:
14419: @c ---------------------------------------------------------------------
14420: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14421: @subsection Ambiguous conditions
14422: @c ---------------------------------------------------------------------
14423: @cindex floating-point words, ambiguous conditions
14424: @cindex ambiguous conditions, floating-point words
14425:
14426: @table @i
14427: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14428: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14429: System-dependent. Typically results in a @code{-23 THROW} like other
14430: alignment violations.
14431:
14432: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14433: @cindex @code{f@@} used with an address that is not float aligned
14434: @cindex @code{f!} used with an address that is not float aligned
14435: System-dependent. Typically results in a @code{-23 THROW} like other
14436: alignment violations.
14437:
14438: @item floating-point result out of range:
14439: @cindex floating-point result out of range
1.80 anton 14440: System-dependent. Can result in a @code{-43 throw} (floating point
14441: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14442: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14443: unidentified fault), or can produce a special value representing, e.g.,
14444: Infinity.
14445:
14446: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14447: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14448: System-dependent. Typically results in an alignment fault like other
14449: alignment violations.
14450:
1.35 anton 14451: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14452: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14453: The floating-point number is converted into decimal nonetheless.
14454:
14455: @item Both arguments are equal to zero (@code{FATAN2}):
14456: @cindex @code{FATAN2}, both arguments are equal to zero
14457: System-dependent. @code{FATAN2} is implemented using the C library
14458: function @code{atan2()}.
14459:
1.29 crook 14460: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14461: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14462: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14463: because of small errors and the tan will be a very large (or very small)
14464: but finite number.
14465:
1.29 crook 14466: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14467: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14468: The result is rounded to the nearest float.
14469:
14470: @item dividing by zero:
14471: @cindex dividing by zero, floating-point
14472: @cindex floating-point dividing by zero
14473: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14474: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14475: (floating point divide by zero) or @code{-55 throw} (Floating-point
14476: unidentified fault).
1.1 anton 14477:
14478: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14479: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14480: System dependent. On IEEE-FP based systems the number is converted into
14481: an infinity.
14482:
1.29 crook 14483: @item @i{float}<1 (@code{FACOSH}):
14484: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14485: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14486: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14487:
1.29 crook 14488: @item @i{float}=<-1 (@code{FLNP1}):
14489: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14490: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14491: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14492: negative infinity for @i{float}=-1).
1.1 anton 14493:
1.29 crook 14494: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14495: @cindex @code{FLN}, @i{float}=<0
14496: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14497: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14498: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14499: negative infinity for @i{float}=0).
1.1 anton 14500:
1.29 crook 14501: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14502: @cindex @code{FASINH}, @i{float}<0
14503: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14504: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14505: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14506: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14507: C library?).
1.1 anton 14508:
1.29 crook 14509: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14510: @cindex @code{FACOS}, |@i{float}|>1
14511: @cindex @code{FASIN}, |@i{float}|>1
14512: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14513: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14514: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14515:
1.29 crook 14516: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14517: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14518: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14519: Platform-dependent; typically, some double number is produced and no
14520: error is reported.
1.1 anton 14521:
14522: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14523: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14524: @code{Precision} characters of the numeric output area are used. If
14525: @code{precision} is too high, these words will smash the data or code
14526: close to @code{here}.
1.1 anton 14527: @end table
14528:
14529: @c =====================================================================
14530: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14531: @section The optional Locals word set
14532: @c =====================================================================
14533: @cindex system documentation, locals words
14534: @cindex locals words, system documentation
14535:
14536: @menu
14537: * locals-idef:: Implementation Defined Options
14538: * locals-ambcond:: Ambiguous Conditions
14539: @end menu
14540:
14541:
14542: @c ---------------------------------------------------------------------
14543: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14544: @subsection Implementation Defined Options
14545: @c ---------------------------------------------------------------------
14546: @cindex implementation-defined options, locals words
14547: @cindex locals words, implementation-defined options
14548:
14549: @table @i
14550: @item maximum number of locals in a definition:
14551: @cindex maximum number of locals in a definition
14552: @cindex locals, maximum number in a definition
14553: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14554: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14555: characters. The number of locals in a definition is bounded by the size
14556: of locals-buffer, which contains the names of the locals.
14557:
14558: @end table
14559:
14560:
14561: @c ---------------------------------------------------------------------
14562: @node locals-ambcond, , locals-idef, The optional Locals word set
14563: @subsection Ambiguous conditions
14564: @c ---------------------------------------------------------------------
14565: @cindex locals words, ambiguous conditions
14566: @cindex ambiguous conditions, locals words
14567:
14568: @table @i
14569: @item executing a named local in interpretation state:
14570: @cindex local in interpretation state
14571: @cindex Interpreting a compile-only word, for a local
14572: Locals have no interpretation semantics. If you try to perform the
14573: interpretation semantics, you will get a @code{-14 throw} somewhere
14574: (Interpreting a compile-only word). If you perform the compilation
14575: semantics, the locals access will be compiled (irrespective of state).
14576:
1.29 crook 14577: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14578: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14579: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14580: @cindex Invalid name argument, @code{TO}
14581: @code{-32 throw} (Invalid name argument)
14582:
14583: @end table
14584:
14585:
14586: @c =====================================================================
14587: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14588: @section The optional Memory-Allocation word set
14589: @c =====================================================================
14590: @cindex system documentation, memory-allocation words
14591: @cindex memory-allocation words, system documentation
14592:
14593: @menu
14594: * memory-idef:: Implementation Defined Options
14595: @end menu
14596:
14597:
14598: @c ---------------------------------------------------------------------
14599: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14600: @subsection Implementation Defined Options
14601: @c ---------------------------------------------------------------------
14602: @cindex implementation-defined options, memory-allocation words
14603: @cindex memory-allocation words, implementation-defined options
14604:
14605: @table @i
1.29 crook 14606: @item values and meaning of @i{ior}:
14607: @cindex @i{ior} values and meaning
14608: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14609: intended as throw codes. They typically are in the range
14610: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14611: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14612:
14613: @end table
14614:
14615: @c =====================================================================
14616: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14617: @section The optional Programming-Tools word set
14618: @c =====================================================================
14619: @cindex system documentation, programming-tools words
14620: @cindex programming-tools words, system documentation
14621:
14622: @menu
14623: * programming-idef:: Implementation Defined Options
14624: * programming-ambcond:: Ambiguous Conditions
14625: @end menu
14626:
14627:
14628: @c ---------------------------------------------------------------------
14629: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14630: @subsection Implementation Defined Options
14631: @c ---------------------------------------------------------------------
14632: @cindex implementation-defined options, programming-tools words
14633: @cindex programming-tools words, implementation-defined options
14634:
14635: @table @i
14636: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14637: @cindex @code{;CODE} ending sequence
14638: @cindex @code{CODE} ending sequence
14639: @code{END-CODE}
14640:
14641: @item manner of processing input following @code{;CODE} and @code{CODE}:
14642: @cindex @code{;CODE}, processing input
14643: @cindex @code{CODE}, processing input
14644: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14645: the input is processed by the text interpreter, (starting) in interpret
14646: state.
14647:
14648: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14649: @cindex @code{ASSEMBLER}, search order capability
14650: The ANS Forth search order word set.
14651:
14652: @item source and format of display by @code{SEE}:
14653: @cindex @code{SEE}, source and format of output
1.80 anton 14654: The source for @code{see} is the executable code used by the inner
1.1 anton 14655: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14656: (and on some platforms, assembly code for primitives) as well as
14657: possible.
1.1 anton 14658:
14659: @end table
14660:
14661: @c ---------------------------------------------------------------------
14662: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14663: @subsection Ambiguous conditions
14664: @c ---------------------------------------------------------------------
14665: @cindex programming-tools words, ambiguous conditions
14666: @cindex ambiguous conditions, programming-tools words
14667:
14668: @table @i
14669:
1.21 crook 14670: @item deleting the compilation word list (@code{FORGET}):
14671: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14672: Not implemented (yet).
14673:
1.29 crook 14674: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14675: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14676: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14677: @cindex control-flow stack underflow
14678: This typically results in an @code{abort"} with a descriptive error
14679: message (may change into a @code{-22 throw} (Control structure mismatch)
14680: in the future). You may also get a memory access error. If you are
14681: unlucky, this ambiguous condition is not caught.
14682:
1.29 crook 14683: @item @i{name} can't be found (@code{FORGET}):
14684: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14685: Not implemented (yet).
14686:
1.29 crook 14687: @item @i{name} not defined via @code{CREATE}:
14688: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14689: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14690: the execution semantics of the last defined word no matter how it was
14691: defined.
14692:
14693: @item @code{POSTPONE} applied to @code{[IF]}:
14694: @cindex @code{POSTPONE} applied to @code{[IF]}
14695: @cindex @code{[IF]} and @code{POSTPONE}
14696: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14697: equivalent to @code{[IF]}.
14698:
14699: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14700: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14701: Continue in the same state of conditional compilation in the next outer
14702: input source. Currently there is no warning to the user about this.
14703:
14704: @item removing a needed definition (@code{FORGET}):
14705: @cindex @code{FORGET}, removing a needed definition
14706: Not implemented (yet).
14707:
14708: @end table
14709:
14710:
14711: @c =====================================================================
14712: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14713: @section The optional Search-Order word set
14714: @c =====================================================================
14715: @cindex system documentation, search-order words
14716: @cindex search-order words, system documentation
14717:
14718: @menu
14719: * search-idef:: Implementation Defined Options
14720: * search-ambcond:: Ambiguous Conditions
14721: @end menu
14722:
14723:
14724: @c ---------------------------------------------------------------------
14725: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14726: @subsection Implementation Defined Options
14727: @c ---------------------------------------------------------------------
14728: @cindex implementation-defined options, search-order words
14729: @cindex search-order words, implementation-defined options
14730:
14731: @table @i
14732: @item maximum number of word lists in search order:
14733: @cindex maximum number of word lists in search order
14734: @cindex search order, maximum depth
14735: @code{s" wordlists" environment? drop .}. Currently 16.
14736:
14737: @item minimum search order:
14738: @cindex minimum search order
14739: @cindex search order, minimum
14740: @code{root root}.
14741:
14742: @end table
14743:
14744: @c ---------------------------------------------------------------------
14745: @node search-ambcond, , search-idef, The optional Search-Order word set
14746: @subsection Ambiguous conditions
14747: @c ---------------------------------------------------------------------
14748: @cindex search-order words, ambiguous conditions
14749: @cindex ambiguous conditions, search-order words
14750:
14751: @table @i
1.21 crook 14752: @item changing the compilation word list (during compilation):
14753: @cindex changing the compilation word list (during compilation)
14754: @cindex compilation word list, change before definition ends
14755: The word is entered into the word list that was the compilation word list
1.1 anton 14756: at the start of the definition. Any changes to the name field (e.g.,
14757: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14758: are applied to the latest defined word (as reported by @code{latest} or
14759: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14760:
14761: @item search order empty (@code{previous}):
14762: @cindex @code{previous}, search order empty
1.26 crook 14763: @cindex vocstack empty, @code{previous}
1.1 anton 14764: @code{abort" Vocstack empty"}.
14765:
14766: @item too many word lists in search order (@code{also}):
14767: @cindex @code{also}, too many word lists in search order
1.26 crook 14768: @cindex vocstack full, @code{also}
1.1 anton 14769: @code{abort" Vocstack full"}.
14770:
14771: @end table
14772:
14773: @c ***************************************************************
1.65 anton 14774: @node Standard vs Extensions, Model, ANS conformance, Top
14775: @chapter Should I use Gforth extensions?
14776: @cindex Gforth extensions
14777:
14778: As you read through the rest of this manual, you will see documentation
14779: for @i{Standard} words, and documentation for some appealing Gforth
14780: @i{extensions}. You might ask yourself the question: @i{``Should I
14781: restrict myself to the standard, or should I use the extensions?''}
14782:
14783: The answer depends on the goals you have for the program you are working
14784: on:
14785:
14786: @itemize @bullet
14787:
14788: @item Is it just for yourself or do you want to share it with others?
14789:
14790: @item
14791: If you want to share it, do the others all use Gforth?
14792:
14793: @item
14794: If it is just for yourself, do you want to restrict yourself to Gforth?
14795:
14796: @end itemize
14797:
14798: If restricting the program to Gforth is ok, then there is no reason not
14799: to use extensions. It is still a good idea to keep to the standard
14800: where it is easy, in case you want to reuse these parts in another
14801: program that you want to be portable.
14802:
14803: If you want to be able to port the program to other Forth systems, there
14804: are the following points to consider:
14805:
14806: @itemize @bullet
14807:
14808: @item
14809: Most Forth systems that are being maintained support the ANS Forth
14810: standard. So if your program complies with the standard, it will be
14811: portable among many systems.
14812:
14813: @item
14814: A number of the Gforth extensions can be implemented in ANS Forth using
14815: public-domain files provided in the @file{compat/} directory. These are
14816: mentioned in the text in passing. There is no reason not to use these
14817: extensions, your program will still be ANS Forth compliant; just include
14818: the appropriate compat files with your program.
14819:
14820: @item
14821: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14822: analyse your program and determine what non-Standard words it relies
14823: upon. However, it does not check whether you use standard words in a
14824: non-standard way.
14825:
14826: @item
14827: Some techniques are not standardized by ANS Forth, and are hard or
14828: impossible to implement in a standard way, but can be implemented in
14829: most Forth systems easily, and usually in similar ways (e.g., accessing
14830: word headers). Forth has a rich historical precedent for programmers
14831: taking advantage of implementation-dependent features of their tools
14832: (for example, relying on a knowledge of the dictionary
14833: structure). Sometimes these techniques are necessary to extract every
14834: last bit of performance from the hardware, sometimes they are just a
14835: programming shorthand.
14836:
14837: @item
14838: Does using a Gforth extension save more work than the porting this part
14839: to other Forth systems (if any) will cost?
14840:
14841: @item
14842: Is the additional functionality worth the reduction in portability and
14843: the additional porting problems?
14844:
14845: @end itemize
14846:
14847: In order to perform these consideratios, you need to know what's
14848: standard and what's not. This manual generally states if something is
1.81 anton 14849: non-standard, but the authoritative source is the
14850: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14851: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14852: into the thought processes of the technical committee.
14853:
14854: Note also that portability between Forth systems is not the only
14855: portability issue; there is also the issue of portability between
14856: different platforms (processor/OS combinations).
14857:
14858: @c ***************************************************************
14859: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14860: @chapter Model
14861:
14862: This chapter has yet to be written. It will contain information, on
14863: which internal structures you can rely.
14864:
14865: @c ***************************************************************
14866: @node Integrating Gforth, Emacs and Gforth, Model, Top
14867: @chapter Integrating Gforth into C programs
14868:
14869: This is not yet implemented.
14870:
14871: Several people like to use Forth as scripting language for applications
14872: that are otherwise written in C, C++, or some other language.
14873:
14874: The Forth system ATLAST provides facilities for embedding it into
14875: applications; unfortunately it has several disadvantages: most
14876: importantly, it is not based on ANS Forth, and it is apparently dead
14877: (i.e., not developed further and not supported). The facilities
1.21 crook 14878: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14879: making the switch should not be hard.
14880:
14881: We also tried to design the interface such that it can easily be
14882: implemented by other Forth systems, so that we may one day arrive at a
14883: standardized interface. Such a standard interface would allow you to
14884: replace the Forth system without having to rewrite C code.
14885:
14886: You embed the Gforth interpreter by linking with the library
14887: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14888: global symbols in this library that belong to the interface, have the
14889: prefix @code{forth_}. (Global symbols that are used internally have the
14890: prefix @code{gforth_}).
14891:
14892: You can include the declarations of Forth types and the functions and
14893: variables of the interface with @code{#include <forth.h>}.
14894:
14895: Types.
14896:
14897: Variables.
14898:
14899: Data and FP Stack pointer. Area sizes.
14900:
14901: functions.
14902:
14903: forth_init(imagefile)
14904: forth_evaluate(string) exceptions?
14905: forth_goto(address) (or forth_execute(xt)?)
14906: forth_continue() (a corountining mechanism)
14907:
14908: Adding primitives.
14909:
14910: No checking.
14911:
14912: Signals?
14913:
14914: Accessing the Stacks
14915:
1.26 crook 14916: @c ******************************************************************
1.1 anton 14917: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14918: @chapter Emacs and Gforth
14919: @cindex Emacs and Gforth
14920:
14921: @cindex @file{gforth.el}
14922: @cindex @file{forth.el}
14923: @cindex Rydqvist, Goran
1.107 dvdkhlng 14924: @cindex Kuehling, David
1.1 anton 14925: @cindex comment editing commands
14926: @cindex @code{\}, editing with Emacs
14927: @cindex debug tracer editing commands
14928: @cindex @code{~~}, removal with Emacs
14929: @cindex Forth mode in Emacs
1.107 dvdkhlng 14930:
1.1 anton 14931: Gforth comes with @file{gforth.el}, an improved version of
14932: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14933: improvements are:
14934:
14935: @itemize @bullet
14936: @item
1.107 dvdkhlng 14937: A better handling of indentation.
14938: @item
14939: A custom hilighting engine for Forth-code.
1.26 crook 14940: @item
14941: Comment paragraph filling (@kbd{M-q})
14942: @item
14943: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14944: @item
14945: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14946: @item
14947: Support of the @code{info-lookup} feature for looking up the
14948: documentation of a word.
1.107 dvdkhlng 14949: @item
14950: Support for reading and writing blocks files.
1.26 crook 14951: @end itemize
14952:
1.107 dvdkhlng 14953: To get a basic description of these features, enter Forth mode and
14954: type @kbd{C-h m}.
1.1 anton 14955:
14956: @cindex source location of error or debugging output in Emacs
14957: @cindex error output, finding the source location in Emacs
14958: @cindex debugging output, finding the source location in Emacs
14959: In addition, Gforth supports Emacs quite well: The source code locations
14960: given in error messages, debugging output (from @code{~~}) and failed
14961: assertion messages are in the right format for Emacs' compilation mode
14962: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14963: Manual}) so the source location corresponding to an error or other
14964: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14965: @kbd{C-c C-c} for the error under the cursor).
14966:
1.107 dvdkhlng 14967: @cindex viewing the documentation of a word in Emacs
14968: @cindex context-sensitive help
14969: Moreover, for words documented in this manual, you can look up the
14970: glossary entry quickly by using @kbd{C-h TAB}
14971: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14972: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14973: later and does not work for words containing @code{:}.
14974:
14975: @menu
14976: * Installing gforth.el:: Making Emacs aware of Forth.
14977: * Emacs Tags:: Viewing the source of a word in Emacs.
14978: * Hilighting:: Making Forth code look prettier.
14979: * Auto-Indentation:: Customizing auto-indentation.
14980: * Blocks Files:: Reading and writing blocks files.
14981: @end menu
14982:
14983: @c ----------------------------------
1.109 anton 14984: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14985: @section Installing gforth.el
14986: @cindex @file{.emacs}
14987: @cindex @file{gforth.el}, installation
14988: To make the features from @file{gforth.el} available in Emacs, add
14989: the following lines to your @file{.emacs} file:
14990:
14991: @example
14992: (autoload 'forth-mode "gforth.el")
14993: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14994: auto-mode-alist))
14995: (autoload 'forth-block-mode "gforth.el")
14996: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14997: auto-mode-alist))
14998: (add-hook 'forth-mode-hook (function (lambda ()
14999: ;; customize variables here:
15000: (setq forth-indent-level 4)
15001: (setq forth-minor-indent-level 2)
15002: (setq forth-hilight-level 3)
15003: ;;; ...
15004: )))
15005: @end example
15006:
15007: @c ----------------------------------
15008: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
15009: @section Emacs Tags
1.1 anton 15010: @cindex @file{TAGS} file
15011: @cindex @file{etags.fs}
15012: @cindex viewing the source of a word in Emacs
1.43 anton 15013: @cindex @code{require}, placement in files
15014: @cindex @code{include}, placement in files
1.107 dvdkhlng 15015: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
15016: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 15017: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 15018: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 15019: several tags files at the same time (e.g., one for the Gforth sources
15020: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
15021: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
15022: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 15023: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
15024: with @file{etags.fs}, you should avoid putting definitions both before
15025: and after @code{require} etc., otherwise you will see the same file
15026: visited several times by commands like @code{tags-search}.
1.1 anton 15027:
1.107 dvdkhlng 15028: @c ----------------------------------
15029: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
15030: @section Hilighting
15031: @cindex hilighting Forth code in Emacs
15032: @cindex highlighting Forth code in Emacs
15033: @file{gforth.el} comes with a custom source hilighting engine. When
15034: you open a file in @code{forth-mode}, it will be completely parsed,
15035: assigning faces to keywords, comments, strings etc. While you edit
15036: the file, modified regions get parsed and updated on-the-fly.
15037:
15038: Use the variable `forth-hilight-level' to change the level of
15039: decoration from 0 (no hilighting at all) to 3 (the default). Even if
15040: you set the hilighting level to 0, the parser will still work in the
15041: background, collecting information about whether regions of text are
15042: ``compiled'' or ``interpreted''. Those information are required for
15043: auto-indentation to work properly. Set `forth-disable-parser' to
15044: non-nil if your computer is too slow to handle parsing. This will
15045: have an impact on the smartness of the auto-indentation engine,
15046: though.
15047:
15048: Sometimes Forth sources define new features that should be hilighted,
15049: new control structures, defining-words etc. You can use the variable
15050: `forth-custom-words' to make @code{forth-mode} hilight additional
15051: words and constructs. See the docstring of `forth-words' for details
15052: (in Emacs, type @kbd{C-h v forth-words}).
15053:
15054: `forth-custom-words' is meant to be customized in your
15055: @file{.emacs} file. To customize hilighing in a file-specific manner,
15056: set `forth-local-words' in a local-variables section at the end of
15057: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
15058:
15059: Example:
15060: @example
15061: 0 [IF]
15062: Local Variables:
15063: forth-local-words:
15064: ((("t:") definition-starter (font-lock-keyword-face . 1)
15065: "[ \t\n]" t name (font-lock-function-name-face . 3))
15066: ((";t") definition-ender (font-lock-keyword-face . 1)))
15067: End:
15068: [THEN]
15069: @end example
15070:
15071: @c ----------------------------------
15072: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
15073: @section Auto-Indentation
15074: @cindex auto-indentation of Forth code in Emacs
15075: @cindex indentation of Forth code in Emacs
15076: @code{forth-mode} automatically tries to indent lines in a smart way,
15077: whenever you type @key{TAB} or break a line with @kbd{C-m}.
15078:
15079: Simple customization can be achieved by setting
15080: `forth-indent-level' and `forth-minor-indent-level' in your
15081: @file{.emacs} file. For historical reasons @file{gforth.el} indents
15082: per default by multiples of 4 columns. To use the more traditional
15083: 3-column indentation, add the following lines to your @file{.emacs}:
15084:
15085: @example
15086: (add-hook 'forth-mode-hook (function (lambda ()
15087: ;; customize variables here:
15088: (setq forth-indent-level 3)
15089: (setq forth-minor-indent-level 1)
15090: )))
15091: @end example
15092:
15093: If you want indentation to recognize non-default words, customize it
15094: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
15095: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15096: v forth-indent-words}).
15097:
15098: To customize indentation in a file-specific manner, set
15099: `forth-local-indent-words' in a local-variables section at the end of
15100: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15101: Emacs Manual}).
15102:
15103: Example:
15104: @example
15105: 0 [IF]
15106: Local Variables:
15107: forth-local-indent-words:
15108: ((("t:") (0 . 2) (0 . 2))
15109: ((";t") (-2 . 0) (0 . -2)))
15110: End:
15111: [THEN]
15112: @end example
15113:
15114: @c ----------------------------------
1.109 anton 15115: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 15116: @section Blocks Files
15117: @cindex blocks files, use with Emacs
15118: @code{forth-mode} Autodetects blocks files by checking whether the
15119: length of the first line exceeds 1023 characters. It then tries to
15120: convert the file into normal text format. When you save the file, it
15121: will be written to disk as normal stream-source file.
15122:
15123: If you want to write blocks files, use @code{forth-blocks-mode}. It
15124: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 15125:
1.107 dvdkhlng 15126: @itemize @bullet
15127: @item
15128: Files are written to disk in blocks file format.
15129: @item
15130: Screen numbers are displayed in the mode line (enumerated beginning
15131: with the value of `forth-block-base')
15132: @item
15133: Warnings are displayed when lines exceed 64 characters.
15134: @item
15135: The beginning of the currently edited block is marked with an
15136: overlay-arrow.
15137: @end itemize
1.41 anton 15138:
1.107 dvdkhlng 15139: There are some restrictions you should be aware of. When you open a
15140: blocks file that contains tabulator or newline characters, these
15141: characters will be translated into spaces when the file is written
15142: back to disk. If tabs or newlines are encountered during blocks file
15143: reading, an error is output to the echo area. So have a look at the
15144: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 15145:
1.107 dvdkhlng 15146: Please consult the docstring of @code{forth-blocks-mode} for more
15147: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 15148:
1.26 crook 15149: @c ******************************************************************
1.1 anton 15150: @node Image Files, Engine, Emacs and Gforth, Top
15151: @chapter Image Files
1.26 crook 15152: @cindex image file
15153: @cindex @file{.fi} files
1.1 anton 15154: @cindex precompiled Forth code
15155: @cindex dictionary in persistent form
15156: @cindex persistent form of dictionary
15157:
15158: An image file is a file containing an image of the Forth dictionary,
15159: i.e., compiled Forth code and data residing in the dictionary. By
15160: convention, we use the extension @code{.fi} for image files.
15161:
15162: @menu
1.18 anton 15163: * Image Licensing Issues:: Distribution terms for images.
15164: * Image File Background:: Why have image files?
1.67 anton 15165: * Non-Relocatable Image Files:: don't always work.
1.18 anton 15166: * Data-Relocatable Image Files:: are better.
1.67 anton 15167: * Fully Relocatable Image Files:: better yet.
1.18 anton 15168: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 15169: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 15170: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 15171: @end menu
15172:
1.18 anton 15173: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15174: @section Image Licensing Issues
15175: @cindex license for images
15176: @cindex image license
15177:
15178: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15179: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15180: original image; i.e., according to copyright law it is a derived work of
15181: the original image.
15182:
15183: Since Gforth is distributed under the GNU GPL, the newly created image
15184: falls under the GNU GPL, too. In particular, this means that if you
15185: distribute the image, you have to make all of the sources for the image
1.113 anton 15186: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 15187: GNU General Public License (Section 3)}.
15188:
15189: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15190: contains only code compiled from the sources you gave it; if none of
15191: these sources is under the GPL, the terms discussed above do not apply
15192: to the image. However, if your image needs an engine (a gforth binary)
15193: that is under the GPL, you should make sure that you distribute both in
15194: a way that is at most a @emph{mere aggregation}, if you don't want the
15195: terms of the GPL to apply to the image.
15196:
15197: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 15198: @section Image File Background
15199: @cindex image file background
15200:
1.80 anton 15201: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 15202: definitions written in Forth. Since the Forth compiler itself belongs to
15203: those definitions, it is not possible to start the system with the
1.80 anton 15204: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 15205: code as an image file in nearly executable form. When Gforth starts up,
15206: a C routine loads the image file into memory, optionally relocates the
15207: addresses, then sets up the memory (stacks etc.) according to
15208: information in the image file, and (finally) starts executing Forth
15209: code.
1.1 anton 15210:
1.204 anton 15211: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15212: You can use a different image by using the @code{-i},
15213: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15214: Gforth}), e.g.:
15215:
15216: @example
15217: gforth-fast -i myimage.fi
15218: @end example
15219:
15220: There are different variants of image files, and they represent
15221: different compromises between the goals of making it easy to generate
15222: image files and making them portable.
1.1 anton 15223:
15224: @cindex relocation at run-time
1.26 crook 15225: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 15226: run-time. This avoids many of the complications discussed below (image
15227: files are data relocatable without further ado), but costs performance
1.204 anton 15228: (one addition per memory access) and makes it difficult to pass
15229: addresses between Forth and library calls or other programs.
1.1 anton 15230:
15231: @cindex relocation at load-time
1.26 crook 15232: By contrast, the Gforth loader performs relocation at image load time. The
15233: loader also has to replace tokens that represent primitive calls with the
1.1 anton 15234: appropriate code-field addresses (or code addresses in the case of
15235: direct threading).
15236:
15237: There are three kinds of image files, with different degrees of
15238: relocatability: non-relocatable, data-relocatable, and fully relocatable
15239: image files.
15240:
15241: @cindex image file loader
15242: @cindex relocating loader
15243: @cindex loader for image files
15244: These image file variants have several restrictions in common; they are
15245: caused by the design of the image file loader:
15246:
15247: @itemize @bullet
15248: @item
15249: There is only one segment; in particular, this means, that an image file
15250: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 15251: them). The contents of the stacks are not represented, either.
1.1 anton 15252:
15253: @item
15254: The only kinds of relocation supported are: adding the same offset to
15255: all cells that represent data addresses; and replacing special tokens
15256: with code addresses or with pieces of machine code.
15257:
15258: If any complex computations involving addresses are performed, the
15259: results cannot be represented in the image file. Several applications that
15260: use such computations come to mind:
1.204 anton 15261:
1.1 anton 15262: @itemize @minus
15263: @item
15264: Hashing addresses (or data structures which contain addresses) for table
15265: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15266: purpose, you will have no problem, because the hash tables are
15267: recomputed automatically when the system is started. If you use your own
15268: hash tables, you will have to do something similar.
15269:
15270: @item
15271: There's a cute implementation of doubly-linked lists that uses
15272: @code{XOR}ed addresses. You could represent such lists as singly-linked
15273: in the image file, and restore the doubly-linked representation on
15274: startup.@footnote{In my opinion, though, you should think thrice before
15275: using a doubly-linked list (whatever implementation).}
15276:
15277: @item
15278: The code addresses of run-time routines like @code{docol:} cannot be
15279: represented in the image file (because their tokens would be replaced by
15280: machine code in direct threaded implementations). As a workaround,
15281: compute these addresses at run-time with @code{>code-address} from the
15282: executions tokens of appropriate words (see the definitions of
1.80 anton 15283: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 15284:
15285: @item
15286: On many architectures addresses are represented in machine code in some
15287: shifted or mangled form. You cannot put @code{CODE} words that contain
15288: absolute addresses in this form in a relocatable image file. Workarounds
15289: are representing the address in some relative form (e.g., relative to
15290: the CFA, which is present in some register), or loading the address from
15291: a place where it is stored in a non-mangled form.
15292: @end itemize
15293: @end itemize
15294:
15295: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15296: @section Non-Relocatable Image Files
15297: @cindex non-relocatable image files
1.26 crook 15298: @cindex image file, non-relocatable
1.1 anton 15299:
1.204 anton 15300: These files are simple memory dumps of the dictionary. They are
15301: specific to the executable (i.e., @file{gforth} file) they were
15302: created with. What's worse, they are specific to the place on which
15303: the dictionary resided when the image was created. Now, there is no
1.1 anton 15304: guarantee that the dictionary will reside at the same place the next
15305: time you start Gforth, so there's no guarantee that a non-relocatable
1.204 anton 15306: image will work the next time (Gforth will complain instead of
15307: crashing, though). Indeed, on OSs with (enabled) address-space
15308: randomization non-relocatable images are unlikely to work.
1.1 anton 15309:
1.204 anton 15310: You can create a non-relocatable image file with @code{savesystem}, e.g.:
1.1 anton 15311:
1.204 anton 15312: @example
15313: gforth app.fs -e "savesystem app.fi bye"
15314: @end example
1.44 crook 15315:
1.1 anton 15316: doc-savesystem
15317:
1.44 crook 15318:
1.1 anton 15319: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15320: @section Data-Relocatable Image Files
15321: @cindex data-relocatable image files
1.26 crook 15322: @cindex image file, data-relocatable
1.1 anton 15323:
1.204 anton 15324: These files contain relocatable data addresses, but fixed code
15325: addresses (instead of tokens). They are specific to the executable
15326: (i.e., @file{gforth} file) they were created with. Also, they disable
15327: dynamic native code generation (typically a factor of 2 in speed).
15328: You get a data-relocatable image, if you pass the engine you want to
15329: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15330: (@pxref{gforthmi}), e.g.
15331:
15332: @example
15333: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15334: @end example
15335:
15336: Note that the @code{--no-dynamic} is required here for the image to
15337: work (otherwise it will contain references to dynamically generated
15338: code that is not saved in the image).
15339:
1.1 anton 15340:
15341: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15342: @section Fully Relocatable Image Files
15343: @cindex fully relocatable image files
1.26 crook 15344: @cindex image file, fully relocatable
1.1 anton 15345:
15346: @cindex @file{kern*.fi}, relocatability
15347: @cindex @file{gforth.fi}, relocatability
15348: These image files have relocatable data addresses, and tokens for code
15349: addresses. They can be used with different binaries (e.g., with and
15350: without debugging) on the same machine, and even across machines with
1.204 anton 15351: the same data formats (byte order, cell size, floating point format),
15352: and they work with dynamic native code generation. However, they are
15353: usually specific to the version of Gforth they were created with. The
15354: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
1.1 anton 15355:
15356: There are two ways to create a fully relocatable image file:
15357:
15358: @menu
1.29 crook 15359: * gforthmi:: The normal way
1.1 anton 15360: * cross.fs:: The hard way
15361: @end menu
15362:
15363: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15364: @subsection @file{gforthmi}
15365: @cindex @file{comp-i.fs}
15366: @cindex @file{gforthmi}
15367:
15368: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15369: image @i{file} that contains everything you would load by invoking
15370: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15371: @example
1.29 crook 15372: gforthmi @i{file} @i{options}
1.1 anton 15373: @end example
15374:
15375: E.g., if you want to create an image @file{asm.fi} that has the file
15376: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15377: like this:
15378:
15379: @example
15380: gforthmi asm.fi asm.fs
15381: @end example
15382:
1.27 crook 15383: @file{gforthmi} is implemented as a sh script and works like this: It
15384: produces two non-relocatable images for different addresses and then
15385: compares them. Its output reflects this: first you see the output (if
1.62 crook 15386: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15387: files, then you see the output of the comparing program: It displays the
15388: offset used for data addresses and the offset used for code addresses;
1.1 anton 15389: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15390: image files, it displays a line like this:
1.1 anton 15391:
15392: @example
15393: 78DC BFFFFA50 BFFFFA40
15394: @end example
15395:
15396: This means that at offset $78dc from @code{forthstart}, one input image
15397: contains $bffffa50, and the other contains $bffffa40. Since these cells
15398: cannot be represented correctly in the output image, you should examine
15399: these places in the dictionary and verify that these cells are dead
15400: (i.e., not read before they are written).
1.39 anton 15401:
15402: @cindex --application, @code{gforthmi} option
15403: If you insert the option @code{--application} in front of the image file
15404: name, you will get an image that uses the @code{--appl-image} option
15405: instead of the @code{--image-file} option (@pxref{Invoking
15406: Gforth}). When you execute such an image on Unix (by typing the image
15407: name as command), the Gforth engine will pass all options to the image
15408: instead of trying to interpret them as engine options.
1.1 anton 15409:
1.27 crook 15410: If you type @file{gforthmi} with no arguments, it prints some usage
15411: instructions.
15412:
1.1 anton 15413: @cindex @code{savesystem} during @file{gforthmi}
15414: @cindex @code{bye} during @file{gforthmi}
15415: @cindex doubly indirect threaded code
1.44 crook 15416: @cindex environment variables
15417: @cindex @code{GFORTHD} -- environment variable
15418: @cindex @code{GFORTH} -- environment variable
1.1 anton 15419: @cindex @code{gforth-ditc}
1.29 crook 15420: There are a few wrinkles: After processing the passed @i{options}, the
1.204 anton 15421: words @code{savesystem} and @code{bye} must be visible. A special
15422: doubly indirect threaded version of the @file{gforth} executable is
15423: used for creating the non-relocatable images; you can pass the exact
15424: filename of this executable through the environment variable
15425: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15426: that is not doubly indirect threaded, you will not get a fully
15427: relocatable image, but a data-relocatable image
15428: (@pxref{Data-Relocatable Image Files}), because there is no code
15429: address offset). The normal @file{gforth} executable is used for
15430: creating the relocatable image; you can pass the exact filename of
15431: this executable through the environment variable @code{GFORTH}.
1.1 anton 15432:
15433: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15434: @subsection @file{cross.fs}
15435: @cindex @file{cross.fs}
15436: @cindex cross-compiler
15437: @cindex metacompiler
1.47 crook 15438: @cindex target compiler
1.1 anton 15439:
15440: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15441: programming language (@pxref{Cross Compiler}).
1.1 anton 15442:
1.47 crook 15443: @code{cross} allows you to create image files for machines with
1.1 anton 15444: different data sizes and data formats than the one used for generating
15445: the image file. You can also use it to create an application image that
15446: does not contain a Forth compiler. These features are bought with
15447: restrictions and inconveniences in programming. E.g., addresses have to
15448: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15449: order to make the code relocatable.
15450:
15451:
15452: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15453: @section Stack and Dictionary Sizes
15454: @cindex image file, stack and dictionary sizes
15455: @cindex dictionary size default
15456: @cindex stack size default
15457:
15458: If you invoke Gforth with a command line flag for the size
15459: (@pxref{Invoking Gforth}), the size you specify is stored in the
15460: dictionary. If you save the dictionary with @code{savesystem} or create
15461: an image with @file{gforthmi}, this size will become the default
15462: for the resulting image file. E.g., the following will create a
1.21 crook 15463: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15464:
15465: @example
15466: gforthmi gforth.fi -m 1M
15467: @end example
15468:
15469: In other words, if you want to set the default size for the dictionary
15470: and the stacks of an image, just invoke @file{gforthmi} with the
15471: appropriate options when creating the image.
15472:
15473: @cindex stack size, cache-friendly
15474: Note: For cache-friendly behaviour (i.e., good performance), you should
15475: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15476: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15477: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15478:
15479: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15480: @section Running Image Files
15481: @cindex running image files
15482: @cindex invoking image files
15483: @cindex image file invocation
15484:
15485: @cindex -i, invoke image file
15486: @cindex --image file, invoke image file
1.29 crook 15487: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15488: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15489: @example
1.29 crook 15490: gforth -i @i{image}
1.1 anton 15491: @end example
15492:
15493: @cindex executable image file
1.26 crook 15494: @cindex image file, executable
1.1 anton 15495: If your operating system supports starting scripts with a line of the
15496: form @code{#! ...}, you just have to type the image file name to start
15497: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15498: just a convention). I.e., to run Gforth with the image file @i{image},
15499: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15500: This works because every @code{.fi} file starts with a line of this
15501: format:
15502:
15503: @example
15504: #! /usr/local/bin/gforth-0.4.0 -i
15505: @end example
15506:
15507: The file and pathname for the Gforth engine specified on this line is
15508: the specific Gforth executable that it was built against; i.e. the value
15509: of the environment variable @code{GFORTH} at the time that
15510: @file{gforthmi} was executed.
1.1 anton 15511:
1.27 crook 15512: You can make use of the same shell capability to make a Forth source
15513: file into an executable. For example, if you place this text in a file:
1.26 crook 15514:
15515: @example
15516: #! /usr/local/bin/gforth
15517:
15518: ." Hello, world" CR
15519: bye
15520: @end example
15521:
15522: @noindent
1.27 crook 15523: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15524: directly from the command line. The sequence @code{#!} is used in two
15525: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15526: system@footnote{The Unix kernel actually recognises two types of files:
15527: executable files and files of data, where the data is processed by an
15528: interpreter that is specified on the ``interpreter line'' -- the first
15529: line of the file, starting with the sequence #!. There may be a small
15530: limit (e.g., 32) on the number of characters that may be specified on
15531: the interpreter line.} secondly it is treated as a comment character by
15532: Gforth. Because of the second usage, a space is required between
1.80 anton 15533: @code{#!} and the path to the executable (moreover, some Unixes
15534: require the sequence @code{#! /}).
1.27 crook 15535:
15536: The disadvantage of this latter technique, compared with using
1.80 anton 15537: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15538: compiled on-the-fly, each time the program is invoked.
1.26 crook 15539:
1.1 anton 15540: doc-#!
15541:
1.44 crook 15542:
1.1 anton 15543: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15544: @section Modifying the Startup Sequence
15545: @cindex startup sequence for image file
15546: @cindex image file initialization sequence
15547: @cindex initialization sequence of image file
15548:
1.120 anton 15549: You can add your own initialization to the startup sequence of an image
15550: through the deferred word @code{'cold}. @code{'cold} is invoked just
15551: before the image-specific command line processing (i.e., loading files
15552: and evaluating (@code{-e}) strings) starts.
1.1 anton 15553:
15554: A sequence for adding your initialization usually looks like this:
15555:
15556: @example
15557: :noname
15558: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15559: ... \ your stuff
15560: ; IS 'cold
15561: @end example
15562:
1.157 anton 15563: After @code{'cold}, Gforth processes the image options
15564: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15565: another deferred word. This normally prints Gforth's startup message
15566: and does nothing else.
15567:
1.1 anton 15568: @cindex turnkey image files
1.26 crook 15569: @cindex image file, turnkey applications
1.157 anton 15570: So, if you want to make a turnkey image (i.e., an image for an
15571: application instead of an extended Forth system), you can do this in
15572: two ways:
15573:
15574: @itemize @bullet
15575:
15576: @item
15577: If you want to do your interpretation of the OS command-line
15578: arguments, hook into @code{'cold}. In that case you probably also
15579: want to build the image with @code{gforthmi --application}
15580: (@pxref{gforthmi}) to keep the engine from processing OS command line
15581: options. You can then do your own command-line processing with
15582: @code{next-arg}
15583:
15584: @item
15585: If you want to have the normal Gforth processing of OS command-line
15586: arguments, hook into @code{bootmessage}.
15587:
15588: @end itemize
15589:
15590: In either case, you probably do not want the word that you execute in
15591: these hooks to exit normally, but use @code{bye} or @code{throw}.
15592: Otherwise the Gforth startup process would continue and eventually
15593: present the Forth command line to the user.
1.26 crook 15594:
15595: doc-'cold
1.157 anton 15596: doc-bootmessage
1.44 crook 15597:
1.1 anton 15598: @c ******************************************************************
1.113 anton 15599: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15600: @chapter Engine
15601: @cindex engine
15602: @cindex virtual machine
15603:
1.26 crook 15604: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15605: may be helpful for finding your way in the Gforth sources.
15606:
1.109 anton 15607: The ideas in this section have also been published in the following
15608: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15609: Forth-Tagung '93; M. Anton Ertl,
15610: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15611: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15612: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15613: Threaded code variations and optimizations (extended version)}},
15614: Forth-Tagung '02.
1.1 anton 15615:
15616: @menu
15617: * Portability::
15618: * Threading::
15619: * Primitives::
15620: * Performance::
15621: @end menu
15622:
15623: @node Portability, Threading, Engine, Engine
15624: @section Portability
15625: @cindex engine portability
15626:
1.26 crook 15627: An important goal of the Gforth Project is availability across a wide
15628: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15629: achieved this goal by manually coding the engine in assembly language
15630: for several then-popular processors. This approach is very
15631: labor-intensive and the results are short-lived due to progress in
15632: computer architecture.
1.1 anton 15633:
15634: @cindex C, using C for the engine
15635: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15636: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15637: particularly popular for UNIX-based Forths due to the large variety of
15638: architectures of UNIX machines. Unfortunately an implementation in C
15639: does not mix well with the goals of efficiency and with using
15640: traditional techniques: Indirect or direct threading cannot be expressed
15641: in C, and switch threading, the fastest technique available in C, is
15642: significantly slower. Another problem with C is that it is very
15643: cumbersome to express double integer arithmetic.
15644:
15645: @cindex GNU C for the engine
15646: @cindex long long
15647: Fortunately, there is a portable language that does not have these
15648: limitations: GNU C, the version of C processed by the GNU C compiler
15649: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15650: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15651: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15652: threading possible, its @code{long long} type (@pxref{Long Long, ,
15653: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15654: double numbers on many systems. GNU C is freely available on all
1.1 anton 15655: important (and many unimportant) UNIX machines, VMS, 80386s running
15656: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15657: on all these machines.
15658:
15659: Writing in a portable language has the reputation of producing code that
15660: is slower than assembly. For our Forth engine we repeatedly looked at
15661: the code produced by the compiler and eliminated most compiler-induced
15662: inefficiencies by appropriate changes in the source code.
15663:
15664: @cindex explicit register declarations
15665: @cindex --enable-force-reg, configuration flag
15666: @cindex -DFORCE_REG
15667: However, register allocation cannot be portably influenced by the
15668: programmer, leading to some inefficiencies on register-starved
15669: machines. We use explicit register declarations (@pxref{Explicit Reg
15670: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15671: improve the speed on some machines. They are turned on by using the
15672: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15673: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15674: machine, but also on the compiler version: On some machines some
15675: compiler versions produce incorrect code when certain explicit register
15676: declarations are used. So by default @code{-DFORCE_REG} is not used.
15677:
15678: @node Threading, Primitives, Portability, Engine
15679: @section Threading
15680: @cindex inner interpreter implementation
15681: @cindex threaded code implementation
15682:
15683: @cindex labels as values
15684: GNU C's labels as values extension (available since @code{gcc-2.0},
15685: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15686: makes it possible to take the address of @i{label} by writing
15687: @code{&&@i{label}}. This address can then be used in a statement like
15688: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15689: @code{goto x}.
15690:
1.26 crook 15691: @cindex @code{NEXT}, indirect threaded
1.1 anton 15692: @cindex indirect threaded inner interpreter
15693: @cindex inner interpreter, indirect threaded
1.26 crook 15694: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15695: @example
15696: cfa = *ip++;
15697: ca = *cfa;
15698: goto *ca;
15699: @end example
15700: @cindex instruction pointer
15701: For those unfamiliar with the names: @code{ip} is the Forth instruction
15702: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15703: execution token and points to the code field of the next word to be
15704: executed; The @code{ca} (code address) fetched from there points to some
15705: executable code, e.g., a primitive or the colon definition handler
15706: @code{docol}.
15707:
1.26 crook 15708: @cindex @code{NEXT}, direct threaded
1.1 anton 15709: @cindex direct threaded inner interpreter
15710: @cindex inner interpreter, direct threaded
15711: Direct threading is even simpler:
15712: @example
15713: ca = *ip++;
15714: goto *ca;
15715: @end example
15716:
15717: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15718: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15719:
15720: @menu
15721: * Scheduling::
15722: * Direct or Indirect Threaded?::
1.109 anton 15723: * Dynamic Superinstructions::
1.1 anton 15724: * DOES>::
15725: @end menu
15726:
15727: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15728: @subsection Scheduling
15729: @cindex inner interpreter optimization
15730:
15731: There is a little complication: Pipelined and superscalar processors,
15732: i.e., RISC and some modern CISC machines can process independent
15733: instructions while waiting for the results of an instruction. The
15734: compiler usually reorders (schedules) the instructions in a way that
15735: achieves good usage of these delay slots. However, on our first tries
15736: the compiler did not do well on scheduling primitives. E.g., for
15737: @code{+} implemented as
15738: @example
15739: n=sp[0]+sp[1];
15740: sp++;
15741: sp[0]=n;
15742: NEXT;
15743: @end example
1.81 anton 15744: the @code{NEXT} comes strictly after the other code, i.e., there is
15745: nearly no scheduling. After a little thought the problem becomes clear:
15746: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15747: addresses (and the version of @code{gcc} we used would not know it even
15748: if it was possible), so it could not move the load of the cfa above the
15749: store to the TOS. Indeed the pointers could be the same, if code on or
15750: very near the top of stack were executed. In the interest of speed we
15751: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15752: in scheduling: @code{NEXT} is divided into several parts:
15753: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15754: like:
1.1 anton 15755: @example
1.81 anton 15756: NEXT_P0;
1.1 anton 15757: n=sp[0]+sp[1];
15758: sp++;
15759: NEXT_P1;
15760: sp[0]=n;
15761: NEXT_P2;
15762: @end example
15763:
1.81 anton 15764: There are various schemes that distribute the different operations of
15765: NEXT between these parts in several ways; in general, different schemes
15766: perform best on different processors. We use a scheme for most
15767: architectures that performs well for most processors of this
1.109 anton 15768: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15769: the scheme on installation time.
15770:
1.1 anton 15771:
1.109 anton 15772: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15773: @subsection Direct or Indirect Threaded?
15774: @cindex threading, direct or indirect?
15775:
1.109 anton 15776: Threaded forth code consists of references to primitives (simple machine
15777: code routines like @code{+}) and to non-primitives (e.g., colon
15778: definitions, variables, constants); for a specific class of
15779: non-primitives (e.g., variables) there is one code routine (e.g.,
15780: @code{dovar}), but each variable needs a separate reference to its data.
15781:
15782: Traditionally Forth has been implemented as indirect threaded code,
15783: because this allows to use only one cell to reference a non-primitive
15784: (basically you point to the data, and find the code address there).
15785:
15786: @cindex primitive-centric threaded code
15787: However, threaded code in Gforth (since 0.6.0) uses two cells for
15788: non-primitives, one for the code address, and one for the data address;
15789: the data pointer is an immediate argument for the virtual machine
15790: instruction represented by the code address. We call this
15791: @emph{primitive-centric} threaded code, because all code addresses point
15792: to simple primitives. E.g., for a variable, the code address is for
15793: @code{lit} (also used for integer literals like @code{99}).
15794:
15795: Primitive-centric threaded code allows us to use (faster) direct
15796: threading as dispatch method, completely portably (direct threaded code
15797: in Gforth before 0.6.0 required architecture-specific code). It also
15798: eliminates the performance problems related to I-cache consistency that
15799: 386 implementations have with direct threaded code, and allows
15800: additional optimizations.
15801:
15802: @cindex hybrid direct/indirect threaded code
15803: There is a catch, however: the @var{xt} parameter of @code{execute} can
15804: occupy only one cell, so how do we pass non-primitives with their code
15805: @emph{and} data addresses to them? Our answer is to use indirect
15806: threaded dispatch for @code{execute} and other words that use a
15807: single-cell xt. So, normal threaded code in colon definitions uses
15808: direct threading, and @code{execute} and similar words, which dispatch
15809: to xts on the data stack, use indirect threaded code. We call this
15810: @emph{hybrid direct/indirect} threaded code.
15811:
15812: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15813: @cindex gforth engine
15814: @cindex gforth-fast engine
15815: The engines @command{gforth} and @command{gforth-fast} use hybrid
15816: direct/indirect threaded code. This means that with these engines you
15817: cannot use @code{,} to compile an xt. Instead, you have to use
15818: @code{compile,}.
15819:
15820: @cindex gforth-itc engine
1.115 anton 15821: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15822: This engine uses plain old indirect threaded code. It still compiles in
15823: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15824: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15825: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15826: and execute @code{' , is compile,}. Your program can check if it is
15827: running on a hybrid direct/indirect threaded engine or a pure indirect
15828: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15829:
15830:
15831: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15832: @subsection Dynamic Superinstructions
15833: @cindex Dynamic superinstructions with replication
15834: @cindex Superinstructions
15835: @cindex Replication
15836:
15837: The engines @command{gforth} and @command{gforth-fast} use another
15838: optimization: Dynamic superinstructions with replication. As an
15839: example, consider the following colon definition:
15840:
15841: @example
15842: : squared ( n1 -- n2 )
15843: dup * ;
15844: @end example
15845:
15846: Gforth compiles this into the threaded code sequence
15847:
15848: @example
15849: dup
15850: *
15851: ;s
15852: @end example
15853:
15854: In normal direct threaded code there is a code address occupying one
15855: cell for each of these primitives. Each code address points to a
15856: machine code routine, and the interpreter jumps to this machine code in
15857: order to execute the primitive. The routines for these three
15858: primitives are (in @command{gforth-fast} on the 386):
15859:
15860: @example
15861: Code dup
15862: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15863: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15864: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15865: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15866: end-code
15867: Code *
15868: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15869: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15870: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15871: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15872: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15873: end-code
15874: Code ;s
15875: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15876: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15877: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15878: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15879: end-code
15880: @end example
15881:
15882: With dynamic superinstructions and replication the compiler does not
15883: just lay down the threaded code, but also copies the machine code
15884: fragments, usually without the jump at the end.
15885:
15886: @example
15887: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15888: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15889: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15890: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15891: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15892: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15893: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15894: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15895: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15896: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15897: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15898: @end example
15899:
15900: Only when a threaded-code control-flow change happens (e.g., in
15901: @code{;s}), the jump is appended. This optimization eliminates many of
15902: these jumps and makes the rest much more predictable. The speedup
15903: depends on the processor and the application; on the Athlon and Pentium
15904: III this optimization typically produces a speedup by a factor of 2.
15905:
15906: The code addresses in the direct-threaded code are set to point to the
15907: appropriate points in the copied machine code, in this example like
15908: this:
1.1 anton 15909:
1.109 anton 15910: @example
15911: primitive code address
15912: dup $4057D27D
15913: * $4057D286
15914: ;s $4057D292
15915: @end example
15916:
15917: Thus there can be threaded-code jumps to any place in this piece of
15918: code. This also simplifies decompilation quite a bit.
15919:
15920: @cindex --no-dynamic command-line option
15921: @cindex --no-super command-line option
15922: You can disable this optimization with @option{--no-dynamic}. You can
15923: use the copying without eliminating the jumps (i.e., dynamic
15924: replication, but without superinstructions) with @option{--no-super};
15925: this gives the branch prediction benefit alone; the effect on
1.110 anton 15926: performance depends on the CPU; on the Athlon and Pentium III the
15927: speedup is a little less than for dynamic superinstructions with
15928: replication.
15929:
15930: @cindex patching threaded code
15931: One use of these options is if you want to patch the threaded code.
15932: With superinstructions, many of the dispatch jumps are eliminated, so
15933: patching often has no effect. These options preserve all the dispatch
15934: jumps.
1.109 anton 15935:
15936: @cindex --dynamic command-line option
1.110 anton 15937: On some machines dynamic superinstructions are disabled by default,
15938: because it is unsafe on these machines. However, if you feel
15939: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15940:
15941: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15942: @subsection DOES>
15943: @cindex @code{DOES>} implementation
15944:
1.26 crook 15945: @cindex @code{dodoes} routine
15946: @cindex @code{DOES>}-code
1.1 anton 15947: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15948: the chunk of code executed by every word defined by a
1.109 anton 15949: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15950: this is only needed if the xt of the word is @code{execute}d. The main
15951: problem here is: How to find the Forth code to be executed, i.e. the
15952: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15953: solutions:
1.1 anton 15954:
1.21 crook 15955: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15956: @code{DOES>}-code address is stored in the cell after the code address
15957: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15958: illegal in the Forth-79 and all later standards, because in fig-Forth
15959: this address lies in the body (which is illegal in these
15960: standards). However, by making the code field larger for all words this
15961: solution becomes legal again. We use this approach. Leaving a cell
15962: unused in most words is a bit wasteful, but on the machines we are
15963: targeting this is hardly a problem.
15964:
1.1 anton 15965:
15966: @node Primitives, Performance, Threading, Engine
15967: @section Primitives
15968: @cindex primitives, implementation
15969: @cindex virtual machine instructions, implementation
15970:
15971: @menu
15972: * Automatic Generation::
15973: * TOS Optimization::
15974: * Produced code::
15975: @end menu
15976:
15977: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15978: @subsection Automatic Generation
15979: @cindex primitives, automatic generation
15980:
15981: @cindex @file{prims2x.fs}
1.109 anton 15982:
1.1 anton 15983: Since the primitives are implemented in a portable language, there is no
15984: longer any need to minimize the number of primitives. On the contrary,
15985: having many primitives has an advantage: speed. In order to reduce the
15986: number of errors in primitives and to make programming them easier, we
1.109 anton 15987: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15988: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15989: generates most (and sometimes all) of the C code for a primitive from
15990: the stack effect notation. The source for a primitive has the following
15991: form:
1.1 anton 15992:
15993: @cindex primitive source format
15994: @format
1.58 anton 15995: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15996: [@code{""}@i{glossary entry}@code{""}]
15997: @i{C code}
1.1 anton 15998: [@code{:}
1.29 crook 15999: @i{Forth code}]
1.1 anton 16000: @end format
16001:
16002: The items in brackets are optional. The category and glossary fields
16003: are there for generating the documentation, the Forth code is there
16004: for manual implementations on machines without GNU C. E.g., the source
16005: for the primitive @code{+} is:
16006: @example
1.58 anton 16007: + ( n1 n2 -- n ) core plus
1.1 anton 16008: n = n1+n2;
16009: @end example
16010:
16011: This looks like a specification, but in fact @code{n = n1+n2} is C
16012: code. Our primitive generation tool extracts a lot of information from
16013: the stack effect notations@footnote{We use a one-stack notation, even
16014: though we have separate data and floating-point stacks; The separate
16015: notation can be generated easily from the unified notation.}: The number
16016: of items popped from and pushed on the stack, their type, and by what
16017: name they are referred to in the C code. It then generates a C code
16018: prelude and postlude for each primitive. The final C code for @code{+}
16019: looks like this:
16020:
16021: @example
1.46 pazsan 16022: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 16023: /* */ /* documentation */
1.81 anton 16024: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 16025: @{
16026: DEF_CA /* definition of variable ca (indirect threading) */
16027: Cell n1; /* definitions of variables */
16028: Cell n2;
16029: Cell n;
1.81 anton 16030: NEXT_P0; /* NEXT part 0 */
1.1 anton 16031: n1 = (Cell) sp[1]; /* input */
16032: n2 = (Cell) TOS;
16033: sp += 1; /* stack adjustment */
16034: @{
16035: n = n1+n2; /* C code taken from the source */
16036: @}
16037: NEXT_P1; /* NEXT part 1 */
16038: TOS = (Cell)n; /* output */
16039: NEXT_P2; /* NEXT part 2 */
16040: @}
16041: @end example
16042:
16043: This looks long and inefficient, but the GNU C compiler optimizes quite
16044: well and produces optimal code for @code{+} on, e.g., the R3000 and the
16045: HP RISC machines: Defining the @code{n}s does not produce any code, and
16046: using them as intermediate storage also adds no cost.
16047:
1.26 crook 16048: There are also other optimizations that are not illustrated by this
16049: example: assignments between simple variables are usually for free (copy
1.1 anton 16050: propagation). If one of the stack items is not used by the primitive
16051: (e.g. in @code{drop}), the compiler eliminates the load from the stack
16052: (dead code elimination). On the other hand, there are some things that
16053: the compiler does not do, therefore they are performed by
16054: @file{prims2x.fs}: The compiler does not optimize code away that stores
16055: a stack item to the place where it just came from (e.g., @code{over}).
16056:
16057: While programming a primitive is usually easy, there are a few cases
16058: where the programmer has to take the actions of the generator into
16059: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 16060: fall through to @code{NEXT}.
1.109 anton 16061:
16062: For more information
1.1 anton 16063:
16064: @node TOS Optimization, Produced code, Automatic Generation, Primitives
16065: @subsection TOS Optimization
16066: @cindex TOS optimization for primitives
16067: @cindex primitives, keeping the TOS in a register
16068:
16069: An important optimization for stack machine emulators, e.g., Forth
16070: engines, is keeping one or more of the top stack items in
1.29 crook 16071: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
16072: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 16073: @itemize @bullet
16074: @item
1.29 crook 16075: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 16076: due to fewer loads from and stores to the stack.
1.29 crook 16077: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
16078: @i{y<n}, due to additional moves between registers.
1.1 anton 16079: @end itemize
16080:
16081: @cindex -DUSE_TOS
16082: @cindex -DUSE_NO_TOS
16083: In particular, keeping one item in a register is never a disadvantage,
16084: if there are enough registers. Keeping two items in registers is a
16085: disadvantage for frequent words like @code{?branch}, constants,
16086: variables, literals and @code{i}. Therefore our generator only produces
16087: code that keeps zero or one items in registers. The generated C code
16088: covers both cases; the selection between these alternatives is made at
16089: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
16090: code for @code{+} is just a simple variable name in the one-item case,
16091: otherwise it is a macro that expands into @code{sp[0]}. Note that the
16092: GNU C compiler tries to keep simple variables like @code{TOS} in
16093: registers, and it usually succeeds, if there are enough registers.
16094:
16095: @cindex -DUSE_FTOS
16096: @cindex -DUSE_NO_FTOS
16097: The primitive generator performs the TOS optimization for the
16098: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16099: operations the benefit of this optimization is even larger:
16100: floating-point operations take quite long on most processors, but can be
16101: performed in parallel with other operations as long as their results are
16102: not used. If the FP-TOS is kept in a register, this works. If
16103: it is kept on the stack, i.e., in memory, the store into memory has to
16104: wait for the result of the floating-point operation, lengthening the
16105: execution time of the primitive considerably.
16106:
16107: The TOS optimization makes the automatic generation of primitives a
16108: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16109: @code{TOS} is not sufficient. There are some special cases to
16110: consider:
16111: @itemize @bullet
16112: @item In the case of @code{dup ( w -- w w )} the generator must not
16113: eliminate the store to the original location of the item on the stack,
16114: if the TOS optimization is turned on.
16115: @item Primitives with stack effects of the form @code{--}
1.29 crook 16116: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16117: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 16118: must load the TOS from the stack at the end. But for the null stack
16119: effect @code{--} no stores or loads should be generated.
16120: @end itemize
16121:
16122: @node Produced code, , TOS Optimization, Primitives
16123: @subsection Produced code
16124: @cindex primitives, assembly code listing
16125:
16126: @cindex @file{engine.s}
16127: To see what assembly code is produced for the primitives on your machine
16128: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 16129: look at the resulting file @file{engine.s}. Alternatively, you can also
16130: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 16131:
16132: @node Performance, , Primitives, Engine
16133: @section Performance
16134: @cindex performance of some Forth interpreters
16135: @cindex engine performance
16136: @cindex benchmarking Forth systems
16137: @cindex Gforth performance
16138:
16139: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 16140: impossible to write a significantly faster threaded-code engine.
1.1 anton 16141:
16142: On register-starved machines like the 386 architecture processors
16143: improvements are possible, because @code{gcc} does not utilize the
16144: registers as well as a human, even with explicit register declarations;
16145: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16146: and hand-tuned it for the 486; this system is 1.19 times faster on the
16147: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 16148: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
16149: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16150: registers fit in real registers (and we can even afford to use the TOS
16151: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 16152: earlier results. And dynamic superinstructions provide another speedup
16153: (but only around a factor 1.2 on the 486).
1.1 anton 16154:
16155: @cindex Win32Forth performance
16156: @cindex NT Forth performance
16157: @cindex eforth performance
16158: @cindex ThisForth performance
16159: @cindex PFE performance
16160: @cindex TILE performance
1.81 anton 16161: The potential advantage of assembly language implementations is not
1.112 anton 16162: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 16163: (direct threaded, compiled with @code{gcc-2.95.1} and
16164: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16165: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16166: (with and without peephole (aka pinhole) optimization of the threaded
16167: code); all these systems were written in assembly language. We also
16168: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16169: with @code{gcc-2.6.3} with the default configuration for Linux:
16170: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16171: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16172: employs peephole optimization of the threaded code) and TILE (compiled
16173: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16174: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16175: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16176: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16177: then extended it to run the benchmarks, added the peephole optimizer,
16178: ran the benchmarks and reported the results.
1.40 anton 16179:
1.1 anton 16180: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16181: matrix multiplication come from the Stanford integer benchmarks and have
16182: been translated into Forth by Martin Fraeman; we used the versions
16183: included in the TILE Forth package, but with bigger data set sizes; and
16184: a recursive Fibonacci number computation for benchmarking calling
16185: performance. The following table shows the time taken for the benchmarks
16186: scaled by the time taken by Gforth (in other words, it shows the speedup
16187: factor that Gforth achieved over the other systems).
16188:
16189: @example
1.112 anton 16190: relative Win32- NT eforth This-
16191: time Gforth Forth Forth eforth +opt PFE Forth TILE
16192: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
16193: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
16194: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
16195: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 16196: @end example
16197:
1.26 crook 16198: You may be quite surprised by the good performance of Gforth when
16199: compared with systems written in assembly language. One important reason
16200: for the disappointing performance of these other systems is probably
16201: that they are not written optimally for the 486 (e.g., they use the
16202: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16203: but costly method for relocating the Forth image: like @code{cforth}, it
16204: computes the actual addresses at run time, resulting in two address
16205: computations per @code{NEXT} (@pxref{Image File Background}).
16206:
1.1 anton 16207: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16208: explained with the self-imposed restriction of the latter systems to
16209: standard C, which makes efficient threading impossible (however, the
1.4 anton 16210: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 16211: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16212: Moreover, current C compilers have a hard time optimizing other aspects
16213: of the ThisForth and the TILE source.
16214:
1.26 crook 16215: The performance of Gforth on 386 architecture processors varies widely
16216: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16217: allocate any of the virtual machine registers into real machine
16218: registers by itself and would not work correctly with explicit register
1.112 anton 16219: declarations, giving a significantly slower engine (on a 486DX2/66
16220: running the Sieve) than the one measured above.
1.1 anton 16221:
1.26 crook 16222: Note that there have been several releases of Win32Forth since the
16223: release presented here, so the results presented above may have little
1.40 anton 16224: predictive value for the performance of Win32Forth today (results for
16225: the current release on an i486DX2/66 are welcome).
1.1 anton 16226:
16227: @cindex @file{Benchres}
1.66 anton 16228: In
16229: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16230: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 16231: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 16232: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16233: several native code systems; that version of Gforth is slower on a 486
1.112 anton 16234: than the version used here. You can find a newer version of these
16235: measurements at
1.47 crook 16236: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 16237: find numbers for Gforth on various machines in @file{Benchres}.
16238:
1.26 crook 16239: @c ******************************************************************
1.113 anton 16240: @c @node Binding to System Library, Cross Compiler, Engine, Top
16241: @c @chapter Binding to System Library
1.13 pazsan 16242:
1.113 anton 16243: @c ****************************************************************
16244: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 16245: @chapter Cross Compiler
1.47 crook 16246: @cindex @file{cross.fs}
16247: @cindex cross-compiler
16248: @cindex metacompiler
16249: @cindex target compiler
1.13 pazsan 16250:
1.46 pazsan 16251: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16252: mostly written in Forth, including crucial parts like the outer
16253: interpreter and compiler, it needs compiled Forth code to get
16254: started. The cross compiler allows to create new images for other
16255: architectures, even running under another Forth system.
1.13 pazsan 16256:
16257: @menu
1.67 anton 16258: * Using the Cross Compiler::
16259: * How the Cross Compiler Works::
1.13 pazsan 16260: @end menu
16261:
1.21 crook 16262: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 16263: @section Using the Cross Compiler
1.46 pazsan 16264:
16265: The cross compiler uses a language that resembles Forth, but isn't. The
16266: main difference is that you can execute Forth code after definition,
16267: while you usually can't execute the code compiled by cross, because the
16268: code you are compiling is typically for a different computer than the
16269: one you are compiling on.
16270:
1.81 anton 16271: @c anton: This chapter is somewhat different from waht I would expect: I
16272: @c would expect an explanation of the cross language and how to create an
16273: @c application image with it. The section explains some aspects of
16274: @c creating a Gforth kernel.
16275:
1.46 pazsan 16276: The Makefile is already set up to allow you to create kernels for new
16277: architectures with a simple make command. The generic kernels using the
16278: GCC compiled virtual machine are created in the normal build process
16279: with @code{make}. To create a embedded Gforth executable for e.g. the
16280: 8086 processor (running on a DOS machine), type
16281:
16282: @example
16283: make kernl-8086.fi
16284: @end example
16285:
16286: This will use the machine description from the @file{arch/8086}
16287: directory to create a new kernel. A machine file may look like that:
16288:
16289: @example
16290: \ Parameter for target systems 06oct92py
16291:
16292: 4 Constant cell \ cell size in bytes
16293: 2 Constant cell<< \ cell shift to bytes
16294: 5 Constant cell>bit \ cell shift to bits
16295: 8 Constant bits/char \ bits per character
16296: 8 Constant bits/byte \ bits per byte [default: 8]
16297: 8 Constant float \ bytes per float
16298: 8 Constant /maxalign \ maximum alignment in bytes
16299: false Constant bigendian \ byte order
16300: ( true=big, false=little )
16301:
16302: include machpc.fs \ feature list
16303: @end example
16304:
16305: This part is obligatory for the cross compiler itself, the feature list
16306: is used by the kernel to conditionally compile some features in and out,
16307: depending on whether the target supports these features.
16308:
16309: There are some optional features, if you define your own primitives,
16310: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 16311: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 16312: @code{prims-include} includes primitives, and @code{>boot} prepares for
16313: booting.
16314:
16315: @example
16316: : asm-include ." Include assembler" cr
16317: s" arch/8086/asm.fs" included ;
16318:
16319: : prims-include ." Include primitives" cr
16320: s" arch/8086/prim.fs" included ;
16321:
16322: : >boot ." Prepare booting" cr
16323: s" ' boot >body into-forth 1+ !" evaluate ;
16324: @end example
16325:
16326: These words are used as sort of macro during the cross compilation in
1.81 anton 16327: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 16328: be possible --- but more complicated --- to write a new kernel project
16329: file, too.
16330:
16331: @file{kernel/main.fs} expects the machine description file name on the
16332: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16333: @code{mach-file} leaves a counted string on the stack, or
16334: @code{machine-file} leaves an address, count pair of the filename on the
16335: stack.
16336:
16337: The feature list is typically controlled using @code{SetValue}, generic
16338: files that are used by several projects can use @code{DefaultValue}
16339: instead. Both functions work like @code{Value}, when the value isn't
16340: defined, but @code{SetValue} works like @code{to} if the value is
16341: defined, and @code{DefaultValue} doesn't set anything, if the value is
16342: defined.
16343:
16344: @example
16345: \ generic mach file for pc gforth 03sep97jaw
16346:
16347: true DefaultValue NIL \ relocating
16348:
16349: >ENVIRON
16350:
16351: true DefaultValue file \ controls the presence of the
16352: \ file access wordset
16353: true DefaultValue OS \ flag to indicate a operating system
16354:
16355: true DefaultValue prims \ true: primitives are c-code
16356:
16357: true DefaultValue floating \ floating point wordset is present
16358:
16359: true DefaultValue glocals \ gforth locals are present
16360: \ will be loaded
16361: true DefaultValue dcomps \ double number comparisons
16362:
16363: true DefaultValue hash \ hashing primitives are loaded/present
16364:
16365: true DefaultValue xconds \ used together with glocals,
16366: \ special conditionals supporting gforths'
16367: \ local variables
16368: true DefaultValue header \ save a header information
16369:
16370: true DefaultValue backtrace \ enables backtrace code
16371:
16372: false DefaultValue ec
16373: false DefaultValue crlf
16374:
16375: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16376:
16377: &16 KB DefaultValue stack-size
16378: &15 KB &512 + DefaultValue fstack-size
16379: &15 KB DefaultValue rstack-size
16380: &14 KB &512 + DefaultValue lstack-size
16381: @end example
1.13 pazsan 16382:
1.48 anton 16383: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16384: @section How the Cross Compiler Works
1.13 pazsan 16385:
16386: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16387: @appendix Bugs
1.1 anton 16388: @cindex bug reporting
16389:
1.21 crook 16390: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16391:
1.103 anton 16392: If you find a bug, please submit a bug report through
16393: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16394:
16395: @itemize @bullet
16396: @item
1.81 anton 16397: A program (or a sequence of keyboard commands) that reproduces the bug.
16398: @item
16399: A description of what you think constitutes the buggy behaviour.
16400: @item
1.21 crook 16401: The Gforth version used (it is announced at the start of an
16402: interactive Gforth session).
16403: @item
16404: The machine and operating system (on Unix
16405: systems @code{uname -a} will report this information).
16406: @item
1.81 anton 16407: The installation options (you can find the configure options at the
16408: start of @file{config.status}) and configuration (@code{configure}
16409: output or @file{config.cache}).
1.21 crook 16410: @item
16411: A complete list of changes (if any) you (or your installer) have made to the
16412: Gforth sources.
16413: @end itemize
1.1 anton 16414:
16415: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16416: to Report Bugs, gcc.info, GNU C Manual}.
16417:
16418:
1.21 crook 16419: @node Origin, Forth-related information, Bugs, Top
16420: @appendix Authors and Ancestors of Gforth
1.1 anton 16421:
16422: @section Authors and Contributors
16423: @cindex authors of Gforth
16424: @cindex contributors to Gforth
16425:
16426: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16427: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16428: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16429: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16430: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16431: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16432: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16433: working on automatic support for calling C libraries. Helpful comments
16434: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16435: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16436: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16437: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16438: comments from many others; thank you all, sorry for not listing you
16439: here (but digging through my mailbox to extract your names is on my
16440: to-do list).
1.1 anton 16441:
16442: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16443: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16444: was developed across the Internet, and its authors did not meet
1.20 pazsan 16445: physically for the first 4 years of development.
1.1 anton 16446:
16447: @section Pedigree
1.26 crook 16448: @cindex pedigree of Gforth
1.1 anton 16449:
1.81 anton 16450: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16451: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16452:
1.20 pazsan 16453: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16454: 32 bit native code version of VolksForth for the Atari ST, written
16455: mostly by Dietrich Weineck.
16456:
1.81 anton 16457: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16458: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16459: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16460:
1.147 anton 16461: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16462: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16463:
16464: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16465: 1979. Robert Selzer and Bill Ragsdale developed the original
16466: implementation of fig-Forth for the 6502 based on microForth.
16467:
16468: The principal architect of microForth was Dean Sanderson. microForth was
16469: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16470: the 1802, and subsequently implemented on the 8080, the 6800 and the
16471: Z80.
16472:
16473: All earlier Forth systems were custom-made, usually by Charles Moore,
16474: who discovered (as he puts it) Forth during the late 60s. The first full
16475: Forth existed in 1971.
16476:
1.81 anton 16477: A part of the information in this section comes from
16478: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16479: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16480: Charles H. Moore, presented at the HOPL-II conference and preprinted
16481: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16482: genealogical information about Forth there. For a more general (and
16483: graphical) Forth family tree look see
16484: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16485: Forth Family Tree and Timeline}.
1.1 anton 16486:
1.81 anton 16487: @c ------------------------------------------------------------------
1.113 anton 16488: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16489: @appendix Other Forth-related information
16490: @cindex Forth-related information
16491:
1.81 anton 16492: @c anton: I threw most of this stuff out, because it can be found through
16493: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16494:
16495: @cindex comp.lang.forth
16496: @cindex frequently asked questions
1.81 anton 16497: There is an active news group (comp.lang.forth) discussing Forth
16498: (including Gforth) and Forth-related issues. Its
16499: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16500: (frequently asked questions and their answers) contains a lot of
16501: information on Forth. You should read it before posting to
16502: comp.lang.forth.
1.21 crook 16503:
1.81 anton 16504: The ANS Forth standard is most usable in its
16505: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16506:
1.113 anton 16507: @c ---------------------------------------------------
16508: @node Licenses, Word Index, Forth-related information, Top
16509: @appendix Licenses
16510:
16511: @menu
16512: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 16513: * Copying:: GPL (for copying this software).
1.113 anton 16514: @end menu
16515:
1.192 anton 16516: @node GNU Free Documentation License, Copying, Licenses, Licenses
16517: @appendixsec GNU Free Documentation License
1.113 anton 16518: @include fdl.texi
16519:
1.192 anton 16520: @node Copying, , GNU Free Documentation License, Licenses
16521: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16522: @include gpl.texi
16523:
16524:
16525:
1.81 anton 16526: @c ------------------------------------------------------------------
1.113 anton 16527: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16528: @unnumbered Word Index
16529:
1.26 crook 16530: This index is a list of Forth words that have ``glossary'' entries
16531: within this manual. Each word is listed with its stack effect and
16532: wordset.
1.1 anton 16533:
16534: @printindex fn
16535:
1.81 anton 16536: @c anton: the name index seems superfluous given the word and concept indices.
16537:
16538: @c @node Name Index, Concept Index, Word Index, Top
16539: @c @unnumbered Name Index
1.41 anton 16540:
1.81 anton 16541: @c This index is a list of Forth words that have ``glossary'' entries
16542: @c within this manual.
1.41 anton 16543:
1.81 anton 16544: @c @printindex ky
1.41 anton 16545:
1.113 anton 16546: @c -------------------------------------------------------
1.81 anton 16547: @node Concept Index, , Word Index, Top
1.1 anton 16548: @unnumbered Concept and Word Index
16549:
1.26 crook 16550: Not all entries listed in this index are present verbatim in the
16551: text. This index also duplicates, in abbreviated form, all of the words
16552: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16553:
16554: @printindex cp
16555:
16556: @bye
1.81 anton 16557:
16558:
1.1 anton 16559:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>