Annotation of gforth/doc/gforth.ds, revision 1.192
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.113 anton 14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
1.29 crook 21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
1.29 crook 63:
1.191 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.190 anton 177: * Floating Point Tutorial::
1.87 anton 178: * Files Tutorial::
1.48 anton 179: * Interpretation and Compilation Semantics and Immediacy Tutorial::
180: * Execution Tokens Tutorial::
181: * Exceptions Tutorial::
182: * Defining Words Tutorial::
183: * Arrays and Records Tutorial::
184: * POSTPONE Tutorial::
185: * Literal Tutorial::
186: * Advanced macros Tutorial::
187: * Compilation Tokens Tutorial::
188: * Wordlists and Search Order Tutorial::
1.29 crook 189:
1.24 anton 190: An Introduction to ANS Forth
191:
1.67 anton 192: * Introducing the Text Interpreter::
193: * Stacks and Postfix notation::
194: * Your first definition::
195: * How does that work?::
196: * Forth is written in Forth::
197: * Review - elements of a Forth system::
198: * Where to go next::
199: * Exercises::
1.24 anton 200:
1.12 anton 201: Forth Words
202:
203: * Notation::
1.65 anton 204: * Case insensitivity::
205: * Comments::
206: * Boolean Flags::
1.12 anton 207: * Arithmetic::
208: * Stack Manipulation::
209: * Memory::
210: * Control Structures::
211: * Defining Words::
1.65 anton 212: * Interpretation and Compilation Semantics::
1.47 crook 213: * Tokens for Words::
1.81 anton 214: * Compiling words::
1.65 anton 215: * The Text Interpreter::
1.111 anton 216: * The Input Stream::
1.65 anton 217: * Word Lists::
218: * Environmental Queries::
1.12 anton 219: * Files::
220: * Blocks::
221: * Other I/O::
1.121 anton 222: * OS command line arguments::
1.78 anton 223: * Locals::
224: * Structures::
225: * Object-oriented Forth::
1.12 anton 226: * Programming Tools::
1.150 anton 227: * C Interface::
1.12 anton 228: * Assembler and Code Words::
229: * Threading Words::
1.65 anton 230: * Passing Commands to the OS::
231: * Keeping track of Time::
232: * Miscellaneous Words::
1.12 anton 233:
234: Arithmetic
235:
236: * Single precision::
1.67 anton 237: * Double precision:: Double-cell integer arithmetic
1.12 anton 238: * Bitwise operations::
1.67 anton 239: * Numeric comparison::
1.32 anton 240: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 241: * Floating Point::
242:
243: Stack Manipulation
244:
245: * Data stack::
246: * Floating point stack::
247: * Return stack::
248: * Locals stack::
249: * Stack pointer manipulation::
250:
251: Memory
252:
1.32 anton 253: * Memory model::
254: * Dictionary allocation::
255: * Heap Allocation::
256: * Memory Access::
257: * Address arithmetic::
258: * Memory Blocks::
1.12 anton 259:
260: Control Structures
261:
1.41 anton 262: * Selection:: IF ... ELSE ... ENDIF
263: * Simple Loops:: BEGIN ...
1.32 anton 264: * Counted Loops:: DO
1.67 anton 265: * Arbitrary control structures::
266: * Calls and returns::
1.12 anton 267: * Exception Handling::
268:
269: Defining Words
270:
1.67 anton 271: * CREATE::
1.44 crook 272: * Variables:: Variables and user variables
1.67 anton 273: * Constants::
1.44 crook 274: * Values:: Initialised variables
1.67 anton 275: * Colon Definitions::
1.44 crook 276: * Anonymous Definitions:: Definitions without names
1.71 anton 277: * Supplying names:: Passing definition names as strings
1.67 anton 278: * User-defined Defining Words::
1.170 pazsan 279: * Deferred Words:: Allow forward references
1.67 anton 280: * Aliases::
1.47 crook 281:
1.63 anton 282: User-defined Defining Words
283:
284: * CREATE..DOES> applications::
285: * CREATE..DOES> details::
286: * Advanced does> usage example::
1.155 anton 287: * Const-does>::
1.63 anton 288:
1.47 crook 289: Interpretation and Compilation Semantics
290:
1.67 anton 291: * Combined words::
1.12 anton 292:
1.71 anton 293: Tokens for Words
294:
295: * Execution token:: represents execution/interpretation semantics
296: * Compilation token:: represents compilation semantics
297: * Name token:: represents named words
298:
1.82 anton 299: Compiling words
300:
301: * Literals:: Compiling data values
302: * Macros:: Compiling words
303:
1.21 crook 304: The Text Interpreter
305:
1.67 anton 306: * Input Sources::
307: * Number Conversion::
308: * Interpret/Compile states::
309: * Interpreter Directives::
1.21 crook 310:
1.26 crook 311: Word Lists
312:
1.75 anton 313: * Vocabularies::
1.67 anton 314: * Why use word lists?::
1.75 anton 315: * Word list example::
1.26 crook 316:
317: Files
318:
1.48 anton 319: * Forth source files::
320: * General files::
1.167 anton 321: * Redirection::
1.48 anton 322: * Search Paths::
323:
324: Search Paths
325:
1.75 anton 326: * Source Search Paths::
1.26 crook 327: * General Search Paths::
328:
329: Other I/O
330:
1.32 anton 331: * Simple numeric output:: Predefined formats
332: * Formatted numeric output:: Formatted (pictured) output
333: * String Formats:: How Forth stores strings in memory
1.67 anton 334: * Displaying characters and strings:: Other stuff
1.178 anton 335: * Terminal output:: Cursor positioning etc.
1.181 anton 336: * Single-key input::
337: * Line input and conversion::
1.112 anton 338: * Pipes:: How to create your own pipes
1.149 pazsan 339: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 340:
341: Locals
342:
343: * Gforth locals::
344: * ANS Forth locals::
345:
346: Gforth locals
347:
348: * Where are locals visible by name?::
349: * How long do locals live?::
1.78 anton 350: * Locals programming style::
351: * Locals implementation::
1.26 crook 352:
1.12 anton 353: Structures
354:
355: * Why explicit structure support?::
356: * Structure Usage::
357: * Structure Naming Convention::
358: * Structure Implementation::
359: * Structure Glossary::
1.183 anton 360: * Forth200x Structures::
1.12 anton 361:
362: Object-oriented Forth
363:
1.48 anton 364: * Why object-oriented programming?::
365: * Object-Oriented Terminology::
366: * Objects::
367: * OOF::
368: * Mini-OOF::
1.23 crook 369: * Comparison with other object models::
1.12 anton 370:
1.24 anton 371: The @file{objects.fs} model
1.12 anton 372:
373: * Properties of the Objects model::
374: * Basic Objects Usage::
1.41 anton 375: * The Objects base class::
1.12 anton 376: * Creating objects::
377: * Object-Oriented Programming Style::
378: * Class Binding::
379: * Method conveniences::
380: * Classes and Scoping::
1.41 anton 381: * Dividing classes::
1.12 anton 382: * Object Interfaces::
383: * Objects Implementation::
384: * Objects Glossary::
385:
1.24 anton 386: The @file{oof.fs} model
1.12 anton 387:
1.67 anton 388: * Properties of the OOF model::
389: * Basic OOF Usage::
390: * The OOF base class::
391: * Class Declaration::
392: * Class Implementation::
1.12 anton 393:
1.24 anton 394: The @file{mini-oof.fs} model
1.23 crook 395:
1.48 anton 396: * Basic Mini-OOF Usage::
397: * Mini-OOF Example::
398: * Mini-OOF Implementation::
1.23 crook 399:
1.78 anton 400: Programming Tools
401:
1.150 anton 402: * Examining:: Data and Code.
403: * Forgetting words:: Usually before reloading.
1.78 anton 404: * Debugging:: Simple and quick.
405: * Assertions:: Making your programs self-checking.
406: * Singlestep Debugger:: Executing your program word by word.
407:
1.155 anton 408: C Interface
409:
410: * Calling C Functions::
411: * Declaring C Functions::
1.180 anton 412: * Calling C function pointers::
1.155 anton 413: * Callbacks::
1.178 anton 414: * C interface internals::
1.155 anton 415: * Low-Level C Interface Words::
416:
1.78 anton 417: Assembler and Code Words
418:
419: * Code and ;code::
420: * Common Assembler:: Assembler Syntax
421: * Common Disassembler::
422: * 386 Assembler:: Deviations and special cases
423: * Alpha Assembler:: Deviations and special cases
424: * MIPS assembler:: Deviations and special cases
1.167 anton 425: * PowerPC assembler:: Deviations and special cases
1.78 anton 426: * Other assemblers:: How to write them
427:
1.12 anton 428: Tools
429:
430: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 431: * Stack depth changes:: Where does this stack item come from?
1.12 anton 432:
433: ANS conformance
434:
435: * The Core Words::
436: * The optional Block word set::
437: * The optional Double Number word set::
438: * The optional Exception word set::
439: * The optional Facility word set::
440: * The optional File-Access word set::
441: * The optional Floating-Point word set::
442: * The optional Locals word set::
443: * The optional Memory-Allocation word set::
444: * The optional Programming-Tools word set::
445: * The optional Search-Order word set::
446:
447: The Core Words
448:
449: * core-idef:: Implementation Defined Options
450: * core-ambcond:: Ambiguous Conditions
451: * core-other:: Other System Documentation
452:
453: The optional Block word set
454:
455: * block-idef:: Implementation Defined Options
456: * block-ambcond:: Ambiguous Conditions
457: * block-other:: Other System Documentation
458:
459: The optional Double Number word set
460:
461: * double-ambcond:: Ambiguous Conditions
462:
463: The optional Exception word set
464:
465: * exception-idef:: Implementation Defined Options
466:
467: The optional Facility word set
468:
469: * facility-idef:: Implementation Defined Options
470: * facility-ambcond:: Ambiguous Conditions
471:
472: The optional File-Access word set
473:
474: * file-idef:: Implementation Defined Options
475: * file-ambcond:: Ambiguous Conditions
476:
477: The optional Floating-Point word set
478:
479: * floating-idef:: Implementation Defined Options
480: * floating-ambcond:: Ambiguous Conditions
481:
482: The optional Locals word set
483:
484: * locals-idef:: Implementation Defined Options
485: * locals-ambcond:: Ambiguous Conditions
486:
487: The optional Memory-Allocation word set
488:
489: * memory-idef:: Implementation Defined Options
490:
491: The optional Programming-Tools word set
492:
493: * programming-idef:: Implementation Defined Options
494: * programming-ambcond:: Ambiguous Conditions
495:
496: The optional Search-Order word set
497:
498: * search-idef:: Implementation Defined Options
499: * search-ambcond:: Ambiguous Conditions
500:
1.109 anton 501: Emacs and Gforth
502:
503: * Installing gforth.el:: Making Emacs aware of Forth.
504: * Emacs Tags:: Viewing the source of a word in Emacs.
505: * Hilighting:: Making Forth code look prettier.
506: * Auto-Indentation:: Customizing auto-indentation.
507: * Blocks Files:: Reading and writing blocks files.
508:
1.12 anton 509: Image Files
510:
1.24 anton 511: * Image Licensing Issues:: Distribution terms for images.
512: * Image File Background:: Why have image files?
1.67 anton 513: * Non-Relocatable Image Files:: don't always work.
1.24 anton 514: * Data-Relocatable Image Files:: are better.
1.67 anton 515: * Fully Relocatable Image Files:: better yet.
1.24 anton 516: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 517: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 518: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 519:
520: Fully Relocatable Image Files
521:
1.27 crook 522: * gforthmi:: The normal way
1.12 anton 523: * cross.fs:: The hard way
524:
525: Engine
526:
527: * Portability::
528: * Threading::
529: * Primitives::
530: * Performance::
531:
532: Threading
533:
534: * Scheduling::
535: * Direct or Indirect Threaded?::
1.109 anton 536: * Dynamic Superinstructions::
1.12 anton 537: * DOES>::
538:
539: Primitives
540:
541: * Automatic Generation::
542: * TOS Optimization::
543: * Produced code::
1.13 pazsan 544:
545: Cross Compiler
546:
1.67 anton 547: * Using the Cross Compiler::
548: * How the Cross Compiler Works::
1.13 pazsan 549:
1.113 anton 550: Licenses
551:
552: * GNU Free Documentation License:: License for copying this manual.
1.192 ! anton 553: * Copying:: GPL (for copying this software).
1.113 anton 554:
1.24 anton 555: @end detailmenu
1.1 anton 556: @end menu
557:
1.113 anton 558: @c ----------------------------------------------------------
1.1 anton 559: @iftex
560: @unnumbered Preface
561: @cindex Preface
1.21 crook 562: This manual documents Gforth. Some introductory material is provided for
563: readers who are unfamiliar with Forth or who are migrating to Gforth
564: from other Forth compilers. However, this manual is primarily a
565: reference manual.
1.1 anton 566: @end iftex
567:
1.28 crook 568: @comment TODO much more blurb here.
1.26 crook 569:
570: @c ******************************************************************
1.113 anton 571: @node Goals, Gforth Environment, Top, Top
1.26 crook 572: @comment node-name, next, previous, up
573: @chapter Goals of Gforth
574: @cindex goals of the Gforth project
575: The goal of the Gforth Project is to develop a standard model for
576: ANS Forth. This can be split into several subgoals:
577:
578: @itemize @bullet
579: @item
580: Gforth should conform to the ANS Forth Standard.
581: @item
582: It should be a model, i.e. it should define all the
583: implementation-dependent things.
584: @item
585: It should become standard, i.e. widely accepted and used. This goal
586: is the most difficult one.
587: @end itemize
588:
589: To achieve these goals Gforth should be
590: @itemize @bullet
591: @item
592: Similar to previous models (fig-Forth, F83)
593: @item
594: Powerful. It should provide for all the things that are considered
595: necessary today and even some that are not yet considered necessary.
596: @item
597: Efficient. It should not get the reputation of being exceptionally
598: slow.
599: @item
600: Free.
601: @item
602: Available on many machines/easy to port.
603: @end itemize
604:
605: Have we achieved these goals? Gforth conforms to the ANS Forth
606: standard. It may be considered a model, but we have not yet documented
607: which parts of the model are stable and which parts we are likely to
608: change. It certainly has not yet become a de facto standard, but it
609: appears to be quite popular. It has some similarities to and some
610: differences from previous models. It has some powerful features, but not
611: yet everything that we envisioned. We certainly have achieved our
1.65 anton 612: execution speed goals (@pxref{Performance})@footnote{However, in 1998
613: the bar was raised when the major commercial Forth vendors switched to
614: native code compilers.}. It is free and available on many machines.
1.29 crook 615:
1.26 crook 616: @c ******************************************************************
1.48 anton 617: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 618: @chapter Gforth Environment
619: @cindex Gforth environment
1.21 crook 620:
1.45 crook 621: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 622: material in this chapter.
1.21 crook 623:
624: @menu
1.29 crook 625: * Invoking Gforth:: Getting in
626: * Leaving Gforth:: Getting out
627: * Command-line editing::
1.48 anton 628: * Environment variables:: that affect how Gforth starts up
1.29 crook 629: * Gforth Files:: What gets installed and where
1.112 anton 630: * Gforth in pipes::
1.48 anton 631: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 632: @end menu
633:
1.49 anton 634: For related information about the creation of images see @ref{Image Files}.
1.29 crook 635:
1.21 crook 636: @comment ----------------------------------------------
1.48 anton 637: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 638: @section Invoking Gforth
639: @cindex invoking Gforth
640: @cindex running Gforth
641: @cindex command-line options
642: @cindex options on the command line
643: @cindex flags on the command line
1.21 crook 644:
1.30 anton 645: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 646: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 647: will usually just say @code{gforth} -- this automatically loads the
648: default image file @file{gforth.fi}. In many other cases the default
649: Gforth image will be invoked like this:
1.21 crook 650: @example
1.30 anton 651: gforth [file | -e forth-code] ...
1.21 crook 652: @end example
1.29 crook 653: @noindent
654: This interprets the contents of the files and the Forth code in the order they
655: are given.
1.21 crook 656:
1.109 anton 657: In addition to the @command{gforth} engine, there is also an engine
658: called @command{gforth-fast}, which is faster, but gives less
659: informative error messages (@pxref{Error messages}) and may catch some
1.166 anton 660: errors (in particular, stack underflows and integer division errors)
661: later or not at all. You should use it for debugged,
1.109 anton 662: performance-critical programs.
663:
664: Moreover, there is an engine called @command{gforth-itc}, which is
665: useful in some backwards-compatibility situations (@pxref{Direct or
666: Indirect Threaded?}).
1.30 anton 667:
1.29 crook 668: In general, the command line looks like this:
1.21 crook 669:
670: @example
1.30 anton 671: gforth[-fast] [engine options] [image options]
1.21 crook 672: @end example
673:
1.30 anton 674: The engine options must come before the rest of the command
1.29 crook 675: line. They are:
1.26 crook 676:
1.29 crook 677: @table @code
678: @cindex -i, command-line option
679: @cindex --image-file, command-line option
680: @item --image-file @i{file}
681: @itemx -i @i{file}
682: Loads the Forth image @i{file} instead of the default
683: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 684:
1.39 anton 685: @cindex --appl-image, command-line option
686: @item --appl-image @i{file}
687: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 688: to the image (instead of processing them as engine options). This is
689: useful for building executable application images on Unix, built with
1.39 anton 690: @code{gforthmi --application ...}.
691:
1.29 crook 692: @cindex --path, command-line option
693: @cindex -p, command-line option
694: @item --path @i{path}
695: @itemx -p @i{path}
696: Uses @i{path} for searching the image file and Forth source code files
697: instead of the default in the environment variable @code{GFORTHPATH} or
698: the path specified at installation time (e.g.,
699: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
700: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 701:
1.29 crook 702: @cindex --dictionary-size, command-line option
703: @cindex -m, command-line option
704: @cindex @i{size} parameters for command-line options
705: @cindex size of the dictionary and the stacks
706: @item --dictionary-size @i{size}
707: @itemx -m @i{size}
708: Allocate @i{size} space for the Forth dictionary space instead of
709: using the default specified in the image (typically 256K). The
710: @i{size} specification for this and subsequent options consists of
711: an integer and a unit (e.g.,
712: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
713: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
714: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
715: @code{e} is used.
1.21 crook 716:
1.29 crook 717: @cindex --data-stack-size, command-line option
718: @cindex -d, command-line option
719: @item --data-stack-size @i{size}
720: @itemx -d @i{size}
721: Allocate @i{size} space for the data stack instead of using the
722: default specified in the image (typically 16K).
1.21 crook 723:
1.29 crook 724: @cindex --return-stack-size, command-line option
725: @cindex -r, command-line option
726: @item --return-stack-size @i{size}
727: @itemx -r @i{size}
728: Allocate @i{size} space for the return stack instead of using the
729: default specified in the image (typically 15K).
1.21 crook 730:
1.29 crook 731: @cindex --fp-stack-size, command-line option
732: @cindex -f, command-line option
733: @item --fp-stack-size @i{size}
734: @itemx -f @i{size}
735: Allocate @i{size} space for the floating point stack instead of
736: using the default specified in the image (typically 15.5K). In this case
737: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 738:
1.48 anton 739: @cindex --locals-stack-size, command-line option
740: @cindex -l, command-line option
741: @item --locals-stack-size @i{size}
742: @itemx -l @i{size}
743: Allocate @i{size} space for the locals stack instead of using the
744: default specified in the image (typically 14.5K).
745:
1.176 anton 746: @cindex --vm-commit, command-line option
747: @cindex overcommit memory for dictionary and stacks
748: @cindex memory overcommit for dictionary and stacks
749: @item --vm-commit
750: Normally, Gforth tries to start up even if there is not enough virtual
751: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
752: on OSs that support it); so you can ask for a really big dictionary
753: and/or stacks, and as long as you don't use more virtual memory than
754: is available, everything will be fine (but if you use more, processes
755: get killed). With this option you just use the default allocation
756: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
757: means that you cannot and should not ask for as big dictionary and
758: stacks, but once Gforth successfully starts up, out-of-memory won't
759: kill it.
760:
1.48 anton 761: @cindex -h, command-line option
762: @cindex --help, command-line option
763: @item --help
764: @itemx -h
765: Print a message about the command-line options
766:
767: @cindex -v, command-line option
768: @cindex --version, command-line option
769: @item --version
770: @itemx -v
771: Print version and exit
772:
773: @cindex --debug, command-line option
774: @item --debug
775: Print some information useful for debugging on startup.
776:
777: @cindex --offset-image, command-line option
778: @item --offset-image
779: Start the dictionary at a slightly different position than would be used
780: otherwise (useful for creating data-relocatable images,
781: @pxref{Data-Relocatable Image Files}).
782:
783: @cindex --no-offset-im, command-line option
784: @item --no-offset-im
785: Start the dictionary at the normal position.
786:
787: @cindex --clear-dictionary, command-line option
788: @item --clear-dictionary
789: Initialize all bytes in the dictionary to 0 before loading the image
790: (@pxref{Data-Relocatable Image Files}).
791:
792: @cindex --die-on-signal, command-line-option
793: @item --die-on-signal
794: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
795: or the segmentation violation SIGSEGV) by translating it into a Forth
796: @code{THROW}. With this option, Gforth exits if it receives such a
797: signal. This option is useful when the engine and/or the image might be
798: severely broken (such that it causes another signal before recovering
799: from the first); this option avoids endless loops in such cases.
1.109 anton 800:
1.119 anton 801: @cindex --no-dynamic, command-line option
802: @cindex --dynamic, command-line option
1.109 anton 803: @item --no-dynamic
804: @item --dynamic
805: Disable or enable dynamic superinstructions with replication
806: (@pxref{Dynamic Superinstructions}).
807:
1.119 anton 808: @cindex --no-super, command-line option
1.109 anton 809: @item --no-super
1.110 anton 810: Disable dynamic superinstructions, use just dynamic replication; this is
811: useful if you want to patch threaded code (@pxref{Dynamic
812: Superinstructions}).
1.119 anton 813:
814: @cindex --ss-number, command-line option
815: @item --ss-number=@var{N}
816: Use only the first @var{N} static superinstructions compiled into the
817: engine (default: use them all; note that only @code{gforth-fast} has
818: any). This option is useful for measuring the performance impact of
819: static superinstructions.
820:
821: @cindex --ss-min-..., command-line options
822: @item --ss-min-codesize
823: @item --ss-min-ls
824: @item --ss-min-lsu
825: @item --ss-min-nexts
826: Use specified metric for determining the cost of a primitive or static
827: superinstruction for static superinstruction selection. @code{Codesize}
828: is the native code size of the primive or static superinstruction,
829: @code{ls} is the number of loads and stores, @code{lsu} is the number of
830: loads, stores, and updates, and @code{nexts} is the number of dispatches
831: (not taking dynamic superinstructions into account), i.e. every
832: primitive or static superinstruction has cost 1. Default:
833: @code{codesize} if you use dynamic code generation, otherwise
834: @code{nexts}.
835:
836: @cindex --ss-greedy, command-line option
837: @item --ss-greedy
838: This option is useful for measuring the performance impact of static
839: superinstructions. By default, an optimal shortest-path algorithm is
840: used for selecting static superinstructions. With @option{--ss-greedy}
841: this algorithm is modified to assume that anything after the static
842: superinstruction currently under consideration is not combined into
843: static superinstructions. With @option{--ss-min-nexts} this produces
844: the same result as a greedy algorithm that always selects the longest
845: superinstruction available at the moment. E.g., if there are
846: superinstructions AB and BCD, then for the sequence A B C D the optimal
847: algorithm will select A BCD and the greedy algorithm will select AB C D.
848:
849: @cindex --print-metrics, command-line option
850: @item --print-metrics
851: Prints some metrics used during static superinstruction selection:
852: @code{code size} is the actual size of the dynamically generated code.
853: @code{Metric codesize} is the sum of the codesize metrics as seen by
854: static superinstruction selection; there is a difference from @code{code
855: size}, because not all primitives and static superinstructions are
856: compiled into dynamically generated code, and because of markers. The
857: other metrics correspond to the @option{ss-min-...} options. This
858: option is useful for evaluating the effects of the @option{--ss-...}
859: options.
1.109 anton 860:
1.48 anton 861: @end table
862:
863: @cindex loading files at startup
864: @cindex executing code on startup
865: @cindex batch processing with Gforth
866: As explained above, the image-specific command-line arguments for the
867: default image @file{gforth.fi} consist of a sequence of filenames and
868: @code{-e @var{forth-code}} options that are interpreted in the sequence
869: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 870: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
871: option takes only one argument; if you want to evaluate more Forth
872: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 873: after processing the command line (instead of entering interactive mode)
1.121 anton 874: append @code{-e bye} to the command line. You can also process the
875: command-line arguments with a Forth program (@pxref{OS command line
876: arguments}).
1.48 anton 877:
878: @cindex versions, invoking other versions of Gforth
879: If you have several versions of Gforth installed, @code{gforth} will
880: invoke the version that was installed last. @code{gforth-@i{version}}
881: invokes a specific version. If your environment contains the variable
882: @code{GFORTHPATH}, you may want to override it by using the
883: @code{--path} option.
884:
885: Not yet implemented:
886: On startup the system first executes the system initialization file
887: (unless the option @code{--no-init-file} is given; note that the system
888: resulting from using this option may not be ANS Forth conformant). Then
889: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 890: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 891: then in @file{~}, then in the normal path (see above).
892:
893:
894:
895: @comment ----------------------------------------------
896: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
897: @section Leaving Gforth
898: @cindex Gforth - leaving
899: @cindex leaving Gforth
900:
901: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
902: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
903: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 904: data are discarded. For ways of saving the state of the system before
905: leaving Gforth see @ref{Image Files}.
1.48 anton 906:
907: doc-bye
908:
909:
910: @comment ----------------------------------------------
1.65 anton 911: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 912: @section Command-line editing
913: @cindex command-line editing
914:
915: Gforth maintains a history file that records every line that you type to
916: the text interpreter. This file is preserved between sessions, and is
917: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
918: repeatedly you can recall successively older commands from this (or
919: previous) session(s). The full list of command-line editing facilities is:
920:
921: @itemize @bullet
922: @item
923: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
924: commands from the history buffer.
925: @item
926: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
927: from the history buffer.
928: @item
929: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
930: @item
931: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
932: @item
933: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
934: closing up the line.
935: @item
936: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
937: @item
938: @kbd{Ctrl-a} to move the cursor to the start of the line.
939: @item
940: @kbd{Ctrl-e} to move the cursor to the end of the line.
941: @item
942: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
943: line.
944: @item
945: @key{TAB} to step through all possible full-word completions of the word
946: currently being typed.
947: @item
1.65 anton 948: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
949: using @code{bye}).
950: @item
951: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
952: character under the cursor.
1.48 anton 953: @end itemize
954:
955: When editing, displayable characters are inserted to the left of the
956: cursor position; the line is always in ``insert'' (as opposed to
957: ``overstrike'') mode.
958:
959: @cindex history file
960: @cindex @file{.gforth-history}
961: On Unix systems, the history file is @file{~/.gforth-history} by
962: default@footnote{i.e. it is stored in the user's home directory.}. You
963: can find out the name and location of your history file using:
964:
965: @example
966: history-file type \ Unix-class systems
967:
968: history-file type \ Other systems
969: history-dir type
970: @end example
971:
972: If you enter long definitions by hand, you can use a text editor to
973: paste them out of the history file into a Forth source file for reuse at
974: a later time.
975:
976: Gforth never trims the size of the history file, so you should do this
977: periodically, if necessary.
978:
979: @comment this is all defined in history.fs
980: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
981: @comment chosen?
982:
983:
984: @comment ----------------------------------------------
1.65 anton 985: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 986: @section Environment variables
987: @cindex environment variables
988:
989: Gforth uses these environment variables:
990:
991: @itemize @bullet
992: @item
993: @cindex @code{GFORTHHIST} -- environment variable
994: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
995: open/create the history file, @file{.gforth-history}. Default:
996: @code{$HOME}.
997:
998: @item
999: @cindex @code{GFORTHPATH} -- environment variable
1000: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1001: for Forth source-code files.
1002:
1003: @item
1.147 anton 1004: @cindex @code{LANG} -- environment variable
1005: @code{LANG} -- see @code{LC_CTYPE}
1006:
1007: @item
1008: @cindex @code{LC_ALL} -- environment variable
1009: @code{LC_ALL} -- see @code{LC_CTYPE}
1010:
1011: @item
1012: @cindex @code{LC_CTYPE} -- environment variable
1013: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1014: startup, Gforth uses the UTF-8 encoding for strings internally and
1015: expects its input and produces its output in UTF-8 encoding, otherwise
1016: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1017: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1018: that is unset, in @code{LANG}.
1019:
1020: @item
1.129 anton 1021: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1022:
1023: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1024: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1025: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1026: and the command are directly concatenated, so if a space between them is
1027: necessary, append it to the prefix.
1028:
1029: @item
1.48 anton 1030: @cindex @code{GFORTH} -- environment variable
1.49 anton 1031: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1032:
1033: @item
1034: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1035: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1036:
1037: @item
1038: @cindex @code{TMP}, @code{TEMP} - environment variable
1039: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1040: location for the history file.
1041: @end itemize
1042:
1043: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1044: @comment mentioning these.
1045:
1046: All the Gforth environment variables default to sensible values if they
1047: are not set.
1048:
1049:
1050: @comment ----------------------------------------------
1.112 anton 1051: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1052: @section Gforth files
1053: @cindex Gforth files
1054:
1055: When you install Gforth on a Unix system, it installs files in these
1056: locations by default:
1057:
1058: @itemize @bullet
1059: @item
1060: @file{/usr/local/bin/gforth}
1061: @item
1062: @file{/usr/local/bin/gforthmi}
1063: @item
1064: @file{/usr/local/man/man1/gforth.1} - man page.
1065: @item
1066: @file{/usr/local/info} - the Info version of this manual.
1067: @item
1068: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1069: @item
1070: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1071: @item
1072: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1073: @item
1074: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1075: @end itemize
1076:
1077: You can select different places for installation by using
1078: @code{configure} options (listed with @code{configure --help}).
1079:
1080: @comment ----------------------------------------------
1.112 anton 1081: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1082: @section Gforth in pipes
1083: @cindex pipes, Gforth as part of
1084:
1085: Gforth can be used in pipes created elsewhere (described here). It can
1086: also create pipes on its own (@pxref{Pipes}).
1087:
1088: @cindex input from pipes
1089: If you pipe into Gforth, your program should read with @code{read-file}
1090: or @code{read-line} from @code{stdin} (@pxref{General files}).
1091: @code{Key} does not recognize the end of input. Words like
1092: @code{accept} echo the input and are therefore usually not useful for
1093: reading from a pipe. You have to invoke the Forth program with an OS
1094: command-line option, as you have no chance to use the Forth command line
1095: (the text interpreter would try to interpret the pipe input).
1096:
1097: @cindex output in pipes
1098: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1099:
1100: @cindex silent exiting from Gforth
1101: When you write to a pipe that has been closed at the other end, Gforth
1102: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1103: into the exception @code{broken-pipe-error}. If your application does
1104: not catch that exception, the system catches it and exits, usually
1105: silently (unless you were working on the Forth command line; then it
1106: prints an error message and exits). This is usually the desired
1107: behaviour.
1108:
1109: If you do not like this behaviour, you have to catch the exception
1110: yourself, and react to it.
1111:
1112: Here's an example of an invocation of Gforth that is usable in a pipe:
1113:
1114: @example
1115: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1116: type repeat ; foo bye"
1117: @end example
1118:
1119: This example just copies the input verbatim to the output. A very
1120: simple pipe containing this example looks like this:
1121:
1122: @example
1123: cat startup.fs |
1124: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1125: type repeat ; foo bye"|
1126: head
1127: @end example
1128:
1129: @cindex stderr and pipes
1130: Pipes involving Gforth's @code{stderr} output do not work.
1131:
1132: @comment ----------------------------------------------
1133: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1134: @section Startup speed
1135: @cindex Startup speed
1136: @cindex speed, startup
1137:
1138: If Gforth is used for CGI scripts or in shell scripts, its startup
1139: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1140: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1141: system time.
1142:
1143: If startup speed is a problem, you may consider the following ways to
1144: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1145: (for example, by using Fast-CGI).
1.48 anton 1146:
1.112 anton 1147: An easy step that influences Gforth startup speed is the use of the
1148: @option{--no-dynamic} option; this decreases image loading speed, but
1149: increases compile-time and run-time.
1150:
1151: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1152: building it with @code{XLDFLAGS=-static}. This requires more memory for
1153: the code and will therefore slow down the first invocation, but
1154: subsequent invocations avoid the dynamic linking overhead. Another
1155: disadvantage is that Gforth won't profit from library upgrades. As a
1156: result, @code{gforth-static -e bye} takes about 17.1ms user and
1157: 8.2ms system time.
1158:
1159: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1160: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1161: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1162: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1163: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1164: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1165: address for the dictionary, for whatever reason; so you better provide a
1166: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1167: bye} takes about 15.3ms user and 7.5ms system time.
1168:
1169: The final step is to disable dictionary hashing in Gforth. Gforth
1170: builds the hash table on startup, which takes much of the startup
1171: overhead. You can do this by commenting out the @code{include hash.fs}
1172: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1173: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1174: The disadvantages are that functionality like @code{table} and
1175: @code{ekey} is missing and that text interpretation (e.g., compiling)
1176: now takes much longer. So, you should only use this method if there is
1177: no significant text interpretation to perform (the script should be
1.62 crook 1178: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1179: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1180:
1181: @c ******************************************************************
1182: @node Tutorial, Introduction, Gforth Environment, Top
1183: @chapter Forth Tutorial
1184: @cindex Tutorial
1185: @cindex Forth Tutorial
1186:
1.67 anton 1187: @c Topics from nac's Introduction that could be mentioned:
1188: @c press <ret> after each line
1189: @c Prompt
1190: @c numbers vs. words in dictionary on text interpretation
1191: @c what happens on redefinition
1192: @c parsing words (in particular, defining words)
1193:
1.83 anton 1194: The difference of this chapter from the Introduction
1195: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1196: be used while sitting in front of a computer, and covers much more
1197: material, but does not explain how the Forth system works.
1198:
1.62 crook 1199: This tutorial can be used with any ANS-compliant Forth; any
1200: Gforth-specific features are marked as such and you can skip them if you
1201: work with another Forth. This tutorial does not explain all features of
1202: Forth, just enough to get you started and give you some ideas about the
1203: facilities available in Forth. Read the rest of the manual and the
1204: standard when you are through this.
1.48 anton 1205:
1206: The intended way to use this tutorial is that you work through it while
1207: sitting in front of the console, take a look at the examples and predict
1208: what they will do, then try them out; if the outcome is not as expected,
1209: find out why (e.g., by trying out variations of the example), so you
1210: understand what's going on. There are also some assignments that you
1211: should solve.
1212:
1213: This tutorial assumes that you have programmed before and know what,
1214: e.g., a loop is.
1215:
1216: @c !! explain compat library
1217:
1218: @menu
1219: * Starting Gforth Tutorial::
1220: * Syntax Tutorial::
1221: * Crash Course Tutorial::
1222: * Stack Tutorial::
1223: * Arithmetics Tutorial::
1224: * Stack Manipulation Tutorial::
1225: * Using files for Forth code Tutorial::
1226: * Comments Tutorial::
1227: * Colon Definitions Tutorial::
1228: * Decompilation Tutorial::
1229: * Stack-Effect Comments Tutorial::
1230: * Types Tutorial::
1231: * Factoring Tutorial::
1232: * Designing the stack effect Tutorial::
1233: * Local Variables Tutorial::
1234: * Conditional execution Tutorial::
1235: * Flags and Comparisons Tutorial::
1236: * General Loops Tutorial::
1237: * Counted loops Tutorial::
1238: * Recursion Tutorial::
1239: * Leaving definitions or loops Tutorial::
1240: * Return Stack Tutorial::
1241: * Memory Tutorial::
1242: * Characters and Strings Tutorial::
1243: * Alignment Tutorial::
1.190 anton 1244: * Floating Point Tutorial::
1.87 anton 1245: * Files Tutorial::
1.48 anton 1246: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1247: * Execution Tokens Tutorial::
1248: * Exceptions Tutorial::
1249: * Defining Words Tutorial::
1250: * Arrays and Records Tutorial::
1251: * POSTPONE Tutorial::
1252: * Literal Tutorial::
1253: * Advanced macros Tutorial::
1254: * Compilation Tokens Tutorial::
1255: * Wordlists and Search Order Tutorial::
1256: @end menu
1257:
1258: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1259: @section Starting Gforth
1.66 anton 1260: @cindex starting Gforth tutorial
1.48 anton 1261: You can start Gforth by typing its name:
1262:
1263: @example
1264: gforth
1265: @end example
1266:
1267: That puts you into interactive mode; you can leave Gforth by typing
1268: @code{bye}. While in Gforth, you can edit the command line and access
1269: the command line history with cursor keys, similar to bash.
1270:
1271:
1272: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1273: @section Syntax
1.66 anton 1274: @cindex syntax tutorial
1.48 anton 1275:
1.171 anton 1276: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1277: space). Words are separated by white space. E.g., each of the
1278: following lines contains exactly one word:
1279:
1280: @example
1281: word
1282: !@@#$%^&*()
1283: 1234567890
1284: 5!a
1285: @end example
1286:
1287: A frequent beginner's error is to leave away necessary white space,
1288: resulting in an error like @samp{Undefined word}; so if you see such an
1289: error, check if you have put spaces wherever necessary.
1290:
1291: @example
1292: ." hello, world" \ correct
1293: ."hello, world" \ gives an "Undefined word" error
1294: @end example
1295:
1.65 anton 1296: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1297: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1298: your system is case-sensitive, you may have to type all the examples
1299: given here in upper case.
1300:
1301:
1302: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1303: @section Crash Course
1304:
1305: Type
1306:
1307: @example
1308: 0 0 !
1309: here execute
1310: ' catch >body 20 erase abort
1311: ' (quit) >body 20 erase
1312: @end example
1313:
1314: The last two examples are guaranteed to destroy parts of Gforth (and
1315: most other systems), so you better leave Gforth afterwards (if it has
1316: not finished by itself). On some systems you may have to kill gforth
1317: from outside (e.g., in Unix with @code{kill}).
1318:
1319: Now that you know how to produce crashes (and that there's not much to
1320: them), let's learn how to produce meaningful programs.
1321:
1322:
1323: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1324: @section Stack
1.66 anton 1325: @cindex stack tutorial
1.48 anton 1326:
1327: The most obvious feature of Forth is the stack. When you type in a
1328: number, it is pushed on the stack. You can display the content of the
1329: stack with @code{.s}.
1330:
1331: @example
1332: 1 2 .s
1333: 3 .s
1334: @end example
1335:
1336: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1337: appear in @code{.s} output as they appeared in the input.
1338:
1339: You can print the top of stack element with @code{.}.
1340:
1341: @example
1342: 1 2 3 . . .
1343: @end example
1344:
1345: In general, words consume their stack arguments (@code{.s} is an
1346: exception).
1347:
1.141 anton 1348: @quotation Assignment
1.48 anton 1349: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1350: @end quotation
1.48 anton 1351:
1352:
1353: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1354: @section Arithmetics
1.66 anton 1355: @cindex arithmetics tutorial
1.48 anton 1356:
1357: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1358: operate on the top two stack items:
1359:
1360: @example
1.67 anton 1361: 2 2 .s
1362: + .s
1363: .
1.48 anton 1364: 2 1 - .
1365: 7 3 mod .
1366: @end example
1367:
1368: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1369: as in the corresponding infix expression (this is generally the case in
1370: Forth).
1371:
1372: Parentheses are superfluous (and not available), because the order of
1373: the words unambiguously determines the order of evaluation and the
1374: operands:
1375:
1376: @example
1377: 3 4 + 5 * .
1378: 3 4 5 * + .
1379: @end example
1380:
1.141 anton 1381: @quotation Assignment
1.48 anton 1382: What are the infix expressions corresponding to the Forth code above?
1383: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1384: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1385: @end quotation
1.48 anton 1386:
1387: To change the sign, use @code{negate}:
1388:
1389: @example
1390: 2 negate .
1391: @end example
1392:
1.141 anton 1393: @quotation Assignment
1.48 anton 1394: Convert -(-3)*4-5 to Forth.
1.141 anton 1395: @end quotation
1.48 anton 1396:
1397: @code{/mod} performs both @code{/} and @code{mod}.
1398:
1399: @example
1400: 7 3 /mod . .
1401: @end example
1402:
1.66 anton 1403: Reference: @ref{Arithmetic}.
1404:
1405:
1.48 anton 1406: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1407: @section Stack Manipulation
1.66 anton 1408: @cindex stack manipulation tutorial
1.48 anton 1409:
1410: Stack manipulation words rearrange the data on the stack.
1411:
1412: @example
1413: 1 .s drop .s
1414: 1 .s dup .s drop drop .s
1415: 1 2 .s over .s drop drop drop
1416: 1 2 .s swap .s drop drop
1417: 1 2 3 .s rot .s drop drop drop
1418: @end example
1419:
1420: These are the most important stack manipulation words. There are also
1421: variants that manipulate twice as many stack items:
1422:
1423: @example
1424: 1 2 3 4 .s 2swap .s 2drop 2drop
1425: @end example
1426:
1427: Two more stack manipulation words are:
1428:
1429: @example
1430: 1 2 .s nip .s drop
1431: 1 2 .s tuck .s 2drop drop
1432: @end example
1433:
1.141 anton 1434: @quotation Assignment
1.48 anton 1435: Replace @code{nip} and @code{tuck} with combinations of other stack
1436: manipulation words.
1437:
1438: @example
1439: Given: How do you get:
1440: 1 2 3 3 2 1
1441: 1 2 3 1 2 3 2
1442: 1 2 3 1 2 3 3
1443: 1 2 3 1 3 3
1444: 1 2 3 2 1 3
1445: 1 2 3 4 4 3 2 1
1446: 1 2 3 1 2 3 1 2 3
1447: 1 2 3 4 1 2 3 4 1 2
1448: 1 2 3
1449: 1 2 3 1 2 3 4
1450: 1 2 3 1 3
1451: @end example
1.141 anton 1452: @end quotation
1.48 anton 1453:
1454: @example
1455: 5 dup * .
1456: @end example
1457:
1.141 anton 1458: @quotation Assignment
1.48 anton 1459: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1460: Write a piece of Forth code that expects two numbers on the stack
1461: (@var{a} and @var{b}, with @var{b} on top) and computes
1462: @code{(a-b)(a+1)}.
1.141 anton 1463: @end quotation
1.48 anton 1464:
1.66 anton 1465: Reference: @ref{Stack Manipulation}.
1466:
1467:
1.48 anton 1468: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1469: @section Using files for Forth code
1.66 anton 1470: @cindex loading Forth code, tutorial
1471: @cindex files containing Forth code, tutorial
1.48 anton 1472:
1473: While working at the Forth command line is convenient for one-line
1474: examples and short one-off code, you probably want to store your source
1475: code in files for convenient editing and persistence. You can use your
1476: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1477: Gforth}) to create @var{file.fs} and use
1.48 anton 1478:
1479: @example
1.102 anton 1480: s" @var{file.fs}" included
1.48 anton 1481: @end example
1482:
1483: to load it into your Forth system. The file name extension I use for
1484: Forth files is @samp{.fs}.
1485:
1486: You can easily start Gforth with some files loaded like this:
1487:
1488: @example
1.102 anton 1489: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1490: @end example
1491:
1492: If an error occurs during loading these files, Gforth terminates,
1493: whereas an error during @code{INCLUDED} within Gforth usually gives you
1494: a Gforth command line. Starting the Forth system every time gives you a
1495: clean start every time, without interference from the results of earlier
1496: tries.
1497:
1498: I often put all the tests in a file, then load the code and run the
1499: tests with
1500:
1501: @example
1.102 anton 1502: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1503: @end example
1504:
1505: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1506: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1507: restart this command without ado.
1508:
1509: The advantage of this approach is that the tests can be repeated easily
1510: every time the program ist changed, making it easy to catch bugs
1511: introduced by the change.
1512:
1.66 anton 1513: Reference: @ref{Forth source files}.
1514:
1.48 anton 1515:
1516: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1517: @section Comments
1.66 anton 1518: @cindex comments tutorial
1.48 anton 1519:
1520: @example
1521: \ That's a comment; it ends at the end of the line
1522: ( Another comment; it ends here: ) .s
1523: @end example
1524:
1525: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1526: separated with white space from the following text.
1527:
1528: @example
1529: \This gives an "Undefined word" error
1530: @end example
1531:
1532: The first @code{)} ends a comment started with @code{(}, so you cannot
1533: nest @code{(}-comments; and you cannot comment out text containing a
1534: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1535: avoid @code{)} in word names.}.
1536:
1537: I use @code{\}-comments for descriptive text and for commenting out code
1538: of one or more line; I use @code{(}-comments for describing the stack
1539: effect, the stack contents, or for commenting out sub-line pieces of
1540: code.
1541:
1542: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1543: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1544: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1545: with @kbd{M-q}.
1546:
1.66 anton 1547: Reference: @ref{Comments}.
1548:
1.48 anton 1549:
1550: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1551: @section Colon Definitions
1.66 anton 1552: @cindex colon definitions, tutorial
1553: @cindex definitions, tutorial
1554: @cindex procedures, tutorial
1555: @cindex functions, tutorial
1.48 anton 1556:
1557: are similar to procedures and functions in other programming languages.
1558:
1559: @example
1560: : squared ( n -- n^2 )
1561: dup * ;
1562: 5 squared .
1563: 7 squared .
1564: @end example
1565:
1566: @code{:} starts the colon definition; its name is @code{squared}. The
1567: following comment describes its stack effect. The words @code{dup *}
1568: are not executed, but compiled into the definition. @code{;} ends the
1569: colon definition.
1570:
1571: The newly-defined word can be used like any other word, including using
1572: it in other definitions:
1573:
1574: @example
1575: : cubed ( n -- n^3 )
1576: dup squared * ;
1577: -5 cubed .
1578: : fourth-power ( n -- n^4 )
1579: squared squared ;
1580: 3 fourth-power .
1581: @end example
1582:
1.141 anton 1583: @quotation Assignment
1.48 anton 1584: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1585: @code{/mod} in terms of other Forth words, and check if they work (hint:
1586: test your tests on the originals first). Don't let the
1587: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1588: @end quotation
1.48 anton 1589:
1.66 anton 1590: Reference: @ref{Colon Definitions}.
1591:
1.48 anton 1592:
1593: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1594: @section Decompilation
1.66 anton 1595: @cindex decompilation tutorial
1596: @cindex see tutorial
1.48 anton 1597:
1598: You can decompile colon definitions with @code{see}:
1599:
1600: @example
1601: see squared
1602: see cubed
1603: @end example
1604:
1605: In Gforth @code{see} shows you a reconstruction of the source code from
1606: the executable code. Informations that were present in the source, but
1607: not in the executable code, are lost (e.g., comments).
1608:
1.65 anton 1609: You can also decompile the predefined words:
1610:
1611: @example
1612: see .
1613: see +
1614: @end example
1615:
1616:
1.48 anton 1617: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1618: @section Stack-Effect Comments
1.66 anton 1619: @cindex stack-effect comments, tutorial
1620: @cindex --, tutorial
1.48 anton 1621: By convention the comment after the name of a definition describes the
1.171 anton 1622: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1623: the stack before the execution of the definition, i.e., the parameters
1624: that are passed into the colon definition; the part behind the @samp{--}
1625: is the state of the stack after the execution of the definition, i.e.,
1626: the results of the definition. The stack comment only shows the top
1627: stack items that the definition accesses and/or changes.
1628:
1629: You should put a correct stack effect on every definition, even if it is
1630: just @code{( -- )}. You should also add some descriptive comment to
1631: more complicated words (I usually do this in the lines following
1632: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1633: you have to work through every definition before you can understand
1.48 anton 1634: any).
1635:
1.141 anton 1636: @quotation Assignment
1.48 anton 1637: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1638: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1639: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1640: are done, you can compare your stack effects to those in this manual
1.48 anton 1641: (@pxref{Word Index}).
1.141 anton 1642: @end quotation
1.48 anton 1643:
1644: Sometimes programmers put comments at various places in colon
1645: definitions that describe the contents of the stack at that place (stack
1646: comments); i.e., they are like the first part of a stack-effect
1647: comment. E.g.,
1648:
1649: @example
1650: : cubed ( n -- n^3 )
1651: dup squared ( n n^2 ) * ;
1652: @end example
1653:
1654: In this case the stack comment is pretty superfluous, because the word
1655: is simple enough. If you think it would be a good idea to add such a
1656: comment to increase readability, you should also consider factoring the
1657: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1658: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1659: however, if you decide not to refactor it, then having such a comment is
1660: better than not having it.
1661:
1662: The names of the stack items in stack-effect and stack comments in the
1663: standard, in this manual, and in many programs specify the type through
1664: a type prefix, similar to Fortran and Hungarian notation. The most
1665: frequent prefixes are:
1666:
1667: @table @code
1668: @item n
1669: signed integer
1670: @item u
1671: unsigned integer
1672: @item c
1673: character
1674: @item f
1675: Boolean flags, i.e. @code{false} or @code{true}.
1676: @item a-addr,a-
1677: Cell-aligned address
1678: @item c-addr,c-
1679: Char-aligned address (note that a Char may have two bytes in Windows NT)
1680: @item xt
1681: Execution token, same size as Cell
1682: @item w,x
1683: Cell, can contain an integer or an address. It usually takes 32, 64 or
1684: 16 bits (depending on your platform and Forth system). A cell is more
1685: commonly known as machine word, but the term @emph{word} already means
1686: something different in Forth.
1687: @item d
1688: signed double-cell integer
1689: @item ud
1690: unsigned double-cell integer
1691: @item r
1692: Float (on the FP stack)
1693: @end table
1694:
1695: You can find a more complete list in @ref{Notation}.
1696:
1.141 anton 1697: @quotation Assignment
1.48 anton 1698: Write stack-effect comments for all definitions you have written up to
1699: now.
1.141 anton 1700: @end quotation
1.48 anton 1701:
1702:
1703: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1704: @section Types
1.66 anton 1705: @cindex types tutorial
1.48 anton 1706:
1707: In Forth the names of the operations are not overloaded; so similar
1708: operations on different types need different names; e.g., @code{+} adds
1709: integers, and you have to use @code{f+} to add floating-point numbers.
1710: The following prefixes are often used for related operations on
1711: different types:
1712:
1713: @table @code
1714: @item (none)
1715: signed integer
1716: @item u
1717: unsigned integer
1718: @item c
1719: character
1720: @item d
1721: signed double-cell integer
1722: @item ud, du
1723: unsigned double-cell integer
1724: @item 2
1725: two cells (not-necessarily double-cell numbers)
1726: @item m, um
1727: mixed single-cell and double-cell operations
1728: @item f
1729: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1730: and @samp{r} represents FP numbers).
1.48 anton 1731: @end table
1732:
1733: If there are no differences between the signed and the unsigned variant
1734: (e.g., for @code{+}), there is only the prefix-less variant.
1735:
1736: Forth does not perform type checking, neither at compile time, nor at
1737: run time. If you use the wrong oeration, the data are interpreted
1738: incorrectly:
1739:
1740: @example
1741: -1 u.
1742: @end example
1743:
1744: If you have only experience with type-checked languages until now, and
1745: have heard how important type-checking is, don't panic! In my
1746: experience (and that of other Forthers), type errors in Forth code are
1747: usually easy to find (once you get used to it), the increased vigilance
1748: of the programmer tends to catch some harder errors in addition to most
1749: type errors, and you never have to work around the type system, so in
1750: most situations the lack of type-checking seems to be a win (projects to
1751: add type checking to Forth have not caught on).
1752:
1753:
1754: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1755: @section Factoring
1.66 anton 1756: @cindex factoring tutorial
1.48 anton 1757:
1758: If you try to write longer definitions, you will soon find it hard to
1759: keep track of the stack contents. Therefore, good Forth programmers
1760: tend to write only short definitions (e.g., three lines). The art of
1761: finding meaningful short definitions is known as factoring (as in
1762: factoring polynomials).
1763:
1764: Well-factored programs offer additional advantages: smaller, more
1765: general words, are easier to test and debug and can be reused more and
1766: better than larger, specialized words.
1767:
1768: So, if you run into difficulties with stack management, when writing
1769: code, try to define meaningful factors for the word, and define the word
1770: in terms of those. Even if a factor contains only two words, it is
1771: often helpful.
1772:
1.65 anton 1773: Good factoring is not easy, and it takes some practice to get the knack
1774: for it; but even experienced Forth programmers often don't find the
1775: right solution right away, but only when rewriting the program. So, if
1776: you don't come up with a good solution immediately, keep trying, don't
1777: despair.
1.48 anton 1778:
1779: @c example !!
1780:
1781:
1782: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1783: @section Designing the stack effect
1.66 anton 1784: @cindex Stack effect design, tutorial
1785: @cindex design of stack effects, tutorial
1.48 anton 1786:
1787: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1788: function; and since there is only one result, you don't have to deal with
1.48 anton 1789: the order of results, either.
1790:
1.117 anton 1791: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1792: parameter and result order of a definition is important and should be
1793: designed well. The general guideline is to design the stack effect such
1794: that the word is simple to use in most cases, even if that complicates
1795: the implementation of the word. Some concrete rules are:
1796:
1797: @itemize @bullet
1798:
1799: @item
1800: Words consume all of their parameters (e.g., @code{.}).
1801:
1802: @item
1803: If there is a convention on the order of parameters (e.g., from
1804: mathematics or another programming language), stick with it (e.g.,
1805: @code{-}).
1806:
1807: @item
1808: If one parameter usually requires only a short computation (e.g., it is
1809: a constant), pass it on the top of the stack. Conversely, parameters
1810: that usually require a long sequence of code to compute should be passed
1811: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1812: read, because the reader does not need to keep track of the bottom item
1.48 anton 1813: through a long sequence of code (or, alternatively, through stack
1.49 anton 1814: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1815: address on top of the stack because it is usually simpler to compute
1816: than the stored value (often the address is just a variable).
1817:
1818: @item
1819: Similarly, results that are usually consumed quickly should be returned
1820: on the top of stack, whereas a result that is often used in long
1821: computations should be passed as bottom result. E.g., the file words
1822: like @code{open-file} return the error code on the top of stack, because
1823: it is usually consumed quickly by @code{throw}; moreover, the error code
1824: has to be checked before doing anything with the other results.
1825:
1826: @end itemize
1827:
1828: These rules are just general guidelines, don't lose sight of the overall
1829: goal to make the words easy to use. E.g., if the convention rule
1830: conflicts with the computation-length rule, you might decide in favour
1831: of the convention if the word will be used rarely, and in favour of the
1832: computation-length rule if the word will be used frequently (because
1833: with frequent use the cost of breaking the computation-length rule would
1834: be quite high, and frequent use makes it easier to remember an
1835: unconventional order).
1836:
1837: @c example !! structure package
1838:
1.65 anton 1839:
1.48 anton 1840: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1841: @section Local Variables
1.66 anton 1842: @cindex local variables, tutorial
1.48 anton 1843:
1844: You can define local variables (@emph{locals}) in a colon definition:
1845:
1846: @example
1847: : swap @{ a b -- b a @}
1848: b a ;
1849: 1 2 swap .s 2drop
1850: @end example
1851:
1852: (If your Forth system does not support this syntax, include
1.187 anton 1853: @file{compat/anslocal.fs} first).
1.48 anton 1854:
1855: In this example @code{@{ a b -- b a @}} is the locals definition; it
1856: takes two cells from the stack, puts the top of stack in @code{b} and
1857: the next stack element in @code{a}. @code{--} starts a comment ending
1858: with @code{@}}. After the locals definition, using the name of the
1859: local will push its value on the stack. You can leave the comment
1860: part (@code{-- b a}) away:
1861:
1862: @example
1863: : swap ( x1 x2 -- x2 x1 )
1864: @{ a b @} b a ;
1865: @end example
1866:
1867: In Gforth you can have several locals definitions, anywhere in a colon
1868: definition; in contrast, in a standard program you can have only one
1869: locals definition per colon definition, and that locals definition must
1.163 anton 1870: be outside any control structure.
1.48 anton 1871:
1872: With locals you can write slightly longer definitions without running
1873: into stack trouble. However, I recommend trying to write colon
1874: definitions without locals for exercise purposes to help you gain the
1875: essential factoring skills.
1876:
1.141 anton 1877: @quotation Assignment
1.48 anton 1878: Rewrite your definitions until now with locals
1.141 anton 1879: @end quotation
1.48 anton 1880:
1.66 anton 1881: Reference: @ref{Locals}.
1882:
1.48 anton 1883:
1884: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1885: @section Conditional execution
1.66 anton 1886: @cindex conditionals, tutorial
1887: @cindex if, tutorial
1.48 anton 1888:
1889: In Forth you can use control structures only inside colon definitions.
1890: An @code{if}-structure looks like this:
1891:
1892: @example
1893: : abs ( n1 -- +n2 )
1894: dup 0 < if
1895: negate
1896: endif ;
1897: 5 abs .
1898: -5 abs .
1899: @end example
1900:
1901: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1902: the following code is performed, otherwise execution continues after the
1.51 pazsan 1903: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1904: elements and produces a flag:
1.48 anton 1905:
1906: @example
1907: 1 2 < .
1908: 2 1 < .
1909: 1 1 < .
1910: @end example
1911:
1912: Actually the standard name for @code{endif} is @code{then}. This
1913: tutorial presents the examples using @code{endif}, because this is often
1914: less confusing for people familiar with other programming languages
1915: where @code{then} has a different meaning. If your system does not have
1916: @code{endif}, define it with
1917:
1918: @example
1919: : endif postpone then ; immediate
1920: @end example
1921:
1922: You can optionally use an @code{else}-part:
1923:
1924: @example
1925: : min ( n1 n2 -- n )
1926: 2dup < if
1927: drop
1928: else
1929: nip
1930: endif ;
1931: 2 3 min .
1932: 3 2 min .
1933: @end example
1934:
1.141 anton 1935: @quotation Assignment
1.48 anton 1936: Write @code{min} without @code{else}-part (hint: what's the definition
1937: of @code{nip}?).
1.141 anton 1938: @end quotation
1.48 anton 1939:
1.66 anton 1940: Reference: @ref{Selection}.
1941:
1.48 anton 1942:
1943: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1944: @section Flags and Comparisons
1.66 anton 1945: @cindex flags tutorial
1946: @cindex comparison tutorial
1.48 anton 1947:
1948: In a false-flag all bits are clear (0 when interpreted as integer). In
1949: a canonical true-flag all bits are set (-1 as a twos-complement signed
1950: integer); in many contexts (e.g., @code{if}) any non-zero value is
1951: treated as true flag.
1952:
1953: @example
1954: false .
1955: true .
1956: true hex u. decimal
1957: @end example
1958:
1959: Comparison words produce canonical flags:
1960:
1961: @example
1962: 1 1 = .
1963: 1 0= .
1964: 0 1 < .
1965: 0 0 < .
1966: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1967: -1 1 < .
1968: @end example
1969:
1.66 anton 1970: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1971: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1972: these combinations are standard (for details see the standard,
1973: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1974:
1.171 anton 1975: You can use @code{and or xor invert} as operations on canonical flags.
1976: Actually they are bitwise operations:
1.48 anton 1977:
1978: @example
1979: 1 2 and .
1980: 1 2 or .
1981: 1 3 xor .
1982: 1 invert .
1983: @end example
1984:
1985: You can convert a zero/non-zero flag into a canonical flag with
1986: @code{0<>} (and complement it on the way with @code{0=}).
1987:
1988: @example
1989: 1 0= .
1990: 1 0<> .
1991: @end example
1992:
1.65 anton 1993: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1994: operation of the Boolean operations to avoid @code{if}s:
1995:
1996: @example
1997: : foo ( n1 -- n2 )
1998: 0= if
1999: 14
2000: else
2001: 0
2002: endif ;
2003: 0 foo .
2004: 1 foo .
2005:
2006: : foo ( n1 -- n2 )
2007: 0= 14 and ;
2008: 0 foo .
2009: 1 foo .
2010: @end example
2011:
1.141 anton 2012: @quotation Assignment
1.48 anton 2013: Write @code{min} without @code{if}.
1.141 anton 2014: @end quotation
1.48 anton 2015:
1.66 anton 2016: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2017: @ref{Bitwise operations}.
2018:
1.48 anton 2019:
2020: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2021: @section General Loops
1.66 anton 2022: @cindex loops, indefinite, tutorial
1.48 anton 2023:
2024: The endless loop is the most simple one:
2025:
2026: @example
2027: : endless ( -- )
2028: 0 begin
2029: dup . 1+
2030: again ;
2031: endless
2032: @end example
2033:
2034: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2035: does nothing at run-time, @code{again} jumps back to @code{begin}.
2036:
2037: A loop with one exit at any place looks like this:
2038:
2039: @example
2040: : log2 ( +n1 -- n2 )
2041: \ logarithmus dualis of n1>0, rounded down to the next integer
2042: assert( dup 0> )
2043: 2/ 0 begin
2044: over 0> while
2045: 1+ swap 2/ swap
2046: repeat
2047: nip ;
2048: 7 log2 .
2049: 8 log2 .
2050: @end example
2051:
2052: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2053: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2054: continues behind the @code{while}. @code{Repeat} jumps back to
2055: @code{begin}, just like @code{again}.
2056:
2057: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2058: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2059: one bit (arithmetic shift right):
2060:
2061: @example
2062: -5 2 / .
2063: -5 2/ .
2064: @end example
2065:
2066: @code{assert(} is no standard word, but you can get it on systems other
2067: then Gforth by including @file{compat/assert.fs}. You can see what it
2068: does by trying
2069:
2070: @example
2071: 0 log2 .
2072: @end example
2073:
2074: Here's a loop with an exit at the end:
2075:
2076: @example
2077: : log2 ( +n1 -- n2 )
2078: \ logarithmus dualis of n1>0, rounded down to the next integer
2079: assert( dup 0 > )
2080: -1 begin
2081: 1+ swap 2/ swap
2082: over 0 <=
2083: until
2084: nip ;
2085: @end example
2086:
2087: @code{Until} consumes a flag; if it is non-zero, execution continues at
2088: the @code{begin}, otherwise after the @code{until}.
2089:
1.141 anton 2090: @quotation Assignment
1.48 anton 2091: Write a definition for computing the greatest common divisor.
1.141 anton 2092: @end quotation
1.48 anton 2093:
1.66 anton 2094: Reference: @ref{Simple Loops}.
2095:
1.48 anton 2096:
2097: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2098: @section Counted loops
1.66 anton 2099: @cindex loops, counted, tutorial
1.48 anton 2100:
2101: @example
2102: : ^ ( n1 u -- n )
1.171 anton 2103: \ n = the uth power of n1
1.48 anton 2104: 1 swap 0 u+do
2105: over *
2106: loop
2107: nip ;
2108: 3 2 ^ .
2109: 4 3 ^ .
2110: @end example
2111:
2112: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2113: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2114: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2115: times (or not at all, if @code{u3-u4<0}).
2116:
2117: You can see the stack effect design rules at work in the stack effect of
2118: the loop start words: Since the start value of the loop is more
2119: frequently constant than the end value, the start value is passed on
2120: the top-of-stack.
2121:
2122: You can access the counter of a counted loop with @code{i}:
2123:
2124: @example
2125: : fac ( u -- u! )
2126: 1 swap 1+ 1 u+do
2127: i *
2128: loop ;
2129: 5 fac .
2130: 7 fac .
2131: @end example
2132:
2133: There is also @code{+do}, which expects signed numbers (important for
2134: deciding whether to enter the loop).
2135:
1.141 anton 2136: @quotation Assignment
1.48 anton 2137: Write a definition for computing the nth Fibonacci number.
1.141 anton 2138: @end quotation
1.48 anton 2139:
1.65 anton 2140: You can also use increments other than 1:
2141:
2142: @example
2143: : up2 ( n1 n2 -- )
2144: +do
2145: i .
2146: 2 +loop ;
2147: 10 0 up2
2148:
2149: : down2 ( n1 n2 -- )
2150: -do
2151: i .
2152: 2 -loop ;
2153: 0 10 down2
2154: @end example
1.48 anton 2155:
1.66 anton 2156: Reference: @ref{Counted Loops}.
2157:
1.48 anton 2158:
2159: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2160: @section Recursion
1.66 anton 2161: @cindex recursion tutorial
1.48 anton 2162:
2163: Usually the name of a definition is not visible in the definition; but
2164: earlier definitions are usually visible:
2165:
2166: @example
1.166 anton 2167: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2168: : / ( n1 n2 -- n )
2169: dup 0= if
2170: -10 throw \ report division by zero
2171: endif
2172: / \ old version
2173: ;
2174: 1 0 /
2175: @end example
2176:
2177: For recursive definitions you can use @code{recursive} (non-standard) or
2178: @code{recurse}:
2179:
2180: @example
2181: : fac1 ( n -- n! ) recursive
2182: dup 0> if
2183: dup 1- fac1 *
2184: else
2185: drop 1
2186: endif ;
2187: 7 fac1 .
2188:
2189: : fac2 ( n -- n! )
2190: dup 0> if
2191: dup 1- recurse *
2192: else
2193: drop 1
2194: endif ;
2195: 8 fac2 .
2196: @end example
2197:
1.141 anton 2198: @quotation Assignment
1.48 anton 2199: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2200: @end quotation
1.48 anton 2201:
1.66 anton 2202: Reference (including indirect recursion): @xref{Calls and returns}.
2203:
1.48 anton 2204:
2205: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2206: @section Leaving definitions or loops
1.66 anton 2207: @cindex leaving definitions, tutorial
2208: @cindex leaving loops, tutorial
1.48 anton 2209:
2210: @code{EXIT} exits the current definition right away. For every counted
2211: loop that is left in this way, an @code{UNLOOP} has to be performed
2212: before the @code{EXIT}:
2213:
2214: @c !! real examples
2215: @example
2216: : ...
2217: ... u+do
2218: ... if
2219: ... unloop exit
2220: endif
2221: ...
2222: loop
2223: ... ;
2224: @end example
2225:
2226: @code{LEAVE} leaves the innermost counted loop right away:
2227:
2228: @example
2229: : ...
2230: ... u+do
2231: ... if
2232: ... leave
2233: endif
2234: ...
2235: loop
2236: ... ;
2237: @end example
2238:
1.65 anton 2239: @c !! example
1.48 anton 2240:
1.66 anton 2241: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2242:
2243:
1.48 anton 2244: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2245: @section Return Stack
1.66 anton 2246: @cindex return stack tutorial
1.48 anton 2247:
2248: In addition to the data stack Forth also has a second stack, the return
2249: stack; most Forth systems store the return addresses of procedure calls
2250: there (thus its name). Programmers can also use this stack:
2251:
2252: @example
2253: : foo ( n1 n2 -- )
2254: .s
2255: >r .s
1.50 anton 2256: r@@ .
1.48 anton 2257: >r .s
1.50 anton 2258: r@@ .
1.48 anton 2259: r> .
1.50 anton 2260: r@@ .
1.48 anton 2261: r> . ;
2262: 1 2 foo
2263: @end example
2264:
2265: @code{>r} takes an element from the data stack and pushes it onto the
2266: return stack; conversely, @code{r>} moves an elementm from the return to
2267: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2268: on the data stack.
1.48 anton 2269:
2270: Forth programmers usually use the return stack for storing data
2271: temporarily, if using the data stack alone would be too complex, and
2272: factoring and locals are not an option:
2273:
2274: @example
2275: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2276: rot >r rot r> ;
2277: @end example
2278:
2279: The return address of the definition and the loop control parameters of
2280: counted loops usually reside on the return stack, so you have to take
2281: all items, that you have pushed on the return stack in a colon
2282: definition or counted loop, from the return stack before the definition
2283: or loop ends. You cannot access items that you pushed on the return
2284: stack outside some definition or loop within the definition of loop.
2285:
2286: If you miscount the return stack items, this usually ends in a crash:
2287:
2288: @example
2289: : crash ( n -- )
2290: >r ;
2291: 5 crash
2292: @end example
2293:
2294: You cannot mix using locals and using the return stack (according to the
2295: standard; Gforth has no problem). However, they solve the same
2296: problems, so this shouldn't be an issue.
2297:
1.141 anton 2298: @quotation Assignment
1.48 anton 2299: Can you rewrite any of the definitions you wrote until now in a better
2300: way using the return stack?
1.141 anton 2301: @end quotation
1.48 anton 2302:
1.66 anton 2303: Reference: @ref{Return stack}.
2304:
1.48 anton 2305:
2306: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2307: @section Memory
1.66 anton 2308: @cindex memory access/allocation tutorial
1.48 anton 2309:
2310: You can create a global variable @code{v} with
2311:
2312: @example
2313: variable v ( -- addr )
2314: @end example
2315:
2316: @code{v} pushes the address of a cell in memory on the stack. This cell
2317: was reserved by @code{variable}. You can use @code{!} (store) to store
2318: values into this cell and @code{@@} (fetch) to load the value from the
2319: stack into memory:
2320:
2321: @example
2322: v .
2323: 5 v ! .s
1.50 anton 2324: v @@ .
1.48 anton 2325: @end example
2326:
1.65 anton 2327: You can see a raw dump of memory with @code{dump}:
2328:
2329: @example
2330: v 1 cells .s dump
2331: @end example
2332:
2333: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2334: generally, address units (aus)) that @code{n1 cells} occupy. You can
2335: also reserve more memory:
1.48 anton 2336:
2337: @example
2338: create v2 20 cells allot
1.65 anton 2339: v2 20 cells dump
1.48 anton 2340: @end example
2341:
1.65 anton 2342: creates a word @code{v2} and reserves 20 uninitialized cells; the
2343: address pushed by @code{v2} points to the start of these 20 cells. You
2344: can use address arithmetic to access these cells:
1.48 anton 2345:
2346: @example
2347: 3 v2 5 cells + !
1.65 anton 2348: v2 20 cells dump
1.48 anton 2349: @end example
2350:
2351: You can reserve and initialize memory with @code{,}:
2352:
2353: @example
2354: create v3
2355: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2356: v3 @@ .
2357: v3 cell+ @@ .
2358: v3 2 cells + @@ .
1.65 anton 2359: v3 5 cells dump
1.48 anton 2360: @end example
2361:
1.141 anton 2362: @quotation Assignment
1.48 anton 2363: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2364: @code{u} cells, with the first of these cells at @code{addr}, the next
2365: one at @code{addr cell+} etc.
1.141 anton 2366: @end quotation
1.48 anton 2367:
2368: You can also reserve memory without creating a new word:
2369:
2370: @example
1.60 anton 2371: here 10 cells allot .
2372: here .
1.48 anton 2373: @end example
2374:
2375: @code{Here} pushes the start address of the memory area. You should
2376: store it somewhere, or you will have a hard time finding the memory area
2377: again.
2378:
2379: @code{Allot} manages dictionary memory. The dictionary memory contains
2380: the system's data structures for words etc. on Gforth and most other
2381: Forth systems. It is managed like a stack: You can free the memory that
2382: you have just @code{allot}ed with
2383:
2384: @example
2385: -10 cells allot
1.60 anton 2386: here .
1.48 anton 2387: @end example
2388:
2389: Note that you cannot do this if you have created a new word in the
2390: meantime (because then your @code{allot}ed memory is no longer on the
2391: top of the dictionary ``stack'').
2392:
2393: Alternatively, you can use @code{allocate} and @code{free} which allow
2394: freeing memory in any order:
2395:
2396: @example
2397: 10 cells allocate throw .s
2398: 20 cells allocate throw .s
2399: swap
2400: free throw
2401: free throw
2402: @end example
2403:
2404: The @code{throw}s deal with errors (e.g., out of memory).
2405:
1.65 anton 2406: And there is also a
2407: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2408: garbage collector}, which eliminates the need to @code{free} memory
2409: explicitly.
1.48 anton 2410:
1.66 anton 2411: Reference: @ref{Memory}.
2412:
1.48 anton 2413:
2414: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2415: @section Characters and Strings
1.66 anton 2416: @cindex strings tutorial
2417: @cindex characters tutorial
1.48 anton 2418:
2419: On the stack characters take up a cell, like numbers. In memory they
2420: have their own size (one 8-bit byte on most systems), and therefore
2421: require their own words for memory access:
2422:
2423: @example
2424: create v4
2425: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2426: v4 4 chars + c@@ .
1.65 anton 2427: v4 5 chars dump
1.48 anton 2428: @end example
2429:
2430: The preferred representation of strings on the stack is @code{addr
2431: u-count}, where @code{addr} is the address of the first character and
2432: @code{u-count} is the number of characters in the string.
2433:
2434: @example
2435: v4 5 type
2436: @end example
2437:
2438: You get a string constant with
2439:
2440: @example
2441: s" hello, world" .s
2442: type
2443: @end example
2444:
2445: Make sure you have a space between @code{s"} and the string; @code{s"}
2446: is a normal Forth word and must be delimited with white space (try what
2447: happens when you remove the space).
2448:
2449: However, this interpretive use of @code{s"} is quite restricted: the
2450: string exists only until the next call of @code{s"} (some Forth systems
2451: keep more than one of these strings, but usually they still have a
1.62 crook 2452: limited lifetime).
1.48 anton 2453:
2454: @example
2455: s" hello," s" world" .s
2456: type
2457: type
2458: @end example
2459:
1.62 crook 2460: You can also use @code{s"} in a definition, and the resulting
2461: strings then live forever (well, for as long as the definition):
1.48 anton 2462:
2463: @example
2464: : foo s" hello," s" world" ;
2465: foo .s
2466: type
2467: type
2468: @end example
2469:
1.141 anton 2470: @quotation Assignment
1.48 anton 2471: @code{Emit ( c -- )} types @code{c} as character (not a number).
2472: Implement @code{type ( addr u -- )}.
1.141 anton 2473: @end quotation
1.48 anton 2474:
1.66 anton 2475: Reference: @ref{Memory Blocks}.
2476:
2477:
1.190 anton 2478: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2479: @section Alignment
1.66 anton 2480: @cindex alignment tutorial
2481: @cindex memory alignment tutorial
1.48 anton 2482:
2483: On many processors cells have to be aligned in memory, if you want to
2484: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2485: not require alignment, access to aligned cells is faster).
1.48 anton 2486:
2487: @code{Create} aligns @code{here} (i.e., the place where the next
2488: allocation will occur, and that the @code{create}d word points to).
2489: Likewise, the memory produced by @code{allocate} starts at an aligned
2490: address. Adding a number of @code{cells} to an aligned address produces
2491: another aligned address.
2492:
2493: However, address arithmetic involving @code{char+} and @code{chars} can
2494: create an address that is not cell-aligned. @code{Aligned ( addr --
2495: a-addr )} produces the next aligned address:
2496:
2497: @example
1.50 anton 2498: v3 char+ aligned .s @@ .
2499: v3 char+ .s @@ .
1.48 anton 2500: @end example
2501:
2502: Similarly, @code{align} advances @code{here} to the next aligned
2503: address:
2504:
2505: @example
2506: create v5 97 c,
2507: here .
2508: align here .
2509: 1000 ,
2510: @end example
2511:
2512: Note that you should use aligned addresses even if your processor does
2513: not require them, if you want your program to be portable.
2514:
1.66 anton 2515: Reference: @ref{Address arithmetic}.
2516:
1.190 anton 2517: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2518: @section Floating Point
2519: @cindex floating point tutorial
2520: @cindex FP tutorial
2521:
2522: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2523: might expect, but there are a few things worth noting:
2524:
2525: The first point is not specific to Forth, but so important and yet not
2526: universally known that I mention it here: FP numbers are not reals.
2527: Many properties (e.g., arithmetic laws) that reals have and that one
2528: expects of all kinds of numbers do not hold for FP numbers. If you
2529: want to use FP computations, you should learn about their problems and
2530: how to avoid them; a good starting point is @cite{David Goldberg,
2531: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2532: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2533: Computing Surveys 23(1):5@minus{}48, March 1991}.
2534:
2535: In Forth source code literal FP numbers need an exponent, e.g.,
2536: @code{1e0}; this can also be written shorter as @code{1e},
2537: @code{+1.0e+0}, and many variations in between. The reason for this
2538: is that, for historical reasons, Forth interprets a decimal point
2539: alone (e.g., @code{1.}) as indicating a double-cell integer. Another
2540: requirement for literal FP numbers is that the current base is
2541: decimal; with a hex base @code{1e} is interpreted as an integer.
2542:
2543: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2544: ANS Forth system may implement the FP stack on the data stack, but
2545: virtually all systems implement a separate FP stack; and programming
2546: in a way that accommodates all models is so cumbersome that nobody
2547: does it.} One advantage of this model is that cells are not in the
2548: way when accessing FP values, and vice versa. Forth has a set of
2549: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2550: frot} and (non-standard) @code{fnip ftuck fpick}.
2551:
2552: FP arithmetic words are prefixed with @code{F}. There is the usual
2553: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2554: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2555: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2556: computation results are usually inaccurate, so exact comparison is
2557: usually a mistake, and one should use approximate comparison.
2558: Unfortunately, @code{f~}, the standard word for that purpose, is not
2559: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2560: well.
2561:
2562: And of course there are words for accessing FP numbers in memory
2563: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2564: faligned}). There are also variants of these words with an @code{sf}
2565: and @code{df} prefix for accessing IEEE format single-precision and
2566: double-precision numbers in memory; their main purpose is for
2567: accessing external FP data (e.g., that has been read from or will be
2568: written to a file).
2569:
2570: Here is an example of a dot-product word and its use:
2571:
2572: @example
2573: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2574: >r swap 2swap swap 0e r> 0 ?DO
2575: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2576: LOOP
2577: 2drop 2drop ;
1.48 anton 2578:
1.190 anton 2579: create v 1.23e f, 4.56e f, 7.89e f,
2580:
2581: v 1 floats v 1 floats 3 v* f.
2582: @end example
2583:
2584: @quotation Assignment
2585: Write a program to solve a quadratic equation. Then read @cite{Henry
2586: G. Baker,
2587: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2588: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2589: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2590: program. Finally, find a test case where the original and the
2591: improved version produce different results.
2592: @end quotation
2593:
2594: Reference: @ref{Floating Point}; @ref{Floating point stack};
2595: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2596: arithmetic}.
2597:
2598: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84 pazsan 2599: @section Files
2600: @cindex files tutorial
2601:
2602: This section gives a short introduction into how to use files inside
2603: Forth. It's broken up into five easy steps:
2604:
2605: @enumerate 1
2606: @item Opened an ASCII text file for input
2607: @item Opened a file for output
2608: @item Read input file until string matched (or some other condition matched)
2609: @item Wrote some lines from input ( modified or not) to output
2610: @item Closed the files.
2611: @end enumerate
2612:
1.153 anton 2613: Reference: @ref{General files}.
2614:
1.84 pazsan 2615: @subsection Open file for input
2616:
2617: @example
2618: s" foo.in" r/o open-file throw Value fd-in
2619: @end example
2620:
2621: @subsection Create file for output
2622:
2623: @example
2624: s" foo.out" w/o create-file throw Value fd-out
2625: @end example
2626:
2627: The available file modes are r/o for read-only access, r/w for
2628: read-write access, and w/o for write-only access. You could open both
2629: files with r/w, too, if you like. All file words return error codes; for
2630: most applications, it's best to pass there error codes with @code{throw}
2631: to the outer error handler.
2632:
2633: If you want words for opening and assigning, define them as follows:
2634:
2635: @example
2636: 0 Value fd-in
2637: 0 Value fd-out
2638: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2639: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2640: @end example
2641:
2642: Usage example:
2643:
2644: @example
2645: s" foo.in" open-input
2646: s" foo.out" open-output
2647: @end example
2648:
2649: @subsection Scan file for a particular line
2650:
2651: @example
2652: 256 Constant max-line
2653: Create line-buffer max-line 2 + allot
2654:
2655: : scan-file ( addr u -- )
2656: begin
2657: line-buffer max-line fd-in read-line throw
2658: while
2659: >r 2dup line-buffer r> compare 0=
2660: until
2661: else
2662: drop
2663: then
2664: 2drop ;
2665: @end example
2666:
2667: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2668: the buffer at addr, and returns the number of bytes read, a flag that is
2669: false when the end of file is reached, and an error code.
1.84 pazsan 2670:
2671: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2672: returns zero if both strings are equal. It returns a positive number if
2673: the first string is lexically greater, a negative if the second string
2674: is lexically greater.
2675:
2676: We haven't seen this loop here; it has two exits. Since the @code{while}
2677: exits with the number of bytes read on the stack, we have to clean up
2678: that separately; that's after the @code{else}.
2679:
2680: Usage example:
2681:
2682: @example
2683: s" The text I search is here" scan-file
2684: @end example
2685:
2686: @subsection Copy input to output
2687:
2688: @example
2689: : copy-file ( -- )
2690: begin
2691: line-buffer max-line fd-in read-line throw
2692: while
2693: line-buffer swap fd-out write-file throw
2694: repeat ;
2695: @end example
2696:
2697: @subsection Close files
2698:
2699: @example
2700: fd-in close-file throw
2701: fd-out close-file throw
2702: @end example
2703:
2704: Likewise, you can put that into definitions, too:
2705:
2706: @example
2707: : close-input ( -- ) fd-in close-file throw ;
2708: : close-output ( -- ) fd-out close-file throw ;
2709: @end example
2710:
1.141 anton 2711: @quotation Assignment
1.84 pazsan 2712: How could you modify @code{copy-file} so that it copies until a second line is
2713: matched? Can you write a program that extracts a section of a text file,
2714: given the line that starts and the line that terminates that section?
1.141 anton 2715: @end quotation
1.84 pazsan 2716:
2717: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2718: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2719: @cindex semantics tutorial
2720: @cindex interpretation semantics tutorial
2721: @cindex compilation semantics tutorial
2722: @cindex immediate, tutorial
1.48 anton 2723:
2724: When a word is compiled, it behaves differently from being interpreted.
2725: E.g., consider @code{+}:
2726:
2727: @example
2728: 1 2 + .
2729: : foo + ;
2730: @end example
2731:
2732: These two behaviours are known as compilation and interpretation
2733: semantics. For normal words (e.g., @code{+}), the compilation semantics
2734: is to append the interpretation semantics to the currently defined word
2735: (@code{foo} in the example above). I.e., when @code{foo} is executed
2736: later, the interpretation semantics of @code{+} (i.e., adding two
2737: numbers) will be performed.
2738:
2739: However, there are words with non-default compilation semantics, e.g.,
2740: the control-flow words like @code{if}. You can use @code{immediate} to
2741: change the compilation semantics of the last defined word to be equal to
2742: the interpretation semantics:
2743:
2744: @example
2745: : [FOO] ( -- )
2746: 5 . ; immediate
2747:
2748: [FOO]
2749: : bar ( -- )
2750: [FOO] ;
2751: bar
2752: see bar
2753: @end example
2754:
2755: Two conventions to mark words with non-default compilation semnatics are
2756: names with brackets (more frequently used) and to write them all in
2757: upper case (less frequently used).
2758:
2759: In Gforth (and many other systems) you can also remove the
2760: interpretation semantics with @code{compile-only} (the compilation
2761: semantics is derived from the original interpretation semantics):
2762:
2763: @example
2764: : flip ( -- )
2765: 6 . ; compile-only \ but not immediate
2766: flip
2767:
2768: : flop ( -- )
2769: flip ;
2770: flop
2771: @end example
2772:
2773: In this example the interpretation semantics of @code{flop} is equal to
2774: the original interpretation semantics of @code{flip}.
2775:
2776: The text interpreter has two states: in interpret state, it performs the
2777: interpretation semantics of words it encounters; in compile state, it
2778: performs the compilation semantics of these words.
2779:
2780: Among other things, @code{:} switches into compile state, and @code{;}
2781: switches back to interpret state. They contain the factors @code{]}
2782: (switch to compile state) and @code{[} (switch to interpret state), that
2783: do nothing but switch the state.
2784:
2785: @example
2786: : xxx ( -- )
2787: [ 5 . ]
2788: ;
2789:
2790: xxx
2791: see xxx
2792: @end example
2793:
2794: These brackets are also the source of the naming convention mentioned
2795: above.
2796:
1.66 anton 2797: Reference: @ref{Interpretation and Compilation Semantics}.
2798:
1.48 anton 2799:
2800: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2801: @section Execution Tokens
1.66 anton 2802: @cindex execution tokens tutorial
2803: @cindex XT tutorial
1.48 anton 2804:
2805: @code{' word} gives you the execution token (XT) of a word. The XT is a
2806: cell representing the interpretation semantics of a word. You can
2807: execute this semantics with @code{execute}:
2808:
2809: @example
2810: ' + .s
2811: 1 2 rot execute .
2812: @end example
2813:
2814: The XT is similar to a function pointer in C. However, parameter
2815: passing through the stack makes it a little more flexible:
2816:
2817: @example
2818: : map-array ( ... addr u xt -- ... )
1.50 anton 2819: \ executes xt ( ... x -- ... ) for every element of the array starting
2820: \ at addr and containing u elements
1.48 anton 2821: @{ xt @}
2822: cells over + swap ?do
1.50 anton 2823: i @@ xt execute
1.48 anton 2824: 1 cells +loop ;
2825:
2826: create a 3 , 4 , 2 , -1 , 4 ,
2827: a 5 ' . map-array .s
2828: 0 a 5 ' + map-array .
2829: s" max-n" environment? drop .s
2830: a 5 ' min map-array .
2831: @end example
2832:
2833: You can use map-array with the XTs of words that consume one element
2834: more than they produce. In theory you can also use it with other XTs,
2835: but the stack effect then depends on the size of the array, which is
2836: hard to understand.
2837:
1.51 pazsan 2838: Since XTs are cell-sized, you can store them in memory and manipulate
2839: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2840: word with @code{compile,}:
2841:
2842: @example
2843: : foo1 ( n1 n2 -- n )
2844: [ ' + compile, ] ;
2845: see foo
2846: @end example
2847:
2848: This is non-standard, because @code{compile,} has no compilation
2849: semantics in the standard, but it works in good Forth systems. For the
2850: broken ones, use
2851:
2852: @example
2853: : [compile,] compile, ; immediate
2854:
2855: : foo1 ( n1 n2 -- n )
2856: [ ' + ] [compile,] ;
2857: see foo
2858: @end example
2859:
2860: @code{'} is a word with default compilation semantics; it parses the
2861: next word when its interpretation semantics are executed, not during
2862: compilation:
2863:
2864: @example
2865: : foo ( -- xt )
2866: ' ;
2867: see foo
2868: : bar ( ... "word" -- ... )
2869: ' execute ;
2870: see bar
1.60 anton 2871: 1 2 bar + .
1.48 anton 2872: @end example
2873:
2874: You often want to parse a word during compilation and compile its XT so
2875: it will be pushed on the stack at run-time. @code{[']} does this:
2876:
2877: @example
2878: : xt-+ ( -- xt )
2879: ['] + ;
2880: see xt-+
2881: 1 2 xt-+ execute .
2882: @end example
2883:
2884: Many programmers tend to see @code{'} and the word it parses as one
2885: unit, and expect it to behave like @code{[']} when compiled, and are
2886: confused by the actual behaviour. If you are, just remember that the
2887: Forth system just takes @code{'} as one unit and has no idea that it is
2888: a parsing word (attempts to convenience programmers in this issue have
2889: usually resulted in even worse pitfalls, see
1.66 anton 2890: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2891: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2892:
2893: Note that the state of the interpreter does not come into play when
1.51 pazsan 2894: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2895: compile state, it still gives you the interpretation semantics. And
2896: whatever that state is, @code{execute} performs the semantics
1.66 anton 2897: represented by the XT (i.e., for XTs produced with @code{'} the
2898: interpretation semantics).
2899:
2900: Reference: @ref{Tokens for Words}.
1.48 anton 2901:
2902:
2903: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2904: @section Exceptions
1.66 anton 2905: @cindex exceptions tutorial
1.48 anton 2906:
2907: @code{throw ( n -- )} causes an exception unless n is zero.
2908:
2909: @example
2910: 100 throw .s
2911: 0 throw .s
2912: @end example
2913:
2914: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2915: it catches exceptions and pushes the number of the exception on the
2916: stack (or 0, if the xt executed without exception). If there was an
2917: exception, the stacks have the same depth as when entering @code{catch}:
2918:
2919: @example
2920: .s
2921: 3 0 ' / catch .s
2922: 3 2 ' / catch .s
2923: @end example
2924:
1.141 anton 2925: @quotation Assignment
1.48 anton 2926: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2927: @end quotation
1.48 anton 2928:
2929: @code{Throw} always jumps to the dynamically next enclosing
2930: @code{catch}, even if it has to leave several call levels to achieve
2931: this:
2932:
2933: @example
2934: : foo 100 throw ;
2935: : foo1 foo ." after foo" ;
1.51 pazsan 2936: : bar ['] foo1 catch ;
1.60 anton 2937: bar .
1.48 anton 2938: @end example
2939:
2940: It is often important to restore a value upon leaving a definition, even
2941: if the definition is left through an exception. You can ensure this
2942: like this:
2943:
2944: @example
2945: : ...
2946: save-x
1.51 pazsan 2947: ['] word-changing-x catch ( ... n )
1.48 anton 2948: restore-x
2949: ( ... n ) throw ;
2950: @end example
2951:
1.172 anton 2952: However, this is still not safe against, e.g., the user pressing
2953: @kbd{Ctrl-C} when execution is between the @code{catch} and
2954: @code{restore-x}.
2955:
2956: Gforth provides an alternative exception handling syntax that is safe
2957: against such cases: @code{try ... restore ... endtry}. If the code
2958: between @code{try} and @code{endtry} has an exception, the stack
2959: depths are restored, the exception number is pushed on the stack, and
2960: the execution continues right after @code{restore}.
1.48 anton 2961:
1.172 anton 2962: The safer equivalent to the restoration code above is
1.48 anton 2963:
2964: @example
2965: : ...
2966: save-x
2967: try
1.92 anton 2968: word-changing-x 0
1.172 anton 2969: restore
2970: restore-x
2971: endtry
1.48 anton 2972: throw ;
2973: @end example
2974:
1.66 anton 2975: Reference: @ref{Exception Handling}.
2976:
1.48 anton 2977:
2978: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2979: @section Defining Words
1.66 anton 2980: @cindex defining words tutorial
2981: @cindex does> tutorial
2982: @cindex create...does> tutorial
2983:
2984: @c before semantics?
1.48 anton 2985:
2986: @code{:}, @code{create}, and @code{variable} are definition words: They
2987: define other words. @code{Constant} is another definition word:
2988:
2989: @example
2990: 5 constant foo
2991: foo .
2992: @end example
2993:
2994: You can also use the prefixes @code{2} (double-cell) and @code{f}
2995: (floating point) with @code{variable} and @code{constant}.
2996:
2997: You can also define your own defining words. E.g.:
2998:
2999: @example
3000: : variable ( "name" -- )
3001: create 0 , ;
3002: @end example
3003:
3004: You can also define defining words that create words that do something
3005: other than just producing their address:
3006:
3007: @example
3008: : constant ( n "name" -- )
3009: create ,
3010: does> ( -- n )
1.50 anton 3011: ( addr ) @@ ;
1.48 anton 3012:
3013: 5 constant foo
3014: foo .
3015: @end example
3016:
3017: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3018: @code{does>} replaces @code{;}, but it also does something else: It
3019: changes the last defined word such that it pushes the address of the
3020: body of the word and then performs the code after the @code{does>}
3021: whenever it is called.
3022:
3023: In the example above, @code{constant} uses @code{,} to store 5 into the
3024: body of @code{foo}. When @code{foo} executes, it pushes the address of
3025: the body onto the stack, then (in the code after the @code{does>})
3026: fetches the 5 from there.
3027:
3028: The stack comment near the @code{does>} reflects the stack effect of the
3029: defined word, not the stack effect of the code after the @code{does>}
3030: (the difference is that the code expects the address of the body that
3031: the stack comment does not show).
3032:
3033: You can use these definition words to do factoring in cases that involve
3034: (other) definition words. E.g., a field offset is always added to an
3035: address. Instead of defining
3036:
3037: @example
3038: 2 cells constant offset-field1
3039: @end example
3040:
3041: and using this like
3042:
3043: @example
3044: ( addr ) offset-field1 +
3045: @end example
3046:
3047: you can define a definition word
3048:
3049: @example
3050: : simple-field ( n "name" -- )
3051: create ,
3052: does> ( n1 -- n1+n )
1.50 anton 3053: ( addr ) @@ + ;
1.48 anton 3054: @end example
1.21 crook 3055:
1.48 anton 3056: Definition and use of field offsets now look like this:
1.21 crook 3057:
1.48 anton 3058: @example
3059: 2 cells simple-field field1
1.60 anton 3060: create mystruct 4 cells allot
3061: mystruct .s field1 .s drop
1.48 anton 3062: @end example
1.21 crook 3063:
1.48 anton 3064: If you want to do something with the word without performing the code
3065: after the @code{does>}, you can access the body of a @code{create}d word
3066: with @code{>body ( xt -- addr )}:
1.21 crook 3067:
1.48 anton 3068: @example
3069: : value ( n "name" -- )
3070: create ,
3071: does> ( -- n1 )
1.50 anton 3072: @@ ;
1.48 anton 3073: : to ( n "name" -- )
3074: ' >body ! ;
1.21 crook 3075:
1.48 anton 3076: 5 value foo
3077: foo .
3078: 7 to foo
3079: foo .
3080: @end example
1.21 crook 3081:
1.141 anton 3082: @quotation Assignment
1.48 anton 3083: Define @code{defer ( "name" -- )}, which creates a word that stores an
3084: XT (at the start the XT of @code{abort}), and upon execution
3085: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3086: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3087: recursion is one application of @code{defer}.
1.141 anton 3088: @end quotation
1.29 crook 3089:
1.66 anton 3090: Reference: @ref{User-defined Defining Words}.
3091:
3092:
1.48 anton 3093: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3094: @section Arrays and Records
1.66 anton 3095: @cindex arrays tutorial
3096: @cindex records tutorial
3097: @cindex structs tutorial
1.29 crook 3098:
1.48 anton 3099: Forth has no standard words for defining data structures such as arrays
3100: and records (structs in C terminology), but you can build them yourself
3101: based on address arithmetic. You can also define words for defining
3102: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3103:
1.48 anton 3104: One of the first projects a Forth newcomer sets out upon when learning
3105: about defining words is an array defining word (possibly for
3106: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3107: learn something from it. However, don't be disappointed when you later
3108: learn that you have little use for these words (inappropriate use would
3109: be even worse). I have not yet found a set of useful array words yet;
3110: the needs are just too diverse, and named, global arrays (the result of
3111: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3112: consider how to pass them as parameters). Another such project is a set
3113: of words to help dealing with strings.
1.29 crook 3114:
1.48 anton 3115: On the other hand, there is a useful set of record words, and it has
3116: been defined in @file{compat/struct.fs}; these words are predefined in
3117: Gforth. They are explained in depth elsewhere in this manual (see
3118: @pxref{Structures}). The @code{simple-field} example above is
3119: simplified variant of fields in this package.
1.21 crook 3120:
3121:
1.48 anton 3122: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3123: @section @code{POSTPONE}
1.66 anton 3124: @cindex postpone tutorial
1.21 crook 3125:
1.48 anton 3126: You can compile the compilation semantics (instead of compiling the
3127: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3128:
1.48 anton 3129: @example
3130: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3131: POSTPONE + ; immediate
1.48 anton 3132: : foo ( n1 n2 -- n )
3133: MY-+ ;
3134: 1 2 foo .
3135: see foo
3136: @end example
1.21 crook 3137:
1.48 anton 3138: During the definition of @code{foo} the text interpreter performs the
3139: compilation semantics of @code{MY-+}, which performs the compilation
3140: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3141:
3142: This example also displays separate stack comments for the compilation
3143: semantics and for the stack effect of the compiled code. For words with
3144: default compilation semantics these stack effects are usually not
3145: displayed; the stack effect of the compilation semantics is always
3146: @code{( -- )} for these words, the stack effect for the compiled code is
3147: the stack effect of the interpretation semantics.
3148:
3149: Note that the state of the interpreter does not come into play when
3150: performing the compilation semantics in this way. You can also perform
3151: it interpretively, e.g.:
3152:
3153: @example
3154: : foo2 ( n1 n2 -- n )
3155: [ MY-+ ] ;
3156: 1 2 foo .
3157: see foo
3158: @end example
1.21 crook 3159:
1.48 anton 3160: However, there are some broken Forth systems where this does not always
1.62 crook 3161: work, and therefore this practice was been declared non-standard in
1.48 anton 3162: 1999.
3163: @c !! repair.fs
3164:
3165: Here is another example for using @code{POSTPONE}:
1.44 crook 3166:
1.48 anton 3167: @example
3168: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3169: POSTPONE negate POSTPONE + ; immediate compile-only
3170: : bar ( n1 n2 -- n )
3171: MY-- ;
3172: 2 1 bar .
3173: see bar
3174: @end example
1.21 crook 3175:
1.48 anton 3176: You can define @code{ENDIF} in this way:
1.21 crook 3177:
1.48 anton 3178: @example
3179: : ENDIF ( Compilation: orig -- )
3180: POSTPONE then ; immediate
3181: @end example
1.21 crook 3182:
1.141 anton 3183: @quotation Assignment
1.48 anton 3184: Write @code{MY-2DUP} that has compilation semantics equivalent to
3185: @code{2dup}, but compiles @code{over over}.
1.141 anton 3186: @end quotation
1.29 crook 3187:
1.66 anton 3188: @c !! @xref{Macros} for reference
3189:
3190:
1.48 anton 3191: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3192: @section @code{Literal}
1.66 anton 3193: @cindex literal tutorial
1.29 crook 3194:
1.48 anton 3195: You cannot @code{POSTPONE} numbers:
1.21 crook 3196:
1.48 anton 3197: @example
3198: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3199: @end example
3200:
1.48 anton 3201: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3202:
1.48 anton 3203: @example
3204: : [FOO] ( compilation: --; run-time: -- n )
3205: 500 POSTPONE literal ; immediate
1.29 crook 3206:
1.60 anton 3207: : flip [FOO] ;
1.48 anton 3208: flip .
3209: see flip
3210: @end example
1.29 crook 3211:
1.48 anton 3212: @code{LITERAL} consumes a number at compile-time (when it's compilation
3213: semantics are executed) and pushes it at run-time (when the code it
3214: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3215: number computed at compile time into the current word:
1.29 crook 3216:
1.48 anton 3217: @example
3218: : bar ( -- n )
3219: [ 2 2 + ] literal ;
3220: see bar
3221: @end example
1.29 crook 3222:
1.141 anton 3223: @quotation Assignment
1.48 anton 3224: Write @code{]L} which allows writing the example above as @code{: bar (
3225: -- n ) [ 2 2 + ]L ;}
1.141 anton 3226: @end quotation
1.48 anton 3227:
1.66 anton 3228: @c !! @xref{Macros} for reference
3229:
1.48 anton 3230:
3231: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3232: @section Advanced macros
1.66 anton 3233: @cindex macros, advanced tutorial
3234: @cindex run-time code generation, tutorial
1.48 anton 3235:
1.66 anton 3236: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3237: Execution Tokens}. It frequently performs @code{execute}, a relatively
3238: expensive operation in some Forth implementations. You can use
1.48 anton 3239: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3240: and produce a word that contains the word to be performed directly:
3241:
3242: @c use ]] ... [[
3243: @example
3244: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3245: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3246: \ array beginning at addr and containing u elements
3247: @{ xt @}
3248: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3249: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3250: 1 cells POSTPONE literal POSTPONE +loop ;
3251:
3252: : sum-array ( addr u -- n )
3253: 0 rot rot [ ' + compile-map-array ] ;
3254: see sum-array
3255: a 5 sum-array .
3256: @end example
3257:
3258: You can use the full power of Forth for generating the code; here's an
3259: example where the code is generated in a loop:
3260:
3261: @example
3262: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3263: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3264: POSTPONE tuck POSTPONE @@
1.48 anton 3265: POSTPONE literal POSTPONE * POSTPONE +
3266: POSTPONE swap POSTPONE cell+ ;
3267:
3268: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3269: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3270: 0 postpone literal postpone swap
3271: [ ' compile-vmul-step compile-map-array ]
3272: postpone drop ;
3273: see compile-vmul
3274:
3275: : a-vmul ( addr -- n )
1.51 pazsan 3276: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3277: [ a 5 compile-vmul ] ;
3278: see a-vmul
3279: a a-vmul .
3280: @end example
3281:
3282: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3283: also use @code{map-array} instead (try it now!).
1.48 anton 3284:
3285: You can use this technique for efficient multiplication of large
3286: matrices. In matrix multiplication, you multiply every line of one
3287: matrix with every column of the other matrix. You can generate the code
3288: for one line once, and use it for every column. The only downside of
3289: this technique is that it is cumbersome to recover the memory consumed
3290: by the generated code when you are done (and in more complicated cases
3291: it is not possible portably).
3292:
1.66 anton 3293: @c !! @xref{Macros} for reference
3294:
3295:
1.48 anton 3296: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3297: @section Compilation Tokens
1.66 anton 3298: @cindex compilation tokens, tutorial
3299: @cindex CT, tutorial
1.48 anton 3300:
3301: This section is Gforth-specific. You can skip it.
3302:
3303: @code{' word compile,} compiles the interpretation semantics. For words
3304: with default compilation semantics this is the same as performing the
3305: compilation semantics. To represent the compilation semantics of other
3306: words (e.g., words like @code{if} that have no interpretation
3307: semantics), Gforth has the concept of a compilation token (CT,
3308: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3309: You can perform the compilation semantics represented by a CT with
3310: @code{execute}:
1.29 crook 3311:
1.48 anton 3312: @example
3313: : foo2 ( n1 n2 -- n )
3314: [ comp' + execute ] ;
3315: see foo
3316: @end example
1.29 crook 3317:
1.48 anton 3318: You can compile the compilation semantics represented by a CT with
3319: @code{postpone,}:
1.30 anton 3320:
1.48 anton 3321: @example
3322: : foo3 ( -- )
3323: [ comp' + postpone, ] ;
3324: see foo3
3325: @end example
1.30 anton 3326:
1.51 pazsan 3327: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3328: @code{comp'} is particularly useful for words that have no
3329: interpretation semantics:
1.29 crook 3330:
1.30 anton 3331: @example
1.48 anton 3332: ' if
1.60 anton 3333: comp' if .s 2drop
1.30 anton 3334: @end example
3335:
1.66 anton 3336: Reference: @ref{Tokens for Words}.
3337:
1.29 crook 3338:
1.48 anton 3339: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3340: @section Wordlists and Search Order
1.66 anton 3341: @cindex wordlists tutorial
3342: @cindex search order, tutorial
1.48 anton 3343:
3344: The dictionary is not just a memory area that allows you to allocate
3345: memory with @code{allot}, it also contains the Forth words, arranged in
3346: several wordlists. When searching for a word in a wordlist,
3347: conceptually you start searching at the youngest and proceed towards
3348: older words (in reality most systems nowadays use hash-tables); i.e., if
3349: you define a word with the same name as an older word, the new word
3350: shadows the older word.
3351:
3352: Which wordlists are searched in which order is determined by the search
3353: order. You can display the search order with @code{order}. It displays
3354: first the search order, starting with the wordlist searched first, then
3355: it displays the wordlist that will contain newly defined words.
1.21 crook 3356:
1.48 anton 3357: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3358:
1.48 anton 3359: @example
3360: wordlist constant mywords
3361: @end example
1.21 crook 3362:
1.48 anton 3363: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3364: defined words (the @emph{current} wordlist):
1.21 crook 3365:
1.48 anton 3366: @example
3367: mywords set-current
3368: order
3369: @end example
1.26 crook 3370:
1.48 anton 3371: Gforth does not display a name for the wordlist in @code{mywords}
3372: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3373:
1.48 anton 3374: You can get the current wordlist with @code{get-current ( -- wid)}. If
3375: you want to put something into a specific wordlist without overall
3376: effect on the current wordlist, this typically looks like this:
1.21 crook 3377:
1.48 anton 3378: @example
3379: get-current mywords set-current ( wid )
3380: create someword
3381: ( wid ) set-current
3382: @end example
1.21 crook 3383:
1.48 anton 3384: You can write the search order with @code{set-order ( wid1 .. widn n --
3385: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3386: searched wordlist is topmost.
1.21 crook 3387:
1.48 anton 3388: @example
3389: get-order mywords swap 1+ set-order
3390: order
3391: @end example
1.21 crook 3392:
1.48 anton 3393: Yes, the order of wordlists in the output of @code{order} is reversed
3394: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3395:
1.141 anton 3396: @quotation Assignment
1.48 anton 3397: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3398: wordlist to the search order. Define @code{previous ( -- )}, which
3399: removes the first searched wordlist from the search order. Experiment
3400: with boundary conditions (you will see some crashes or situations that
3401: are hard or impossible to leave).
1.141 anton 3402: @end quotation
1.21 crook 3403:
1.48 anton 3404: The search order is a powerful foundation for providing features similar
3405: to Modula-2 modules and C++ namespaces. However, trying to modularize
3406: programs in this way has disadvantages for debugging and reuse/factoring
3407: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3408: though). These disadvantages are not so clear in other
1.82 anton 3409: languages/programming environments, because these languages are not so
1.48 anton 3410: strong in debugging and reuse.
1.21 crook 3411:
1.66 anton 3412: @c !! example
3413:
3414: Reference: @ref{Word Lists}.
1.21 crook 3415:
1.29 crook 3416: @c ******************************************************************
1.48 anton 3417: @node Introduction, Words, Tutorial, Top
1.29 crook 3418: @comment node-name, next, previous, up
3419: @chapter An Introduction to ANS Forth
3420: @cindex Forth - an introduction
1.21 crook 3421:
1.83 anton 3422: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3423: that it is slower-paced in its examples, but uses them to dive deep into
3424: explaining Forth internals (not covered by the Tutorial). Apart from
3425: that, this chapter covers far less material. It is suitable for reading
3426: without using a computer.
3427:
1.29 crook 3428: The primary purpose of this manual is to document Gforth. However, since
3429: Forth is not a widely-known language and there is a lack of up-to-date
3430: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3431: material. For other sources of Forth-related
3432: information, see @ref{Forth-related information}.
1.21 crook 3433:
1.29 crook 3434: The examples in this section should work on any ANS Forth; the
3435: output shown was produced using Gforth. Each example attempts to
3436: reproduce the exact output that Gforth produces. If you try out the
3437: examples (and you should), what you should type is shown @kbd{like this}
3438: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3439: that, where the example shows @key{RET} it means that you should
1.29 crook 3440: press the ``carriage return'' key. Unfortunately, some output formats for
3441: this manual cannot show the difference between @kbd{this} and
3442: @code{this} which will make trying out the examples harder (but not
3443: impossible).
1.21 crook 3444:
1.29 crook 3445: Forth is an unusual language. It provides an interactive development
3446: environment which includes both an interpreter and compiler. Forth
3447: programming style encourages you to break a problem down into many
3448: @cindex factoring
3449: small fragments (@dfn{factoring}), and then to develop and test each
3450: fragment interactively. Forth advocates assert that breaking the
3451: edit-compile-test cycle used by conventional programming languages can
3452: lead to great productivity improvements.
1.21 crook 3453:
1.29 crook 3454: @menu
1.67 anton 3455: * Introducing the Text Interpreter::
3456: * Stacks and Postfix notation::
3457: * Your first definition::
3458: * How does that work?::
3459: * Forth is written in Forth::
3460: * Review - elements of a Forth system::
3461: * Where to go next::
3462: * Exercises::
1.29 crook 3463: @end menu
1.21 crook 3464:
1.29 crook 3465: @comment ----------------------------------------------
3466: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3467: @section Introducing the Text Interpreter
3468: @cindex text interpreter
3469: @cindex outer interpreter
1.21 crook 3470:
1.30 anton 3471: @c IMO this is too detailed and the pace is too slow for
3472: @c an introduction. If you know German, take a look at
3473: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3474: @c to see how I do it - anton
3475:
1.44 crook 3476: @c nac-> Where I have accepted your comments 100% and modified the text
3477: @c accordingly, I have deleted your comments. Elsewhere I have added a
3478: @c response like this to attempt to rationalise what I have done. Of
3479: @c course, this is a very clumsy mechanism for something that would be
3480: @c done far more efficiently over a beer. Please delete any dialogue
3481: @c you consider closed.
3482:
1.29 crook 3483: When you invoke the Forth image, you will see a startup banner printed
3484: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3485: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3486: its command line interpreter, which is called the @dfn{Text Interpreter}
3487: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3488: about the text interpreter as you read through this chapter, for more
3489: detail @pxref{The Text Interpreter}).
1.21 crook 3490:
1.29 crook 3491: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3492: input. Type a number and press the @key{RET} key:
1.21 crook 3493:
1.26 crook 3494: @example
1.30 anton 3495: @kbd{45@key{RET}} ok
1.26 crook 3496: @end example
1.21 crook 3497:
1.29 crook 3498: Rather than give you a prompt to invite you to input something, the text
3499: interpreter prints a status message @i{after} it has processed a line
3500: of input. The status message in this case (``@code{ ok}'' followed by
3501: carriage-return) indicates that the text interpreter was able to process
3502: all of your input successfully. Now type something illegal:
3503:
3504: @example
1.30 anton 3505: @kbd{qwer341@key{RET}}
1.134 anton 3506: *the terminal*:2: Undefined word
3507: >>>qwer341<<<
3508: Backtrace:
3509: $2A95B42A20 throw
3510: $2A95B57FB8 no.extensions
1.29 crook 3511: @end example
1.23 crook 3512:
1.134 anton 3513: The exact text, other than the ``Undefined word'' may differ slightly
3514: on your system, but the effect is the same; when the text interpreter
1.29 crook 3515: detects an error, it discards any remaining text on a line, resets
1.134 anton 3516: certain internal state and prints an error message. For a detailed
3517: description of error messages see @ref{Error messages}.
1.23 crook 3518:
1.29 crook 3519: The text interpreter waits for you to press carriage-return, and then
3520: processes your input line. Starting at the beginning of the line, it
3521: breaks the line into groups of characters separated by spaces. For each
3522: group of characters in turn, it makes two attempts to do something:
1.23 crook 3523:
1.29 crook 3524: @itemize @bullet
3525: @item
1.44 crook 3526: @cindex name dictionary
1.29 crook 3527: It tries to treat it as a command. It does this by searching a @dfn{name
3528: dictionary}. If the group of characters matches an entry in the name
3529: dictionary, the name dictionary provides the text interpreter with
3530: information that allows the text interpreter perform some actions. In
3531: Forth jargon, we say that the group
3532: @cindex word
3533: @cindex definition
3534: @cindex execution token
3535: @cindex xt
3536: of characters names a @dfn{word}, that the dictionary search returns an
3537: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3538: word, and that the text interpreter executes the xt. Often, the terms
3539: @dfn{word} and @dfn{definition} are used interchangeably.
3540: @item
3541: If the text interpreter fails to find a match in the name dictionary, it
3542: tries to treat the group of characters as a number in the current number
3543: base (when you start up Forth, the current number base is base 10). If
3544: the group of characters legitimately represents a number, the text
3545: interpreter pushes the number onto a stack (we'll learn more about that
3546: in the next section).
3547: @end itemize
1.23 crook 3548:
1.29 crook 3549: If the text interpreter is unable to do either of these things with any
3550: group of characters, it discards the group of characters and the rest of
3551: the line, then prints an error message. If the text interpreter reaches
3552: the end of the line without error, it prints the status message ``@code{ ok}''
3553: followed by carriage-return.
1.21 crook 3554:
1.29 crook 3555: This is the simplest command we can give to the text interpreter:
1.23 crook 3556:
3557: @example
1.30 anton 3558: @key{RET} ok
1.23 crook 3559: @end example
1.21 crook 3560:
1.29 crook 3561: The text interpreter did everything we asked it to do (nothing) without
3562: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3563: command:
1.21 crook 3564:
1.23 crook 3565: @example
1.30 anton 3566: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3567: *the terminal*:3: Undefined word
3568: 12 dup >>>fred<<< dup
3569: Backtrace:
3570: $2A95B42A20 throw
3571: $2A95B57FB8 no.extensions
1.23 crook 3572: @end example
1.21 crook 3573:
1.29 crook 3574: When you press the carriage-return key, the text interpreter starts to
3575: work its way along the line:
1.21 crook 3576:
1.29 crook 3577: @itemize @bullet
3578: @item
3579: When it gets to the space after the @code{2}, it takes the group of
3580: characters @code{12} and looks them up in the name
3581: dictionary@footnote{We can't tell if it found them or not, but assume
3582: for now that it did not}. There is no match for this group of characters
3583: in the name dictionary, so it tries to treat them as a number. It is
3584: able to do this successfully, so it puts the number, 12, ``on the stack''
3585: (whatever that means).
3586: @item
3587: The text interpreter resumes scanning the line and gets the next group
3588: of characters, @code{dup}. It looks it up in the name dictionary and
3589: (you'll have to take my word for this) finds it, and executes the word
3590: @code{dup} (whatever that means).
3591: @item
3592: Once again, the text interpreter resumes scanning the line and gets the
3593: group of characters @code{fred}. It looks them up in the name
3594: dictionary, but can't find them. It tries to treat them as a number, but
3595: they don't represent any legal number.
3596: @end itemize
1.21 crook 3597:
1.29 crook 3598: At this point, the text interpreter gives up and prints an error
3599: message. The error message shows exactly how far the text interpreter
3600: got in processing the line. In particular, it shows that the text
3601: interpreter made no attempt to do anything with the final character
3602: group, @code{dup}, even though we have good reason to believe that the
3603: text interpreter would have no problem looking that word up and
3604: executing it a second time.
1.21 crook 3605:
3606:
1.29 crook 3607: @comment ----------------------------------------------
3608: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3609: @section Stacks, postfix notation and parameter passing
3610: @cindex text interpreter
3611: @cindex outer interpreter
1.21 crook 3612:
1.29 crook 3613: In procedural programming languages (like C and Pascal), the
3614: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3615: functions or procedures are called with @dfn{explicit parameters}. For
3616: example, in C we might write:
1.21 crook 3617:
1.23 crook 3618: @example
1.29 crook 3619: total = total + new_volume(length,height,depth);
1.23 crook 3620: @end example
1.21 crook 3621:
1.23 crook 3622: @noindent
1.29 crook 3623: where new_volume is a function-call to another piece of code, and total,
3624: length, height and depth are all variables. length, height and depth are
3625: parameters to the function-call.
1.21 crook 3626:
1.29 crook 3627: In Forth, the equivalent of the function or procedure is the
3628: @dfn{definition} and parameters are implicitly passed between
3629: definitions using a shared stack that is visible to the
3630: programmer. Although Forth does support variables, the existence of the
3631: stack means that they are used far less often than in most other
3632: programming languages. When the text interpreter encounters a number, it
3633: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3634: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3635: used for any operation is implied unambiguously by the operation being
3636: performed. The stack used for all integer operations is called the @dfn{data
3637: stack} and, since this is the stack used most commonly, references to
3638: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3639:
1.29 crook 3640: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3641:
1.23 crook 3642: @example
1.30 anton 3643: @kbd{1 2 3@key{RET}} ok
1.23 crook 3644: @end example
1.21 crook 3645:
1.29 crook 3646: Then this instructs the text interpreter to placed three numbers on the
3647: (data) stack. An analogy for the behaviour of the stack is to take a
3648: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3649: the table. The 3 was the last card onto the pile (``last-in'') and if
3650: you take a card off the pile then, unless you're prepared to fiddle a
3651: bit, the card that you take off will be the 3 (``first-out''). The
3652: number that will be first-out of the stack is called the @dfn{top of
3653: stack}, which
3654: @cindex TOS definition
3655: is often abbreviated to @dfn{TOS}.
1.21 crook 3656:
1.29 crook 3657: To understand how parameters are passed in Forth, consider the
3658: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3659: be surprised to learn that this definition performs addition. More
3660: precisely, it adds two number together and produces a result. Where does
3661: it get the two numbers from? It takes the top two numbers off the
3662: stack. Where does it place the result? On the stack. You can act-out the
3663: behaviour of @code{+} with your playing cards like this:
1.21 crook 3664:
3665: @itemize @bullet
3666: @item
1.29 crook 3667: Pick up two cards from the stack on the table
1.21 crook 3668: @item
1.29 crook 3669: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3670: numbers''
1.21 crook 3671: @item
1.29 crook 3672: Decide that the answer is 5
1.21 crook 3673: @item
1.29 crook 3674: Shuffle the two cards back into the pack and find a 5
1.21 crook 3675: @item
1.29 crook 3676: Put a 5 on the remaining ace that's on the table.
1.21 crook 3677: @end itemize
3678:
1.29 crook 3679: If you don't have a pack of cards handy but you do have Forth running,
3680: you can use the definition @code{.s} to show the current state of the stack,
3681: without affecting the stack. Type:
1.21 crook 3682:
3683: @example
1.124 anton 3684: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3685: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3686: @end example
3687:
1.124 anton 3688: The text interpreter looks up the word @code{clearstacks} and executes
3689: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3690: left on it by earlier examples. The text interpreter pushes each of the
3691: three numbers in turn onto the stack. Finally, the text interpreter
3692: looks up the word @code{.s} and executes it. The effect of executing
3693: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3694: followed by a list of all the items on the stack; the item on the far
3695: right-hand side is the TOS.
1.21 crook 3696:
1.29 crook 3697: You can now type:
1.21 crook 3698:
1.29 crook 3699: @example
1.30 anton 3700: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3701: @end example
1.21 crook 3702:
1.29 crook 3703: @noindent
3704: which is correct; there are now 2 items on the stack and the result of
3705: the addition is 5.
1.23 crook 3706:
1.29 crook 3707: If you're playing with cards, try doing a second addition: pick up the
3708: two cards, work out that their sum is 6, shuffle them into the pack,
3709: look for a 6 and place that on the table. You now have just one item on
3710: the stack. What happens if you try to do a third addition? Pick up the
3711: first card, pick up the second card -- ah! There is no second card. This
3712: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3713: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3714: Underflow or an Invalid Memory Address error).
1.23 crook 3715:
1.29 crook 3716: The opposite situation to a stack underflow is a @dfn{stack overflow},
3717: which simply accepts that there is a finite amount of storage space
3718: reserved for the stack. To stretch the playing card analogy, if you had
3719: enough packs of cards and you piled the cards up on the table, you would
3720: eventually be unable to add another card; you'd hit the ceiling. Gforth
3721: allows you to set the maximum size of the stacks. In general, the only
3722: time that you will get a stack overflow is because a definition has a
3723: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3724:
1.29 crook 3725: There's one final use for the playing card analogy. If you model your
3726: stack using a pack of playing cards, the maximum number of items on
3727: your stack will be 52 (I assume you didn't use the Joker). The maximum
3728: @i{value} of any item on the stack is 13 (the King). In fact, the only
3729: possible numbers are positive integer numbers 1 through 13; you can't
3730: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3731: think about some of the cards, you can accommodate different
3732: numbers. For example, you could think of the Jack as representing 0,
3733: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3734: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3735: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3736:
1.29 crook 3737: In that analogy, the limit was the amount of information that a single
3738: stack entry could hold, and Forth has a similar limit. In Forth, the
3739: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3740: implementation dependent and affects the maximum value that a stack
3741: entry can hold. A Standard Forth provides a cell size of at least
3742: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3743:
1.29 crook 3744: Forth does not do any type checking for you, so you are free to
3745: manipulate and combine stack items in any way you wish. A convenient way
3746: of treating stack items is as 2's complement signed integers, and that
3747: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3748:
1.29 crook 3749: @example
1.30 anton 3750: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3751: @end example
1.21 crook 3752:
1.29 crook 3753: If you use numbers and definitions like @code{+} in order to turn Forth
3754: into a great big pocket calculator, you will realise that it's rather
3755: different from a normal calculator. Rather than typing 2 + 3 = you had
3756: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3757: result). The terminology used to describe this difference is to say that
3758: your calculator uses @dfn{Infix Notation} (parameters and operators are
3759: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3760: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3761:
1.29 crook 3762: Whilst postfix notation might look confusing to begin with, it has
3763: several important advantages:
1.21 crook 3764:
1.23 crook 3765: @itemize @bullet
3766: @item
1.29 crook 3767: it is unambiguous
1.23 crook 3768: @item
1.29 crook 3769: it is more concise
1.23 crook 3770: @item
1.29 crook 3771: it fits naturally with a stack-based system
1.23 crook 3772: @end itemize
1.21 crook 3773:
1.29 crook 3774: To examine these claims in more detail, consider these sums:
1.21 crook 3775:
1.29 crook 3776: @example
3777: 6 + 5 * 4 =
3778: 4 * 5 + 6 =
3779: @end example
1.21 crook 3780:
1.29 crook 3781: If you're just learning maths or your maths is very rusty, you will
3782: probably come up with the answer 44 for the first and 26 for the
3783: second. If you are a bit of a whizz at maths you will remember the
3784: @i{convention} that multiplication takes precendence over addition, and
3785: you'd come up with the answer 26 both times. To explain the answer 26
3786: to someone who got the answer 44, you'd probably rewrite the first sum
3787: like this:
1.21 crook 3788:
1.29 crook 3789: @example
3790: 6 + (5 * 4) =
3791: @end example
1.21 crook 3792:
1.29 crook 3793: If what you really wanted was to perform the addition before the
3794: multiplication, you would have to use parentheses to force it.
1.21 crook 3795:
1.29 crook 3796: If you did the first two sums on a pocket calculator you would probably
3797: get the right answers, unless you were very cautious and entered them using
3798: these keystroke sequences:
1.21 crook 3799:
1.29 crook 3800: 6 + 5 = * 4 =
3801: 4 * 5 = + 6 =
1.21 crook 3802:
1.29 crook 3803: Postfix notation is unambiguous because the order that the operators
3804: are applied is always explicit; that also means that parentheses are
3805: never required. The operators are @i{active} (the act of quoting the
3806: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3807:
1.29 crook 3808: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3809: equivalent ways:
1.26 crook 3810:
3811: @example
1.29 crook 3812: 6 5 4 * + or:
3813: 5 4 * 6 +
1.26 crook 3814: @end example
1.23 crook 3815:
1.29 crook 3816: An important thing that you should notice about this notation is that
3817: the @i{order} of the numbers does not change; if you want to subtract
3818: 2 from 10 you type @code{10 2 -}.
1.1 anton 3819:
1.29 crook 3820: The reason that Forth uses postfix notation is very simple to explain: it
3821: makes the implementation extremely simple, and it follows naturally from
3822: using the stack as a mechanism for passing parameters. Another way of
3823: thinking about this is to realise that all Forth definitions are
3824: @i{active}; they execute as they are encountered by the text
3825: interpreter. The result of this is that the syntax of Forth is trivially
3826: simple.
1.1 anton 3827:
3828:
3829:
1.29 crook 3830: @comment ----------------------------------------------
3831: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3832: @section Your first Forth definition
3833: @cindex first definition
1.1 anton 3834:
1.29 crook 3835: Until now, the examples we've seen have been trivial; we've just been
3836: using Forth as a bigger-than-pocket calculator. Also, each calculation
3837: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3838: again@footnote{That's not quite true. If you press the up-arrow key on
3839: your keyboard you should be able to scroll back to any earlier command,
3840: edit it and re-enter it.} In this section we'll see how to add new
3841: words to Forth's vocabulary.
1.1 anton 3842:
1.29 crook 3843: The easiest way to create a new word is to use a @dfn{colon
3844: definition}. We'll define a few and try them out before worrying too
3845: much about how they work. Try typing in these examples; be careful to
3846: copy the spaces accurately:
1.1 anton 3847:
1.29 crook 3848: @example
3849: : add-two 2 + . ;
3850: : greet ." Hello and welcome" ;
3851: : demo 5 add-two ;
3852: @end example
1.1 anton 3853:
1.29 crook 3854: @noindent
3855: Now try them out:
1.1 anton 3856:
1.29 crook 3857: @example
1.30 anton 3858: @kbd{greet@key{RET}} Hello and welcome ok
3859: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3860: @kbd{4 add-two@key{RET}} 6 ok
3861: @kbd{demo@key{RET}} 7 ok
3862: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3863: @end example
1.1 anton 3864:
1.29 crook 3865: The first new thing that we've introduced here is the pair of words
3866: @code{:} and @code{;}. These are used to start and terminate a new
3867: definition, respectively. The first word after the @code{:} is the name
3868: for the new definition.
1.1 anton 3869:
1.29 crook 3870: As you can see from the examples, a definition is built up of words that
3871: have already been defined; Forth makes no distinction between
3872: definitions that existed when you started the system up, and those that
3873: you define yourself.
1.1 anton 3874:
1.29 crook 3875: The examples also introduce the words @code{.} (dot), @code{."}
3876: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3877: the stack and displays it. It's like @code{.s} except that it only
3878: displays the top item of the stack and it is destructive; after it has
3879: executed, the number is no longer on the stack. There is always one
3880: space printed after the number, and no spaces before it. Dot-quote
3881: defines a string (a sequence of characters) that will be printed when
3882: the word is executed. The string can contain any printable characters
3883: except @code{"}. A @code{"} has a special function; it is not a Forth
3884: word but it acts as a delimiter (the way that delimiters work is
3885: described in the next section). Finally, @code{dup} duplicates the value
3886: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3887:
1.29 crook 3888: We already know that the text interpreter searches through the
3889: dictionary to locate names. If you've followed the examples earlier, you
3890: will already have a definition called @code{add-two}. Lets try modifying
3891: it by typing in a new definition:
1.1 anton 3892:
1.29 crook 3893: @example
1.30 anton 3894: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3895: @end example
1.5 anton 3896:
1.29 crook 3897: Forth recognised that we were defining a word that already exists, and
3898: printed a message to warn us of that fact. Let's try out the new
3899: definition:
1.5 anton 3900:
1.29 crook 3901: @example
1.30 anton 3902: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3903: @end example
1.1 anton 3904:
1.29 crook 3905: @noindent
3906: All that we've actually done here, though, is to create a new
3907: definition, with a particular name. The fact that there was already a
3908: definition with the same name did not make any difference to the way
3909: that the new definition was created (except that Forth printed a warning
3910: message). The old definition of add-two still exists (try @code{demo}
3911: again to see that this is true). Any new definition will use the new
3912: definition of @code{add-two}, but old definitions continue to use the
3913: version that already existed at the time that they were @code{compiled}.
1.1 anton 3914:
1.29 crook 3915: Before you go on to the next section, try defining and redefining some
3916: words of your own.
1.1 anton 3917:
1.29 crook 3918: @comment ----------------------------------------------
3919: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3920: @section How does that work?
3921: @cindex parsing words
1.1 anton 3922:
1.30 anton 3923: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3924:
3925: @c Is it a good idea to talk about the interpretation semantics of a
3926: @c number? We don't have an xt to go along with it. - anton
3927:
3928: @c Now that I have eliminated execution semantics, I wonder if it would not
3929: @c be better to keep them (or add run-time semantics), to make it easier to
3930: @c explain what compilation semantics usually does. - anton
3931:
1.44 crook 3932: @c nac-> I removed the term ``default compilation sematics'' from the
3933: @c introductory chapter. Removing ``execution semantics'' was making
3934: @c everything simpler to explain, then I think the use of this term made
3935: @c everything more complex again. I replaced it with ``default
3936: @c semantics'' (which is used elsewhere in the manual) by which I mean
3937: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3938: @c flag set''.
3939:
3940: @c anton: I have eliminated default semantics (except in one place where it
3941: @c means "default interpretation and compilation semantics"), because it
3942: @c makes no sense in the presence of combined words. I reverted to
3943: @c "execution semantics" where necessary.
3944:
3945: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3946: @c section (and, unusually for me, I think I even made it shorter!). See
3947: @c what you think -- I know I have not addressed your primary concern
3948: @c that it is too heavy-going for an introduction. From what I understood
3949: @c of your course notes it looks as though they might be a good framework.
3950: @c Things that I've tried to capture here are some things that came as a
3951: @c great revelation here when I first understood them. Also, I like the
3952: @c fact that a very simple code example shows up almost all of the issues
3953: @c that you need to understand to see how Forth works. That's unique and
3954: @c worthwhile to emphasise.
3955:
1.83 anton 3956: @c anton: I think it's a good idea to present the details, especially those
3957: @c that you found to be a revelation, and probably the tutorial tries to be
3958: @c too superficial and does not get some of the things across that make
3959: @c Forth special. I do believe that most of the time these things should
3960: @c be discussed at the end of a section or in separate sections instead of
3961: @c in the middle of a section (e.g., the stuff you added in "User-defined
3962: @c defining words" leads in a completely different direction from the rest
3963: @c of the section).
3964:
1.29 crook 3965: Now we're going to take another look at the definition of @code{add-two}
3966: from the previous section. From our knowledge of the way that the text
3967: interpreter works, we would have expected this result when we tried to
3968: define @code{add-two}:
1.21 crook 3969:
1.29 crook 3970: @example
1.44 crook 3971: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3972: *the terminal*:4: Undefined word
3973: : >>>add-two<<< 2 + . ;
1.29 crook 3974: @end example
1.28 crook 3975:
1.29 crook 3976: The reason that this didn't happen is bound up in the way that @code{:}
3977: works. The word @code{:} does two special things. The first special
3978: thing that it does prevents the text interpreter from ever seeing the
3979: characters @code{add-two}. The text interpreter uses a variable called
3980: @cindex modifying >IN
1.44 crook 3981: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3982: input line. When it encounters the word @code{:} it behaves in exactly
3983: the same way as it does for any other word; it looks it up in the name
3984: dictionary, finds its xt and executes it. When @code{:} executes, it
3985: looks at the input buffer, finds the word @code{add-two} and advances the
3986: value of @code{>IN} to point past it. It then does some other stuff
3987: associated with creating the new definition (including creating an entry
3988: for @code{add-two} in the name dictionary). When the execution of @code{:}
3989: completes, control returns to the text interpreter, which is oblivious
3990: to the fact that it has been tricked into ignoring part of the input
3991: line.
1.21 crook 3992:
1.29 crook 3993: @cindex parsing words
3994: Words like @code{:} -- words that advance the value of @code{>IN} and so
3995: prevent the text interpreter from acting on the whole of the input line
3996: -- are called @dfn{parsing words}.
1.21 crook 3997:
1.29 crook 3998: @cindex @code{state} - effect on the text interpreter
3999: @cindex text interpreter - effect of state
4000: The second special thing that @code{:} does is change the value of a
4001: variable called @code{state}, which affects the way that the text
4002: interpreter behaves. When Gforth starts up, @code{state} has the value
4003: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4004: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4005: the text interpreter is said to be @dfn{compiling}.
4006:
4007: In this example, the text interpreter is compiling when it processes the
4008: string ``@code{2 + . ;}''. It still breaks the string down into
4009: character sequences in the same way. However, instead of pushing the
4010: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4011: into the definition of @code{add-two} that will make the number @code{2} get
4012: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4013: the behaviours of @code{+} and @code{.} are also compiled into the
4014: definition.
4015:
4016: One category of words don't get compiled. These so-called @dfn{immediate
4017: words} get executed (performed @i{now}) regardless of whether the text
4018: interpreter is interpreting or compiling. The word @code{;} is an
4019: immediate word. Rather than being compiled into the definition, it
4020: executes. Its effect is to terminate the current definition, which
4021: includes changing the value of @code{state} back to 0.
4022:
4023: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4024: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4025: definition.
1.28 crook 4026:
1.30 anton 4027: In Forth, every word or number can be described in terms of two
1.29 crook 4028: properties:
1.28 crook 4029:
4030: @itemize @bullet
4031: @item
1.29 crook 4032: @cindex interpretation semantics
1.44 crook 4033: Its @dfn{interpretation semantics} describe how it will behave when the
4034: text interpreter encounters it in @dfn{interpret} state. The
4035: interpretation semantics of a word are represented by an @dfn{execution
4036: token}.
1.28 crook 4037: @item
1.29 crook 4038: @cindex compilation semantics
1.44 crook 4039: Its @dfn{compilation semantics} describe how it will behave when the
4040: text interpreter encounters it in @dfn{compile} state. The compilation
4041: semantics of a word are represented in an implementation-dependent way;
4042: Gforth uses a @dfn{compilation token}.
1.29 crook 4043: @end itemize
4044:
4045: @noindent
4046: Numbers are always treated in a fixed way:
4047:
4048: @itemize @bullet
1.28 crook 4049: @item
1.44 crook 4050: When the number is @dfn{interpreted}, its behaviour is to push the
4051: number onto the stack.
1.28 crook 4052: @item
1.30 anton 4053: When the number is @dfn{compiled}, a piece of code is appended to the
4054: current definition that pushes the number when it runs. (In other words,
4055: the compilation semantics of a number are to postpone its interpretation
4056: semantics until the run-time of the definition that it is being compiled
4057: into.)
1.29 crook 4058: @end itemize
4059:
1.44 crook 4060: Words don't behave in such a regular way, but most have @i{default
4061: semantics} which means that they behave like this:
1.29 crook 4062:
4063: @itemize @bullet
1.28 crook 4064: @item
1.30 anton 4065: The @dfn{interpretation semantics} of the word are to do something useful.
4066: @item
1.29 crook 4067: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4068: @dfn{interpretation semantics} to the current definition (so that its
4069: run-time behaviour is to do something useful).
1.28 crook 4070: @end itemize
4071:
1.30 anton 4072: @cindex immediate words
1.44 crook 4073: The actual behaviour of any particular word can be controlled by using
4074: the words @code{immediate} and @code{compile-only} when the word is
4075: defined. These words set flags in the name dictionary entry of the most
4076: recently defined word, and these flags are retrieved by the text
4077: interpreter when it finds the word in the name dictionary.
4078:
4079: A word that is marked as @dfn{immediate} has compilation semantics that
4080: are identical to its interpretation semantics. In other words, it
4081: behaves like this:
1.29 crook 4082:
4083: @itemize @bullet
4084: @item
1.30 anton 4085: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4086: @item
1.30 anton 4087: The @dfn{compilation semantics} of the word are to do something useful
4088: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4089: @end itemize
1.28 crook 4090:
1.44 crook 4091: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4092: performing the interpretation semantics of the word directly; an attempt
4093: to do so will generate an error. It is never necessary to use
4094: @code{compile-only} (and it is not even part of ANS Forth, though it is
4095: provided by many implementations) but it is good etiquette to apply it
4096: to a word that will not behave correctly (and might have unexpected
4097: side-effects) in interpret state. For example, it is only legal to use
4098: the conditional word @code{IF} within a definition. If you forget this
4099: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4100: @code{compile-only} allows the text interpreter to generate a helpful
4101: error message rather than subjecting you to the consequences of your
4102: folly.
4103:
1.29 crook 4104: This example shows the difference between an immediate and a
4105: non-immediate word:
1.28 crook 4106:
1.29 crook 4107: @example
4108: : show-state state @@ . ;
4109: : show-state-now show-state ; immediate
4110: : word1 show-state ;
4111: : word2 show-state-now ;
1.28 crook 4112: @end example
1.23 crook 4113:
1.29 crook 4114: The word @code{immediate} after the definition of @code{show-state-now}
4115: makes that word an immediate word. These definitions introduce a new
4116: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4117: variable, and leaves it on the stack. Therefore, the behaviour of
4118: @code{show-state} is to print a number that represents the current value
4119: of @code{state}.
1.28 crook 4120:
1.29 crook 4121: When you execute @code{word1}, it prints the number 0, indicating that
4122: the system is interpreting. When the text interpreter compiled the
4123: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4124: compilation semantics are to append its interpretation semantics to the
1.29 crook 4125: current definition. When you execute @code{word1}, it performs the
1.30 anton 4126: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4127: (and therefore @code{show-state}) are executed, the system is
4128: interpreting.
1.28 crook 4129:
1.30 anton 4130: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4131: you should have seen the number -1 printed, followed by ``@code{
4132: ok}''. When the text interpreter compiled the definition of
4133: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4134: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4135: semantics. It is executed straight away (even before the text
4136: interpreter has moved on to process another group of characters; the
4137: @code{;} in this example). The effect of executing it are to display the
4138: value of @code{state} @i{at the time that the definition of}
4139: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4140: system is compiling at this time. If you execute @code{word2} it does
4141: nothing at all.
1.28 crook 4142:
1.29 crook 4143: @cindex @code{."}, how it works
4144: Before leaving the subject of immediate words, consider the behaviour of
4145: @code{."} in the definition of @code{greet}, in the previous
4146: section. This word is both a parsing word and an immediate word. Notice
4147: that there is a space between @code{."} and the start of the text
4148: @code{Hello and welcome}, but that there is no space between the last
4149: letter of @code{welcome} and the @code{"} character. The reason for this
4150: is that @code{."} is a Forth word; it must have a space after it so that
4151: the text interpreter can identify it. The @code{"} is not a Forth word;
4152: it is a @dfn{delimiter}. The examples earlier show that, when the string
4153: is displayed, there is neither a space before the @code{H} nor after the
4154: @code{e}. Since @code{."} is an immediate word, it executes at the time
4155: that @code{greet} is defined. When it executes, its behaviour is to
4156: search forward in the input line looking for the delimiter. When it
4157: finds the delimiter, it updates @code{>IN} to point past the
4158: delimiter. It also compiles some magic code into the definition of
4159: @code{greet}; the xt of a run-time routine that prints a text string. It
4160: compiles the string @code{Hello and welcome} into memory so that it is
4161: available to be printed later. When the text interpreter gains control,
4162: the next word it finds in the input stream is @code{;} and so it
4163: terminates the definition of @code{greet}.
1.28 crook 4164:
4165:
4166: @comment ----------------------------------------------
1.29 crook 4167: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4168: @section Forth is written in Forth
4169: @cindex structure of Forth programs
4170:
4171: When you start up a Forth compiler, a large number of definitions
4172: already exist. In Forth, you develop a new application using bottom-up
4173: programming techniques to create new definitions that are defined in
4174: terms of existing definitions. As you create each definition you can
4175: test and debug it interactively.
4176:
4177: If you have tried out the examples in this section, you will probably
4178: have typed them in by hand; when you leave Gforth, your definitions will
4179: be lost. You can avoid this by using a text editor to enter Forth source
4180: code into a file, and then loading code from the file using
1.49 anton 4181: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4182: processed by the text interpreter, just as though you had typed it in by
4183: hand@footnote{Actually, there are some subtle differences -- see
4184: @ref{The Text Interpreter}.}.
4185:
4186: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4187: files for program entry (@pxref{Blocks}).
1.28 crook 4188:
1.29 crook 4189: In common with many, if not most, Forth compilers, most of Gforth is
4190: actually written in Forth. All of the @file{.fs} files in the
4191: installation directory@footnote{For example,
1.30 anton 4192: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4193: study to see examples of Forth programming.
1.28 crook 4194:
1.29 crook 4195: Gforth maintains a history file that records every line that you type to
4196: the text interpreter. This file is preserved between sessions, and is
4197: used to provide a command-line recall facility. If you enter long
4198: definitions by hand, you can use a text editor to paste them out of the
4199: history file into a Forth source file for reuse at a later time
1.49 anton 4200: (for more information @pxref{Command-line editing}).
1.28 crook 4201:
4202:
4203: @comment ----------------------------------------------
1.29 crook 4204: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4205: @section Review - elements of a Forth system
4206: @cindex elements of a Forth system
1.28 crook 4207:
1.29 crook 4208: To summarise this chapter:
1.28 crook 4209:
4210: @itemize @bullet
4211: @item
1.29 crook 4212: Forth programs use @dfn{factoring} to break a problem down into small
4213: fragments called @dfn{words} or @dfn{definitions}.
4214: @item
4215: Forth program development is an interactive process.
4216: @item
4217: The main command loop that accepts input, and controls both
4218: interpretation and compilation, is called the @dfn{text interpreter}
4219: (also known as the @dfn{outer interpreter}).
4220: @item
4221: Forth has a very simple syntax, consisting of words and numbers
4222: separated by spaces or carriage-return characters. Any additional syntax
4223: is imposed by @dfn{parsing words}.
4224: @item
4225: Forth uses a stack to pass parameters between words. As a result, it
4226: uses postfix notation.
4227: @item
4228: To use a word that has previously been defined, the text interpreter
4229: searches for the word in the @dfn{name dictionary}.
4230: @item
1.30 anton 4231: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4232: @item
1.29 crook 4233: The text interpreter uses the value of @code{state} to select between
4234: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4235: semantics} of a word that it encounters.
1.28 crook 4236: @item
1.30 anton 4237: The relationship between the @dfn{interpretation semantics} and
4238: @dfn{compilation semantics} for a word
1.29 crook 4239: depend upon the way in which the word was defined (for example, whether
4240: it is an @dfn{immediate} word).
1.28 crook 4241: @item
1.29 crook 4242: Forth definitions can be implemented in Forth (called @dfn{high-level
4243: definitions}) or in some other way (usually a lower-level language and
4244: as a result often called @dfn{low-level definitions}, @dfn{code
4245: definitions} or @dfn{primitives}).
1.28 crook 4246: @item
1.29 crook 4247: Many Forth systems are implemented mainly in Forth.
1.28 crook 4248: @end itemize
4249:
4250:
1.29 crook 4251: @comment ----------------------------------------------
1.48 anton 4252: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4253: @section Where To Go Next
4254: @cindex where to go next
1.28 crook 4255:
1.29 crook 4256: Amazing as it may seem, if you have read (and understood) this far, you
4257: know almost all the fundamentals about the inner workings of a Forth
4258: system. You certainly know enough to be able to read and understand the
4259: rest of this manual and the ANS Forth document, to learn more about the
4260: facilities that Forth in general and Gforth in particular provide. Even
4261: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4262: However, that's not a good idea just yet... better to try writing some
1.29 crook 4263: programs in Gforth.
1.28 crook 4264:
1.29 crook 4265: Forth has such a rich vocabulary that it can be hard to know where to
4266: start in learning it. This section suggests a few sets of words that are
4267: enough to write small but useful programs. Use the word index in this
4268: document to learn more about each word, then try it out and try to write
4269: small definitions using it. Start by experimenting with these words:
1.28 crook 4270:
4271: @itemize @bullet
4272: @item
1.29 crook 4273: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4274: @item
4275: Comparison: @code{MIN MAX =}
4276: @item
4277: Logic: @code{AND OR XOR NOT}
4278: @item
4279: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4280: @item
1.29 crook 4281: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4282: @item
1.29 crook 4283: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4284: @item
1.29 crook 4285: Defining words: @code{: ; CREATE}
1.28 crook 4286: @item
1.29 crook 4287: Memory allocation words: @code{ALLOT ,}
1.28 crook 4288: @item
1.29 crook 4289: Tools: @code{SEE WORDS .S MARKER}
4290: @end itemize
4291:
4292: When you have mastered those, go on to:
4293:
4294: @itemize @bullet
1.28 crook 4295: @item
1.29 crook 4296: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4297: @item
1.29 crook 4298: Memory access: @code{@@ !}
1.28 crook 4299: @end itemize
1.23 crook 4300:
1.29 crook 4301: When you have mastered these, there's nothing for it but to read through
4302: the whole of this manual and find out what you've missed.
4303:
4304: @comment ----------------------------------------------
1.48 anton 4305: @node Exercises, , Where to go next, Introduction
1.29 crook 4306: @section Exercises
4307: @cindex exercises
4308:
4309: TODO: provide a set of programming excercises linked into the stuff done
4310: already and into other sections of the manual. Provide solutions to all
4311: the exercises in a .fs file in the distribution.
4312:
4313: @c Get some inspiration from Starting Forth and Kelly&Spies.
4314:
4315: @c excercises:
4316: @c 1. take inches and convert to feet and inches.
4317: @c 2. take temperature and convert from fahrenheight to celcius;
4318: @c may need to care about symmetric vs floored??
4319: @c 3. take input line and do character substitution
4320: @c to encipher or decipher
4321: @c 4. as above but work on a file for in and out
4322: @c 5. take input line and convert to pig-latin
4323: @c
4324: @c thing of sets of things to exercise then come up with
4325: @c problems that need those things.
4326:
4327:
1.26 crook 4328: @c ******************************************************************
1.29 crook 4329: @node Words, Error messages, Introduction, Top
1.1 anton 4330: @chapter Forth Words
1.26 crook 4331: @cindex words
1.1 anton 4332:
4333: @menu
4334: * Notation::
1.65 anton 4335: * Case insensitivity::
4336: * Comments::
4337: * Boolean Flags::
1.1 anton 4338: * Arithmetic::
4339: * Stack Manipulation::
1.5 anton 4340: * Memory::
1.1 anton 4341: * Control Structures::
4342: * Defining Words::
1.65 anton 4343: * Interpretation and Compilation Semantics::
1.47 crook 4344: * Tokens for Words::
1.81 anton 4345: * Compiling words::
1.65 anton 4346: * The Text Interpreter::
1.111 anton 4347: * The Input Stream::
1.65 anton 4348: * Word Lists::
4349: * Environmental Queries::
1.12 anton 4350: * Files::
4351: * Blocks::
4352: * Other I/O::
1.121 anton 4353: * OS command line arguments::
1.78 anton 4354: * Locals::
4355: * Structures::
4356: * Object-oriented Forth::
1.12 anton 4357: * Programming Tools::
1.150 anton 4358: * C Interface::
1.12 anton 4359: * Assembler and Code Words::
4360: * Threading Words::
1.65 anton 4361: * Passing Commands to the OS::
4362: * Keeping track of Time::
4363: * Miscellaneous Words::
1.1 anton 4364: @end menu
4365:
1.65 anton 4366: @node Notation, Case insensitivity, Words, Words
1.1 anton 4367: @section Notation
4368: @cindex notation of glossary entries
4369: @cindex format of glossary entries
4370: @cindex glossary notation format
4371: @cindex word glossary entry format
4372:
4373: The Forth words are described in this section in the glossary notation
1.67 anton 4374: that has become a de-facto standard for Forth texts:
1.1 anton 4375:
4376: @format
1.29 crook 4377: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4378: @end format
1.29 crook 4379: @i{Description}
1.1 anton 4380:
4381: @table @var
4382: @item word
1.28 crook 4383: The name of the word.
1.1 anton 4384:
4385: @item Stack effect
4386: @cindex stack effect
1.29 crook 4387: The stack effect is written in the notation @code{@i{before} --
4388: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4389: stack entries before and after the execution of the word. The rest of
4390: the stack is not touched by the word. The top of stack is rightmost,
4391: i.e., a stack sequence is written as it is typed in. Note that Gforth
4392: uses a separate floating point stack, but a unified stack
1.29 crook 4393: notation. Also, return stack effects are not shown in @i{stack
4394: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4395: the type and/or the function of the item. See below for a discussion of
4396: the types.
4397:
4398: All words have two stack effects: A compile-time stack effect and a
4399: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4400: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4401: this standard behaviour, or the word does other unusual things at
4402: compile time, both stack effects are shown; otherwise only the run-time
4403: stack effect is shown.
4404:
4405: @cindex pronounciation of words
4406: @item pronunciation
4407: How the word is pronounced.
4408:
4409: @cindex wordset
1.67 anton 4410: @cindex environment wordset
1.1 anton 4411: @item wordset
1.21 crook 4412: The ANS Forth standard is divided into several word sets. A standard
4413: system need not support all of them. Therefore, in theory, the fewer
4414: word sets your program uses the more portable it will be. However, we
4415: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4416: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4417: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4418: describes words that will work in future releases of Gforth;
4419: @code{gforth-internal} words are more volatile. Environmental query
4420: strings are also displayed like words; you can recognize them by the
1.21 crook 4421: @code{environment} in the word set field.
1.1 anton 4422:
4423: @item Description
4424: A description of the behaviour of the word.
4425: @end table
4426:
4427: @cindex types of stack items
4428: @cindex stack item types
4429: The type of a stack item is specified by the character(s) the name
4430: starts with:
4431:
4432: @table @code
4433: @item f
4434: @cindex @code{f}, stack item type
4435: Boolean flags, i.e. @code{false} or @code{true}.
4436: @item c
4437: @cindex @code{c}, stack item type
4438: Char
4439: @item w
4440: @cindex @code{w}, stack item type
4441: Cell, can contain an integer or an address
4442: @item n
4443: @cindex @code{n}, stack item type
4444: signed integer
4445: @item u
4446: @cindex @code{u}, stack item type
4447: unsigned integer
4448: @item d
4449: @cindex @code{d}, stack item type
4450: double sized signed integer
4451: @item ud
4452: @cindex @code{ud}, stack item type
4453: double sized unsigned integer
4454: @item r
4455: @cindex @code{r}, stack item type
4456: Float (on the FP stack)
1.21 crook 4457: @item a-
1.1 anton 4458: @cindex @code{a_}, stack item type
4459: Cell-aligned address
1.21 crook 4460: @item c-
1.1 anton 4461: @cindex @code{c_}, stack item type
4462: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4463: @item f-
1.1 anton 4464: @cindex @code{f_}, stack item type
4465: Float-aligned address
1.21 crook 4466: @item df-
1.1 anton 4467: @cindex @code{df_}, stack item type
4468: Address aligned for IEEE double precision float
1.21 crook 4469: @item sf-
1.1 anton 4470: @cindex @code{sf_}, stack item type
4471: Address aligned for IEEE single precision float
4472: @item xt
4473: @cindex @code{xt}, stack item type
4474: Execution token, same size as Cell
4475: @item wid
4476: @cindex @code{wid}, stack item type
1.21 crook 4477: Word list ID, same size as Cell
1.68 anton 4478: @item ior, wior
4479: @cindex ior type description
4480: @cindex wior type description
4481: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4482: @item f83name
4483: @cindex @code{f83name}, stack item type
4484: Pointer to a name structure
4485: @item "
4486: @cindex @code{"}, stack item type
1.12 anton 4487: string in the input stream (not on the stack). The terminating character
4488: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4489: quotes.
4490: @end table
4491:
1.65 anton 4492: @comment ----------------------------------------------
4493: @node Case insensitivity, Comments, Notation, Words
4494: @section Case insensitivity
4495: @cindex case sensitivity
4496: @cindex upper and lower case
4497:
4498: Gforth is case-insensitive; you can enter definitions and invoke
4499: Standard words using upper, lower or mixed case (however,
4500: @pxref{core-idef, Implementation-defined options, Implementation-defined
4501: options}).
4502:
4503: ANS Forth only @i{requires} implementations to recognise Standard words
4504: when they are typed entirely in upper case. Therefore, a Standard
4505: program must use upper case for all Standard words. You can use whatever
4506: case you like for words that you define, but in a Standard program you
4507: have to use the words in the same case that you defined them.
4508:
4509: Gforth supports case sensitivity through @code{table}s (case-sensitive
4510: wordlists, @pxref{Word Lists}).
4511:
4512: Two people have asked how to convert Gforth to be case-sensitive; while
4513: we think this is a bad idea, you can change all wordlists into tables
4514: like this:
4515:
4516: @example
4517: ' table-find forth-wordlist wordlist-map @ !
4518: @end example
4519:
4520: Note that you now have to type the predefined words in the same case
4521: that we defined them, which are varying. You may want to convert them
4522: to your favourite case before doing this operation (I won't explain how,
4523: because if you are even contemplating doing this, you'd better have
4524: enough knowledge of Forth systems to know this already).
4525:
4526: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4527: @section Comments
1.26 crook 4528: @cindex comments
1.21 crook 4529:
1.29 crook 4530: Forth supports two styles of comment; the traditional @i{in-line} comment,
4531: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4532:
1.44 crook 4533:
1.23 crook 4534: doc-(
1.21 crook 4535: doc-\
1.23 crook 4536: doc-\G
1.21 crook 4537:
1.44 crook 4538:
1.21 crook 4539: @node Boolean Flags, Arithmetic, Comments, Words
4540: @section Boolean Flags
1.26 crook 4541: @cindex Boolean flags
1.21 crook 4542:
4543: A Boolean flag is cell-sized. A cell with all bits clear represents the
4544: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4545: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4546: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4547: @c on and off to Memory?
4548: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4549:
1.21 crook 4550: doc-true
4551: doc-false
1.29 crook 4552: doc-on
4553: doc-off
1.21 crook 4554:
1.44 crook 4555:
1.21 crook 4556: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4557: @section Arithmetic
4558: @cindex arithmetic words
4559:
4560: @cindex division with potentially negative operands
4561: Forth arithmetic is not checked, i.e., you will not hear about integer
4562: overflow on addition or multiplication, you may hear about division by
4563: zero if you are lucky. The operator is written after the operands, but
4564: the operands are still in the original order. I.e., the infix @code{2-1}
4565: corresponds to @code{2 1 -}. Forth offers a variety of division
4566: operators. If you perform division with potentially negative operands,
4567: you do not want to use @code{/} or @code{/mod} with its undefined
4568: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4569: former, @pxref{Mixed precision}).
1.26 crook 4570: @comment TODO discuss the different division forms and the std approach
1.1 anton 4571:
4572: @menu
4573: * Single precision::
1.67 anton 4574: * Double precision:: Double-cell integer arithmetic
1.1 anton 4575: * Bitwise operations::
1.67 anton 4576: * Numeric comparison::
1.29 crook 4577: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4578: * Floating Point::
4579: @end menu
4580:
1.67 anton 4581: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4582: @subsection Single precision
4583: @cindex single precision arithmetic words
4584:
1.67 anton 4585: @c !! cell undefined
4586:
4587: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4588: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4589: treat them. For the rules used by the text interpreter for recognising
4590: single-precision integers see @ref{Number Conversion}.
1.21 crook 4591:
1.67 anton 4592: These words are all defined for signed operands, but some of them also
4593: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4594: @code{*}.
1.44 crook 4595:
1.1 anton 4596: doc-+
1.21 crook 4597: doc-1+
1.128 anton 4598: doc-under+
1.1 anton 4599: doc--
1.21 crook 4600: doc-1-
1.1 anton 4601: doc-*
4602: doc-/
4603: doc-mod
4604: doc-/mod
4605: doc-negate
4606: doc-abs
4607: doc-min
4608: doc-max
1.27 crook 4609: doc-floored
1.1 anton 4610:
1.44 crook 4611:
1.67 anton 4612: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4613: @subsection Double precision
4614: @cindex double precision arithmetic words
4615:
1.49 anton 4616: For the rules used by the text interpreter for
4617: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4618:
4619: A double precision number is represented by a cell pair, with the most
1.67 anton 4620: significant cell at the TOS. It is trivial to convert an unsigned single
4621: to a double: simply push a @code{0} onto the TOS. Since numbers are
4622: represented by Gforth using 2's complement arithmetic, converting a
4623: signed single to a (signed) double requires sign-extension across the
4624: most significant cell. This can be achieved using @code{s>d}. The moral
4625: of the story is that you cannot convert a number without knowing whether
4626: it represents an unsigned or a signed number.
1.21 crook 4627:
1.67 anton 4628: These words are all defined for signed operands, but some of them also
4629: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4630:
1.21 crook 4631: doc-s>d
1.67 anton 4632: doc-d>s
1.21 crook 4633: doc-d+
4634: doc-d-
4635: doc-dnegate
4636: doc-dabs
4637: doc-dmin
4638: doc-dmax
4639:
1.44 crook 4640:
1.67 anton 4641: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4642: @subsection Bitwise operations
4643: @cindex bitwise operation words
4644:
4645:
4646: doc-and
4647: doc-or
4648: doc-xor
4649: doc-invert
4650: doc-lshift
4651: doc-rshift
4652: doc-2*
4653: doc-d2*
4654: doc-2/
4655: doc-d2/
4656:
4657:
4658: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4659: @subsection Numeric comparison
4660: @cindex numeric comparison words
4661:
1.67 anton 4662: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4663: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4664:
1.28 crook 4665: doc-<
4666: doc-<=
4667: doc-<>
4668: doc-=
4669: doc->
4670: doc->=
4671:
1.21 crook 4672: doc-0<
1.23 crook 4673: doc-0<=
1.21 crook 4674: doc-0<>
4675: doc-0=
1.23 crook 4676: doc-0>
4677: doc-0>=
1.28 crook 4678:
4679: doc-u<
4680: doc-u<=
1.44 crook 4681: @c u<> and u= exist but are the same as <> and =
1.31 anton 4682: @c doc-u<>
4683: @c doc-u=
1.28 crook 4684: doc-u>
4685: doc-u>=
4686:
4687: doc-within
4688:
4689: doc-d<
4690: doc-d<=
4691: doc-d<>
4692: doc-d=
4693: doc-d>
4694: doc-d>=
1.23 crook 4695:
1.21 crook 4696: doc-d0<
1.23 crook 4697: doc-d0<=
4698: doc-d0<>
1.21 crook 4699: doc-d0=
1.23 crook 4700: doc-d0>
4701: doc-d0>=
4702:
1.21 crook 4703: doc-du<
1.28 crook 4704: doc-du<=
1.44 crook 4705: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4706: @c doc-du<>
4707: @c doc-du=
1.28 crook 4708: doc-du>
4709: doc-du>=
1.1 anton 4710:
1.44 crook 4711:
1.21 crook 4712: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4713: @subsection Mixed precision
4714: @cindex mixed precision arithmetic words
4715:
1.44 crook 4716:
1.1 anton 4717: doc-m+
4718: doc-*/
4719: doc-*/mod
4720: doc-m*
4721: doc-um*
4722: doc-m*/
4723: doc-um/mod
4724: doc-fm/mod
4725: doc-sm/rem
4726:
1.44 crook 4727:
1.21 crook 4728: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4729: @subsection Floating Point
4730: @cindex floating point arithmetic words
4731:
1.49 anton 4732: For the rules used by the text interpreter for
4733: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4734:
1.67 anton 4735: Gforth has a separate floating point stack, but the documentation uses
4736: the unified notation.@footnote{It's easy to generate the separate
4737: notation from that by just separating the floating-point numbers out:
4738: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4739: r3 )}.}
1.1 anton 4740:
4741: @cindex floating-point arithmetic, pitfalls
4742: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4743: unwary (e.g., floating point addition is not associative) and even a
4744: few for the wary. You should not use them unless you know what you are
4745: doing or you don't care that the results you get are totally bogus. If
4746: you want to learn about the problems of floating point numbers (and
4747: how to avoid them), you might start with @cite{David Goldberg,
4748: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4749: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4750: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4751:
1.44 crook 4752:
1.21 crook 4753: doc-d>f
4754: doc-f>d
1.1 anton 4755: doc-f+
4756: doc-f-
4757: doc-f*
4758: doc-f/
4759: doc-fnegate
4760: doc-fabs
4761: doc-fmax
4762: doc-fmin
4763: doc-floor
4764: doc-fround
4765: doc-f**
4766: doc-fsqrt
4767: doc-fexp
4768: doc-fexpm1
4769: doc-fln
4770: doc-flnp1
4771: doc-flog
4772: doc-falog
1.32 anton 4773: doc-f2*
4774: doc-f2/
4775: doc-1/f
4776: doc-precision
4777: doc-set-precision
4778:
4779: @cindex angles in trigonometric operations
4780: @cindex trigonometric operations
4781: Angles in floating point operations are given in radians (a full circle
4782: has 2 pi radians).
4783:
1.1 anton 4784: doc-fsin
4785: doc-fcos
4786: doc-fsincos
4787: doc-ftan
4788: doc-fasin
4789: doc-facos
4790: doc-fatan
4791: doc-fatan2
4792: doc-fsinh
4793: doc-fcosh
4794: doc-ftanh
4795: doc-fasinh
4796: doc-facosh
4797: doc-fatanh
1.21 crook 4798: doc-pi
1.28 crook 4799:
1.32 anton 4800: @cindex equality of floats
4801: @cindex floating-point comparisons
1.31 anton 4802: One particular problem with floating-point arithmetic is that comparison
4803: for equality often fails when you would expect it to succeed. For this
4804: reason approximate equality is often preferred (but you still have to
1.67 anton 4805: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4806: differently from what you might expect. The comparison words are:
1.31 anton 4807:
4808: doc-f~rel
4809: doc-f~abs
1.68 anton 4810: doc-f~
1.31 anton 4811: doc-f=
4812: doc-f<>
4813:
4814: doc-f<
4815: doc-f<=
4816: doc-f>
4817: doc-f>=
4818:
1.21 crook 4819: doc-f0<
1.28 crook 4820: doc-f0<=
4821: doc-f0<>
1.21 crook 4822: doc-f0=
1.28 crook 4823: doc-f0>
4824: doc-f0>=
4825:
1.1 anton 4826:
4827: @node Stack Manipulation, Memory, Arithmetic, Words
4828: @section Stack Manipulation
4829: @cindex stack manipulation words
4830:
4831: @cindex floating-point stack in the standard
1.21 crook 4832: Gforth maintains a number of separate stacks:
4833:
1.29 crook 4834: @cindex data stack
4835: @cindex parameter stack
1.21 crook 4836: @itemize @bullet
4837: @item
1.29 crook 4838: A data stack (also known as the @dfn{parameter stack}) -- for
4839: characters, cells, addresses, and double cells.
1.21 crook 4840:
1.29 crook 4841: @cindex floating-point stack
1.21 crook 4842: @item
1.44 crook 4843: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4844:
1.29 crook 4845: @cindex return stack
1.21 crook 4846: @item
1.44 crook 4847: A return stack -- for holding the return addresses of colon
1.32 anton 4848: definitions and other (non-FP) data.
1.21 crook 4849:
1.29 crook 4850: @cindex locals stack
1.21 crook 4851: @item
1.44 crook 4852: A locals stack -- for holding local variables.
1.21 crook 4853: @end itemize
4854:
1.1 anton 4855: @menu
4856: * Data stack::
4857: * Floating point stack::
4858: * Return stack::
4859: * Locals stack::
4860: * Stack pointer manipulation::
4861: @end menu
4862:
4863: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4864: @subsection Data stack
4865: @cindex data stack manipulation words
4866: @cindex stack manipulations words, data stack
4867:
1.44 crook 4868:
1.1 anton 4869: doc-drop
4870: doc-nip
4871: doc-dup
4872: doc-over
4873: doc-tuck
4874: doc-swap
1.21 crook 4875: doc-pick
1.1 anton 4876: doc-rot
4877: doc--rot
4878: doc-?dup
4879: doc-roll
4880: doc-2drop
4881: doc-2nip
4882: doc-2dup
4883: doc-2over
4884: doc-2tuck
4885: doc-2swap
4886: doc-2rot
4887:
1.44 crook 4888:
1.1 anton 4889: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4890: @subsection Floating point stack
4891: @cindex floating-point stack manipulation words
4892: @cindex stack manipulation words, floating-point stack
4893:
1.32 anton 4894: Whilst every sane Forth has a separate floating-point stack, it is not
4895: strictly required; an ANS Forth system could theoretically keep
4896: floating-point numbers on the data stack. As an additional difficulty,
4897: you don't know how many cells a floating-point number takes. It is
4898: reportedly possible to write words in a way that they work also for a
4899: unified stack model, but we do not recommend trying it. Instead, just
4900: say that your program has an environmental dependency on a separate
4901: floating-point stack.
4902:
4903: doc-floating-stack
4904:
1.1 anton 4905: doc-fdrop
4906: doc-fnip
4907: doc-fdup
4908: doc-fover
4909: doc-ftuck
4910: doc-fswap
1.21 crook 4911: doc-fpick
1.1 anton 4912: doc-frot
4913:
1.44 crook 4914:
1.1 anton 4915: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4916: @subsection Return stack
4917: @cindex return stack manipulation words
4918: @cindex stack manipulation words, return stack
4919:
1.32 anton 4920: @cindex return stack and locals
4921: @cindex locals and return stack
4922: A Forth system is allowed to keep local variables on the
4923: return stack. This is reasonable, as local variables usually eliminate
4924: the need to use the return stack explicitly. So, if you want to produce
4925: a standard compliant program and you are using local variables in a
4926: word, forget about return stack manipulations in that word (refer to the
4927: standard document for the exact rules).
4928:
1.1 anton 4929: doc->r
4930: doc-r>
4931: doc-r@
4932: doc-rdrop
4933: doc-2>r
4934: doc-2r>
4935: doc-2r@
4936: doc-2rdrop
4937:
1.44 crook 4938:
1.1 anton 4939: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4940: @subsection Locals stack
4941:
1.78 anton 4942: Gforth uses an extra locals stack. It is described, along with the
4943: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4944:
1.1 anton 4945: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4946: @subsection Stack pointer manipulation
4947: @cindex stack pointer manipulation words
4948:
1.44 crook 4949: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4950: doc-sp0
1.1 anton 4951: doc-sp@
4952: doc-sp!
1.21 crook 4953: doc-fp0
1.1 anton 4954: doc-fp@
4955: doc-fp!
1.21 crook 4956: doc-rp0
1.1 anton 4957: doc-rp@
4958: doc-rp!
1.21 crook 4959: doc-lp0
1.1 anton 4960: doc-lp@
4961: doc-lp!
4962:
1.44 crook 4963:
1.1 anton 4964: @node Memory, Control Structures, Stack Manipulation, Words
4965: @section Memory
1.26 crook 4966: @cindex memory words
1.1 anton 4967:
1.32 anton 4968: @menu
4969: * Memory model::
4970: * Dictionary allocation::
4971: * Heap Allocation::
4972: * Memory Access::
4973: * Address arithmetic::
4974: * Memory Blocks::
4975: @end menu
4976:
1.67 anton 4977: In addition to the standard Forth memory allocation words, there is also
4978: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4979: garbage collector}.
4980:
1.32 anton 4981: @node Memory model, Dictionary allocation, Memory, Memory
4982: @subsection ANS Forth and Gforth memory models
4983:
4984: @c The ANS Forth description is a mess (e.g., is the heap part of
4985: @c the dictionary?), so let's not stick to closely with it.
4986:
1.67 anton 4987: ANS Forth considers a Forth system as consisting of several address
4988: spaces, of which only @dfn{data space} is managed and accessible with
4989: the memory words. Memory not necessarily in data space includes the
4990: stacks, the code (called code space) and the headers (called name
4991: space). In Gforth everything is in data space, but the code for the
4992: primitives is usually read-only.
1.32 anton 4993:
4994: Data space is divided into a number of areas: The (data space portion of
4995: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4996: refer to the search data structure embodied in word lists and headers,
4997: because it is used for looking up names, just as you would in a
4998: conventional dictionary.}, the heap, and a number of system-allocated
4999: buffers.
5000:
1.68 anton 5001: @cindex address arithmetic restrictions, ANS vs. Gforth
5002: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5003: In ANS Forth data space is also divided into contiguous regions. You
5004: can only use address arithmetic within a contiguous region, not between
5005: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5006: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5007: allocation}).
5008:
5009: Gforth provides one big address space, and address arithmetic can be
5010: performed between any addresses. However, in the dictionary headers or
5011: code are interleaved with data, so almost the only contiguous data space
5012: regions there are those described by ANS Forth as contiguous; but you
5013: can be sure that the dictionary is allocated towards increasing
5014: addresses even between contiguous regions. The memory order of
5015: allocations in the heap is platform-dependent (and possibly different
5016: from one run to the next).
5017:
1.27 crook 5018:
1.32 anton 5019: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5020: @subsection Dictionary allocation
1.27 crook 5021: @cindex reserving data space
5022: @cindex data space - reserving some
5023:
1.32 anton 5024: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5025: you want to deallocate X, you also deallocate everything
5026: allocated after X.
5027:
1.68 anton 5028: @cindex contiguous regions in dictionary allocation
1.32 anton 5029: The allocations using the words below are contiguous and grow the region
5030: towards increasing addresses. Other words that allocate dictionary
5031: memory of any kind (i.e., defining words including @code{:noname}) end
5032: the contiguous region and start a new one.
5033:
5034: In ANS Forth only @code{create}d words are guaranteed to produce an
5035: address that is the start of the following contiguous region. In
5036: particular, the cell allocated by @code{variable} is not guaranteed to
5037: be contiguous with following @code{allot}ed memory.
5038:
5039: You can deallocate memory by using @code{allot} with a negative argument
5040: (with some restrictions, see @code{allot}). For larger deallocations use
5041: @code{marker}.
1.27 crook 5042:
1.29 crook 5043:
1.27 crook 5044: doc-here
5045: doc-unused
5046: doc-allot
5047: doc-c,
1.29 crook 5048: doc-f,
1.27 crook 5049: doc-,
5050: doc-2,
5051:
1.32 anton 5052: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5053: course you should allocate memory in an aligned way, too. I.e., before
5054: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5055: The words below align @code{here} if it is not already. Basically it is
5056: only already aligned for a type, if the last allocation was a multiple
5057: of the size of this type and if @code{here} was aligned for this type
5058: before.
5059:
5060: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5061: ANS Forth (@code{maxalign}ed in Gforth).
5062:
5063: doc-align
5064: doc-falign
5065: doc-sfalign
5066: doc-dfalign
5067: doc-maxalign
5068: doc-cfalign
5069:
5070:
5071: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5072: @subsection Heap allocation
5073: @cindex heap allocation
5074: @cindex dynamic allocation of memory
5075: @cindex memory-allocation word set
5076:
1.68 anton 5077: @cindex contiguous regions and heap allocation
1.32 anton 5078: Heap allocation supports deallocation of allocated memory in any
5079: order. Dictionary allocation is not affected by it (i.e., it does not
5080: end a contiguous region). In Gforth, these words are implemented using
5081: the standard C library calls malloc(), free() and resize().
5082:
1.68 anton 5083: The memory region produced by one invocation of @code{allocate} or
5084: @code{resize} is internally contiguous. There is no contiguity between
5085: such a region and any other region (including others allocated from the
5086: heap).
5087:
1.32 anton 5088: doc-allocate
5089: doc-free
5090: doc-resize
5091:
1.27 crook 5092:
1.32 anton 5093: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5094: @subsection Memory Access
5095: @cindex memory access words
5096:
5097: doc-@
5098: doc-!
5099: doc-+!
5100: doc-c@
5101: doc-c!
5102: doc-2@
5103: doc-2!
5104: doc-f@
5105: doc-f!
5106: doc-sf@
5107: doc-sf!
5108: doc-df@
5109: doc-df!
1.144 anton 5110: doc-sw@
5111: doc-uw@
5112: doc-w!
5113: doc-sl@
5114: doc-ul@
5115: doc-l!
1.68 anton 5116:
1.32 anton 5117: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5118: @subsection Address arithmetic
1.1 anton 5119: @cindex address arithmetic words
5120:
1.67 anton 5121: Address arithmetic is the foundation on which you can build data
5122: structures like arrays, records (@pxref{Structures}) and objects
5123: (@pxref{Object-oriented Forth}).
1.32 anton 5124:
1.68 anton 5125: @cindex address unit
5126: @cindex au (address unit)
1.1 anton 5127: ANS Forth does not specify the sizes of the data types. Instead, it
5128: offers a number of words for computing sizes and doing address
1.29 crook 5129: arithmetic. Address arithmetic is performed in terms of address units
5130: (aus); on most systems the address unit is one byte. Note that a
5131: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5132: platforms where it is a noop, it compiles to nothing).
1.1 anton 5133:
1.67 anton 5134: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5135: you have the address of a cell, perform @code{1 cells +}, and you will
5136: have the address of the next cell.
5137:
1.68 anton 5138: @cindex contiguous regions and address arithmetic
1.67 anton 5139: In ANS Forth you can perform address arithmetic only within a contiguous
5140: region, i.e., if you have an address into one region, you can only add
5141: and subtract such that the result is still within the region; you can
5142: only subtract or compare addresses from within the same contiguous
5143: region. Reasons: several contiguous regions can be arranged in memory
5144: in any way; on segmented systems addresses may have unusual
5145: representations, such that address arithmetic only works within a
5146: region. Gforth provides a few more guarantees (linear address space,
5147: dictionary grows upwards), but in general I have found it easy to stay
5148: within contiguous regions (exception: computing and comparing to the
5149: address just beyond the end of an array).
5150:
1.1 anton 5151: @cindex alignment of addresses for types
5152: ANS Forth also defines words for aligning addresses for specific
5153: types. Many computers require that accesses to specific data types
5154: must only occur at specific addresses; e.g., that cells may only be
5155: accessed at addresses divisible by 4. Even if a machine allows unaligned
5156: accesses, it can usually perform aligned accesses faster.
5157:
5158: For the performance-conscious: alignment operations are usually only
5159: necessary during the definition of a data structure, not during the
5160: (more frequent) accesses to it.
5161:
5162: ANS Forth defines no words for character-aligning addresses. This is not
5163: an oversight, but reflects the fact that addresses that are not
5164: char-aligned have no use in the standard and therefore will not be
5165: created.
5166:
5167: @cindex @code{CREATE} and alignment
1.29 crook 5168: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5169: are cell-aligned; in addition, Gforth guarantees that these addresses
5170: are aligned for all purposes.
5171:
1.26 crook 5172: Note that the ANS Forth word @code{char} has nothing to do with address
5173: arithmetic.
1.1 anton 5174:
1.44 crook 5175:
1.1 anton 5176: doc-chars
5177: doc-char+
5178: doc-cells
5179: doc-cell+
5180: doc-cell
5181: doc-aligned
5182: doc-floats
5183: doc-float+
5184: doc-float
5185: doc-faligned
5186: doc-sfloats
5187: doc-sfloat+
5188: doc-sfaligned
5189: doc-dfloats
5190: doc-dfloat+
5191: doc-dfaligned
5192: doc-maxaligned
5193: doc-cfaligned
5194: doc-address-unit-bits
1.145 anton 5195: doc-/w
5196: doc-/l
1.44 crook 5197:
1.32 anton 5198: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5199: @subsection Memory Blocks
5200: @cindex memory block words
1.27 crook 5201: @cindex character strings - moving and copying
5202:
1.49 anton 5203: Memory blocks often represent character strings; For ways of storing
5204: character strings in memory see @ref{String Formats}. For other
5205: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5206:
1.67 anton 5207: A few of these words work on address unit blocks. In that case, you
5208: usually have to insert @code{CHARS} before the word when working on
5209: character strings. Most words work on character blocks, and expect a
5210: char-aligned address.
5211:
5212: When copying characters between overlapping memory regions, use
5213: @code{chars move} or choose carefully between @code{cmove} and
5214: @code{cmove>}.
1.44 crook 5215:
1.1 anton 5216: doc-move
5217: doc-erase
5218: doc-cmove
5219: doc-cmove>
5220: doc-fill
5221: doc-blank
1.21 crook 5222: doc-compare
1.111 anton 5223: doc-str=
5224: doc-str<
5225: doc-string-prefix?
1.21 crook 5226: doc-search
1.27 crook 5227: doc--trailing
5228: doc-/string
1.82 anton 5229: doc-bounds
1.141 anton 5230: doc-pad
1.111 anton 5231:
1.27 crook 5232: @comment TODO examples
5233:
1.1 anton 5234:
1.26 crook 5235: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5236: @section Control Structures
5237: @cindex control structures
5238:
1.33 anton 5239: Control structures in Forth cannot be used interpretively, only in a
5240: colon definition@footnote{To be precise, they have no interpretation
5241: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5242: not like this limitation, but have not seen a satisfying way around it
5243: yet, although many schemes have been proposed.
1.1 anton 5244:
5245: @menu
1.33 anton 5246: * Selection:: IF ... ELSE ... ENDIF
5247: * Simple Loops:: BEGIN ...
1.29 crook 5248: * Counted Loops:: DO
1.67 anton 5249: * Arbitrary control structures::
5250: * Calls and returns::
1.1 anton 5251: * Exception Handling::
5252: @end menu
5253:
5254: @node Selection, Simple Loops, Control Structures, Control Structures
5255: @subsection Selection
5256: @cindex selection control structures
5257: @cindex control structures for selection
5258:
5259: @cindex @code{IF} control structure
5260: @example
1.29 crook 5261: @i{flag}
1.1 anton 5262: IF
1.29 crook 5263: @i{code}
1.1 anton 5264: ENDIF
5265: @end example
1.21 crook 5266: @noindent
1.33 anton 5267:
1.44 crook 5268: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5269: with any bit set represents truth) @i{code} is executed.
1.33 anton 5270:
1.1 anton 5271: @example
1.29 crook 5272: @i{flag}
1.1 anton 5273: IF
1.29 crook 5274: @i{code1}
1.1 anton 5275: ELSE
1.29 crook 5276: @i{code2}
1.1 anton 5277: ENDIF
5278: @end example
5279:
1.44 crook 5280: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5281: executed.
1.33 anton 5282:
1.1 anton 5283: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5284: standard, and @code{ENDIF} is not, although it is quite popular. We
5285: recommend using @code{ENDIF}, because it is less confusing for people
5286: who also know other languages (and is not prone to reinforcing negative
5287: prejudices against Forth in these people). Adding @code{ENDIF} to a
5288: system that only supplies @code{THEN} is simple:
5289: @example
1.82 anton 5290: : ENDIF POSTPONE then ; immediate
1.1 anton 5291: @end example
5292:
5293: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5294: (adv.)} has the following meanings:
5295: @quotation
5296: ... 2b: following next after in order ... 3d: as a necessary consequence
5297: (if you were there, then you saw them).
5298: @end quotation
5299: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5300: and many other programming languages has the meaning 3d.]
5301:
1.21 crook 5302: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5303: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5304: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5305: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5306: @file{compat/control.fs}.
5307:
5308: @cindex @code{CASE} control structure
5309: @example
1.29 crook 5310: @i{n}
1.1 anton 5311: CASE
1.29 crook 5312: @i{n1} OF @i{code1} ENDOF
5313: @i{n2} OF @i{code2} ENDOF
1.1 anton 5314: @dots{}
1.68 anton 5315: ( n ) @i{default-code} ( n )
1.131 anton 5316: ENDCASE ( )
1.1 anton 5317: @end example
5318:
1.131 anton 5319: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5320: no @i{ni} matches, the optional @i{default-code} is executed. The
5321: optional default case can be added by simply writing the code after
5322: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5323: but must not consume it. The value @i{n} is consumed by this
5324: construction (either by a OF that matches, or by the ENDCASE, if no OF
5325: matches).
1.1 anton 5326:
1.69 anton 5327: @progstyle
1.131 anton 5328: To keep the code understandable, you should ensure that you change the
5329: stack in the same way (wrt. number and types of stack items consumed
5330: and pushed) on all paths through a selection construct.
1.69 anton 5331:
1.1 anton 5332: @node Simple Loops, Counted Loops, Selection, Control Structures
5333: @subsection Simple Loops
5334: @cindex simple loops
5335: @cindex loops without count
5336:
5337: @cindex @code{WHILE} loop
5338: @example
5339: BEGIN
1.29 crook 5340: @i{code1}
5341: @i{flag}
1.1 anton 5342: WHILE
1.29 crook 5343: @i{code2}
1.1 anton 5344: REPEAT
5345: @end example
5346:
1.29 crook 5347: @i{code1} is executed and @i{flag} is computed. If it is true,
5348: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5349: false, execution continues after the @code{REPEAT}.
5350:
5351: @cindex @code{UNTIL} loop
5352: @example
5353: BEGIN
1.29 crook 5354: @i{code}
5355: @i{flag}
1.1 anton 5356: UNTIL
5357: @end example
5358:
1.29 crook 5359: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5360:
1.69 anton 5361: @progstyle
5362: To keep the code understandable, a complete iteration of the loop should
5363: not change the number and types of the items on the stacks.
5364:
1.1 anton 5365: @cindex endless loop
5366: @cindex loops, endless
5367: @example
5368: BEGIN
1.29 crook 5369: @i{code}
1.1 anton 5370: AGAIN
5371: @end example
5372:
5373: This is an endless loop.
5374:
5375: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5376: @subsection Counted Loops
5377: @cindex counted loops
5378: @cindex loops, counted
5379: @cindex @code{DO} loops
5380:
5381: The basic counted loop is:
5382: @example
1.29 crook 5383: @i{limit} @i{start}
1.1 anton 5384: ?DO
1.29 crook 5385: @i{body}
1.1 anton 5386: LOOP
5387: @end example
5388:
1.29 crook 5389: This performs one iteration for every integer, starting from @i{start}
5390: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5391: accessed with @code{i}. For example, the loop:
1.1 anton 5392: @example
5393: 10 0 ?DO
5394: i .
5395: LOOP
5396: @end example
1.21 crook 5397: @noindent
5398: prints @code{0 1 2 3 4 5 6 7 8 9}
5399:
1.1 anton 5400: The index of the innermost loop can be accessed with @code{i}, the index
5401: of the next loop with @code{j}, and the index of the third loop with
5402: @code{k}.
5403:
1.44 crook 5404:
1.1 anton 5405: doc-i
5406: doc-j
5407: doc-k
5408:
1.44 crook 5409:
1.1 anton 5410: The loop control data are kept on the return stack, so there are some
1.21 crook 5411: restrictions on mixing return stack accesses and counted loop words. In
5412: particuler, if you put values on the return stack outside the loop, you
5413: cannot read them inside the loop@footnote{well, not in a way that is
5414: portable.}. If you put values on the return stack within a loop, you
5415: have to remove them before the end of the loop and before accessing the
5416: index of the loop.
1.1 anton 5417:
5418: There are several variations on the counted loop:
5419:
1.21 crook 5420: @itemize @bullet
5421: @item
5422: @code{LEAVE} leaves the innermost counted loop immediately; execution
5423: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5424:
5425: @example
5426: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5427: @end example
5428: prints @code{0 1 2 3}
5429:
1.1 anton 5430:
1.21 crook 5431: @item
5432: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5433: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5434: return stack so @code{EXIT} can get to its return address. For example:
5435:
5436: @example
5437: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5438: @end example
5439: prints @code{0 1 2 3}
5440:
5441:
5442: @item
1.29 crook 5443: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5444: (and @code{LOOP} iterates until they become equal by wrap-around
5445: arithmetic). This behaviour is usually not what you want. Therefore,
5446: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5447: @code{?DO}), which do not enter the loop if @i{start} is greater than
5448: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5449: unsigned loop parameters.
5450:
1.21 crook 5451: @item
5452: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5453: the loop, independent of the loop parameters. Do not use @code{DO}, even
5454: if you know that the loop is entered in any case. Such knowledge tends
5455: to become invalid during maintenance of a program, and then the
5456: @code{DO} will make trouble.
5457:
5458: @item
1.29 crook 5459: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5460: index by @i{n} instead of by 1. The loop is terminated when the border
5461: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5462:
1.21 crook 5463: @example
5464: 4 0 +DO i . 2 +LOOP
5465: @end example
5466: @noindent
5467: prints @code{0 2}
5468:
5469: @example
5470: 4 1 +DO i . 2 +LOOP
5471: @end example
5472: @noindent
5473: prints @code{1 3}
1.1 anton 5474:
1.68 anton 5475: @item
1.1 anton 5476: @cindex negative increment for counted loops
5477: @cindex counted loops with negative increment
1.29 crook 5478: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5479:
1.21 crook 5480: @example
5481: -1 0 ?DO i . -1 +LOOP
5482: @end example
5483: @noindent
5484: prints @code{0 -1}
1.1 anton 5485:
1.21 crook 5486: @example
5487: 0 0 ?DO i . -1 +LOOP
5488: @end example
5489: prints nothing.
1.1 anton 5490:
1.29 crook 5491: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5492: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5493: index by @i{u} each iteration. The loop is terminated when the border
5494: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5495: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5496:
1.21 crook 5497: @example
5498: -2 0 -DO i . 1 -LOOP
5499: @end example
5500: @noindent
5501: prints @code{0 -1}
1.1 anton 5502:
1.21 crook 5503: @example
5504: -1 0 -DO i . 1 -LOOP
5505: @end example
5506: @noindent
5507: prints @code{0}
5508:
5509: @example
5510: 0 0 -DO i . 1 -LOOP
5511: @end example
5512: @noindent
5513: prints nothing.
1.1 anton 5514:
1.21 crook 5515: @end itemize
1.1 anton 5516:
5517: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5518: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5519: for these words that uses only standard words is provided in
5520: @file{compat/loops.fs}.
1.1 anton 5521:
5522:
5523: @cindex @code{FOR} loops
1.26 crook 5524: Another counted loop is:
1.1 anton 5525: @example
1.29 crook 5526: @i{n}
1.1 anton 5527: FOR
1.29 crook 5528: @i{body}
1.1 anton 5529: NEXT
5530: @end example
5531: This is the preferred loop of native code compiler writers who are too
1.26 crook 5532: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5533: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5534: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5535: Forth systems may behave differently, even if they support @code{FOR}
5536: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5537:
5538: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5539: @subsection Arbitrary control structures
5540: @cindex control structures, user-defined
5541:
5542: @cindex control-flow stack
5543: ANS Forth permits and supports using control structures in a non-nested
5544: way. Information about incomplete control structures is stored on the
5545: control-flow stack. This stack may be implemented on the Forth data
5546: stack, and this is what we have done in Gforth.
5547:
5548: @cindex @code{orig}, control-flow stack item
5549: @cindex @code{dest}, control-flow stack item
5550: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5551: entry represents a backward branch target. A few words are the basis for
5552: building any control structure possible (except control structures that
5553: need storage, like calls, coroutines, and backtracking).
5554:
1.44 crook 5555:
1.1 anton 5556: doc-if
5557: doc-ahead
5558: doc-then
5559: doc-begin
5560: doc-until
5561: doc-again
5562: doc-cs-pick
5563: doc-cs-roll
5564:
1.44 crook 5565:
1.21 crook 5566: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5567: manipulate the control-flow stack in a portable way. Without them, you
5568: would need to know how many stack items are occupied by a control-flow
5569: entry (many systems use one cell. In Gforth they currently take three,
5570: but this may change in the future).
5571:
1.1 anton 5572: Some standard control structure words are built from these words:
5573:
1.44 crook 5574:
1.1 anton 5575: doc-else
5576: doc-while
5577: doc-repeat
5578:
1.44 crook 5579:
5580: @noindent
1.1 anton 5581: Gforth adds some more control-structure words:
5582:
1.44 crook 5583:
1.1 anton 5584: doc-endif
5585: doc-?dup-if
5586: doc-?dup-0=-if
5587:
1.44 crook 5588:
5589: @noindent
1.1 anton 5590: Counted loop words constitute a separate group of words:
5591:
1.44 crook 5592:
1.1 anton 5593: doc-?do
5594: doc-+do
5595: doc-u+do
5596: doc--do
5597: doc-u-do
5598: doc-do
5599: doc-for
5600: doc-loop
5601: doc-+loop
5602: doc--loop
5603: doc-next
5604: doc-leave
5605: doc-?leave
5606: doc-unloop
5607: doc-done
5608:
1.44 crook 5609:
1.21 crook 5610: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5611: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5612: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5613: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5614: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5615: resolved (by using one of the loop-ending words or @code{DONE}).
5616:
1.44 crook 5617: @noindent
1.26 crook 5618: Another group of control structure words are:
1.1 anton 5619:
1.44 crook 5620:
1.1 anton 5621: doc-case
5622: doc-endcase
5623: doc-of
5624: doc-endof
5625:
1.44 crook 5626:
1.21 crook 5627: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5628: @code{CS-ROLL}.
1.1 anton 5629:
5630: @subsubsection Programming Style
1.47 crook 5631: @cindex control structures programming style
5632: @cindex programming style, arbitrary control structures
1.1 anton 5633:
5634: In order to ensure readability we recommend that you do not create
5635: arbitrary control structures directly, but define new control structure
5636: words for the control structure you want and use these words in your
1.26 crook 5637: program. For example, instead of writing:
1.1 anton 5638:
5639: @example
1.26 crook 5640: BEGIN
1.1 anton 5641: ...
1.26 crook 5642: IF [ 1 CS-ROLL ]
1.1 anton 5643: ...
1.26 crook 5644: AGAIN THEN
1.1 anton 5645: @end example
5646:
1.21 crook 5647: @noindent
1.1 anton 5648: we recommend defining control structure words, e.g.,
5649:
5650: @example
1.26 crook 5651: : WHILE ( DEST -- ORIG DEST )
5652: POSTPONE IF
5653: 1 CS-ROLL ; immediate
5654:
5655: : REPEAT ( orig dest -- )
5656: POSTPONE AGAIN
5657: POSTPONE THEN ; immediate
1.1 anton 5658: @end example
5659:
1.21 crook 5660: @noindent
1.1 anton 5661: and then using these to create the control structure:
5662:
5663: @example
1.26 crook 5664: BEGIN
1.1 anton 5665: ...
1.26 crook 5666: WHILE
1.1 anton 5667: ...
1.26 crook 5668: REPEAT
1.1 anton 5669: @end example
5670:
5671: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5672: @code{WHILE} are predefined, so in this example it would not be
5673: necessary to define them.
5674:
5675: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5676: @subsection Calls and returns
5677: @cindex calling a definition
5678: @cindex returning from a definition
5679:
1.3 anton 5680: @cindex recursive definitions
5681: A definition can be called simply be writing the name of the definition
1.26 crook 5682: to be called. Normally a definition is invisible during its own
1.3 anton 5683: definition. If you want to write a directly recursive definition, you
1.26 crook 5684: can use @code{recursive} to make the current definition visible, or
5685: @code{recurse} to call the current definition directly.
1.3 anton 5686:
1.44 crook 5687:
1.3 anton 5688: doc-recursive
5689: doc-recurse
5690:
1.44 crook 5691:
1.21 crook 5692: @comment TODO add example of the two recursion methods
1.12 anton 5693: @quotation
5694: @progstyle
5695: I prefer using @code{recursive} to @code{recurse}, because calling the
5696: definition by name is more descriptive (if the name is well-chosen) than
5697: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5698: implementation, it is much better to read (and think) ``now sort the
5699: partitions'' than to read ``now do a recursive call''.
5700: @end quotation
1.3 anton 5701:
1.29 crook 5702: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5703:
5704: @example
1.28 crook 5705: Defer foo
1.3 anton 5706:
5707: : bar ( ... -- ... )
5708: ... foo ... ;
5709:
5710: :noname ( ... -- ... )
5711: ... bar ... ;
5712: IS foo
5713: @end example
5714:
1.170 pazsan 5715: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5716:
1.26 crook 5717: The current definition returns control to the calling definition when
1.33 anton 5718: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5719:
5720: doc-exit
5721: doc-;s
5722:
1.44 crook 5723:
1.1 anton 5724: @node Exception Handling, , Calls and returns, Control Structures
5725: @subsection Exception Handling
1.26 crook 5726: @cindex exceptions
1.1 anton 5727:
1.68 anton 5728: @c quit is a very bad idea for error handling,
5729: @c because it does not translate into a THROW
5730: @c it also does not belong into this chapter
5731:
5732: If a word detects an error condition that it cannot handle, it can
5733: @code{throw} an exception. In the simplest case, this will terminate
5734: your program, and report an appropriate error.
1.21 crook 5735:
1.68 anton 5736: doc-throw
1.1 anton 5737:
1.69 anton 5738: @code{Throw} consumes a cell-sized error number on the stack. There are
5739: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5740: Gforth (and most other systems) you can use the iors produced by various
5741: words as error numbers (e.g., a typical use of @code{allocate} is
5742: @code{allocate throw}). Gforth also provides the word @code{exception}
5743: to define your own error numbers (with decent error reporting); an ANS
5744: Forth version of this word (but without the error messages) is available
5745: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5746: numbers (anything outside the range -4095..0), but won't get nice error
5747: messages, only numbers. For example, try:
5748:
5749: @example
1.69 anton 5750: -10 throw \ ANS defined
5751: -267 throw \ system defined
5752: s" my error" exception throw \ user defined
5753: 7 throw \ arbitrary number
1.68 anton 5754: @end example
5755:
5756: doc---exception-exception
1.1 anton 5757:
1.69 anton 5758: A common idiom to @code{THROW} a specific error if a flag is true is
5759: this:
5760:
5761: @example
5762: @code{( flag ) 0<> @i{errno} and throw}
5763: @end example
5764:
5765: Your program can provide exception handlers to catch exceptions. An
5766: exception handler can be used to correct the problem, or to clean up
5767: some data structures and just throw the exception to the next exception
5768: handler. Note that @code{throw} jumps to the dynamically innermost
5769: exception handler. The system's exception handler is outermost, and just
5770: prints an error and restarts command-line interpretation (or, in batch
5771: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5772:
1.68 anton 5773: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5774:
1.68 anton 5775: doc-catch
1.160 anton 5776: doc-nothrow
1.68 anton 5777:
5778: The most common use of exception handlers is to clean up the state when
5779: an error happens. E.g.,
1.1 anton 5780:
1.26 crook 5781: @example
1.68 anton 5782: base @ >r hex \ actually the hex should be inside foo, or we h
5783: ['] foo catch ( nerror|0 )
5784: r> base !
1.69 anton 5785: ( nerror|0 ) throw \ pass it on
1.26 crook 5786: @end example
1.1 anton 5787:
1.69 anton 5788: A use of @code{catch} for handling the error @code{myerror} might look
5789: like this:
1.44 crook 5790:
1.68 anton 5791: @example
1.69 anton 5792: ['] foo catch
5793: CASE
1.160 anton 5794: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5795: dup throw \ default: pass other errors on, do nothing on non-errors
5796: ENDCASE
1.68 anton 5797: @end example
1.44 crook 5798:
1.68 anton 5799: Having to wrap the code into a separate word is often cumbersome,
5800: therefore Gforth provides an alternative syntax:
1.1 anton 5801:
5802: @example
1.69 anton 5803: TRY
1.68 anton 5804: @i{code1}
1.172 anton 5805: IFERROR
5806: @i{code2}
5807: THEN
5808: @i{code3}
1.69 anton 5809: ENDTRY
1.1 anton 5810: @end example
5811:
1.172 anton 5812: This performs @i{code1}. If @i{code1} completes normally, execution
5813: continues with @i{code3}. If @i{code1} or there is an exception
5814: before @code{endtry}, the stacks are reset to the state during
5815: @code{try}, the throw value is pushed on the data stack, and execution
5816: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26 crook 5817:
1.68 anton 5818: doc-try
5819: doc-endtry
1.172 anton 5820: doc-iferror
5821:
5822: If you don't need @i{code2}, you can write @code{restore} instead of
5823: @code{iferror then}:
5824:
5825: @example
5826: TRY
5827: @i{code1}
5828: RESTORE
5829: @i{code3}
5830: ENDTRY
5831: @end example
1.26 crook 5832:
1.172 anton 5833: @cindex unwind-protect
1.69 anton 5834: The cleanup example from above in this syntax:
1.26 crook 5835:
1.68 anton 5836: @example
1.174 anton 5837: base @@ @{ oldbase @}
1.172 anton 5838: TRY
1.68 anton 5839: hex foo \ now the hex is placed correctly
1.69 anton 5840: 0 \ value for throw
1.172 anton 5841: RESTORE
5842: oldbase base !
5843: ENDTRY
5844: throw
1.1 anton 5845: @end example
5846:
1.172 anton 5847: An additional advantage of this variant is that an exception between
5848: @code{restore} and @code{endtry} (e.g., from the user pressing
5849: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5850: so the base will be restored under all circumstances.
5851:
5852: However, you have to ensure that this code does not cause an exception
5853: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5854: Moreover, you should also make sure that the stack contents needed by
5855: the @code{iferror}/@code{restore} code exist everywhere between
5856: @code{try} and @code{endtry}; in our example this is achived by
5857: putting the data in a local before the @code{try} (you cannot use the
5858: return stack because the exception frame (@i{sys1}) is in the way
5859: there).
5860:
5861: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5862:
5863: @cindex @code{recover} (old Gforth versions)
5864: If you do not want this exception-restarting behaviour, you achieve
5865: this as follows:
5866:
5867: @example
5868: TRY
5869: @i{code1}
5870: ENDTRY-IFERROR
5871: @i{code2}
5872: THEN
5873: @end example
5874:
5875: If there is an exception in @i{code1}, then @i{code2} is executed,
5876: otherwise execution continues behind the @code{then} (or in a possible
5877: @code{else} branch). This corresponds to the construct
5878:
5879: @example
5880: TRY
5881: @i{code1}
5882: RECOVER
5883: @i{code2}
5884: ENDTRY
5885: @end example
5886:
5887: in Gforth before version 0.7. So you can directly replace
5888: @code{recover}-using code; however, we recommend that you check if it
5889: would not be better to use one of the other @code{try} variants while
5890: you are at it.
5891:
1.173 anton 5892: To ease the transition, Gforth provides two compatibility files:
5893: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5894: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5895: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5896: ... endtry} syntax on new systems, so you can use that file as a
5897: stopgap to run old programs. Both files work on any system (they just
5898: do nothing if the system already has the syntax it implements), so you
5899: can unconditionally @code{require} one of these files, even if you use
5900: a mix old and new systems.
5901:
1.172 anton 5902: doc-restore
5903: doc-endtry-iferror
5904:
5905: Here's the error handling example:
1.1 anton 5906:
1.68 anton 5907: @example
1.69 anton 5908: TRY
1.68 anton 5909: foo
1.172 anton 5910: ENDTRY-IFERROR
1.69 anton 5911: CASE
1.160 anton 5912: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5913: throw \ pass other errors on
5914: ENDCASE
1.172 anton 5915: THEN
1.68 anton 5916: @end example
1.1 anton 5917:
1.69 anton 5918: @progstyle
5919: As usual, you should ensure that the stack depth is statically known at
5920: the end: either after the @code{throw} for passing on errors, or after
5921: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5922: selection construct for handling the error).
5923:
1.68 anton 5924: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5925: and you can provide an error message. @code{Abort} just produces an
5926: ``Aborted'' error.
1.1 anton 5927:
1.68 anton 5928: The problem with these words is that exception handlers cannot
5929: differentiate between different @code{abort"}s; they just look like
5930: @code{-2 throw} to them (the error message cannot be accessed by
5931: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5932: exception handlers.
1.44 crook 5933:
1.68 anton 5934: doc-abort"
1.26 crook 5935: doc-abort
1.29 crook 5936:
5937:
1.44 crook 5938:
1.29 crook 5939: @c -------------------------------------------------------------
1.47 crook 5940: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5941: @section Defining Words
5942: @cindex defining words
5943:
1.47 crook 5944: Defining words are used to extend Forth by creating new entries in the dictionary.
5945:
1.29 crook 5946: @menu
1.67 anton 5947: * CREATE::
1.44 crook 5948: * Variables:: Variables and user variables
1.67 anton 5949: * Constants::
1.44 crook 5950: * Values:: Initialised variables
1.67 anton 5951: * Colon Definitions::
1.44 crook 5952: * Anonymous Definitions:: Definitions without names
1.69 anton 5953: * Supplying names:: Passing definition names as strings
1.67 anton 5954: * User-defined Defining Words::
1.170 pazsan 5955: * Deferred Words:: Allow forward references
1.67 anton 5956: * Aliases::
1.29 crook 5957: @end menu
5958:
1.44 crook 5959: @node CREATE, Variables, Defining Words, Defining Words
5960: @subsection @code{CREATE}
1.29 crook 5961: @cindex simple defining words
5962: @cindex defining words, simple
5963:
5964: Defining words are used to create new entries in the dictionary. The
5965: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5966: this:
5967:
5968: @example
5969: CREATE new-word1
5970: @end example
5971:
1.69 anton 5972: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5973: input stream (@code{new-word1} in our example). It generates a
5974: dictionary entry for @code{new-word1}. When @code{new-word1} is
5975: executed, all that it does is leave an address on the stack. The address
5976: represents the value of the data space pointer (@code{HERE}) at the time
5977: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5978: associating a name with the address of a region of memory.
1.29 crook 5979:
1.34 anton 5980: doc-create
5981:
1.69 anton 5982: Note that in ANS Forth guarantees only for @code{create} that its body
5983: is in dictionary data space (i.e., where @code{here}, @code{allot}
5984: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5985: @code{create}d words can be modified with @code{does>}
5986: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5987: can only be applied to @code{create}d words.
5988:
1.29 crook 5989: By extending this example to reserve some memory in data space, we end
1.69 anton 5990: up with something like a @i{variable}. Here are two different ways to do
5991: it:
1.29 crook 5992:
5993: @example
5994: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5995: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5996: @end example
5997:
5998: The variable can be examined and modified using @code{@@} (``fetch'') and
5999: @code{!} (``store'') like this:
6000:
6001: @example
6002: new-word2 @@ . \ get address, fetch from it and display
6003: 1234 new-word2 ! \ new value, get address, store to it
6004: @end example
6005:
1.44 crook 6006: @cindex arrays
6007: A similar mechanism can be used to create arrays. For example, an
6008: 80-character text input buffer:
1.29 crook 6009:
6010: @example
1.44 crook 6011: CREATE text-buf 80 chars allot
6012:
1.168 anton 6013: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6014: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6015: @end example
1.29 crook 6016:
1.44 crook 6017: You can build arbitrarily complex data structures by allocating
1.49 anton 6018: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6019: learn about some Gforth tools that make it easier,
1.49 anton 6020: @xref{Structures}.
1.44 crook 6021:
6022:
6023: @node Variables, Constants, CREATE, Defining Words
6024: @subsection Variables
6025: @cindex variables
6026:
6027: The previous section showed how a sequence of commands could be used to
6028: generate a variable. As a final refinement, the whole code sequence can
6029: be wrapped up in a defining word (pre-empting the subject of the next
6030: section), making it easier to create new variables:
6031:
6032: @example
6033: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6034: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6035:
6036: myvariableX foo \ variable foo starts off with an unknown value
6037: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6038:
6039: 45 3 * foo ! \ set foo to 135
6040: 1234 joe ! \ set joe to 1234
6041: 3 joe +! \ increment joe by 3.. to 1237
6042: @end example
6043:
6044: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6045: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6046: guarantee that a @code{Variable} is initialised when it is created
6047: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6048: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6049: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6050: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6051: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6052: store a boolean, you can use @code{on} and @code{off} to toggle its
6053: state.
1.29 crook 6054:
1.34 anton 6055: doc-variable
6056: doc-2variable
6057: doc-fvariable
6058:
1.29 crook 6059: @cindex user variables
6060: @cindex user space
6061: The defining word @code{User} behaves in the same way as @code{Variable}.
6062: The difference is that it reserves space in @i{user (data) space} rather
6063: than normal data space. In a Forth system that has a multi-tasker, each
6064: task has its own set of user variables.
6065:
1.34 anton 6066: doc-user
1.67 anton 6067: @c doc-udp
6068: @c doc-uallot
1.34 anton 6069:
1.29 crook 6070: @comment TODO is that stuff about user variables strictly correct? Is it
6071: @comment just terminal tasks that have user variables?
6072: @comment should document tasker.fs (with some examples) elsewhere
6073: @comment in this manual, then expand on user space and user variables.
6074:
1.44 crook 6075: @node Constants, Values, Variables, Defining Words
6076: @subsection Constants
6077: @cindex constants
6078:
6079: @code{Constant} allows you to declare a fixed value and refer to it by
6080: name. For example:
1.29 crook 6081:
6082: @example
6083: 12 Constant INCHES-PER-FOOT
6084: 3E+08 fconstant SPEED-O-LIGHT
6085: @end example
6086:
6087: A @code{Variable} can be both read and written, so its run-time
6088: behaviour is to supply an address through which its current value can be
6089: manipulated. In contrast, the value of a @code{Constant} cannot be
6090: changed once it has been declared@footnote{Well, often it can be -- but
6091: not in a Standard, portable way. It's safer to use a @code{Value} (read
6092: on).} so it's not necessary to supply the address -- it is more
6093: efficient to return the value of the constant directly. That's exactly
6094: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6095: the top of the stack (You can find one
6096: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6097:
1.69 anton 6098: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6099: double and floating-point constants, respectively.
6100:
1.34 anton 6101: doc-constant
6102: doc-2constant
6103: doc-fconstant
6104:
6105: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6106: @c nac-> How could that not be true in an ANS Forth? You can't define a
6107: @c constant, use it and then delete the definition of the constant..
1.69 anton 6108:
6109: @c anton->An ANS Forth system can compile a constant to a literal; On
6110: @c decompilation you would see only the number, just as if it had been used
6111: @c in the first place. The word will stay, of course, but it will only be
6112: @c used by the text interpreter (no run-time duties, except when it is
6113: @c POSTPONEd or somesuch).
6114:
6115: @c nac:
1.44 crook 6116: @c I agree that it's rather deep, but IMO it is an important difference
6117: @c relative to other programming languages.. often it's annoying: it
6118: @c certainly changes my programming style relative to C.
6119:
1.69 anton 6120: @c anton: In what way?
6121:
1.29 crook 6122: Constants in Forth behave differently from their equivalents in other
6123: programming languages. In other languages, a constant (such as an EQU in
6124: assembler or a #define in C) only exists at compile-time; in the
6125: executable program the constant has been translated into an absolute
6126: number and, unless you are using a symbolic debugger, it's impossible to
6127: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6128: an entry in the header space and remains there after the code that uses
6129: it has been defined. In fact, it must remain in the dictionary since it
6130: has run-time duties to perform. For example:
1.29 crook 6131:
6132: @example
6133: 12 Constant INCHES-PER-FOOT
6134: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6135: @end example
6136:
6137: @cindex in-lining of constants
6138: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6139: associated with the constant @code{INCHES-PER-FOOT}. If you use
6140: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6141: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6142: attempt to optimise constants by in-lining them where they are used. You
6143: can force Gforth to in-line a constant like this:
6144:
6145: @example
6146: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6147: @end example
6148:
6149: If you use @code{see} to decompile @i{this} version of
6150: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6151: longer present. To understand how this works, read
6152: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6153:
6154: In-lining constants in this way might improve execution time
6155: fractionally, and can ensure that a constant is now only referenced at
6156: compile-time. However, the definition of the constant still remains in
6157: the dictionary. Some Forth compilers provide a mechanism for controlling
6158: a second dictionary for holding transient words such that this second
6159: dictionary can be deleted later in order to recover memory
6160: space. However, there is no standard way of doing this.
6161:
6162:
1.44 crook 6163: @node Values, Colon Definitions, Constants, Defining Words
6164: @subsection Values
6165: @cindex values
1.34 anton 6166:
1.69 anton 6167: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6168: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6169: (not in ANS Forth) you can access (and change) a @code{value} also with
6170: @code{>body}.
6171:
6172: Here are some
6173: examples:
1.29 crook 6174:
6175: @example
1.69 anton 6176: 12 Value APPLES \ Define APPLES with an initial value of 12
6177: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6178: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6179: APPLES \ puts 35 on the top of the stack.
1.29 crook 6180: @end example
6181:
1.44 crook 6182: doc-value
6183: doc-to
1.29 crook 6184:
1.35 anton 6185:
1.69 anton 6186:
1.44 crook 6187: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6188: @subsection Colon Definitions
6189: @cindex colon definitions
1.35 anton 6190:
6191: @example
1.44 crook 6192: : name ( ... -- ... )
6193: word1 word2 word3 ;
1.29 crook 6194: @end example
6195:
1.44 crook 6196: @noindent
6197: Creates a word called @code{name} that, upon execution, executes
6198: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6199:
1.49 anton 6200: The explanation above is somewhat superficial. For simple examples of
6201: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6202: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6203: Compilation Semantics}.
1.29 crook 6204:
1.44 crook 6205: doc-:
6206: doc-;
1.1 anton 6207:
1.34 anton 6208:
1.69 anton 6209: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6210: @subsection Anonymous Definitions
6211: @cindex colon definitions
6212: @cindex defining words without name
1.34 anton 6213:
1.44 crook 6214: Sometimes you want to define an @dfn{anonymous word}; a word without a
6215: name. You can do this with:
1.1 anton 6216:
1.44 crook 6217: doc-:noname
1.1 anton 6218:
1.44 crook 6219: This leaves the execution token for the word on the stack after the
6220: closing @code{;}. Here's an example in which a deferred word is
6221: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6222:
1.29 crook 6223: @example
1.44 crook 6224: Defer deferred
6225: :noname ( ... -- ... )
6226: ... ;
6227: IS deferred
1.29 crook 6228: @end example
1.26 crook 6229:
1.44 crook 6230: @noindent
6231: Gforth provides an alternative way of doing this, using two separate
6232: words:
1.27 crook 6233:
1.44 crook 6234: doc-noname
6235: @cindex execution token of last defined word
1.116 anton 6236: doc-latestxt
1.1 anton 6237:
1.44 crook 6238: @noindent
6239: The previous example can be rewritten using @code{noname} and
1.116 anton 6240: @code{latestxt}:
1.1 anton 6241:
1.26 crook 6242: @example
1.44 crook 6243: Defer deferred
6244: noname : ( ... -- ... )
6245: ... ;
1.116 anton 6246: latestxt IS deferred
1.26 crook 6247: @end example
1.1 anton 6248:
1.29 crook 6249: @noindent
1.44 crook 6250: @code{noname} works with any defining word, not just @code{:}.
6251:
1.116 anton 6252: @code{latestxt} also works when the last word was not defined as
1.71 anton 6253: @code{noname}. It does not work for combined words, though. It also has
6254: the useful property that is is valid as soon as the header for a
6255: definition has been built. Thus:
1.44 crook 6256:
6257: @example
1.116 anton 6258: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6259: @end example
1.1 anton 6260:
1.44 crook 6261: @noindent
6262: prints 3 numbers; the last two are the same.
1.26 crook 6263:
1.69 anton 6264: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6265: @subsection Supplying the name of a defined word
6266: @cindex names for defined words
6267: @cindex defining words, name given in a string
6268:
6269: By default, a defining word takes the name for the defined word from the
6270: input stream. Sometimes you want to supply the name from a string. You
6271: can do this with:
6272:
6273: doc-nextname
6274:
6275: For example:
6276:
6277: @example
6278: s" foo" nextname create
6279: @end example
6280:
6281: @noindent
6282: is equivalent to:
6283:
6284: @example
6285: create foo
6286: @end example
6287:
6288: @noindent
6289: @code{nextname} works with any defining word.
6290:
1.1 anton 6291:
1.170 pazsan 6292: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6293: @subsection User-defined Defining Words
6294: @cindex user-defined defining words
6295: @cindex defining words, user-defined
1.1 anton 6296:
1.29 crook 6297: You can create a new defining word by wrapping defining-time code around
6298: an existing defining word and putting the sequence in a colon
1.69 anton 6299: definition.
6300:
6301: @c anton: This example is very complex and leads in a quite different
6302: @c direction from the CREATE-DOES> stuff that follows. It should probably
6303: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6304: @c subsection of Defining Words)
6305:
6306: For example, suppose that you have a word @code{stats} that
1.29 crook 6307: gathers statistics about colon definitions given the @i{xt} of the
6308: definition, and you want every colon definition in your application to
6309: make a call to @code{stats}. You can define and use a new version of
6310: @code{:} like this:
6311:
6312: @example
6313: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6314: ... ; \ other code
6315:
1.116 anton 6316: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6317:
6318: my: foo + - ;
6319: @end example
6320:
6321: When @code{foo} is defined using @code{my:} these steps occur:
6322:
6323: @itemize @bullet
6324: @item
6325: @code{my:} is executed.
6326: @item
6327: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6328: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6329: the input stream for a name, builds a dictionary header for the name
6330: @code{foo} and switches @code{state} from interpret to compile.
6331: @item
1.116 anton 6332: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6333: being defined -- @code{foo} -- onto the stack.
6334: @item
6335: The code that was produced by @code{postpone literal} is executed; this
6336: causes the value on the stack to be compiled as a literal in the code
6337: area of @code{foo}.
6338: @item
6339: The code @code{['] stats} compiles a literal into the definition of
6340: @code{my:}. When @code{compile,} is executed, that literal -- the
6341: execution token for @code{stats} -- is layed down in the code area of
6342: @code{foo} , following the literal@footnote{Strictly speaking, the
6343: mechanism that @code{compile,} uses to convert an @i{xt} into something
6344: in the code area is implementation-dependent. A threaded implementation
6345: might spit out the execution token directly whilst another
6346: implementation might spit out a native code sequence.}.
6347: @item
6348: At this point, the execution of @code{my:} is complete, and control
6349: returns to the text interpreter. The text interpreter is in compile
6350: state, so subsequent text @code{+ -} is compiled into the definition of
6351: @code{foo} and the @code{;} terminates the definition as always.
6352: @end itemize
6353:
6354: You can use @code{see} to decompile a word that was defined using
6355: @code{my:} and see how it is different from a normal @code{:}
6356: definition. For example:
6357:
6358: @example
6359: : bar + - ; \ like foo but using : rather than my:
6360: see bar
6361: : bar
6362: + - ;
6363: see foo
6364: : foo
6365: 107645672 stats + - ;
6366:
1.140 anton 6367: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6368: @end example
6369:
6370: You can use techniques like this to make new defining words in terms of
6371: @i{any} existing defining word.
1.1 anton 6372:
6373:
1.29 crook 6374: @cindex defining defining words
1.26 crook 6375: @cindex @code{CREATE} ... @code{DOES>}
6376: If you want the words defined with your defining words to behave
6377: differently from words defined with standard defining words, you can
6378: write your defining word like this:
1.1 anton 6379:
6380: @example
1.26 crook 6381: : def-word ( "name" -- )
1.29 crook 6382: CREATE @i{code1}
1.26 crook 6383: DOES> ( ... -- ... )
1.29 crook 6384: @i{code2} ;
1.26 crook 6385:
6386: def-word name
1.1 anton 6387: @end example
6388:
1.29 crook 6389: @cindex child words
6390: This fragment defines a @dfn{defining word} @code{def-word} and then
6391: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6392: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6393: is not executed at this time. The word @code{name} is sometimes called a
6394: @dfn{child} of @code{def-word}.
6395:
6396: When you execute @code{name}, the address of the body of @code{name} is
6397: put on the data stack and @i{code2} is executed (the address of the body
6398: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6399: @code{CREATE}, i.e., the address a @code{create}d word returns by
6400: default).
6401:
6402: @c anton:
6403: @c www.dictionary.com says:
6404: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6405: @c several generations of absence, usually caused by the chance
6406: @c recombination of genes. 2.An individual or a part that exhibits
6407: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6408: @c of previous behavior after a period of absence.
6409: @c
6410: @c Doesn't seem to fit.
1.29 crook 6411:
1.69 anton 6412: @c @cindex atavism in child words
1.33 anton 6413: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6414: similarly; they all have a common run-time behaviour determined by
6415: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6416: body of the child word. The structure of the data is common to all
6417: children of @code{def-word}, but the data values are specific -- and
6418: private -- to each child word. When a child word is executed, the
6419: address of its private data area is passed as a parameter on TOS to be
6420: used and manipulated@footnote{It is legitimate both to read and write to
6421: this data area.} by @i{code2}.
1.29 crook 6422:
6423: The two fragments of code that make up the defining words act (are
6424: executed) at two completely separate times:
1.1 anton 6425:
1.29 crook 6426: @itemize @bullet
6427: @item
6428: At @i{define time}, the defining word executes @i{code1} to generate a
6429: child word
6430: @item
6431: At @i{child execution time}, when a child word is invoked, @i{code2}
6432: is executed, using parameters (data) that are private and specific to
6433: the child word.
6434: @end itemize
6435:
1.44 crook 6436: Another way of understanding the behaviour of @code{def-word} and
6437: @code{name} is to say that, if you make the following definitions:
1.33 anton 6438: @example
6439: : def-word1 ( "name" -- )
6440: CREATE @i{code1} ;
6441:
6442: : action1 ( ... -- ... )
6443: @i{code2} ;
6444:
6445: def-word1 name1
6446: @end example
6447:
1.44 crook 6448: @noindent
6449: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6450:
1.29 crook 6451: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6452:
1.1 anton 6453: @example
1.29 crook 6454: : CONSTANT ( w "name" -- )
6455: CREATE ,
1.26 crook 6456: DOES> ( -- w )
6457: @@ ;
1.1 anton 6458: @end example
6459:
1.29 crook 6460: @comment There is a beautiful description of how this works and what
6461: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6462: @comment commentary on the Counting Fruits problem.
6463:
6464: When you create a constant with @code{5 CONSTANT five}, a set of
6465: define-time actions take place; first a new word @code{five} is created,
6466: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6467: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6468: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6469: no code of its own; it simply contains a data field and a pointer to the
6470: code that follows @code{DOES>} in its defining word. That makes words
6471: created in this way very compact.
6472:
6473: The final example in this section is intended to remind you that space
6474: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6475: both read and written by a Standard program@footnote{Exercise: use this
6476: example as a starting point for your own implementation of @code{Value}
6477: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6478: @code{[']}.}:
6479:
6480: @example
6481: : foo ( "name" -- )
6482: CREATE -1 ,
6483: DOES> ( -- )
1.33 anton 6484: @@ . ;
1.29 crook 6485:
6486: foo first-word
6487: foo second-word
6488:
6489: 123 ' first-word >BODY !
6490: @end example
6491:
6492: If @code{first-word} had been a @code{CREATE}d word, we could simply
6493: have executed it to get the address of its data field. However, since it
6494: was defined to have @code{DOES>} actions, its execution semantics are to
6495: perform those @code{DOES>} actions. To get the address of its data field
6496: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6497: translate the xt into the address of the data field. When you execute
6498: @code{first-word}, it will display @code{123}. When you execute
6499: @code{second-word} it will display @code{-1}.
1.26 crook 6500:
6501: @cindex stack effect of @code{DOES>}-parts
6502: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6503: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6504: the stack effect of the defined words, not the stack effect of the
6505: following code (the following code expects the address of the body on
6506: the top of stack, which is not reflected in the stack comment). This is
6507: the convention that I use and recommend (it clashes a bit with using
6508: locals declarations for stack effect specification, though).
1.1 anton 6509:
1.53 anton 6510: @menu
6511: * CREATE..DOES> applications::
6512: * CREATE..DOES> details::
1.63 anton 6513: * Advanced does> usage example::
1.155 anton 6514: * Const-does>::
1.53 anton 6515: @end menu
6516:
6517: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6518: @subsubsection Applications of @code{CREATE..DOES>}
6519: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6520:
1.26 crook 6521: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6522:
1.26 crook 6523: @cindex factoring similar colon definitions
6524: When you see a sequence of code occurring several times, and you can
6525: identify a meaning, you will factor it out as a colon definition. When
6526: you see similar colon definitions, you can factor them using
6527: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6528: that look very similar:
1.1 anton 6529: @example
1.26 crook 6530: : ori, ( reg-target reg-source n -- )
6531: 0 asm-reg-reg-imm ;
6532: : andi, ( reg-target reg-source n -- )
6533: 1 asm-reg-reg-imm ;
1.1 anton 6534: @end example
6535:
1.26 crook 6536: @noindent
6537: This could be factored with:
6538: @example
6539: : reg-reg-imm ( op-code -- )
6540: CREATE ,
6541: DOES> ( reg-target reg-source n -- )
6542: @@ asm-reg-reg-imm ;
6543:
6544: 0 reg-reg-imm ori,
6545: 1 reg-reg-imm andi,
6546: @end example
1.1 anton 6547:
1.26 crook 6548: @cindex currying
6549: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6550: supply a part of the parameters for a word (known as @dfn{currying} in
6551: the functional language community). E.g., @code{+} needs two
6552: parameters. Creating versions of @code{+} with one parameter fixed can
6553: be done like this:
1.82 anton 6554:
1.1 anton 6555: @example
1.82 anton 6556: : curry+ ( n1 "name" -- )
1.26 crook 6557: CREATE ,
6558: DOES> ( n2 -- n1+n2 )
6559: @@ + ;
6560:
6561: 3 curry+ 3+
6562: -2 curry+ 2-
1.1 anton 6563: @end example
6564:
1.91 anton 6565:
1.63 anton 6566: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6567: @subsubsection The gory details of @code{CREATE..DOES>}
6568: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6569:
1.26 crook 6570: doc-does>
1.1 anton 6571:
1.26 crook 6572: @cindex @code{DOES>} in a separate definition
6573: This means that you need not use @code{CREATE} and @code{DOES>} in the
6574: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6575: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6576: @example
6577: : does1
6578: DOES> ( ... -- ... )
1.44 crook 6579: ... ;
6580:
6581: : does2
6582: DOES> ( ... -- ... )
6583: ... ;
6584:
6585: : def-word ( ... -- ... )
6586: create ...
6587: IF
6588: does1
6589: ELSE
6590: does2
6591: ENDIF ;
6592: @end example
6593:
6594: In this example, the selection of whether to use @code{does1} or
1.69 anton 6595: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6596: @code{CREATE}d.
6597:
6598: @cindex @code{DOES>} in interpretation state
6599: In a standard program you can apply a @code{DOES>}-part only if the last
6600: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6601: will override the behaviour of the last word defined in any case. In a
6602: standard program, you can use @code{DOES>} only in a colon
6603: definition. In Gforth, you can also use it in interpretation state, in a
6604: kind of one-shot mode; for example:
6605: @example
6606: CREATE name ( ... -- ... )
6607: @i{initialization}
6608: DOES>
6609: @i{code} ;
6610: @end example
6611:
6612: @noindent
6613: is equivalent to the standard:
6614: @example
6615: :noname
6616: DOES>
6617: @i{code} ;
6618: CREATE name EXECUTE ( ... -- ... )
6619: @i{initialization}
6620: @end example
6621:
1.53 anton 6622: doc->body
6623:
1.152 pazsan 6624: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6625: @subsubsection Advanced does> usage example
6626:
6627: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6628: for disassembling instructions, that follow a very repetetive scheme:
6629:
6630: @example
6631: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6632: @var{entry-num} cells @var{table} + !
6633: @end example
6634:
6635: Of course, this inspires the idea to factor out the commonalities to
6636: allow a definition like
6637:
6638: @example
6639: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6640: @end example
6641:
6642: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6643: correlated. Moreover, before I wrote the disassembler, there already
6644: existed code that defines instructions like this:
1.63 anton 6645:
6646: @example
6647: @var{entry-num} @var{inst-format} @var{inst-name}
6648: @end example
6649:
6650: This code comes from the assembler and resides in
6651: @file{arch/mips/insts.fs}.
6652:
6653: So I had to define the @var{inst-format} words that performed the scheme
6654: above when executed. At first I chose to use run-time code-generation:
6655:
6656: @example
6657: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6658: :noname Postpone @var{disasm-operands}
6659: name Postpone sliteral Postpone type Postpone ;
6660: swap cells @var{table} + ! ;
6661: @end example
6662:
6663: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6664:
1.63 anton 6665: An alternative would have been to write this using
6666: @code{create}/@code{does>}:
6667:
6668: @example
6669: : @var{inst-format} ( entry-num "name" -- )
6670: here name string, ( entry-num c-addr ) \ parse and save "name"
6671: noname create , ( entry-num )
1.116 anton 6672: latestxt swap cells @var{table} + !
1.63 anton 6673: does> ( addr w -- )
6674: \ disassemble instruction w at addr
6675: @@ >r
6676: @var{disasm-operands}
6677: r> count type ;
6678: @end example
6679:
6680: Somehow the first solution is simpler, mainly because it's simpler to
6681: shift a string from definition-time to use-time with @code{sliteral}
6682: than with @code{string,} and friends.
6683:
6684: I wrote a lot of words following this scheme and soon thought about
6685: factoring out the commonalities among them. Note that this uses a
6686: two-level defining word, i.e., a word that defines ordinary defining
6687: words.
6688:
6689: This time a solution involving @code{postpone} and friends seemed more
6690: difficult (try it as an exercise), so I decided to use a
6691: @code{create}/@code{does>} word; since I was already at it, I also used
6692: @code{create}/@code{does>} for the lower level (try using
6693: @code{postpone} etc. as an exercise), resulting in the following
6694: definition:
6695:
6696: @example
6697: : define-format ( disasm-xt table-xt -- )
6698: \ define an instruction format that uses disasm-xt for
6699: \ disassembling and enters the defined instructions into table
6700: \ table-xt
6701: create 2,
6702: does> ( u "inst" -- )
6703: \ defines an anonymous word for disassembling instruction inst,
6704: \ and enters it as u-th entry into table-xt
6705: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6706: noname create 2, \ define anonymous word
1.116 anton 6707: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6708: does> ( addr w -- )
6709: \ disassemble instruction w at addr
6710: 2@@ >r ( addr w disasm-xt R: c-addr )
6711: execute ( R: c-addr ) \ disassemble operands
6712: r> count type ; \ print name
6713: @end example
6714:
6715: Note that the tables here (in contrast to above) do the @code{cells +}
6716: by themselves (that's why you have to pass an xt). This word is used in
6717: the following way:
6718:
6719: @example
6720: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6721: @end example
6722:
1.71 anton 6723: As shown above, the defined instruction format is then used like this:
6724:
6725: @example
6726: @var{entry-num} @var{inst-format} @var{inst-name}
6727: @end example
6728:
1.63 anton 6729: In terms of currying, this kind of two-level defining word provides the
6730: parameters in three stages: first @var{disasm-operands} and @var{table},
6731: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6732: the instruction to be disassembled.
6733:
6734: Of course this did not quite fit all the instruction format names used
6735: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6736: the parameters into the right form.
6737:
6738: If you have trouble following this section, don't worry. First, this is
6739: involved and takes time (and probably some playing around) to
6740: understand; second, this is the first two-level
6741: @code{create}/@code{does>} word I have written in seventeen years of
6742: Forth; and if I did not have @file{insts.fs} to start with, I may well
6743: have elected to use just a one-level defining word (with some repeating
6744: of parameters when using the defining word). So it is not necessary to
6745: understand this, but it may improve your understanding of Forth.
1.44 crook 6746:
6747:
1.152 pazsan 6748: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6749: @subsubsection @code{Const-does>}
6750:
6751: A frequent use of @code{create}...@code{does>} is for transferring some
6752: values from definition-time to run-time. Gforth supports this use with
6753:
6754: doc-const-does>
6755:
6756: A typical use of this word is:
6757:
6758: @example
6759: : curry+ ( n1 "name" -- )
6760: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6761: + ;
6762:
6763: 3 curry+ 3+
6764: @end example
6765:
6766: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6767: definition to run-time.
6768:
6769: The advantages of using @code{const-does>} are:
6770:
6771: @itemize
6772:
6773: @item
6774: You don't have to deal with storing and retrieving the values, i.e.,
6775: your program becomes more writable and readable.
6776:
6777: @item
6778: When using @code{does>}, you have to introduce a @code{@@} that cannot
6779: be optimized away (because you could change the data using
6780: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6781:
6782: @end itemize
6783:
6784: An ANS Forth implementation of @code{const-does>} is available in
6785: @file{compat/const-does.fs}.
6786:
6787:
1.170 pazsan 6788: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6789: @subsection Deferred Words
1.44 crook 6790: @cindex deferred words
6791:
6792: The defining word @code{Defer} allows you to define a word by name
6793: without defining its behaviour; the definition of its behaviour is
6794: deferred. Here are two situation where this can be useful:
6795:
6796: @itemize @bullet
6797: @item
6798: Where you want to allow the behaviour of a word to be altered later, and
6799: for all precompiled references to the word to change when its behaviour
6800: is changed.
6801: @item
6802: For mutual recursion; @xref{Calls and returns}.
6803: @end itemize
6804:
6805: In the following example, @code{foo} always invokes the version of
6806: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6807: always invokes the version that prints ``@code{Hello}''. There is no way
6808: of getting @code{foo} to use the later version without re-ordering the
6809: source code and recompiling it.
6810:
6811: @example
6812: : greet ." Good morning" ;
6813: : foo ... greet ... ;
6814: : greet ." Hello" ;
6815: : bar ... greet ... ;
6816: @end example
6817:
6818: This problem can be solved by defining @code{greet} as a @code{Defer}red
6819: word. The behaviour of a @code{Defer}red word can be defined and
6820: redefined at any time by using @code{IS} to associate the xt of a
6821: previously-defined word with it. The previous example becomes:
6822:
6823: @example
1.69 anton 6824: Defer greet ( -- )
1.44 crook 6825: : foo ... greet ... ;
6826: : bar ... greet ... ;
1.69 anton 6827: : greet1 ( -- ) ." Good morning" ;
6828: : greet2 ( -- ) ." Hello" ;
1.132 anton 6829: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6830: @end example
6831:
1.69 anton 6832: @progstyle
6833: You should write a stack comment for every deferred word, and put only
6834: XTs into deferred words that conform to this stack effect. Otherwise
6835: it's too difficult to use the deferred word.
6836:
1.44 crook 6837: A deferred word can be used to improve the statistics-gathering example
6838: from @ref{User-defined Defining Words}; rather than edit the
6839: application's source code to change every @code{:} to a @code{my:}, do
6840: this:
6841:
6842: @example
6843: : real: : ; \ retain access to the original
6844: defer : \ redefine as a deferred word
1.132 anton 6845: ' my: IS : \ use special version of :
1.44 crook 6846: \
6847: \ load application here
6848: \
1.132 anton 6849: ' real: IS : \ go back to the original
1.44 crook 6850: @end example
6851:
6852:
1.132 anton 6853: One thing to note is that @code{IS} has special compilation semantics,
6854: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6855:
6856: @example
6857: : set-greet ( xt -- )
1.132 anton 6858: IS greet ;
1.44 crook 6859:
6860: ' greet1 set-greet
6861: @end example
6862:
1.132 anton 6863: In situations where @code{IS} does not fit, use @code{defer!} instead.
6864:
1.69 anton 6865: A deferred word can only inherit execution semantics from the xt
6866: (because that is all that an xt can represent -- for more discussion of
6867: this @pxref{Tokens for Words}); by default it will have default
6868: interpretation and compilation semantics deriving from this execution
6869: semantics. However, you can change the interpretation and compilation
6870: semantics of the deferred word in the usual ways:
1.44 crook 6871:
6872: @example
1.132 anton 6873: : bar .... ; immediate
1.44 crook 6874: Defer fred immediate
6875: Defer jim
6876:
1.132 anton 6877: ' bar IS jim \ jim has default semantics
6878: ' bar IS fred \ fred is immediate
1.44 crook 6879: @end example
6880:
6881: doc-defer
1.132 anton 6882: doc-defer!
1.44 crook 6883: doc-is
1.132 anton 6884: doc-defer@
6885: doc-action-of
1.44 crook 6886: @comment TODO document these: what's defers [is]
6887: doc-defers
6888:
6889: @c Use @code{words-deferred} to see a list of deferred words.
6890:
1.132 anton 6891: Definitions of these words (except @code{defers}) in ANS Forth are
6892: provided in @file{compat/defer.fs}.
1.44 crook 6893:
6894:
1.170 pazsan 6895: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6896: @subsection Aliases
6897: @cindex aliases
1.1 anton 6898:
1.44 crook 6899: The defining word @code{Alias} allows you to define a word by name that
6900: has the same behaviour as some other word. Here are two situation where
6901: this can be useful:
1.1 anton 6902:
1.44 crook 6903: @itemize @bullet
6904: @item
6905: When you want access to a word's definition from a different word list
6906: (for an example of this, see the definition of the @code{Root} word list
6907: in the Gforth source).
6908: @item
6909: When you want to create a synonym; a definition that can be known by
6910: either of two names (for example, @code{THEN} and @code{ENDIF} are
6911: aliases).
6912: @end itemize
1.1 anton 6913:
1.69 anton 6914: Like deferred words, an alias has default compilation and interpretation
6915: semantics at the beginning (not the modifications of the other word),
6916: but you can change them in the usual ways (@code{immediate},
6917: @code{compile-only}). For example:
1.1 anton 6918:
6919: @example
1.44 crook 6920: : foo ... ; immediate
6921:
6922: ' foo Alias bar \ bar is not an immediate word
6923: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6924: @end example
6925:
1.44 crook 6926: Words that are aliases have the same xt, different headers in the
6927: dictionary, and consequently different name tokens (@pxref{Tokens for
6928: Words}) and possibly different immediate flags. An alias can only have
6929: default or immediate compilation semantics; you can define aliases for
6930: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6931:
1.44 crook 6932: doc-alias
1.1 anton 6933:
6934:
1.47 crook 6935: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6936: @section Interpretation and Compilation Semantics
1.26 crook 6937: @cindex semantics, interpretation and compilation
1.1 anton 6938:
1.71 anton 6939: @c !! state and ' are used without explanation
6940: @c example for immediate/compile-only? or is the tutorial enough
6941:
1.26 crook 6942: @cindex interpretation semantics
1.71 anton 6943: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6944: interpreter does when it encounters the word in interpret state. It also
6945: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6946: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6947: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6948: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6949:
1.26 crook 6950: @cindex compilation semantics
1.71 anton 6951: The @dfn{compilation semantics} of a (named) word are what the text
6952: interpreter does when it encounters the word in compile state. It also
6953: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6954: compiles@footnote{In standard terminology, ``appends to the current
6955: definition''.} the compilation semantics of @i{word}.
1.1 anton 6956:
1.26 crook 6957: @cindex execution semantics
6958: The standard also talks about @dfn{execution semantics}. They are used
6959: only for defining the interpretation and compilation semantics of many
6960: words. By default, the interpretation semantics of a word are to
6961: @code{execute} its execution semantics, and the compilation semantics of
6962: a word are to @code{compile,} its execution semantics.@footnote{In
6963: standard terminology: The default interpretation semantics are its
6964: execution semantics; the default compilation semantics are to append its
6965: execution semantics to the execution semantics of the current
6966: definition.}
6967:
1.71 anton 6968: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6969: the text interpreter, ticked, or @code{postpone}d, so they have no
6970: interpretation or compilation semantics. Their behaviour is represented
6971: by their XT (@pxref{Tokens for Words}), and we call it execution
6972: semantics, too.
6973:
1.26 crook 6974: @comment TODO expand, make it co-operate with new sections on text interpreter.
6975:
6976: @cindex immediate words
6977: @cindex compile-only words
6978: You can change the semantics of the most-recently defined word:
6979:
1.44 crook 6980:
1.26 crook 6981: doc-immediate
6982: doc-compile-only
6983: doc-restrict
6984:
1.82 anton 6985: By convention, words with non-default compilation semantics (e.g.,
6986: immediate words) often have names surrounded with brackets (e.g.,
6987: @code{[']}, @pxref{Execution token}).
1.44 crook 6988:
1.26 crook 6989: Note that ticking (@code{'}) a compile-only word gives an error
6990: (``Interpreting a compile-only word'').
1.1 anton 6991:
1.47 crook 6992: @menu
1.67 anton 6993: * Combined words::
1.47 crook 6994: @end menu
1.44 crook 6995:
1.71 anton 6996:
1.48 anton 6997: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6998: @subsection Combined Words
6999: @cindex combined words
7000:
7001: Gforth allows you to define @dfn{combined words} -- words that have an
7002: arbitrary combination of interpretation and compilation semantics.
7003:
1.26 crook 7004: doc-interpret/compile:
1.1 anton 7005:
1.26 crook 7006: This feature was introduced for implementing @code{TO} and @code{S"}. I
7007: recommend that you do not define such words, as cute as they may be:
7008: they make it hard to get at both parts of the word in some contexts.
7009: E.g., assume you want to get an execution token for the compilation
7010: part. Instead, define two words, one that embodies the interpretation
7011: part, and one that embodies the compilation part. Once you have done
7012: that, you can define a combined word with @code{interpret/compile:} for
7013: the convenience of your users.
1.1 anton 7014:
1.26 crook 7015: You might try to use this feature to provide an optimizing
7016: implementation of the default compilation semantics of a word. For
7017: example, by defining:
1.1 anton 7018: @example
1.26 crook 7019: :noname
7020: foo bar ;
7021: :noname
7022: POSTPONE foo POSTPONE bar ;
1.29 crook 7023: interpret/compile: opti-foobar
1.1 anton 7024: @end example
1.26 crook 7025:
1.23 crook 7026: @noindent
1.26 crook 7027: as an optimizing version of:
7028:
1.1 anton 7029: @example
1.26 crook 7030: : foobar
7031: foo bar ;
1.1 anton 7032: @end example
7033:
1.26 crook 7034: Unfortunately, this does not work correctly with @code{[compile]},
7035: because @code{[compile]} assumes that the compilation semantics of all
7036: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7037: opti-foobar} would compile compilation semantics, whereas
7038: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7039:
1.26 crook 7040: @cindex state-smart words (are a bad idea)
1.82 anton 7041: @anchor{state-smartness}
1.29 crook 7042: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7043: by @code{interpret/compile:} (words are state-smart if they check
7044: @code{STATE} during execution). E.g., they would try to code
7045: @code{foobar} like this:
1.1 anton 7046:
1.26 crook 7047: @example
7048: : foobar
7049: STATE @@
7050: IF ( compilation state )
7051: POSTPONE foo POSTPONE bar
7052: ELSE
7053: foo bar
7054: ENDIF ; immediate
7055: @end example
1.1 anton 7056:
1.26 crook 7057: Although this works if @code{foobar} is only processed by the text
7058: interpreter, it does not work in other contexts (like @code{'} or
7059: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7060: for a state-smart word, not for the interpretation semantics of the
7061: original @code{foobar}; when you execute this execution token (directly
7062: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7063: state, the result will not be what you expected (i.e., it will not
7064: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7065: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7066: M. Anton Ertl,
7067: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7068: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7069:
1.26 crook 7070: @cindex defining words with arbitrary semantics combinations
7071: It is also possible to write defining words that define words with
7072: arbitrary combinations of interpretation and compilation semantics. In
7073: general, they look like this:
1.1 anton 7074:
1.26 crook 7075: @example
7076: : def-word
7077: create-interpret/compile
1.29 crook 7078: @i{code1}
1.26 crook 7079: interpretation>
1.29 crook 7080: @i{code2}
1.26 crook 7081: <interpretation
7082: compilation>
1.29 crook 7083: @i{code3}
1.26 crook 7084: <compilation ;
7085: @end example
1.1 anton 7086:
1.29 crook 7087: For a @i{word} defined with @code{def-word}, the interpretation
7088: semantics are to push the address of the body of @i{word} and perform
7089: @i{code2}, and the compilation semantics are to push the address of
7090: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7091: can also be defined like this (except that the defined constants don't
7092: behave correctly when @code{[compile]}d):
1.1 anton 7093:
1.26 crook 7094: @example
7095: : constant ( n "name" -- )
7096: create-interpret/compile
7097: ,
7098: interpretation> ( -- n )
7099: @@
7100: <interpretation
7101: compilation> ( compilation. -- ; run-time. -- n )
7102: @@ postpone literal
7103: <compilation ;
7104: @end example
1.1 anton 7105:
1.44 crook 7106:
1.26 crook 7107: doc-create-interpret/compile
7108: doc-interpretation>
7109: doc-<interpretation
7110: doc-compilation>
7111: doc-<compilation
1.1 anton 7112:
1.44 crook 7113:
1.29 crook 7114: Words defined with @code{interpret/compile:} and
1.26 crook 7115: @code{create-interpret/compile} have an extended header structure that
7116: differs from other words; however, unless you try to access them with
7117: plain address arithmetic, you should not notice this. Words for
7118: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7119: @code{'} @i{word} @code{>body} also gives you the body of a word created
7120: with @code{create-interpret/compile}.
1.1 anton 7121:
1.44 crook 7122:
1.47 crook 7123: @c -------------------------------------------------------------
1.81 anton 7124: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7125: @section Tokens for Words
7126: @cindex tokens for words
7127:
7128: This section describes the creation and use of tokens that represent
7129: words.
7130:
1.71 anton 7131: @menu
7132: * Execution token:: represents execution/interpretation semantics
7133: * Compilation token:: represents compilation semantics
7134: * Name token:: represents named words
7135: @end menu
1.47 crook 7136:
1.71 anton 7137: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7138: @subsection Execution token
1.47 crook 7139:
7140: @cindex xt
7141: @cindex execution token
1.71 anton 7142: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7143: You can use @code{execute} to invoke this behaviour.
1.47 crook 7144:
1.71 anton 7145: @cindex tick (')
7146: You can use @code{'} to get an execution token that represents the
7147: interpretation semantics of a named word:
1.47 crook 7148:
7149: @example
1.97 anton 7150: 5 ' . ( n xt )
7151: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7152: @end example
1.47 crook 7153:
1.71 anton 7154: doc-'
7155:
7156: @code{'} parses at run-time; there is also a word @code{[']} that parses
7157: when it is compiled, and compiles the resulting XT:
7158:
7159: @example
7160: : foo ['] . execute ;
7161: 5 foo
7162: : bar ' execute ; \ by contrast,
7163: 5 bar . \ ' parses "." when bar executes
7164: @end example
7165:
7166: doc-[']
7167:
7168: If you want the execution token of @i{word}, write @code{['] @i{word}}
7169: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7170: @code{'} and @code{[']} behave somewhat unusually by complaining about
7171: compile-only words (because these words have no interpretation
7172: semantics). You might get what you want by using @code{COMP' @i{word}
7173: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7174: token}).
7175:
1.116 anton 7176: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7177: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7178: for the only behaviour the word has (the execution semantics). For
1.116 anton 7179: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7180: would produce if the word was defined anonymously.
7181:
7182: @example
7183: :noname ." hello" ;
7184: execute
1.47 crook 7185: @end example
7186:
1.71 anton 7187: An XT occupies one cell and can be manipulated like any other cell.
7188:
1.47 crook 7189: @cindex code field address
7190: @cindex CFA
1.71 anton 7191: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7192: operations that produce or consume it). For old hands: In Gforth, the
7193: XT is implemented as a code field address (CFA).
7194:
7195: doc-execute
7196: doc-perform
7197:
7198: @node Compilation token, Name token, Execution token, Tokens for Words
7199: @subsection Compilation token
1.47 crook 7200:
7201: @cindex compilation token
1.71 anton 7202: @cindex CT (compilation token)
7203: Gforth represents the compilation semantics of a named word by a
1.47 crook 7204: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7205: @i{xt} is an execution token. The compilation semantics represented by
7206: the compilation token can be performed with @code{execute}, which
7207: consumes the whole compilation token, with an additional stack effect
7208: determined by the represented compilation semantics.
7209:
7210: At present, the @i{w} part of a compilation token is an execution token,
7211: and the @i{xt} part represents either @code{execute} or
7212: @code{compile,}@footnote{Depending upon the compilation semantics of the
7213: word. If the word has default compilation semantics, the @i{xt} will
7214: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7215: @i{xt} will represent @code{execute}.}. However, don't rely on that
7216: knowledge, unless necessary; future versions of Gforth may introduce
7217: unusual compilation tokens (e.g., a compilation token that represents
7218: the compilation semantics of a literal).
7219:
1.71 anton 7220: You can perform the compilation semantics represented by the compilation
7221: token with @code{execute}. You can compile the compilation semantics
7222: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7223: equivalent to @code{postpone @i{word}}.
7224:
7225: doc-[comp']
7226: doc-comp'
7227: doc-postpone,
7228:
7229: @node Name token, , Compilation token, Tokens for Words
7230: @subsection Name token
1.47 crook 7231:
7232: @cindex name token
1.116 anton 7233: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7234: token is an abstract data type that occurs as argument or result of the
7235: words below.
7236:
7237: @c !! put this elswhere?
1.47 crook 7238: @cindex name field address
7239: @cindex NFA
1.116 anton 7240: The closest thing to the nt in older Forth systems is the name field
7241: address (NFA), but there are significant differences: in older Forth
7242: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7243: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7244: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7245: is a link field in the structure identified by the name token, but
7246: searching usually uses a hash table external to these structures; the
7247: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7248: implemented as the address of that count field.
1.47 crook 7249:
7250: doc-find-name
1.116 anton 7251: doc-latest
7252: doc->name
1.47 crook 7253: doc-name>int
7254: doc-name?int
7255: doc-name>comp
7256: doc-name>string
1.109 anton 7257: doc-id.
7258: doc-.name
7259: doc-.id
1.47 crook 7260:
1.81 anton 7261: @c ----------------------------------------------------------
7262: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7263: @section Compiling words
7264: @cindex compiling words
7265: @cindex macros
7266:
7267: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7268: between compilation and run-time. E.g., you can run arbitrary code
7269: between defining words (or for computing data used by defining words
7270: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7271: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7272: running arbitrary code while compiling a colon definition (exception:
7273: you must not allot dictionary space).
7274:
7275: @menu
7276: * Literals:: Compiling data values
7277: * Macros:: Compiling words
7278: @end menu
7279:
7280: @node Literals, Macros, Compiling words, Compiling words
7281: @subsection Literals
7282: @cindex Literals
7283:
7284: The simplest and most frequent example is to compute a literal during
7285: compilation. E.g., the following definition prints an array of strings,
7286: one string per line:
7287:
7288: @example
7289: : .strings ( addr u -- ) \ gforth
7290: 2* cells bounds U+DO
7291: cr i 2@@ type
7292: 2 cells +LOOP ;
7293: @end example
1.81 anton 7294:
1.82 anton 7295: With a simple-minded compiler like Gforth's, this computes @code{2
7296: cells} on every loop iteration. You can compute this value once and for
7297: all at compile time and compile it into the definition like this:
7298:
7299: @example
7300: : .strings ( addr u -- ) \ gforth
7301: 2* cells bounds U+DO
7302: cr i 2@@ type
7303: [ 2 cells ] literal +LOOP ;
7304: @end example
7305:
7306: @code{[} switches the text interpreter to interpret state (you will get
7307: an @code{ok} prompt if you type this example interactively and insert a
7308: newline between @code{[} and @code{]}), so it performs the
7309: interpretation semantics of @code{2 cells}; this computes a number.
7310: @code{]} switches the text interpreter back into compile state. It then
7311: performs @code{Literal}'s compilation semantics, which are to compile
7312: this number into the current word. You can decompile the word with
7313: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7314:
1.82 anton 7315: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7316: *} in this way.
1.81 anton 7317:
1.82 anton 7318: doc-[
7319: doc-]
1.81 anton 7320: doc-literal
7321: doc-]L
1.82 anton 7322:
7323: There are also words for compiling other data types than single cells as
7324: literals:
7325:
1.81 anton 7326: doc-2literal
7327: doc-fliteral
1.82 anton 7328: doc-sliteral
7329:
7330: @cindex colon-sys, passing data across @code{:}
7331: @cindex @code{:}, passing data across
7332: You might be tempted to pass data from outside a colon definition to the
7333: inside on the data stack. This does not work, because @code{:} puhes a
7334: colon-sys, making stuff below unaccessible. E.g., this does not work:
7335:
7336: @example
7337: 5 : foo literal ; \ error: "unstructured"
7338: @end example
7339:
7340: Instead, you have to pass the value in some other way, e.g., through a
7341: variable:
7342:
7343: @example
7344: variable temp
7345: 5 temp !
7346: : foo [ temp @@ ] literal ;
7347: @end example
7348:
7349:
7350: @node Macros, , Literals, Compiling words
7351: @subsection Macros
7352: @cindex Macros
7353: @cindex compiling compilation semantics
7354:
7355: @code{Literal} and friends compile data values into the current
7356: definition. You can also write words that compile other words into the
7357: current definition. E.g.,
7358:
7359: @example
7360: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7361: POSTPONE + ;
7362:
7363: : foo ( n1 n2 -- n )
7364: [ compile-+ ] ;
7365: 1 2 foo .
7366: @end example
7367:
7368: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7369: What happens in this example? @code{Postpone} compiles the compilation
7370: semantics of @code{+} into @code{compile-+}; later the text interpreter
7371: executes @code{compile-+} and thus the compilation semantics of +, which
7372: compile (the execution semantics of) @code{+} into
7373: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7374: should only be executed in compile state, so this example is not
7375: guaranteed to work on all standard systems, but on any decent system it
7376: will work.}
7377:
7378: doc-postpone
7379: doc-[compile]
7380:
7381: Compiling words like @code{compile-+} are usually immediate (or similar)
7382: so you do not have to switch to interpret state to execute them;
7383: mopifying the last example accordingly produces:
7384:
7385: @example
7386: : [compile-+] ( compilation: --; interpretation: -- )
7387: \ compiled code: ( n1 n2 -- n )
7388: POSTPONE + ; immediate
7389:
7390: : foo ( n1 n2 -- n )
7391: [compile-+] ;
7392: 1 2 foo .
7393: @end example
7394:
7395: Immediate compiling words are similar to macros in other languages (in
7396: particular, Lisp). The important differences to macros in, e.g., C are:
7397:
7398: @itemize @bullet
7399:
7400: @item
7401: You use the same language for defining and processing macros, not a
7402: separate preprocessing language and processor.
7403:
7404: @item
7405: Consequently, the full power of Forth is available in macro definitions.
7406: E.g., you can perform arbitrarily complex computations, or generate
7407: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7408: Tutorial}). This power is very useful when writing a parser generators
7409: or other code-generating software.
7410:
7411: @item
7412: Macros defined using @code{postpone} etc. deal with the language at a
7413: higher level than strings; name binding happens at macro definition
7414: time, so you can avoid the pitfalls of name collisions that can happen
7415: in C macros. Of course, Forth is a liberal language and also allows to
7416: shoot yourself in the foot with text-interpreted macros like
7417:
7418: @example
7419: : [compile-+] s" +" evaluate ; immediate
7420: @end example
7421:
7422: Apart from binding the name at macro use time, using @code{evaluate}
7423: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7424: @end itemize
7425:
7426: You may want the macro to compile a number into a word. The word to do
7427: it is @code{literal}, but you have to @code{postpone} it, so its
7428: compilation semantics take effect when the macro is executed, not when
7429: it is compiled:
7430:
7431: @example
7432: : [compile-5] ( -- ) \ compiled code: ( -- n )
7433: 5 POSTPONE literal ; immediate
7434:
7435: : foo [compile-5] ;
7436: foo .
7437: @end example
7438:
7439: You may want to pass parameters to a macro, that the macro should
7440: compile into the current definition. If the parameter is a number, then
7441: you can use @code{postpone literal} (similar for other values).
7442:
7443: If you want to pass a word that is to be compiled, the usual way is to
7444: pass an execution token and @code{compile,} it:
7445:
7446: @example
7447: : twice1 ( xt -- ) \ compiled code: ... -- ...
7448: dup compile, compile, ;
7449:
7450: : 2+ ( n1 -- n2 )
7451: [ ' 1+ twice1 ] ;
7452: @end example
7453:
7454: doc-compile,
7455:
7456: An alternative available in Gforth, that allows you to pass compile-only
7457: words as parameters is to use the compilation token (@pxref{Compilation
7458: token}). The same example in this technique:
7459:
7460: @example
7461: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7462: 2dup 2>r execute 2r> execute ;
7463:
7464: : 2+ ( n1 -- n2 )
7465: [ comp' 1+ twice ] ;
7466: @end example
7467:
7468: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7469: works even if the executed compilation semantics has an effect on the
7470: data stack.
7471:
7472: You can also define complete definitions with these words; this provides
7473: an alternative to using @code{does>} (@pxref{User-defined Defining
7474: Words}). E.g., instead of
7475:
7476: @example
7477: : curry+ ( n1 "name" -- )
7478: CREATE ,
7479: DOES> ( n2 -- n1+n2 )
7480: @@ + ;
7481: @end example
7482:
7483: you could define
7484:
7485: @example
7486: : curry+ ( n1 "name" -- )
7487: \ name execution: ( n2 -- n1+n2 )
7488: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7489:
1.82 anton 7490: -3 curry+ 3-
7491: see 3-
7492: @end example
1.81 anton 7493:
1.82 anton 7494: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7495: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7496:
1.82 anton 7497: This way of writing defining words is sometimes more, sometimes less
7498: convenient than using @code{does>} (@pxref{Advanced does> usage
7499: example}). One advantage of this method is that it can be optimized
7500: better, because the compiler knows that the value compiled with
7501: @code{literal} is fixed, whereas the data associated with a
7502: @code{create}d word can be changed.
1.47 crook 7503:
1.26 crook 7504: @c ----------------------------------------------------------
1.111 anton 7505: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7506: @section The Text Interpreter
7507: @cindex interpreter - outer
7508: @cindex text interpreter
7509: @cindex outer interpreter
1.1 anton 7510:
1.34 anton 7511: @c Should we really describe all these ugly details? IMO the text
7512: @c interpreter should be much cleaner, but that may not be possible within
7513: @c ANS Forth. - anton
1.44 crook 7514: @c nac-> I wanted to explain how it works to show how you can exploit
7515: @c it in your own programs. When I was writing a cross-compiler, figuring out
7516: @c some of these gory details was very helpful to me. None of the textbooks
7517: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7518: @c seems to positively avoid going into too much detail for some of
7519: @c the internals.
1.34 anton 7520:
1.71 anton 7521: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7522: @c it is; for the ugly details, I would prefer another place. I wonder
7523: @c whether we should have a chapter before "Words" that describes some
7524: @c basic concepts referred to in words, and a chapter after "Words" that
7525: @c describes implementation details.
7526:
1.29 crook 7527: The text interpreter@footnote{This is an expanded version of the
7528: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7529: that processes input from the current input device. It is also called
7530: the outer interpreter, in contrast to the inner interpreter
7531: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7532: implementations.
1.27 crook 7533:
1.29 crook 7534: @cindex interpret state
7535: @cindex compile state
7536: The text interpreter operates in one of two states: @dfn{interpret
7537: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7538: aptly-named variable @code{state}.
1.29 crook 7539:
7540: This section starts by describing how the text interpreter behaves when
7541: it is in interpret state, processing input from the user input device --
7542: the keyboard. This is the mode that a Forth system is in after it starts
7543: up.
7544:
7545: @cindex input buffer
7546: @cindex terminal input buffer
7547: The text interpreter works from an area of memory called the @dfn{input
7548: buffer}@footnote{When the text interpreter is processing input from the
7549: keyboard, this area of memory is called the @dfn{terminal input buffer}
7550: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7551: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7552: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7553: leading spaces (called @dfn{delimiters}) then parses a string (a
7554: sequence of non-space characters) until it reaches either a space
7555: character or the end of the buffer. Having parsed a string, it makes two
7556: attempts to process it:
1.27 crook 7557:
1.29 crook 7558: @cindex dictionary
1.27 crook 7559: @itemize @bullet
7560: @item
1.29 crook 7561: It looks for the string in a @dfn{dictionary} of definitions. If the
7562: string is found, the string names a @dfn{definition} (also known as a
7563: @dfn{word}) and the dictionary search returns information that allows
7564: the text interpreter to perform the word's @dfn{interpretation
7565: semantics}. In most cases, this simply means that the word will be
7566: executed.
1.27 crook 7567: @item
7568: If the string is not found in the dictionary, the text interpreter
1.29 crook 7569: attempts to treat it as a number, using the rules described in
7570: @ref{Number Conversion}. If the string represents a legal number in the
7571: current radix, the number is pushed onto a parameter stack (the data
7572: stack for integers, the floating-point stack for floating-point
7573: numbers).
7574: @end itemize
7575:
7576: If both attempts fail, or if the word is found in the dictionary but has
7577: no interpretation semantics@footnote{This happens if the word was
7578: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7579: remainder of the input buffer, issues an error message and waits for
7580: more input. If one of the attempts succeeds, the text interpreter
7581: repeats the parsing process until the whole of the input buffer has been
7582: processed, at which point it prints the status message ``@code{ ok}''
7583: and waits for more input.
7584:
1.71 anton 7585: @c anton: this should be in the input stream subsection (or below it)
7586:
1.29 crook 7587: @cindex parse area
7588: The text interpreter keeps track of its position in the input buffer by
7589: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7590: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7591: of the input buffer. The region from offset @code{>IN @@} to the end of
7592: the input buffer is called the @dfn{parse area}@footnote{In other words,
7593: the text interpreter processes the contents of the input buffer by
7594: parsing strings from the parse area until the parse area is empty.}.
7595: This example shows how @code{>IN} changes as the text interpreter parses
7596: the input buffer:
7597:
7598: @example
7599: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7600: CR ." ->" TYPE ." <-" ; IMMEDIATE
7601:
7602: 1 2 3 remaining + remaining .
7603:
7604: : foo 1 2 3 remaining SWAP remaining ;
7605: @end example
7606:
7607: @noindent
7608: The result is:
7609:
7610: @example
7611: ->+ remaining .<-
7612: ->.<-5 ok
7613:
7614: ->SWAP remaining ;-<
7615: ->;<- ok
7616: @end example
7617:
7618: @cindex parsing words
7619: The value of @code{>IN} can also be modified by a word in the input
7620: buffer that is executed by the text interpreter. This means that a word
7621: can ``trick'' the text interpreter into either skipping a section of the
7622: input buffer@footnote{This is how parsing words work.} or into parsing a
7623: section twice. For example:
1.27 crook 7624:
1.29 crook 7625: @example
1.71 anton 7626: : lat ." <<foo>>" ;
7627: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7628: @end example
7629:
7630: @noindent
7631: When @code{flat} is executed, this output is produced@footnote{Exercise
7632: for the reader: what would happen if the @code{3} were replaced with
7633: @code{4}?}:
7634:
7635: @example
1.71 anton 7636: <<bar>><<foo>>
1.29 crook 7637: @end example
7638:
1.71 anton 7639: This technique can be used to work around some of the interoperability
7640: problems of parsing words. Of course, it's better to avoid parsing
7641: words where possible.
7642:
1.29 crook 7643: @noindent
7644: Two important notes about the behaviour of the text interpreter:
1.27 crook 7645:
7646: @itemize @bullet
7647: @item
7648: It processes each input string to completion before parsing additional
1.29 crook 7649: characters from the input buffer.
7650: @item
7651: It treats the input buffer as a read-only region (and so must your code).
7652: @end itemize
7653:
7654: @noindent
7655: When the text interpreter is in compile state, its behaviour changes in
7656: these ways:
7657:
7658: @itemize @bullet
7659: @item
7660: If a parsed string is found in the dictionary, the text interpreter will
7661: perform the word's @dfn{compilation semantics}. In most cases, this
7662: simply means that the execution semantics of the word will be appended
7663: to the current definition.
1.27 crook 7664: @item
1.29 crook 7665: When a number is encountered, it is compiled into the current definition
7666: (as a literal) rather than being pushed onto a parameter stack.
7667: @item
7668: If an error occurs, @code{state} is modified to put the text interpreter
7669: back into interpret state.
7670: @item
7671: Each time a line is entered from the keyboard, Gforth prints
7672: ``@code{ compiled}'' rather than `` @code{ok}''.
7673: @end itemize
7674:
7675: @cindex text interpreter - input sources
7676: When the text interpreter is using an input device other than the
7677: keyboard, its behaviour changes in these ways:
7678:
7679: @itemize @bullet
7680: @item
7681: When the parse area is empty, the text interpreter attempts to refill
7682: the input buffer from the input source. When the input source is
1.71 anton 7683: exhausted, the input source is set back to the previous input source.
1.29 crook 7684: @item
7685: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7686: time the parse area is emptied.
7687: @item
7688: If an error occurs, the input source is set back to the user input
7689: device.
1.27 crook 7690: @end itemize
1.21 crook 7691:
1.49 anton 7692: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7693:
1.26 crook 7694: doc->in
1.27 crook 7695: doc-source
7696:
1.26 crook 7697: doc-tib
7698: doc-#tib
1.1 anton 7699:
1.44 crook 7700:
1.26 crook 7701: @menu
1.67 anton 7702: * Input Sources::
7703: * Number Conversion::
7704: * Interpret/Compile states::
7705: * Interpreter Directives::
1.26 crook 7706: @end menu
1.1 anton 7707:
1.29 crook 7708: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7709: @subsection Input Sources
7710: @cindex input sources
7711: @cindex text interpreter - input sources
7712:
1.44 crook 7713: By default, the text interpreter processes input from the user input
1.29 crook 7714: device (the keyboard) when Forth starts up. The text interpreter can
7715: process input from any of these sources:
7716:
7717: @itemize @bullet
7718: @item
7719: The user input device -- the keyboard.
7720: @item
7721: A file, using the words described in @ref{Forth source files}.
7722: @item
7723: A block, using the words described in @ref{Blocks}.
7724: @item
7725: A text string, using @code{evaluate}.
7726: @end itemize
7727:
7728: A program can identify the current input device from the values of
7729: @code{source-id} and @code{blk}.
7730:
1.44 crook 7731:
1.29 crook 7732: doc-source-id
7733: doc-blk
7734:
7735: doc-save-input
7736: doc-restore-input
7737:
7738: doc-evaluate
1.111 anton 7739: doc-query
1.1 anton 7740:
1.29 crook 7741:
1.44 crook 7742:
1.29 crook 7743: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7744: @subsection Number Conversion
7745: @cindex number conversion
7746: @cindex double-cell numbers, input format
7747: @cindex input format for double-cell numbers
7748: @cindex single-cell numbers, input format
7749: @cindex input format for single-cell numbers
7750: @cindex floating-point numbers, input format
7751: @cindex input format for floating-point numbers
1.1 anton 7752:
1.29 crook 7753: This section describes the rules that the text interpreter uses when it
7754: tries to convert a string into a number.
1.1 anton 7755:
1.26 crook 7756: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7757: number base@footnote{For example, 0-9 when the number base is decimal or
7758: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7759:
1.26 crook 7760: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7761:
1.29 crook 7762: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7763: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7764:
1.26 crook 7765: Let * represent any number of instances of the previous character
7766: (including none).
1.1 anton 7767:
1.26 crook 7768: Let any other character represent itself.
1.1 anton 7769:
1.29 crook 7770: @noindent
1.26 crook 7771: Now, the conversion rules are:
1.21 crook 7772:
1.26 crook 7773: @itemize @bullet
7774: @item
7775: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7776: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7777: @item
7778: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7779: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7780: arithmetic. Examples are -45 -5681 -0
7781: @item
7782: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7783: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7784: (all three of these represent the same number).
1.26 crook 7785: @item
7786: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7787: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7788: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7789: -34.65 (all three of these represent the same number).
1.26 crook 7790: @item
1.29 crook 7791: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7792: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7793: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7794: number) +12.E-4
1.26 crook 7795: @end itemize
1.1 anton 7796:
1.174 anton 7797: By default, the number base used for integer number conversion is
7798: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7799: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7800: change @code{base} anywhere, make sure to save the old value and
7801: restore it afterwards; better yet, use @code{base-execute}, which does
7802: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7803: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7804:
1.29 crook 7805: doc-dpl
1.174 anton 7806: doc-base-execute
1.26 crook 7807: doc-base
7808: doc-hex
7809: doc-decimal
1.1 anton 7810:
1.26 crook 7811: @cindex '-prefix for character strings
7812: @cindex &-prefix for decimal numbers
1.133 anton 7813: @cindex #-prefix for decimal numbers
1.26 crook 7814: @cindex %-prefix for binary numbers
7815: @cindex $-prefix for hexadecimal numbers
1.133 anton 7816: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7817: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7818: prefix@footnote{Some Forth implementations provide a similar scheme by
7819: implementing @code{$} etc. as parsing words that process the subsequent
7820: number in the input stream and push it onto the stack. For example, see
7821: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7822: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7823: is required between the prefix and the number.} before the first digit
1.133 anton 7824: of an (integer) number. The following prefixes are supported:
1.1 anton 7825:
1.26 crook 7826: @itemize @bullet
7827: @item
1.35 anton 7828: @code{&} -- decimal
1.26 crook 7829: @item
1.133 anton 7830: @code{#} -- decimal
7831: @item
1.35 anton 7832: @code{%} -- binary
1.26 crook 7833: @item
1.35 anton 7834: @code{$} -- hexadecimal
1.26 crook 7835: @item
1.133 anton 7836: @code{0x} -- hexadecimal, if base<33.
7837: @item
7838: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7839: optional @code{'} may be present after the character.
1.26 crook 7840: @end itemize
1.1 anton 7841:
1.26 crook 7842: Here are some examples, with the equivalent decimal number shown after
7843: in braces:
1.1 anton 7844:
1.26 crook 7845: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7846: 'A (65),
7847: -'a' (-97),
1.26 crook 7848: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7849:
1.26 crook 7850: @cindex number conversion - traps for the unwary
1.29 crook 7851: @noindent
1.26 crook 7852: Number conversion has a number of traps for the unwary:
1.1 anton 7853:
1.26 crook 7854: @itemize @bullet
7855: @item
7856: You cannot determine the current number base using the code sequence
1.35 anton 7857: @code{base @@ .} -- the number base is always 10 in the current number
7858: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7859: @item
7860: If the number base is set to a value greater than 14 (for example,
7861: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7862: it to be intepreted as either a single-precision integer or a
7863: floating-point number (Gforth treats it as an integer). The ambiguity
7864: can be resolved by explicitly stating the sign of the mantissa and/or
7865: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7866: ambiguity arises; either representation will be treated as a
7867: floating-point number.
7868: @item
1.29 crook 7869: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7870: It is used to specify file types.
7871: @item
1.72 anton 7872: ANS Forth requires the @code{.} of a double-precision number to be the
7873: final character in the string. Gforth allows the @code{.} to be
7874: anywhere after the first digit.
1.26 crook 7875: @item
7876: The number conversion process does not check for overflow.
7877: @item
1.72 anton 7878: In an ANS Forth program @code{base} is required to be decimal when
7879: converting floating-point numbers. In Gforth, number conversion to
7880: floating-point numbers always uses base &10, irrespective of the value
7881: of @code{base}.
1.26 crook 7882: @end itemize
1.1 anton 7883:
1.49 anton 7884: You can read numbers into your programs with the words described in
1.181 anton 7885: @ref{Line input and conversion}.
1.1 anton 7886:
1.82 anton 7887: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7888: @subsection Interpret/Compile states
7889: @cindex Interpret/Compile states
1.1 anton 7890:
1.29 crook 7891: A standard program is not permitted to change @code{state}
7892: explicitly. However, it can change @code{state} implicitly, using the
7893: words @code{[} and @code{]}. When @code{[} is executed it switches
7894: @code{state} to interpret state, and therefore the text interpreter
7895: starts interpreting. When @code{]} is executed it switches @code{state}
7896: to compile state and therefore the text interpreter starts
1.44 crook 7897: compiling. The most common usage for these words is for switching into
7898: interpret state and back from within a colon definition; this technique
1.49 anton 7899: can be used to compile a literal (for an example, @pxref{Literals}) or
7900: for conditional compilation (for an example, @pxref{Interpreter
7901: Directives}).
1.44 crook 7902:
1.35 anton 7903:
7904: @c This is a bad example: It's non-standard, and it's not necessary.
7905: @c However, I can't think of a good example for switching into compile
7906: @c state when there is no current word (@code{state}-smart words are not a
7907: @c good reason). So maybe we should use an example for switching into
7908: @c interpret @code{state} in a colon def. - anton
1.44 crook 7909: @c nac-> I agree. I started out by putting in the example, then realised
7910: @c that it was non-ANS, so wrote more words around it. I hope this
7911: @c re-written version is acceptable to you. I do want to keep the example
7912: @c as it is helpful for showing what is and what is not portable, particularly
7913: @c where it outlaws a style in common use.
7914:
1.72 anton 7915: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7916: @c that, we can also show what's not. In any case, I have written a
7917: @c section Compiling Words which also deals with [ ].
1.35 anton 7918:
1.95 anton 7919: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7920:
1.95 anton 7921: @c @code{[} and @code{]} also give you the ability to switch into compile
7922: @c state and back, but we cannot think of any useful Standard application
7923: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7924:
7925: @c @example
7926: @c : AA ." this is A" ;
7927: @c : BB ." this is B" ;
7928: @c : CC ." this is C" ;
7929:
7930: @c create table ] aa bb cc [
7931:
7932: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7933: @c cells table + @@ execute ;
7934: @c @end example
7935:
7936: @c This example builds a jump table; @code{0 go} will display ``@code{this
7937: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7938: @c defining @code{table} like this:
7939:
7940: @c @example
7941: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7942: @c @end example
7943:
7944: @c The problem with this code is that the definition of @code{table} is not
7945: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7946: @c @i{may} work on systems where code space and data space co-incide, the
7947: @c Standard only allows data space to be assigned for a @code{CREATE}d
7948: @c word. In addition, the Standard only allows @code{@@} to access data
7949: @c space, whilst this example is using it to access code space. The only
7950: @c portable, Standard way to build this table is to build it in data space,
7951: @c like this:
7952:
7953: @c @example
7954: @c create table ' aa , ' bb , ' cc ,
7955: @c @end example
1.29 crook 7956:
1.95 anton 7957: @c doc-state
1.44 crook 7958:
1.29 crook 7959:
1.82 anton 7960: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7961: @subsection Interpreter Directives
7962: @cindex interpreter directives
1.72 anton 7963: @cindex conditional compilation
1.1 anton 7964:
1.29 crook 7965: These words are usually used in interpret state; typically to control
7966: which parts of a source file are processed by the text
1.26 crook 7967: interpreter. There are only a few ANS Forth Standard words, but Gforth
7968: supplements these with a rich set of immediate control structure words
7969: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7970: used in compile state (@pxref{Control Structures}). Typical usages:
7971:
7972: @example
1.72 anton 7973: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7974: .
7975: .
1.72 anton 7976: HAVE-ASSEMBLER [IF]
1.29 crook 7977: : ASSEMBLER-FEATURE
7978: ...
7979: ;
7980: [ENDIF]
7981: .
7982: .
7983: : SEE
7984: ... \ general-purpose SEE code
1.72 anton 7985: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7986: ... \ assembler-specific SEE code
7987: [ [ENDIF] ]
7988: ;
7989: @end example
1.1 anton 7990:
1.44 crook 7991:
1.26 crook 7992: doc-[IF]
7993: doc-[ELSE]
7994: doc-[THEN]
7995: doc-[ENDIF]
1.1 anton 7996:
1.26 crook 7997: doc-[IFDEF]
7998: doc-[IFUNDEF]
1.1 anton 7999:
1.26 crook 8000: doc-[?DO]
8001: doc-[DO]
8002: doc-[FOR]
8003: doc-[LOOP]
8004: doc-[+LOOP]
8005: doc-[NEXT]
1.1 anton 8006:
1.26 crook 8007: doc-[BEGIN]
8008: doc-[UNTIL]
8009: doc-[AGAIN]
8010: doc-[WHILE]
8011: doc-[REPEAT]
1.1 anton 8012:
1.27 crook 8013:
1.26 crook 8014: @c -------------------------------------------------------------
1.111 anton 8015: @node The Input Stream, Word Lists, The Text Interpreter, Words
8016: @section The Input Stream
8017: @cindex input stream
8018:
8019: @c !! integrate this better with the "Text Interpreter" section
8020: The text interpreter reads from the input stream, which can come from
8021: several sources (@pxref{Input Sources}). Some words, in particular
8022: defining words, but also words like @code{'}, read parameters from the
8023: input stream instead of from the stack.
8024:
8025: Such words are called parsing words, because they parse the input
8026: stream. Parsing words are hard to use in other words, because it is
8027: hard to pass program-generated parameters through the input stream.
8028: They also usually have an unintuitive combination of interpretation and
8029: compilation semantics when implemented naively, leading to various
8030: approaches that try to produce a more intuitive behaviour
8031: (@pxref{Combined words}).
8032:
8033: It should be obvious by now that parsing words are a bad idea. If you
8034: want to implement a parsing word for convenience, also provide a factor
8035: of the word that does not parse, but takes the parameters on the stack.
8036: To implement the parsing word on top if it, you can use the following
8037: words:
8038:
8039: @c anton: these belong in the input stream section
8040: doc-parse
1.138 anton 8041: doc-parse-name
1.111 anton 8042: doc-parse-word
8043: doc-name
8044: doc-word
8045: doc-refill
8046:
8047: Conversely, if you have the bad luck (or lack of foresight) to have to
8048: deal with parsing words without having such factors, how do you pass a
8049: string that is not in the input stream to it?
8050:
8051: doc-execute-parsing
8052:
1.146 anton 8053: A definition of this word in ANS Forth is provided in
8054: @file{compat/execute-parsing.fs}.
8055:
1.111 anton 8056: If you want to run a parsing word on a file, the following word should
8057: help:
8058:
8059: doc-execute-parsing-file
8060:
8061: @c -------------------------------------------------------------
8062: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8063: @section Word Lists
8064: @cindex word lists
1.32 anton 8065: @cindex header space
1.1 anton 8066:
1.36 anton 8067: A wordlist is a list of named words; you can add new words and look up
8068: words by name (and you can remove words in a restricted way with
8069: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8070:
8071: @cindex search order stack
8072: The text interpreter searches the wordlists present in the search order
8073: (a stack of wordlists), from the top to the bottom. Within each
8074: wordlist, the search starts conceptually at the newest word; i.e., if
8075: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8076:
1.26 crook 8077: @cindex compilation word list
1.36 anton 8078: New words are added to the @dfn{compilation wordlist} (aka current
8079: wordlist).
1.1 anton 8080:
1.36 anton 8081: @cindex wid
8082: A word list is identified by a cell-sized word list identifier (@i{wid})
8083: in much the same way as a file is identified by a file handle. The
8084: numerical value of the wid has no (portable) meaning, and might change
8085: from session to session.
1.1 anton 8086:
1.29 crook 8087: The ANS Forth ``Search order'' word set is intended to provide a set of
8088: low-level tools that allow various different schemes to be
1.74 anton 8089: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8090: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8091: Forth.
1.1 anton 8092:
1.27 crook 8093: @comment TODO: locals section refers to here, saying that every word list (aka
8094: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8095: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8096:
1.45 crook 8097: @comment TODO: document markers, reveal, tables, mappedwordlist
8098:
8099: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8100: @comment word from the source files, rather than some alias.
1.44 crook 8101:
1.26 crook 8102: doc-forth-wordlist
8103: doc-definitions
8104: doc-get-current
8105: doc-set-current
8106: doc-get-order
1.185 anton 8107: doc-set-order
1.26 crook 8108: doc-wordlist
1.30 anton 8109: doc-table
1.79 anton 8110: doc->order
1.36 anton 8111: doc-previous
1.26 crook 8112: doc-also
1.185 anton 8113: doc-forth
1.26 crook 8114: doc-only
1.185 anton 8115: doc-order
1.15 anton 8116:
1.26 crook 8117: doc-find
8118: doc-search-wordlist
1.15 anton 8119:
1.26 crook 8120: doc-words
8121: doc-vlist
1.44 crook 8122: @c doc-words-deferred
1.1 anton 8123:
1.74 anton 8124: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8125: doc-root
8126: doc-vocabulary
8127: doc-seal
8128: doc-vocs
8129: doc-current
8130: doc-context
1.1 anton 8131:
1.44 crook 8132:
1.26 crook 8133: @menu
1.75 anton 8134: * Vocabularies::
1.67 anton 8135: * Why use word lists?::
1.75 anton 8136: * Word list example::
1.26 crook 8137: @end menu
8138:
1.75 anton 8139: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8140: @subsection Vocabularies
8141: @cindex Vocabularies, detailed explanation
8142:
8143: Here is an example of creating and using a new wordlist using ANS
8144: Forth words:
8145:
8146: @example
8147: wordlist constant my-new-words-wordlist
8148: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8149:
8150: \ add it to the search order
8151: also my-new-words
8152:
8153: \ alternatively, add it to the search order and make it
8154: \ the compilation word list
8155: also my-new-words definitions
8156: \ type "order" to see the problem
8157: @end example
8158:
8159: The problem with this example is that @code{order} has no way to
8160: associate the name @code{my-new-words} with the wid of the word list (in
8161: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8162: that has no associated name). There is no Standard way of associating a
8163: name with a wid.
8164:
8165: In Gforth, this example can be re-coded using @code{vocabulary}, which
8166: associates a name with a wid:
8167:
8168: @example
8169: vocabulary my-new-words
8170:
8171: \ add it to the search order
8172: also my-new-words
8173:
8174: \ alternatively, add it to the search order and make it
8175: \ the compilation word list
8176: my-new-words definitions
8177: \ type "order" to see that the problem is solved
8178: @end example
8179:
8180:
8181: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8182: @subsection Why use word lists?
8183: @cindex word lists - why use them?
8184:
1.74 anton 8185: Here are some reasons why people use wordlists:
1.26 crook 8186:
8187: @itemize @bullet
1.74 anton 8188:
8189: @c anton: Gforth's hashing implementation makes the search speed
8190: @c independent from the number of words. But it is linear with the number
8191: @c of wordlists that have to be searched, so in effect using more wordlists
8192: @c actually slows down compilation.
8193:
8194: @c @item
8195: @c To improve compilation speed by reducing the number of header space
8196: @c entries that must be searched. This is achieved by creating a new
8197: @c word list that contains all of the definitions that are used in the
8198: @c definition of a Forth system but which would not usually be used by
8199: @c programs running on that system. That word list would be on the search
8200: @c list when the Forth system was compiled but would be removed from the
8201: @c search list for normal operation. This can be a useful technique for
8202: @c low-performance systems (for example, 8-bit processors in embedded
8203: @c systems) but is unlikely to be necessary in high-performance desktop
8204: @c systems.
8205:
1.26 crook 8206: @item
8207: To prevent a set of words from being used outside the context in which
8208: they are valid. Two classic examples of this are an integrated editor
8209: (all of the edit commands are defined in a separate word list; the
8210: search order is set to the editor word list when the editor is invoked;
8211: the old search order is restored when the editor is terminated) and an
8212: integrated assembler (the op-codes for the machine are defined in a
8213: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8214:
8215: @item
8216: To organize the words of an application or library into a user-visible
8217: set (in @code{forth-wordlist} or some other common wordlist) and a set
8218: of helper words used just for the implementation (hidden in a separate
1.75 anton 8219: wordlist). This keeps @code{words}' output smaller, separates
8220: implementation and interface, and reduces the chance of name conflicts
8221: within the common wordlist.
1.74 anton 8222:
1.26 crook 8223: @item
8224: To prevent a name-space clash between multiple definitions with the same
8225: name. For example, when building a cross-compiler you might have a word
8226: @code{IF} that generates conditional code for your target system. By
8227: placing this definition in a different word list you can control whether
8228: the host system's @code{IF} or the target system's @code{IF} get used in
8229: any particular context by controlling the order of the word lists on the
8230: search order stack.
1.74 anton 8231:
1.26 crook 8232: @end itemize
1.1 anton 8233:
1.74 anton 8234: The downsides of using wordlists are:
8235:
8236: @itemize
8237:
8238: @item
8239: Debugging becomes more cumbersome.
8240:
8241: @item
8242: Name conflicts worked around with wordlists are still there, and you
8243: have to arrange the search order carefully to get the desired results;
8244: if you forget to do that, you get hard-to-find errors (as in any case
8245: where you read the code differently from the compiler; @code{see} can
1.75 anton 8246: help seeing which of several possible words the name resolves to in such
8247: cases). @code{See} displays just the name of the words, not what
8248: wordlist they belong to, so it might be misleading. Using unique names
8249: is a better approach to avoid name conflicts.
1.74 anton 8250:
8251: @item
8252: You have to explicitly undo any changes to the search order. In many
8253: cases it would be more convenient if this happened implicitly. Gforth
8254: currently does not provide such a feature, but it may do so in the
8255: future.
8256: @end itemize
8257:
8258:
1.75 anton 8259: @node Word list example, , Why use word lists?, Word Lists
8260: @subsection Word list example
8261: @cindex word lists - example
1.1 anton 8262:
1.74 anton 8263: The following example is from the
8264: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8265: garbage collector} and uses wordlists to separate public words from
8266: helper words:
8267:
8268: @example
8269: get-current ( wid )
8270: vocabulary garbage-collector also garbage-collector definitions
8271: ... \ define helper words
8272: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8273: ... \ define the public (i.e., API) words
8274: \ they can refer to the helper words
8275: previous \ restore original search order (helper words become invisible)
8276: @end example
8277:
1.26 crook 8278: @c -------------------------------------------------------------
8279: @node Environmental Queries, Files, Word Lists, Words
8280: @section Environmental Queries
8281: @cindex environmental queries
1.21 crook 8282:
1.26 crook 8283: ANS Forth introduced the idea of ``environmental queries'' as a way
8284: for a program running on a system to determine certain characteristics of the system.
8285: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8286:
1.32 anton 8287: The Standard requires that the header space used for environmental queries
8288: be distinct from the header space used for definitions.
1.21 crook 8289:
1.26 crook 8290: Typically, environmental queries are supported by creating a set of
1.29 crook 8291: definitions in a word list that is @i{only} used during environmental
1.26 crook 8292: queries; that is what Gforth does. There is no Standard way of adding
8293: definitions to the set of recognised environmental queries, but any
8294: implementation that supports the loading of optional word sets must have
8295: some mechanism for doing this (after loading the word set, the
8296: associated environmental query string must return @code{true}). In
8297: Gforth, the word list used to honour environmental queries can be
8298: manipulated just like any other word list.
1.21 crook 8299:
1.44 crook 8300:
1.26 crook 8301: doc-environment?
8302: doc-environment-wordlist
1.21 crook 8303:
1.26 crook 8304: doc-gforth
8305: doc-os-class
1.21 crook 8306:
1.44 crook 8307:
1.26 crook 8308: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8309: returning two items on the stack, querying it using @code{environment?}
8310: will return an additional item; the @code{true} flag that shows that the
8311: string was recognised.
1.21 crook 8312:
1.26 crook 8313: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8314:
1.26 crook 8315: Here are some examples of using environmental queries:
1.21 crook 8316:
1.26 crook 8317: @example
8318: s" address-unit-bits" environment? 0=
8319: [IF]
8320: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8321: [ELSE]
8322: drop \ ensure balanced stack effect
1.26 crook 8323: [THEN]
1.21 crook 8324:
1.75 anton 8325: \ this might occur in the prelude of a standard program that uses THROW
8326: s" exception" environment? [IF]
8327: 0= [IF]
8328: : throw abort" exception thrown" ;
8329: [THEN]
8330: [ELSE] \ we don't know, so make sure
8331: : throw abort" exception thrown" ;
8332: [THEN]
1.21 crook 8333:
1.26 crook 8334: s" gforth" environment? [IF] .( Gforth version ) TYPE
8335: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8336:
8337: \ a program using v*
8338: s" gforth" environment? [IF]
8339: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8340: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8341: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8342: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8343: LOOP
8344: 2drop 2drop ;
8345: [THEN]
8346: [ELSE] \
8347: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8348: ...
8349: [THEN]
1.26 crook 8350: @end example
1.21 crook 8351:
1.26 crook 8352: Here is an example of adding a definition to the environment word list:
1.21 crook 8353:
1.26 crook 8354: @example
8355: get-current environment-wordlist set-current
8356: true constant block
8357: true constant block-ext
8358: set-current
8359: @end example
1.21 crook 8360:
1.26 crook 8361: You can see what definitions are in the environment word list like this:
1.21 crook 8362:
1.26 crook 8363: @example
1.79 anton 8364: environment-wordlist >order words previous
1.26 crook 8365: @end example
1.21 crook 8366:
8367:
1.26 crook 8368: @c -------------------------------------------------------------
8369: @node Files, Blocks, Environmental Queries, Words
8370: @section Files
1.28 crook 8371: @cindex files
8372: @cindex I/O - file-handling
1.21 crook 8373:
1.26 crook 8374: Gforth provides facilities for accessing files that are stored in the
8375: host operating system's file-system. Files that are processed by Gforth
8376: can be divided into two categories:
1.21 crook 8377:
1.23 crook 8378: @itemize @bullet
8379: @item
1.29 crook 8380: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8381: @item
1.29 crook 8382: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8383: @end itemize
8384:
8385: @menu
1.48 anton 8386: * Forth source files::
8387: * General files::
1.167 anton 8388: * Redirection::
1.48 anton 8389: * Search Paths::
1.26 crook 8390: @end menu
8391:
8392: @c -------------------------------------------------------------
8393: @node Forth source files, General files, Files, Files
8394: @subsection Forth source files
8395: @cindex including files
8396: @cindex Forth source files
1.21 crook 8397:
1.26 crook 8398: The simplest way to interpret the contents of a file is to use one of
8399: these two formats:
1.21 crook 8400:
1.26 crook 8401: @example
8402: include mysource.fs
8403: s" mysource.fs" included
8404: @end example
1.21 crook 8405:
1.75 anton 8406: You usually want to include a file only if it is not included already
1.26 crook 8407: (by, say, another source file). In that case, you can use one of these
1.45 crook 8408: three formats:
1.21 crook 8409:
1.26 crook 8410: @example
8411: require mysource.fs
8412: needs mysource.fs
8413: s" mysource.fs" required
8414: @end example
1.21 crook 8415:
1.26 crook 8416: @cindex stack effect of included files
8417: @cindex including files, stack effect
1.45 crook 8418: It is good practice to write your source files such that interpreting them
8419: does not change the stack. Source files designed in this way can be used with
1.26 crook 8420: @code{required} and friends without complications. For example:
1.21 crook 8421:
1.26 crook 8422: @example
1.75 anton 8423: 1024 require foo.fs drop
1.26 crook 8424: @end example
1.21 crook 8425:
1.75 anton 8426: Here you want to pass the argument 1024 (e.g., a buffer size) to
8427: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8428: ), which allows its use with @code{require}. Of course with such
8429: parameters to required files, you have to ensure that the first
8430: @code{require} fits for all uses (i.e., @code{require} it early in the
8431: master load file).
1.44 crook 8432:
1.26 crook 8433: doc-include-file
8434: doc-included
1.28 crook 8435: doc-included?
1.26 crook 8436: doc-include
8437: doc-required
8438: doc-require
8439: doc-needs
1.75 anton 8440: @c doc-init-included-files @c internal
8441: doc-sourcefilename
8442: doc-sourceline#
1.44 crook 8443:
1.26 crook 8444: A definition in ANS Forth for @code{required} is provided in
8445: @file{compat/required.fs}.
1.21 crook 8446:
1.26 crook 8447: @c -------------------------------------------------------------
1.167 anton 8448: @node General files, Redirection, Forth source files, Files
1.26 crook 8449: @subsection General files
8450: @cindex general files
8451: @cindex file-handling
1.21 crook 8452:
1.75 anton 8453: Files are opened/created by name and type. The following file access
8454: methods (FAMs) are recognised:
1.44 crook 8455:
1.75 anton 8456: @cindex fam (file access method)
1.26 crook 8457: doc-r/o
8458: doc-r/w
8459: doc-w/o
8460: doc-bin
1.1 anton 8461:
1.44 crook 8462:
1.26 crook 8463: When a file is opened/created, it returns a file identifier,
1.29 crook 8464: @i{wfileid} that is used for all other file commands. All file
8465: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8466: successful operation and an implementation-defined non-zero value in the
8467: case of an error.
1.21 crook 8468:
1.44 crook 8469:
1.26 crook 8470: doc-open-file
8471: doc-create-file
1.21 crook 8472:
1.26 crook 8473: doc-close-file
8474: doc-delete-file
8475: doc-rename-file
8476: doc-read-file
8477: doc-read-line
1.154 anton 8478: doc-key-file
8479: doc-key?-file
1.26 crook 8480: doc-write-file
8481: doc-write-line
8482: doc-emit-file
8483: doc-flush-file
1.21 crook 8484:
1.26 crook 8485: doc-file-status
8486: doc-file-position
8487: doc-reposition-file
8488: doc-file-size
8489: doc-resize-file
1.21 crook 8490:
1.93 anton 8491: doc-slurp-file
8492: doc-slurp-fid
1.112 anton 8493: doc-stdin
8494: doc-stdout
8495: doc-stderr
1.44 crook 8496:
1.26 crook 8497: @c ---------------------------------------------------------
1.167 anton 8498: @node Redirection, Search Paths, General files, Files
8499: @subsection Redirection
8500: @cindex Redirection
8501: @cindex Input Redirection
8502: @cindex Output Redirection
8503:
8504: You can redirect the output of @code{type} and @code{emit} and all the
8505: words that use them (all output words that don't have an explicit
1.174 anton 8506: target file) to an arbitrary file with the @code{outfile-execute},
8507: used like this:
1.167 anton 8508:
8509: @example
1.174 anton 8510: : some-warning ( n -- )
8511: cr ." warning# " . ;
8512:
1.167 anton 8513: : print-some-warning ( n -- )
1.174 anton 8514: ['] some-warning stderr outfile-execute ;
1.167 anton 8515: @end example
8516:
1.174 anton 8517: After @code{some-warning} is executed, the original output direction
8518: is restored; this construct is safe against exceptions. Similarly,
8519: there is @code{infile-execute} for redirecting the input of @code{key}
8520: and its users (any input word that does not take a file explicitly).
8521:
8522: doc-outfile-execute
8523: doc-infile-execute
1.167 anton 8524:
8525: If you do not want to redirect the input or output to a file, you can
8526: also make use of the fact that @code{key}, @code{emit} and @code{type}
8527: are deferred words (@pxref{Deferred Words}). However, in that case
8528: you have to worry about the restoration and the protection against
8529: exceptions yourself; also, note that for redirecting the output in
8530: this way, you have to redirect both @code{emit} and @code{type}.
8531:
8532: @c ---------------------------------------------------------
8533: @node Search Paths, , Redirection, Files
1.26 crook 8534: @subsection Search Paths
8535: @cindex path for @code{included}
8536: @cindex file search path
8537: @cindex @code{include} search path
8538: @cindex search path for files
1.21 crook 8539:
1.26 crook 8540: If you specify an absolute filename (i.e., a filename starting with
8541: @file{/} or @file{~}, or with @file{:} in the second position (as in
8542: @samp{C:...})) for @code{included} and friends, that file is included
8543: just as you would expect.
1.21 crook 8544:
1.75 anton 8545: If the filename starts with @file{./}, this refers to the directory that
8546: the present file was @code{included} from. This allows files to include
8547: other files relative to their own position (irrespective of the current
8548: working directory or the absolute position). This feature is essential
8549: for libraries consisting of several files, where a file may include
8550: other files from the library. It corresponds to @code{#include "..."}
8551: in C. If the current input source is not a file, @file{.} refers to the
8552: directory of the innermost file being included, or, if there is no file
8553: being included, to the current working directory.
8554:
8555: For relative filenames (not starting with @file{./}), Gforth uses a
8556: search path similar to Forth's search order (@pxref{Word Lists}). It
8557: tries to find the given filename in the directories present in the path,
8558: and includes the first one it finds. There are separate search paths for
8559: Forth source files and general files. If the search path contains the
8560: directory @file{.}, this refers to the directory of the current file, or
8561: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8562:
1.26 crook 8563: Use @file{~+} to refer to the current working directory (as in the
8564: @code{bash}).
1.1 anton 8565:
1.75 anton 8566: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8567:
1.48 anton 8568: @menu
1.75 anton 8569: * Source Search Paths::
1.48 anton 8570: * General Search Paths::
8571: @end menu
8572:
1.26 crook 8573: @c ---------------------------------------------------------
1.75 anton 8574: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8575: @subsubsection Source Search Paths
8576: @cindex search path control, source files
1.5 anton 8577:
1.26 crook 8578: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8579: Gforth}). You can display it and change it using @code{fpath} in
8580: combination with the general path handling words.
1.5 anton 8581:
1.75 anton 8582: doc-fpath
8583: @c the functionality of the following words is easily available through
8584: @c fpath and the general path words. The may go away.
8585: @c doc-.fpath
8586: @c doc-fpath+
8587: @c doc-fpath=
8588: @c doc-open-fpath-file
1.44 crook 8589:
8590: @noindent
1.26 crook 8591: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8592:
1.26 crook 8593: @example
1.75 anton 8594: fpath path= /usr/lib/forth/|./
1.26 crook 8595: require timer.fs
8596: @end example
1.5 anton 8597:
1.75 anton 8598:
1.26 crook 8599: @c ---------------------------------------------------------
1.75 anton 8600: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8601: @subsubsection General Search Paths
1.75 anton 8602: @cindex search path control, source files
1.5 anton 8603:
1.26 crook 8604: Your application may need to search files in several directories, like
8605: @code{included} does. To facilitate this, Gforth allows you to define
8606: and use your own search paths, by providing generic equivalents of the
8607: Forth search path words:
1.5 anton 8608:
1.75 anton 8609: doc-open-path-file
8610: doc-path-allot
8611: doc-clear-path
8612: doc-also-path
1.26 crook 8613: doc-.path
8614: doc-path+
8615: doc-path=
1.5 anton 8616:
1.75 anton 8617: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8618:
1.75 anton 8619: Here's an example of creating an empty search path:
8620: @c
1.26 crook 8621: @example
1.75 anton 8622: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8623: @end example
1.5 anton 8624:
1.26 crook 8625: @c -------------------------------------------------------------
8626: @node Blocks, Other I/O, Files, Words
8627: @section Blocks
1.28 crook 8628: @cindex I/O - blocks
8629: @cindex blocks
8630:
8631: When you run Gforth on a modern desk-top computer, it runs under the
8632: control of an operating system which provides certain services. One of
8633: these services is @var{file services}, which allows Forth source code
8634: and data to be stored in files and read into Gforth (@pxref{Files}).
8635:
8636: Traditionally, Forth has been an important programming language on
8637: systems where it has interfaced directly to the underlying hardware with
8638: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8639: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8640:
8641: A block is a 1024-byte data area, which can be used to hold data or
8642: Forth source code. No structure is imposed on the contents of the
8643: block. A block is identified by its number; blocks are numbered
8644: contiguously from 1 to an implementation-defined maximum.
8645:
8646: A typical system that used blocks but no operating system might use a
8647: single floppy-disk drive for mass storage, with the disks formatted to
8648: provide 256-byte sectors. Blocks would be implemented by assigning the
8649: first four sectors of the disk to block 1, the second four sectors to
8650: block 2 and so on, up to the limit of the capacity of the disk. The disk
8651: would not contain any file system information, just the set of blocks.
8652:
1.29 crook 8653: @cindex blocks file
1.28 crook 8654: On systems that do provide file services, blocks are typically
1.29 crook 8655: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8656: file}. The size of the blocks file will be an exact multiple of 1024
8657: bytes, corresponding to the number of blocks it contains. This is the
8658: mechanism that Gforth uses.
8659:
1.29 crook 8660: @cindex @file{blocks.fb}
1.75 anton 8661: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8662: having specified a blocks file, Gforth defaults to the blocks file
8663: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8664: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8665:
1.29 crook 8666: @cindex block buffers
1.28 crook 8667: When you read and write blocks under program control, Gforth uses a
1.29 crook 8668: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8669: not used when you use @code{load} to interpret the contents of a block.
8670:
1.75 anton 8671: The behaviour of the block buffers is analagous to that of a cache.
8672: Each block buffer has three states:
1.28 crook 8673:
8674: @itemize @bullet
8675: @item
8676: Unassigned
8677: @item
8678: Assigned-clean
8679: @item
8680: Assigned-dirty
8681: @end itemize
8682:
1.29 crook 8683: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8684: block, the block (specified by its block number) must be assigned to a
8685: block buffer.
8686:
8687: The assignment of a block to a block buffer is performed by @code{block}
8688: or @code{buffer}. Use @code{block} when you wish to modify the existing
8689: contents of a block. Use @code{buffer} when you don't care about the
8690: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8691: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8692: with the particular block is already stored in a block buffer due to an
8693: earlier @code{block} command, @code{buffer} will return that block
8694: buffer and the existing contents of the block will be
8695: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8696: block buffer for the block.}.
1.28 crook 8697:
1.47 crook 8698: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8699: @code{buffer}, that block buffer becomes the @i{current block
8700: buffer}. Data may only be manipulated (read or written) within the
8701: current block buffer.
1.47 crook 8702:
8703: When the contents of the current block buffer has been modified it is
1.48 anton 8704: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8705: either abandon the changes (by doing nothing) or mark the block as
8706: changed (assigned-dirty), using @code{update}. Using @code{update} does
8707: not change the blocks file; it simply changes a block buffer's state to
8708: @i{assigned-dirty}. The block will be written implicitly when it's
8709: buffer is needed for another block, or explicitly by @code{flush} or
8710: @code{save-buffers}.
8711:
8712: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8713: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8714: @code{flush}.
1.28 crook 8715:
1.29 crook 8716: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8717: algorithm to assign a block buffer to a block. That means that any
8718: particular block can only be assigned to one specific block buffer,
1.29 crook 8719: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8720: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8721: the new block immediately. If it is @i{assigned-dirty} its current
8722: contents are written back to the blocks file on disk before it is
1.28 crook 8723: allocated to the new block.
8724:
8725: Although no structure is imposed on the contents of a block, it is
8726: traditional to display the contents as 16 lines each of 64 characters. A
8727: block provides a single, continuous stream of input (for example, it
8728: acts as a single parse area) -- there are no end-of-line characters
8729: within a block, and no end-of-file character at the end of a
8730: block. There are two consequences of this:
1.26 crook 8731:
1.28 crook 8732: @itemize @bullet
8733: @item
8734: The last character of one line wraps straight into the first character
8735: of the following line
8736: @item
8737: The word @code{\} -- comment to end of line -- requires special
8738: treatment; in the context of a block it causes all characters until the
8739: end of the current 64-character ``line'' to be ignored.
8740: @end itemize
8741:
8742: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8743: the current blocks file will be extended to the appropriate size and the
1.28 crook 8744: block buffer will be initialised with spaces.
8745:
1.47 crook 8746: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8747: for details) but doesn't encourage the use of blocks; the mechanism is
8748: only provided for backward compatibility -- ANS Forth requires blocks to
8749: be available when files are.
1.28 crook 8750:
8751: Common techniques that are used when working with blocks include:
8752:
8753: @itemize @bullet
8754: @item
8755: A screen editor that allows you to edit blocks without leaving the Forth
8756: environment.
8757: @item
8758: Shadow screens; where every code block has an associated block
8759: containing comments (for example: code in odd block numbers, comments in
8760: even block numbers). Typically, the block editor provides a convenient
8761: mechanism to toggle between code and comments.
8762: @item
8763: Load blocks; a single block (typically block 1) contains a number of
8764: @code{thru} commands which @code{load} the whole of the application.
8765: @end itemize
1.26 crook 8766:
1.29 crook 8767: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8768: integrated into a Forth programming environment.
1.26 crook 8769:
8770: @comment TODO what about errors on open-blocks?
1.44 crook 8771:
1.26 crook 8772: doc-open-blocks
8773: doc-use
1.75 anton 8774: doc-block-offset
1.26 crook 8775: doc-get-block-fid
8776: doc-block-position
1.28 crook 8777:
1.75 anton 8778: doc-list
1.28 crook 8779: doc-scr
8780:
1.184 anton 8781: doc-block
1.28 crook 8782: doc-buffer
8783:
1.75 anton 8784: doc-empty-buffers
8785: doc-empty-buffer
1.26 crook 8786: doc-update
1.28 crook 8787: doc-updated?
1.26 crook 8788: doc-save-buffers
1.75 anton 8789: doc-save-buffer
1.26 crook 8790: doc-flush
1.28 crook 8791:
1.26 crook 8792: doc-load
8793: doc-thru
8794: doc-+load
8795: doc-+thru
1.45 crook 8796: doc---gforthman--->
1.26 crook 8797: doc-block-included
8798:
1.44 crook 8799:
1.26 crook 8800: @c -------------------------------------------------------------
1.126 pazsan 8801: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8802: @section Other I/O
1.28 crook 8803: @cindex I/O - keyboard and display
1.26 crook 8804:
8805: @menu
8806: * Simple numeric output:: Predefined formats
8807: * Formatted numeric output:: Formatted (pictured) output
8808: * String Formats:: How Forth stores strings in memory
1.67 anton 8809: * Displaying characters and strings:: Other stuff
1.175 anton 8810: * Terminal output:: Cursor positioning etc.
1.181 anton 8811: * Single-key input::
8812: * Line input and conversion::
1.112 anton 8813: * Pipes:: How to create your own pipes
1.149 pazsan 8814: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8815: @end menu
8816:
8817: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8818: @subsection Simple numeric output
1.28 crook 8819: @cindex numeric output - simple/free-format
1.5 anton 8820:
1.26 crook 8821: The simplest output functions are those that display numbers from the
8822: data or floating-point stacks. Floating-point output is always displayed
8823: using base 10. Numbers displayed from the data stack use the value stored
8824: in @code{base}.
1.5 anton 8825:
1.44 crook 8826:
1.26 crook 8827: doc-.
8828: doc-dec.
8829: doc-hex.
8830: doc-u.
8831: doc-.r
8832: doc-u.r
8833: doc-d.
8834: doc-ud.
8835: doc-d.r
8836: doc-ud.r
8837: doc-f.
8838: doc-fe.
8839: doc-fs.
1.111 anton 8840: doc-f.rdp
1.44 crook 8841:
1.26 crook 8842: Examples of printing the number 1234.5678E23 in the different floating-point output
8843: formats are shown below:
1.5 anton 8844:
8845: @example
1.26 crook 8846: f. 123456779999999000000000000.
8847: fe. 123.456779999999E24
8848: fs. 1.23456779999999E26
1.5 anton 8849: @end example
8850:
8851:
1.26 crook 8852: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8853: @subsection Formatted numeric output
1.28 crook 8854: @cindex formatted numeric output
1.26 crook 8855: @cindex pictured numeric output
1.28 crook 8856: @cindex numeric output - formatted
1.26 crook 8857:
1.29 crook 8858: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8859: output} for formatted printing of integers. In this technique, digits
8860: are extracted from the number (using the current output radix defined by
8861: @code{base}), converted to ASCII codes and appended to a string that is
8862: built in a scratch-pad area of memory (@pxref{core-idef,
8863: Implementation-defined options, Implementation-defined
8864: options}). Arbitrary characters can be appended to the string during the
8865: extraction process. The completed string is specified by an address
8866: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8867: under program control.
1.5 anton 8868:
1.75 anton 8869: All of the integer output words described in the previous section
8870: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8871: numeric output.
1.5 anton 8872:
1.47 crook 8873: Three important things to remember about pictured numeric output:
1.5 anton 8874:
1.26 crook 8875: @itemize @bullet
8876: @item
1.28 crook 8877: It always operates on double-precision numbers; to display a
1.49 anton 8878: single-precision number, convert it first (for ways of doing this
8879: @pxref{Double precision}).
1.26 crook 8880: @item
1.28 crook 8881: It always treats the double-precision number as though it were
8882: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8883: @item
8884: The string is built up from right to left; least significant digit first.
8885: @end itemize
1.5 anton 8886:
1.44 crook 8887:
1.26 crook 8888: doc-<#
1.47 crook 8889: doc-<<#
1.26 crook 8890: doc-#
8891: doc-#s
8892: doc-hold
8893: doc-sign
8894: doc-#>
1.47 crook 8895: doc-#>>
1.5 anton 8896:
1.26 crook 8897: doc-represent
1.111 anton 8898: doc-f>str-rdp
8899: doc-f>buf-rdp
1.5 anton 8900:
1.44 crook 8901:
8902: @noindent
1.26 crook 8903: Here are some examples of using pictured numeric output:
1.5 anton 8904:
8905: @example
1.26 crook 8906: : my-u. ( u -- )
8907: \ Simplest use of pns.. behaves like Standard u.
8908: 0 \ convert to unsigned double
1.75 anton 8909: <<# \ start conversion
1.26 crook 8910: #s \ convert all digits
8911: #> \ complete conversion
1.75 anton 8912: TYPE SPACE \ display, with trailing space
8913: #>> ; \ release hold area
1.5 anton 8914:
1.26 crook 8915: : cents-only ( u -- )
8916: 0 \ convert to unsigned double
1.75 anton 8917: <<# \ start conversion
1.26 crook 8918: # # \ convert two least-significant digits
8919: #> \ complete conversion, discard other digits
1.75 anton 8920: TYPE SPACE \ display, with trailing space
8921: #>> ; \ release hold area
1.5 anton 8922:
1.26 crook 8923: : dollars-and-cents ( u -- )
8924: 0 \ convert to unsigned double
1.75 anton 8925: <<# \ start conversion
1.26 crook 8926: # # \ convert two least-significant digits
8927: [char] . hold \ insert decimal point
8928: #s \ convert remaining digits
8929: [char] $ hold \ append currency symbol
8930: #> \ complete conversion
1.75 anton 8931: TYPE SPACE \ display, with trailing space
8932: #>> ; \ release hold area
1.5 anton 8933:
1.26 crook 8934: : my-. ( n -- )
8935: \ handling negatives.. behaves like Standard .
8936: s>d \ convert to signed double
8937: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8938: <<# \ start conversion
1.26 crook 8939: #s \ convert all digits
8940: rot sign \ get at sign byte, append "-" if needed
8941: #> \ complete conversion
1.75 anton 8942: TYPE SPACE \ display, with trailing space
8943: #>> ; \ release hold area
1.5 anton 8944:
1.26 crook 8945: : account. ( n -- )
1.75 anton 8946: \ accountants don't like minus signs, they use parentheses
1.26 crook 8947: \ for negative numbers
8948: s>d \ convert to signed double
8949: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8950: <<# \ start conversion
1.26 crook 8951: 2 pick \ get copy of sign byte
8952: 0< IF [char] ) hold THEN \ right-most character of output
8953: #s \ convert all digits
8954: rot \ get at sign byte
8955: 0< IF [char] ( hold THEN
8956: #> \ complete conversion
1.75 anton 8957: TYPE SPACE \ display, with trailing space
8958: #>> ; \ release hold area
8959:
1.5 anton 8960: @end example
8961:
1.26 crook 8962: Here are some examples of using these words:
1.5 anton 8963:
8964: @example
1.26 crook 8965: 1 my-u. 1
8966: hex -1 my-u. decimal FFFFFFFF
8967: 1 cents-only 01
8968: 1234 cents-only 34
8969: 2 dollars-and-cents $0.02
8970: 1234 dollars-and-cents $12.34
8971: 123 my-. 123
8972: -123 my. -123
8973: 123 account. 123
8974: -456 account. (456)
1.5 anton 8975: @end example
8976:
8977:
1.26 crook 8978: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8979: @subsection String Formats
1.27 crook 8980: @cindex strings - see character strings
8981: @cindex character strings - formats
1.28 crook 8982: @cindex I/O - see character strings
1.75 anton 8983: @cindex counted strings
8984:
8985: @c anton: this does not really belong here; maybe the memory section,
8986: @c or the principles chapter
1.26 crook 8987:
1.27 crook 8988: Forth commonly uses two different methods for representing character
8989: strings:
1.26 crook 8990:
8991: @itemize @bullet
8992: @item
8993: @cindex address of counted string
1.45 crook 8994: @cindex counted string
1.29 crook 8995: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8996: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8997: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8998: memory.
8999: @item
1.29 crook 9000: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9001: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9002: first byte of the string.
9003: @end itemize
9004:
9005: ANS Forth encourages the use of the second format when representing
1.75 anton 9006: strings.
1.26 crook 9007:
1.44 crook 9008:
1.26 crook 9009: doc-count
9010:
1.44 crook 9011:
1.49 anton 9012: For words that move, copy and search for strings see @ref{Memory
9013: Blocks}. For words that display characters and strings see
9014: @ref{Displaying characters and strings}.
1.26 crook 9015:
1.175 anton 9016: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9017: @subsection Displaying characters and strings
1.27 crook 9018: @cindex characters - compiling and displaying
9019: @cindex character strings - compiling and displaying
1.26 crook 9020:
9021: This section starts with a glossary of Forth words and ends with a set
9022: of examples.
9023:
9024: doc-bl
9025: doc-space
9026: doc-spaces
9027: doc-emit
9028: doc-toupper
9029: doc-."
9030: doc-.(
1.98 anton 9031: doc-.\"
1.26 crook 9032: doc-type
1.44 crook 9033: doc-typewhite
1.26 crook 9034: doc-cr
1.27 crook 9035: @cindex cursor control
1.26 crook 9036: doc-s"
1.98 anton 9037: doc-s\"
1.26 crook 9038: doc-c"
9039: doc-char
9040: doc-[char]
9041:
1.44 crook 9042:
9043: @noindent
1.26 crook 9044: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9045:
9046: @example
1.26 crook 9047: .( text-1)
9048: : my-word
9049: ." text-2" cr
9050: .( text-3)
9051: ;
9052:
9053: ." text-4"
9054:
9055: : my-char
9056: [char] ALPHABET emit
9057: char emit
9058: ;
1.5 anton 9059: @end example
9060:
1.26 crook 9061: When you load this code into Gforth, the following output is generated:
1.5 anton 9062:
1.26 crook 9063: @example
1.30 anton 9064: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9065: @end example
1.5 anton 9066:
1.26 crook 9067: @itemize @bullet
9068: @item
9069: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9070: is an immediate word; it behaves in the same way whether it is used inside
9071: or outside a colon definition.
9072: @item
9073: Message @code{text-4} is displayed because of Gforth's added interpretation
9074: semantics for @code{."}.
9075: @item
1.29 crook 9076: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9077: performs the compilation semantics for @code{."} within the definition of
9078: @code{my-word}.
9079: @end itemize
1.5 anton 9080:
1.26 crook 9081: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9082:
1.26 crook 9083: @example
1.30 anton 9084: @kbd{my-word @key{RET}} text-2
1.26 crook 9085: ok
1.30 anton 9086: @kbd{my-char fred @key{RET}} Af ok
9087: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9088: @end example
1.5 anton 9089:
9090: @itemize @bullet
9091: @item
1.26 crook 9092: Message @code{text-2} is displayed because of the run-time behaviour of
9093: @code{."}.
9094: @item
9095: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9096: on the stack at run-time. @code{emit} always displays the character
9097: when @code{my-char} is executed.
9098: @item
9099: @code{char} parses a string at run-time and the second @code{emit} displays
9100: the first character of the string.
1.5 anton 9101: @item
1.26 crook 9102: If you type @code{see my-char} you can see that @code{[char]} discarded
9103: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9104: definition of @code{my-char}.
1.5 anton 9105: @end itemize
9106:
9107:
1.181 anton 9108: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9109: @subsection Terminal output
9110: @cindex output to terminal
9111: @cindex terminal output
9112:
9113: If you are outputting to a terminal, you may want to control the
9114: positioning of the cursor:
9115: @cindex cursor positioning
9116:
9117: doc-at-xy
9118:
9119: In order to know where to position the cursor, it is often helpful to
9120: know the size of the screen:
9121: @cindex terminal size
9122:
9123: doc-form
9124:
9125: And sometimes you want to use:
9126: @cindex clear screen
9127:
9128: doc-page
9129:
9130: Note that on non-terminals you should use @code{12 emit}, not
9131: @code{page}, to get a form feed.
9132:
1.5 anton 9133:
1.181 anton 9134: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9135: @subsection Single-key input
9136: @cindex single-key input
9137: @cindex input, single-key
9138:
9139: If you want to get a single printable character, you can use
9140: @code{key}; to check whether a character is available for @code{key},
9141: you can use @code{key?}.
1.5 anton 9142:
1.181 anton 9143: doc-key
9144: doc-key?
1.27 crook 9145:
1.181 anton 9146: If you want to process a mix of printable and non-printable
9147: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9148: produces a keyboard event that you have to convert into a character
9149: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9150:
9151: Typical code for using EKEY looks like this:
9152:
9153: @example
9154: ekey ekey>char if ( c )
9155: ... \ do something with the character
9156: else ekey>fkey if ( key-id )
9157: case
9158: k-up of ... endof
9159: k-f1 of ... endof
9160: k-left k-shift-mask or k-ctrl-mask or of ... endof
9161: ...
9162: endcase
9163: else ( keyboard-event )
9164: drop \ just ignore an unknown keyboard event type
9165: then then
9166: @end example
1.44 crook 9167:
1.45 crook 9168: doc-ekey
1.141 anton 9169: doc-ekey>char
1.181 anton 9170: doc-ekey>fkey
1.45 crook 9171: doc-ekey?
1.141 anton 9172:
1.181 anton 9173: The key identifiers for cursor keys are:
1.141 anton 9174:
9175: doc-k-left
9176: doc-k-right
1.185 anton 9177: doc-k-up
9178: doc-k-down
9179: doc-k-home
9180: doc-k-end
1.141 anton 9181: doc-k-prior
9182: doc-k-next
9183: doc-k-insert
9184: doc-k-delete
9185:
1.181 anton 9186: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9187:
1.181 anton 9188: doc-k-f1
9189: doc-k-f2
9190: doc-k-f3
9191: doc-k-f4
9192: doc-k-f5
9193: doc-k-f6
9194: doc-k-f7
9195: doc-k-f8
9196: doc-k-f9
9197: doc-k-f10
9198: doc-k-f11
9199: doc-k-f12
9200:
9201: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9202:
9203: You can combine these key identifiers with masks for various shift keys:
9204:
9205: doc-k-shift-mask
9206: doc-k-ctrl-mask
9207: doc-k-alt-mask
9208:
9209: Note that, even if a Forth system has @code{ekey>fkey} and the key
9210: identifier words, the keys are not necessarily available or it may not
9211: necessarily be able to report all the keys and all the possible
9212: combinations with shift masks. Therefore, write your programs in such
9213: a way that they are still useful even if the keys and key combinations
9214: cannot be pressed or are not recognized.
9215:
9216: Examples: Older keyboards often do not have an F11 and F12 key. If
9217: you run Gforth in an xterm, the xterm catches a number of combinations
9218: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9219: Gforth currently does not recognize and report combinations with
9220: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9221: above would never be entered).
9222:
9223: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9224: you need the ANSI.SYS driver to get that behaviour); it works by
9225: recognizing the escape sequences that ANSI terminals send when such a
9226: key is pressed. If you have a terminal that sends other escape
9227: sequences, you will not get useful results on Gforth. Other Forth
9228: systems may work in a different way.
9229:
9230:
9231: @node Line input and conversion, Pipes, Single-key input, Other I/O
9232: @subsection Line input and conversion
9233: @cindex line input from terminal
9234: @cindex input, linewise from terminal
9235: @cindex convertin strings to numbers
9236: @cindex I/O - see input
9237:
9238: For ways of storing character strings in memory see @ref{String Formats}.
9239:
9240: @comment TODO examples for >number >float accept key key? pad parse word refill
9241: @comment then index them
1.141 anton 9242:
9243: Words for inputting one line from the keyboard:
9244:
9245: doc-accept
9246: doc-edit-line
9247:
9248: Conversion words:
9249:
1.143 anton 9250: doc-s>number?
9251: doc-s>unumber?
1.26 crook 9252: doc->number
9253: doc->float
1.143 anton 9254:
1.141 anton 9255:
1.27 crook 9256: @comment obsolescent words..
1.141 anton 9257: Obsolescent input and conversion words:
9258:
1.27 crook 9259: doc-convert
1.26 crook 9260: doc-expect
1.27 crook 9261: doc-span
1.5 anton 9262:
9263:
1.181 anton 9264: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9265: @subsection Pipes
9266: @cindex pipes, creating your own
9267:
9268: In addition to using Gforth in pipes created by other processes
9269: (@pxref{Gforth in pipes}), you can create your own pipe with
9270: @code{open-pipe}, and read from or write to it.
9271:
9272: doc-open-pipe
9273: doc-close-pipe
9274:
9275: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9276: you don't catch this exception, Gforth will catch it and exit, usually
9277: silently (@pxref{Gforth in pipes}). Since you probably do not want
9278: this, you should wrap a @code{catch} or @code{try} block around the code
9279: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9280: problem yourself, and then return to regular processing.
9281:
9282: doc-broken-pipe-error
9283:
1.155 anton 9284: @node Xchars and Unicode, , Pipes, Other I/O
9285: @subsection Xchars and Unicode
1.149 pazsan 9286:
1.188 pazsan 9287: ASCII is only appropriate for the English language. Most western
9288: languages however fit somewhat into the Forth frame, since a byte is
9289: sufficient to encode the few special characters in each (though not
9290: always the same encoding can be used; latin-1 is most widely used,
9291: though). For other languages, different char-sets have to be used,
9292: several of them variable-width. Most prominent representant is
9293: UTF-8. Let's call these extended characters xchars. The primitive
9294: fixed-size characters stored as bytes are called pchars in this
9295: section.
9296:
9297: The xchar words add a few data types:
9298:
9299: @itemize
9300:
9301: @item
9302: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9303: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9304: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9305: character set can be used.
9306:
9307: @item
9308: @var{xc-addr} is the address of an xchar in memory. Alignment
9309: requirements are the same as @var{c-addr}. The memory representation of an
9310: xchar differs from the stack representation, and depends on the
9311: encoding used. An xchar may use a variable number of pchars in memory.
9312:
9313: @item
9314: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9315: @var{xc-addr}, @var{u} pchars long.
9316:
9317: @end itemize
9318:
9319: doc-xc-size
9320: doc-x-size
9321: doc-xc@+
9322: doc-xc!+
9323: doc-xc!+?
9324: doc-xchar+
9325: doc-xchar-
9326: doc-+x/string
9327: doc-x\string-
9328: doc--trailing-garbage
9329: doc-x-width
9330: doc-xkey
9331: doc-xemit
9332:
9333: There's a new environment query
9334:
9335: doc-xchar-encoding
1.112 anton 9336:
1.121 anton 9337: @node OS command line arguments, Locals, Other I/O, Words
9338: @section OS command line arguments
9339: @cindex OS command line arguments
9340: @cindex command line arguments, OS
9341: @cindex arguments, OS command line
9342:
9343: The usual way to pass arguments to Gforth programs on the command line
9344: is via the @option{-e} option, e.g.
9345:
9346: @example
9347: gforth -e "123 456" foo.fs -e bye
9348: @end example
9349:
9350: However, you may want to interpret the command-line arguments directly.
9351: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9352: through @code{next-arg}:
1.121 anton 9353:
1.123 anton 9354: doc-next-arg
1.121 anton 9355:
1.123 anton 9356: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9357:
9358: @example
9359: : echo ( -- )
1.122 anton 9360: begin
1.123 anton 9361: next-arg 2dup 0 0 d<> while
9362: type space
9363: repeat
9364: 2drop ;
1.121 anton 9365:
9366: echo cr bye
9367: @end example
9368:
9369: This can be invoked with
9370:
9371: @example
9372: gforth echo.fs hello world
9373: @end example
1.123 anton 9374:
9375: and it will print
9376:
9377: @example
9378: hello world
9379: @end example
9380:
9381: The next lower level of dealing with the OS command line are the
9382: following words:
9383:
9384: doc-arg
9385: doc-shift-args
9386:
9387: Finally, at the lowest level Gforth provides the following words:
9388:
9389: doc-argc
9390: doc-argv
1.121 anton 9391:
1.78 anton 9392: @c -------------------------------------------------------------
1.126 pazsan 9393: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9394: @section Locals
9395: @cindex locals
9396:
9397: Local variables can make Forth programming more enjoyable and Forth
9398: programs easier to read. Unfortunately, the locals of ANS Forth are
9399: laden with restrictions. Therefore, we provide not only the ANS Forth
9400: locals wordset, but also our own, more powerful locals wordset (we
9401: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9402:
1.78 anton 9403: The ideas in this section have also been published in M. Anton Ertl,
9404: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9405: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9406:
9407: @menu
1.78 anton 9408: * Gforth locals::
9409: * ANS Forth locals::
1.5 anton 9410: @end menu
9411:
1.78 anton 9412: @node Gforth locals, ANS Forth locals, Locals, Locals
9413: @subsection Gforth locals
9414: @cindex Gforth locals
9415: @cindex locals, Gforth style
1.5 anton 9416:
1.78 anton 9417: Locals can be defined with
1.44 crook 9418:
1.78 anton 9419: @example
9420: @{ local1 local2 ... -- comment @}
9421: @end example
9422: or
9423: @example
9424: @{ local1 local2 ... @}
9425: @end example
1.5 anton 9426:
1.78 anton 9427: E.g.,
9428: @example
9429: : max @{ n1 n2 -- n3 @}
9430: n1 n2 > if
9431: n1
9432: else
9433: n2
9434: endif ;
9435: @end example
1.44 crook 9436:
1.78 anton 9437: The similarity of locals definitions with stack comments is intended. A
9438: locals definition often replaces the stack comment of a word. The order
9439: of the locals corresponds to the order in a stack comment and everything
9440: after the @code{--} is really a comment.
1.77 anton 9441:
1.78 anton 9442: This similarity has one disadvantage: It is too easy to confuse locals
9443: declarations with stack comments, causing bugs and making them hard to
9444: find. However, this problem can be avoided by appropriate coding
9445: conventions: Do not use both notations in the same program. If you do,
9446: they should be distinguished using additional means, e.g. by position.
1.77 anton 9447:
1.78 anton 9448: @cindex types of locals
9449: @cindex locals types
9450: The name of the local may be preceded by a type specifier, e.g.,
9451: @code{F:} for a floating point value:
1.5 anton 9452:
1.78 anton 9453: @example
9454: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9455: \ complex multiplication
9456: Ar Br f* Ai Bi f* f-
9457: Ar Bi f* Ai Br f* f+ ;
9458: @end example
1.44 crook 9459:
1.78 anton 9460: @cindex flavours of locals
9461: @cindex locals flavours
9462: @cindex value-flavoured locals
9463: @cindex variable-flavoured locals
9464: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9465: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9466: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9467: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9468: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9469: produces its address (which becomes invalid when the variable's scope is
9470: left). E.g., the standard word @code{emit} can be defined in terms of
9471: @code{type} like this:
1.5 anton 9472:
1.78 anton 9473: @example
9474: : emit @{ C^ char* -- @}
9475: char* 1 type ;
9476: @end example
1.5 anton 9477:
1.78 anton 9478: @cindex default type of locals
9479: @cindex locals, default type
9480: A local without type specifier is a @code{W:} local. Both flavours of
9481: locals are initialized with values from the data or FP stack.
1.44 crook 9482:
1.78 anton 9483: Currently there is no way to define locals with user-defined data
9484: structures, but we are working on it.
1.5 anton 9485:
1.78 anton 9486: Gforth allows defining locals everywhere in a colon definition. This
9487: poses the following questions:
1.5 anton 9488:
1.78 anton 9489: @menu
9490: * Where are locals visible by name?::
9491: * How long do locals live?::
9492: * Locals programming style::
9493: * Locals implementation::
9494: @end menu
1.44 crook 9495:
1.78 anton 9496: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9497: @subsubsection Where are locals visible by name?
9498: @cindex locals visibility
9499: @cindex visibility of locals
9500: @cindex scope of locals
1.5 anton 9501:
1.78 anton 9502: Basically, the answer is that locals are visible where you would expect
9503: it in block-structured languages, and sometimes a little longer. If you
9504: want to restrict the scope of a local, enclose its definition in
9505: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9506:
9507:
1.78 anton 9508: doc-scope
9509: doc-endscope
1.5 anton 9510:
9511:
1.78 anton 9512: These words behave like control structure words, so you can use them
9513: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9514: arbitrary ways.
1.77 anton 9515:
1.78 anton 9516: If you want a more exact answer to the visibility question, here's the
9517: basic principle: A local is visible in all places that can only be
9518: reached through the definition of the local@footnote{In compiler
9519: construction terminology, all places dominated by the definition of the
9520: local.}. In other words, it is not visible in places that can be reached
9521: without going through the definition of the local. E.g., locals defined
9522: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9523: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9524: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9525:
1.78 anton 9526: The reasoning behind this solution is: We want to have the locals
9527: visible as long as it is meaningful. The user can always make the
9528: visibility shorter by using explicit scoping. In a place that can
9529: only be reached through the definition of a local, the meaning of a
9530: local name is clear. In other places it is not: How is the local
9531: initialized at the control flow path that does not contain the
9532: definition? Which local is meant, if the same name is defined twice in
9533: two independent control flow paths?
1.77 anton 9534:
1.78 anton 9535: This should be enough detail for nearly all users, so you can skip the
9536: rest of this section. If you really must know all the gory details and
9537: options, read on.
1.77 anton 9538:
1.78 anton 9539: In order to implement this rule, the compiler has to know which places
9540: are unreachable. It knows this automatically after @code{AHEAD},
9541: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9542: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9543: compiler that the control flow never reaches that place. If
9544: @code{UNREACHABLE} is not used where it could, the only consequence is
9545: that the visibility of some locals is more limited than the rule above
9546: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9547: lie to the compiler), buggy code will be produced.
1.77 anton 9548:
1.5 anton 9549:
1.78 anton 9550: doc-unreachable
1.5 anton 9551:
1.23 crook 9552:
1.78 anton 9553: Another problem with this rule is that at @code{BEGIN}, the compiler
9554: does not know which locals will be visible on the incoming
9555: back-edge. All problems discussed in the following are due to this
9556: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9557: loops as examples; the discussion also applies to @code{?DO} and other
9558: loops). Perhaps the most insidious example is:
1.26 crook 9559: @example
1.78 anton 9560: AHEAD
9561: BEGIN
9562: x
9563: [ 1 CS-ROLL ] THEN
9564: @{ x @}
9565: ...
9566: UNTIL
1.26 crook 9567: @end example
1.23 crook 9568:
1.78 anton 9569: This should be legal according to the visibility rule. The use of
9570: @code{x} can only be reached through the definition; but that appears
9571: textually below the use.
9572:
9573: From this example it is clear that the visibility rules cannot be fully
9574: implemented without major headaches. Our implementation treats common
9575: cases as advertised and the exceptions are treated in a safe way: The
9576: compiler makes a reasonable guess about the locals visible after a
9577: @code{BEGIN}; if it is too pessimistic, the
9578: user will get a spurious error about the local not being defined; if the
9579: compiler is too optimistic, it will notice this later and issue a
9580: warning. In the case above the compiler would complain about @code{x}
9581: being undefined at its use. You can see from the obscure examples in
9582: this section that it takes quite unusual control structures to get the
9583: compiler into trouble, and even then it will often do fine.
1.23 crook 9584:
1.78 anton 9585: If the @code{BEGIN} is reachable from above, the most optimistic guess
9586: is that all locals visible before the @code{BEGIN} will also be
9587: visible after the @code{BEGIN}. This guess is valid for all loops that
9588: are entered only through the @code{BEGIN}, in particular, for normal
9589: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9590: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9591: compiler. When the branch to the @code{BEGIN} is finally generated by
9592: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9593: warns the user if it was too optimistic:
1.26 crook 9594: @example
1.78 anton 9595: IF
9596: @{ x @}
9597: BEGIN
9598: \ x ?
9599: [ 1 cs-roll ] THEN
9600: ...
9601: UNTIL
1.26 crook 9602: @end example
1.23 crook 9603:
1.78 anton 9604: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9605: optimistically assumes that it lives until the @code{THEN}. It notices
9606: this difference when it compiles the @code{UNTIL} and issues a
9607: warning. The user can avoid the warning, and make sure that @code{x}
9608: is not used in the wrong area by using explicit scoping:
9609: @example
9610: IF
9611: SCOPE
9612: @{ x @}
9613: ENDSCOPE
9614: BEGIN
9615: [ 1 cs-roll ] THEN
9616: ...
9617: UNTIL
9618: @end example
1.23 crook 9619:
1.78 anton 9620: Since the guess is optimistic, there will be no spurious error messages
9621: about undefined locals.
1.44 crook 9622:
1.78 anton 9623: If the @code{BEGIN} is not reachable from above (e.g., after
9624: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9625: optimistic guess, as the locals visible after the @code{BEGIN} may be
9626: defined later. Therefore, the compiler assumes that no locals are
9627: visible after the @code{BEGIN}. However, the user can use
9628: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9629: visible at the BEGIN as at the point where the top control-flow stack
9630: item was created.
1.23 crook 9631:
1.44 crook 9632:
1.78 anton 9633: doc-assume-live
1.26 crook 9634:
1.23 crook 9635:
1.78 anton 9636: @noindent
9637: E.g.,
9638: @example
9639: @{ x @}
9640: AHEAD
9641: ASSUME-LIVE
9642: BEGIN
9643: x
9644: [ 1 CS-ROLL ] THEN
9645: ...
9646: UNTIL
9647: @end example
1.44 crook 9648:
1.78 anton 9649: Other cases where the locals are defined before the @code{BEGIN} can be
9650: handled by inserting an appropriate @code{CS-ROLL} before the
9651: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9652: behind the @code{ASSUME-LIVE}).
1.23 crook 9653:
1.78 anton 9654: Cases where locals are defined after the @code{BEGIN} (but should be
9655: visible immediately after the @code{BEGIN}) can only be handled by
9656: rearranging the loop. E.g., the ``most insidious'' example above can be
9657: arranged into:
9658: @example
9659: BEGIN
9660: @{ x @}
9661: ... 0=
9662: WHILE
9663: x
9664: REPEAT
9665: @end example
1.44 crook 9666:
1.78 anton 9667: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9668: @subsubsection How long do locals live?
9669: @cindex locals lifetime
9670: @cindex lifetime of locals
1.23 crook 9671:
1.78 anton 9672: The right answer for the lifetime question would be: A local lives at
9673: least as long as it can be accessed. For a value-flavoured local this
9674: means: until the end of its visibility. However, a variable-flavoured
9675: local could be accessed through its address far beyond its visibility
9676: scope. Ultimately, this would mean that such locals would have to be
9677: garbage collected. Since this entails un-Forth-like implementation
9678: complexities, I adopted the same cowardly solution as some other
9679: languages (e.g., C): The local lives only as long as it is visible;
9680: afterwards its address is invalid (and programs that access it
9681: afterwards are erroneous).
1.23 crook 9682:
1.78 anton 9683: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9684: @subsubsection Locals programming style
9685: @cindex locals programming style
9686: @cindex programming style, locals
1.23 crook 9687:
1.78 anton 9688: The freedom to define locals anywhere has the potential to change
9689: programming styles dramatically. In particular, the need to use the
9690: return stack for intermediate storage vanishes. Moreover, all stack
9691: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9692: determined arguments) can be eliminated: If the stack items are in the
9693: wrong order, just write a locals definition for all of them; then
9694: write the items in the order you want.
1.23 crook 9695:
1.78 anton 9696: This seems a little far-fetched and eliminating stack manipulations is
9697: unlikely to become a conscious programming objective. Still, the number
9698: of stack manipulations will be reduced dramatically if local variables
9699: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9700: a traditional implementation of @code{max}).
1.23 crook 9701:
1.78 anton 9702: This shows one potential benefit of locals: making Forth programs more
9703: readable. Of course, this benefit will only be realized if the
9704: programmers continue to honour the principle of factoring instead of
9705: using the added latitude to make the words longer.
1.23 crook 9706:
1.78 anton 9707: @cindex single-assignment style for locals
9708: Using @code{TO} can and should be avoided. Without @code{TO},
9709: every value-flavoured local has only a single assignment and many
9710: advantages of functional languages apply to Forth. I.e., programs are
9711: easier to analyse, to optimize and to read: It is clear from the
9712: definition what the local stands for, it does not turn into something
9713: different later.
1.23 crook 9714:
1.78 anton 9715: E.g., a definition using @code{TO} might look like this:
9716: @example
9717: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9718: u1 u2 min 0
9719: ?do
9720: addr1 c@@ addr2 c@@ -
9721: ?dup-if
9722: unloop exit
9723: then
9724: addr1 char+ TO addr1
9725: addr2 char+ TO addr2
9726: loop
9727: u1 u2 - ;
1.26 crook 9728: @end example
1.78 anton 9729: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9730: every loop iteration. @code{strcmp} is a typical example of the
9731: readability problems of using @code{TO}. When you start reading
9732: @code{strcmp}, you think that @code{addr1} refers to the start of the
9733: string. Only near the end of the loop you realize that it is something
9734: else.
1.23 crook 9735:
1.78 anton 9736: This can be avoided by defining two locals at the start of the loop that
9737: are initialized with the right value for the current iteration.
9738: @example
9739: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9740: addr1 addr2
9741: u1 u2 min 0
9742: ?do @{ s1 s2 @}
9743: s1 c@@ s2 c@@ -
9744: ?dup-if
9745: unloop exit
9746: then
9747: s1 char+ s2 char+
9748: loop
9749: 2drop
9750: u1 u2 - ;
9751: @end example
9752: Here it is clear from the start that @code{s1} has a different value
9753: in every loop iteration.
1.23 crook 9754:
1.78 anton 9755: @node Locals implementation, , Locals programming style, Gforth locals
9756: @subsubsection Locals implementation
9757: @cindex locals implementation
9758: @cindex implementation of locals
1.23 crook 9759:
1.78 anton 9760: @cindex locals stack
9761: Gforth uses an extra locals stack. The most compelling reason for
9762: this is that the return stack is not float-aligned; using an extra stack
9763: also eliminates the problems and restrictions of using the return stack
9764: as locals stack. Like the other stacks, the locals stack grows toward
9765: lower addresses. A few primitives allow an efficient implementation:
9766:
9767:
9768: doc-@local#
9769: doc-f@local#
9770: doc-laddr#
9771: doc-lp+!#
9772: doc-lp!
9773: doc->l
9774: doc-f>l
9775:
9776:
9777: In addition to these primitives, some specializations of these
9778: primitives for commonly occurring inline arguments are provided for
9779: efficiency reasons, e.g., @code{@@local0} as specialization of
9780: @code{@@local#} for the inline argument 0. The following compiling words
9781: compile the right specialized version, or the general version, as
9782: appropriate:
1.23 crook 9783:
1.5 anton 9784:
1.107 dvdkhlng 9785: @c doc-compile-@local
9786: @c doc-compile-f@local
1.78 anton 9787: doc-compile-lp+!
1.5 anton 9788:
9789:
1.78 anton 9790: Combinations of conditional branches and @code{lp+!#} like
9791: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9792: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9793:
1.78 anton 9794: A special area in the dictionary space is reserved for keeping the
9795: local variable names. @code{@{} switches the dictionary pointer to this
9796: area and @code{@}} switches it back and generates the locals
9797: initializing code. @code{W:} etc.@ are normal defining words. This
9798: special area is cleared at the start of every colon definition.
1.5 anton 9799:
1.78 anton 9800: @cindex word list for defining locals
9801: A special feature of Gforth's dictionary is used to implement the
9802: definition of locals without type specifiers: every word list (aka
9803: vocabulary) has its own methods for searching
9804: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9805: with a special search method: When it is searched for a word, it
9806: actually creates that word using @code{W:}. @code{@{} changes the search
9807: order to first search the word list containing @code{@}}, @code{W:} etc.,
9808: and then the word list for defining locals without type specifiers.
1.5 anton 9809:
1.78 anton 9810: The lifetime rules support a stack discipline within a colon
9811: definition: The lifetime of a local is either nested with other locals
9812: lifetimes or it does not overlap them.
1.23 crook 9813:
1.78 anton 9814: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9815: pointer manipulation is generated. Between control structure words
9816: locals definitions can push locals onto the locals stack. @code{AGAIN}
9817: is the simplest of the other three control flow words. It has to
9818: restore the locals stack depth of the corresponding @code{BEGIN}
9819: before branching. The code looks like this:
9820: @format
9821: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9822: @code{branch} <begin>
9823: @end format
1.26 crook 9824:
1.78 anton 9825: @code{UNTIL} is a little more complicated: If it branches back, it
9826: must adjust the stack just like @code{AGAIN}. But if it falls through,
9827: the locals stack must not be changed. The compiler generates the
9828: following code:
9829: @format
9830: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9831: @end format
9832: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9833:
1.78 anton 9834: @code{THEN} can produce somewhat inefficient code:
9835: @format
9836: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9837: <orig target>:
9838: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9839: @end format
9840: The second @code{lp+!#} adjusts the locals stack pointer from the
9841: level at the @i{orig} point to the level after the @code{THEN}. The
9842: first @code{lp+!#} adjusts the locals stack pointer from the current
9843: level to the level at the orig point, so the complete effect is an
9844: adjustment from the current level to the right level after the
9845: @code{THEN}.
1.26 crook 9846:
1.78 anton 9847: @cindex locals information on the control-flow stack
9848: @cindex control-flow stack items, locals information
9849: In a conventional Forth implementation a dest control-flow stack entry
9850: is just the target address and an orig entry is just the address to be
9851: patched. Our locals implementation adds a word list to every orig or dest
9852: item. It is the list of locals visible (or assumed visible) at the point
9853: described by the entry. Our implementation also adds a tag to identify
9854: the kind of entry, in particular to differentiate between live and dead
9855: (reachable and unreachable) orig entries.
1.26 crook 9856:
1.78 anton 9857: A few unusual operations have to be performed on locals word lists:
1.44 crook 9858:
1.5 anton 9859:
1.78 anton 9860: doc-common-list
9861: doc-sub-list?
9862: doc-list-size
1.52 anton 9863:
9864:
1.78 anton 9865: Several features of our locals word list implementation make these
9866: operations easy to implement: The locals word lists are organised as
9867: linked lists; the tails of these lists are shared, if the lists
9868: contain some of the same locals; and the address of a name is greater
9869: than the address of the names behind it in the list.
1.5 anton 9870:
1.78 anton 9871: Another important implementation detail is the variable
9872: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9873: determine if they can be reached directly or only through the branch
9874: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9875: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9876: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9877:
1.78 anton 9878: Counted loops are similar to other loops in most respects, but
9879: @code{LEAVE} requires special attention: It performs basically the same
9880: service as @code{AHEAD}, but it does not create a control-flow stack
9881: entry. Therefore the information has to be stored elsewhere;
9882: traditionally, the information was stored in the target fields of the
9883: branches created by the @code{LEAVE}s, by organizing these fields into a
9884: linked list. Unfortunately, this clever trick does not provide enough
9885: space for storing our extended control flow information. Therefore, we
9886: introduce another stack, the leave stack. It contains the control-flow
9887: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9888:
1.78 anton 9889: Local names are kept until the end of the colon definition, even if
9890: they are no longer visible in any control-flow path. In a few cases
9891: this may lead to increased space needs for the locals name area, but
9892: usually less than reclaiming this space would cost in code size.
1.5 anton 9893:
1.44 crook 9894:
1.78 anton 9895: @node ANS Forth locals, , Gforth locals, Locals
9896: @subsection ANS Forth locals
9897: @cindex locals, ANS Forth style
1.5 anton 9898:
1.78 anton 9899: The ANS Forth locals wordset does not define a syntax for locals, but
9900: words that make it possible to define various syntaxes. One of the
9901: possible syntaxes is a subset of the syntax we used in the Gforth locals
9902: wordset, i.e.:
1.29 crook 9903:
9904: @example
1.78 anton 9905: @{ local1 local2 ... -- comment @}
9906: @end example
9907: @noindent
9908: or
9909: @example
9910: @{ local1 local2 ... @}
1.29 crook 9911: @end example
9912:
1.78 anton 9913: The order of the locals corresponds to the order in a stack comment. The
9914: restrictions are:
1.5 anton 9915:
1.78 anton 9916: @itemize @bullet
9917: @item
9918: Locals can only be cell-sized values (no type specifiers are allowed).
9919: @item
9920: Locals can be defined only outside control structures.
9921: @item
9922: Locals can interfere with explicit usage of the return stack. For the
9923: exact (and long) rules, see the standard. If you don't use return stack
9924: accessing words in a definition using locals, you will be all right. The
9925: purpose of this rule is to make locals implementation on the return
9926: stack easier.
9927: @item
9928: The whole definition must be in one line.
9929: @end itemize
1.5 anton 9930:
1.78 anton 9931: Locals defined in ANS Forth behave like @code{VALUE}s
9932: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9933: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9934:
1.78 anton 9935: Since the syntax above is supported by Gforth directly, you need not do
9936: anything to use it. If you want to port a program using this syntax to
9937: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9938: syntax on the other system.
1.5 anton 9939:
1.78 anton 9940: Note that a syntax shown in the standard, section A.13 looks
9941: similar, but is quite different in having the order of locals
9942: reversed. Beware!
1.5 anton 9943:
1.78 anton 9944: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9945:
1.78 anton 9946: doc-(local)
1.5 anton 9947:
1.78 anton 9948: The ANS Forth locals extension wordset defines a syntax using
9949: @code{locals|}, but it is so awful that we strongly recommend not to use
9950: it. We have implemented this syntax to make porting to Gforth easy, but
9951: do not document it here. The problem with this syntax is that the locals
9952: are defined in an order reversed with respect to the standard stack
9953: comment notation, making programs harder to read, and easier to misread
9954: and miswrite. The only merit of this syntax is that it is easy to
9955: implement using the ANS Forth locals wordset.
1.53 anton 9956:
9957:
1.78 anton 9958: @c ----------------------------------------------------------
9959: @node Structures, Object-oriented Forth, Locals, Words
9960: @section Structures
9961: @cindex structures
9962: @cindex records
1.53 anton 9963:
1.78 anton 9964: This section presents the structure package that comes with Gforth. A
9965: version of the package implemented in ANS Forth is available in
9966: @file{compat/struct.fs}. This package was inspired by a posting on
9967: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9968: possibly John Hayes). A version of this section has been published in
9969: M. Anton Ertl,
9970: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9971: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9972: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9973:
1.78 anton 9974: @menu
9975: * Why explicit structure support?::
9976: * Structure Usage::
9977: * Structure Naming Convention::
9978: * Structure Implementation::
9979: * Structure Glossary::
1.183 anton 9980: * Forth200x Structures::
1.78 anton 9981: @end menu
1.55 anton 9982:
1.78 anton 9983: @node Why explicit structure support?, Structure Usage, Structures, Structures
9984: @subsection Why explicit structure support?
1.53 anton 9985:
1.78 anton 9986: @cindex address arithmetic for structures
9987: @cindex structures using address arithmetic
9988: If we want to use a structure containing several fields, we could simply
9989: reserve memory for it, and access the fields using address arithmetic
9990: (@pxref{Address arithmetic}). As an example, consider a structure with
9991: the following fields
1.57 anton 9992:
1.78 anton 9993: @table @code
9994: @item a
9995: is a float
9996: @item b
9997: is a cell
9998: @item c
9999: is a float
10000: @end table
1.57 anton 10001:
1.78 anton 10002: Given the (float-aligned) base address of the structure we get the
10003: address of the field
1.52 anton 10004:
1.78 anton 10005: @table @code
10006: @item a
10007: without doing anything further.
10008: @item b
10009: with @code{float+}
10010: @item c
10011: with @code{float+ cell+ faligned}
10012: @end table
1.52 anton 10013:
1.78 anton 10014: It is easy to see that this can become quite tiring.
1.52 anton 10015:
1.78 anton 10016: Moreover, it is not very readable, because seeing a
10017: @code{cell+} tells us neither which kind of structure is
10018: accessed nor what field is accessed; we have to somehow infer the kind
10019: of structure, and then look up in the documentation, which field of
10020: that structure corresponds to that offset.
1.53 anton 10021:
1.78 anton 10022: Finally, this kind of address arithmetic also causes maintenance
10023: troubles: If you add or delete a field somewhere in the middle of the
10024: structure, you have to find and change all computations for the fields
10025: afterwards.
1.52 anton 10026:
1.78 anton 10027: So, instead of using @code{cell+} and friends directly, how
10028: about storing the offsets in constants:
1.52 anton 10029:
1.78 anton 10030: @example
10031: 0 constant a-offset
10032: 0 float+ constant b-offset
10033: 0 float+ cell+ faligned c-offset
10034: @end example
1.64 pazsan 10035:
1.78 anton 10036: Now we can get the address of field @code{x} with @code{x-offset
10037: +}. This is much better in all respects. Of course, you still
10038: have to change all later offset definitions if you add a field. You can
10039: fix this by declaring the offsets in the following way:
1.57 anton 10040:
1.78 anton 10041: @example
10042: 0 constant a-offset
10043: a-offset float+ constant b-offset
10044: b-offset cell+ faligned constant c-offset
10045: @end example
1.57 anton 10046:
1.78 anton 10047: Since we always use the offsets with @code{+}, we could use a defining
10048: word @code{cfield} that includes the @code{+} in the action of the
10049: defined word:
1.64 pazsan 10050:
1.78 anton 10051: @example
10052: : cfield ( n "name" -- )
10053: create ,
10054: does> ( name execution: addr1 -- addr2 )
10055: @@ + ;
1.64 pazsan 10056:
1.78 anton 10057: 0 cfield a
10058: 0 a float+ cfield b
10059: 0 b cell+ faligned cfield c
10060: @end example
1.64 pazsan 10061:
1.78 anton 10062: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10063:
1.78 anton 10064: The structure field words now can be used quite nicely. However,
10065: their definition is still a bit cumbersome: We have to repeat the
10066: name, the information about size and alignment is distributed before
10067: and after the field definitions etc. The structure package presented
10068: here addresses these problems.
1.64 pazsan 10069:
1.78 anton 10070: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10071: @subsection Structure Usage
10072: @cindex structure usage
1.57 anton 10073:
1.78 anton 10074: @cindex @code{field} usage
10075: @cindex @code{struct} usage
10076: @cindex @code{end-struct} usage
10077: You can define a structure for a (data-less) linked list with:
1.57 anton 10078: @example
1.78 anton 10079: struct
10080: cell% field list-next
10081: end-struct list%
1.57 anton 10082: @end example
10083:
1.78 anton 10084: With the address of the list node on the stack, you can compute the
10085: address of the field that contains the address of the next node with
10086: @code{list-next}. E.g., you can determine the length of a list
10087: with:
1.57 anton 10088:
10089: @example
1.78 anton 10090: : list-length ( list -- n )
10091: \ "list" is a pointer to the first element of a linked list
10092: \ "n" is the length of the list
10093: 0 BEGIN ( list1 n1 )
10094: over
10095: WHILE ( list1 n1 )
10096: 1+ swap list-next @@ swap
10097: REPEAT
10098: nip ;
1.57 anton 10099: @end example
10100:
1.78 anton 10101: You can reserve memory for a list node in the dictionary with
10102: @code{list% %allot}, which leaves the address of the list node on the
10103: stack. For the equivalent allocation on the heap you can use @code{list%
10104: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10105: use @code{list% %allocate}). You can get the the size of a list
10106: node with @code{list% %size} and its alignment with @code{list%
10107: %alignment}.
10108:
10109: Note that in ANS Forth the body of a @code{create}d word is
10110: @code{aligned} but not necessarily @code{faligned};
10111: therefore, if you do a:
1.57 anton 10112:
10113: @example
1.78 anton 10114: create @emph{name} foo% %allot drop
1.57 anton 10115: @end example
10116:
1.78 anton 10117: @noindent
10118: then the memory alloted for @code{foo%} is guaranteed to start at the
10119: body of @code{@emph{name}} only if @code{foo%} contains only character,
10120: cell and double fields. Therefore, if your structure contains floats,
10121: better use
1.57 anton 10122:
10123: @example
1.78 anton 10124: foo% %allot constant @emph{name}
1.57 anton 10125: @end example
10126:
1.78 anton 10127: @cindex structures containing structures
10128: You can include a structure @code{foo%} as a field of
10129: another structure, like this:
1.65 anton 10130: @example
1.78 anton 10131: struct
10132: ...
10133: foo% field ...
10134: ...
10135: end-struct ...
1.65 anton 10136: @end example
1.52 anton 10137:
1.78 anton 10138: @cindex structure extension
10139: @cindex extended records
10140: Instead of starting with an empty structure, you can extend an
10141: existing structure. E.g., a plain linked list without data, as defined
10142: above, is hardly useful; You can extend it to a linked list of integers,
10143: like this:@footnote{This feature is also known as @emph{extended
10144: records}. It is the main innovation in the Oberon language; in other
10145: words, adding this feature to Modula-2 led Wirth to create a new
10146: language, write a new compiler etc. Adding this feature to Forth just
10147: required a few lines of code.}
1.52 anton 10148:
1.78 anton 10149: @example
10150: list%
10151: cell% field intlist-int
10152: end-struct intlist%
10153: @end example
1.55 anton 10154:
1.78 anton 10155: @code{intlist%} is a structure with two fields:
10156: @code{list-next} and @code{intlist-int}.
1.55 anton 10157:
1.78 anton 10158: @cindex structures containing arrays
10159: You can specify an array type containing @emph{n} elements of
10160: type @code{foo%} like this:
1.55 anton 10161:
10162: @example
1.78 anton 10163: foo% @emph{n} *
1.56 anton 10164: @end example
1.55 anton 10165:
1.78 anton 10166: You can use this array type in any place where you can use a normal
10167: type, e.g., when defining a @code{field}, or with
10168: @code{%allot}.
10169:
10170: @cindex first field optimization
10171: The first field is at the base address of a structure and the word for
10172: this field (e.g., @code{list-next}) actually does not change the address
10173: on the stack. You may be tempted to leave it away in the interest of
10174: run-time and space efficiency. This is not necessary, because the
10175: structure package optimizes this case: If you compile a first-field
10176: words, no code is generated. So, in the interest of readability and
10177: maintainability you should include the word for the field when accessing
10178: the field.
1.52 anton 10179:
10180:
1.78 anton 10181: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10182: @subsection Structure Naming Convention
10183: @cindex structure naming convention
1.52 anton 10184:
1.78 anton 10185: The field names that come to (my) mind are often quite generic, and,
10186: if used, would cause frequent name clashes. E.g., many structures
10187: probably contain a @code{counter} field. The structure names
10188: that come to (my) mind are often also the logical choice for the names
10189: of words that create such a structure.
1.52 anton 10190:
1.78 anton 10191: Therefore, I have adopted the following naming conventions:
1.52 anton 10192:
1.78 anton 10193: @itemize @bullet
10194: @cindex field naming convention
10195: @item
10196: The names of fields are of the form
10197: @code{@emph{struct}-@emph{field}}, where
10198: @code{@emph{struct}} is the basic name of the structure, and
10199: @code{@emph{field}} is the basic name of the field. You can
10200: think of field words as converting the (address of the)
10201: structure into the (address of the) field.
1.52 anton 10202:
1.78 anton 10203: @cindex structure naming convention
10204: @item
10205: The names of structures are of the form
10206: @code{@emph{struct}%}, where
10207: @code{@emph{struct}} is the basic name of the structure.
10208: @end itemize
1.52 anton 10209:
1.78 anton 10210: This naming convention does not work that well for fields of extended
10211: structures; e.g., the integer list structure has a field
10212: @code{intlist-int}, but has @code{list-next}, not
10213: @code{intlist-next}.
1.53 anton 10214:
1.78 anton 10215: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10216: @subsection Structure Implementation
10217: @cindex structure implementation
10218: @cindex implementation of structures
1.52 anton 10219:
1.78 anton 10220: The central idea in the implementation is to pass the data about the
10221: structure being built on the stack, not in some global
10222: variable. Everything else falls into place naturally once this design
10223: decision is made.
1.53 anton 10224:
1.78 anton 10225: The type description on the stack is of the form @emph{align
10226: size}. Keeping the size on the top-of-stack makes dealing with arrays
10227: very simple.
1.53 anton 10228:
1.78 anton 10229: @code{field} is a defining word that uses @code{Create}
10230: and @code{DOES>}. The body of the field contains the offset
10231: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10232:
10233: @example
1.78 anton 10234: @@ +
1.53 anton 10235: @end example
10236:
1.78 anton 10237: @noindent
10238: i.e., add the offset to the address, giving the stack effect
10239: @i{addr1 -- addr2} for a field.
10240:
10241: @cindex first field optimization, implementation
10242: This simple structure is slightly complicated by the optimization
10243: for fields with offset 0, which requires a different
10244: @code{DOES>}-part (because we cannot rely on there being
10245: something on the stack if such a field is invoked during
10246: compilation). Therefore, we put the different @code{DOES>}-parts
10247: in separate words, and decide which one to invoke based on the
10248: offset. For a zero offset, the field is basically a noop; it is
10249: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10250:
1.183 anton 10251: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10252: @subsection Structure Glossary
10253: @cindex structure glossary
1.53 anton 10254:
1.5 anton 10255:
1.78 anton 10256: doc-%align
10257: doc-%alignment
10258: doc-%alloc
10259: doc-%allocate
10260: doc-%allot
10261: doc-cell%
10262: doc-char%
10263: doc-dfloat%
10264: doc-double%
10265: doc-end-struct
10266: doc-field
10267: doc-float%
10268: doc-naligned
10269: doc-sfloat%
10270: doc-%size
10271: doc-struct
1.54 anton 10272:
10273:
1.183 anton 10274: @node Forth200x Structures, , Structure Glossary, Structures
10275: @subsection Forth200x Structures
10276: @cindex Structures in Forth200x
10277:
10278: The Forth 200x standard defines a slightly less convenient form of
10279: structures. In general (when using @code{field+}, you have to perform
10280: the alignment yourself, but there are a number of convenience words
10281: (e.g., @code{field:} that perform the alignment for you.
10282:
10283: A typical usage example is:
10284:
10285: @example
10286: 0
10287: field: s-a
10288: faligned 2 floats +field s-b
10289: constant s-struct
10290: @end example
10291:
10292: An alternative way of writing this structure is:
10293:
10294: @example
10295: begin-structure s-struct
10296: field: s-a
10297: faligned 2 floats +field s-b
10298: end-structure
10299: @end example
10300:
10301: doc-begin-structure
10302: doc-end-structure
10303: doc-+field
10304: doc-cfield:
10305: doc-field:
10306: doc-2field:
10307: doc-ffield:
10308: doc-sffield:
10309: doc-dffield:
10310:
1.26 crook 10311: @c -------------------------------------------------------------
1.78 anton 10312: @node Object-oriented Forth, Programming Tools, Structures, Words
10313: @section Object-oriented Forth
10314:
10315: Gforth comes with three packages for object-oriented programming:
10316: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10317: is preloaded, so you have to @code{include} them before use. The most
10318: important differences between these packages (and others) are discussed
10319: in @ref{Comparison with other object models}. All packages are written
10320: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10321:
1.78 anton 10322: @menu
10323: * Why object-oriented programming?::
10324: * Object-Oriented Terminology::
10325: * Objects::
10326: * OOF::
10327: * Mini-OOF::
10328: * Comparison with other object models::
10329: @end menu
1.5 anton 10330:
1.78 anton 10331: @c ----------------------------------------------------------------
10332: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10333: @subsection Why object-oriented programming?
10334: @cindex object-oriented programming motivation
10335: @cindex motivation for object-oriented programming
1.44 crook 10336:
1.78 anton 10337: Often we have to deal with several data structures (@emph{objects}),
10338: that have to be treated similarly in some respects, but differently in
10339: others. Graphical objects are the textbook example: circles, triangles,
10340: dinosaurs, icons, and others, and we may want to add more during program
10341: development. We want to apply some operations to any graphical object,
10342: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10343: has to do something different for every kind of object.
10344: @comment TODO add some other operations eg perimeter, area
10345: @comment and tie in to concrete examples later..
1.5 anton 10346:
1.78 anton 10347: We could implement @code{draw} as a big @code{CASE}
10348: control structure that executes the appropriate code depending on the
10349: kind of object to be drawn. This would be not be very elegant, and,
10350: moreover, we would have to change @code{draw} every time we add
10351: a new kind of graphical object (say, a spaceship).
1.44 crook 10352:
1.78 anton 10353: What we would rather do is: When defining spaceships, we would tell
10354: the system: ``Here's how you @code{draw} a spaceship; you figure
10355: out the rest''.
1.5 anton 10356:
1.78 anton 10357: This is the problem that all systems solve that (rightfully) call
10358: themselves object-oriented; the object-oriented packages presented here
10359: solve this problem (and not much else).
10360: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10361:
1.78 anton 10362: @c ------------------------------------------------------------------------
10363: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10364: @subsection Object-Oriented Terminology
10365: @cindex object-oriented terminology
10366: @cindex terminology for object-oriented programming
1.5 anton 10367:
1.78 anton 10368: This section is mainly for reference, so you don't have to understand
10369: all of it right away. The terminology is mainly Smalltalk-inspired. In
10370: short:
1.44 crook 10371:
1.78 anton 10372: @table @emph
10373: @cindex class
10374: @item class
10375: a data structure definition with some extras.
1.5 anton 10376:
1.78 anton 10377: @cindex object
10378: @item object
10379: an instance of the data structure described by the class definition.
1.5 anton 10380:
1.78 anton 10381: @cindex instance variables
10382: @item instance variables
10383: fields of the data structure.
1.5 anton 10384:
1.78 anton 10385: @cindex selector
10386: @cindex method selector
10387: @cindex virtual function
10388: @item selector
10389: (or @emph{method selector}) a word (e.g.,
10390: @code{draw}) that performs an operation on a variety of data
10391: structures (classes). A selector describes @emph{what} operation to
10392: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10393:
1.78 anton 10394: @cindex method
10395: @item method
10396: the concrete definition that performs the operation
10397: described by the selector for a specific class. A method specifies
10398: @emph{how} the operation is performed for a specific class.
1.5 anton 10399:
1.78 anton 10400: @cindex selector invocation
10401: @cindex message send
10402: @cindex invoking a selector
10403: @item selector invocation
10404: a call of a selector. One argument of the call (the TOS (top-of-stack))
10405: is used for determining which method is used. In Smalltalk terminology:
10406: a message (consisting of the selector and the other arguments) is sent
10407: to the object.
1.5 anton 10408:
1.78 anton 10409: @cindex receiving object
10410: @item receiving object
10411: the object used for determining the method executed by a selector
10412: invocation. In the @file{objects.fs} model, it is the object that is on
10413: the TOS when the selector is invoked. (@emph{Receiving} comes from
10414: the Smalltalk @emph{message} terminology.)
1.5 anton 10415:
1.78 anton 10416: @cindex child class
10417: @cindex parent class
10418: @cindex inheritance
10419: @item child class
10420: a class that has (@emph{inherits}) all properties (instance variables,
10421: selectors, methods) from a @emph{parent class}. In Smalltalk
10422: terminology: The subclass inherits from the superclass. In C++
10423: terminology: The derived class inherits from the base class.
1.5 anton 10424:
1.78 anton 10425: @end table
1.5 anton 10426:
1.78 anton 10427: @c If you wonder about the message sending terminology, it comes from
10428: @c a time when each object had it's own task and objects communicated via
10429: @c message passing; eventually the Smalltalk developers realized that
10430: @c they can do most things through simple (indirect) calls. They kept the
10431: @c terminology.
1.5 anton 10432:
1.78 anton 10433: @c --------------------------------------------------------------
10434: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10435: @subsection The @file{objects.fs} model
10436: @cindex objects
10437: @cindex object-oriented programming
1.26 crook 10438:
1.78 anton 10439: @cindex @file{objects.fs}
10440: @cindex @file{oof.fs}
1.26 crook 10441:
1.78 anton 10442: This section describes the @file{objects.fs} package. This material also
10443: has been published in M. Anton Ertl,
10444: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10445: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10446: 37--43.
10447: @c McKewan's and Zsoter's packages
1.26 crook 10448:
1.78 anton 10449: This section assumes that you have read @ref{Structures}.
1.5 anton 10450:
1.78 anton 10451: The techniques on which this model is based have been used to implement
10452: the parser generator, Gray, and have also been used in Gforth for
10453: implementing the various flavours of word lists (hashed or not,
10454: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10455:
10456:
1.26 crook 10457: @menu
1.78 anton 10458: * Properties of the Objects model::
10459: * Basic Objects Usage::
10460: * The Objects base class::
10461: * Creating objects::
10462: * Object-Oriented Programming Style::
10463: * Class Binding::
10464: * Method conveniences::
10465: * Classes and Scoping::
10466: * Dividing classes::
10467: * Object Interfaces::
10468: * Objects Implementation::
10469: * Objects Glossary::
1.26 crook 10470: @end menu
1.5 anton 10471:
1.78 anton 10472: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10473:
1.78 anton 10474: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10475: @subsubsection Properties of the @file{objects.fs} model
10476: @cindex @file{objects.fs} properties
1.5 anton 10477:
1.78 anton 10478: @itemize @bullet
10479: @item
10480: It is straightforward to pass objects on the stack. Passing
10481: selectors on the stack is a little less convenient, but possible.
1.44 crook 10482:
1.78 anton 10483: @item
10484: Objects are just data structures in memory, and are referenced by their
10485: address. You can create words for objects with normal defining words
10486: like @code{constant}. Likewise, there is no difference between instance
10487: variables that contain objects and those that contain other data.
1.5 anton 10488:
1.78 anton 10489: @item
10490: Late binding is efficient and easy to use.
1.44 crook 10491:
1.78 anton 10492: @item
10493: It avoids parsing, and thus avoids problems with state-smartness
10494: and reduced extensibility; for convenience there are a few parsing
10495: words, but they have non-parsing counterparts. There are also a few
10496: defining words that parse. This is hard to avoid, because all standard
10497: defining words parse (except @code{:noname}); however, such
10498: words are not as bad as many other parsing words, because they are not
10499: state-smart.
1.5 anton 10500:
1.78 anton 10501: @item
10502: It does not try to incorporate everything. It does a few things and does
10503: them well (IMO). In particular, this model was not designed to support
10504: information hiding (although it has features that may help); you can use
10505: a separate package for achieving this.
1.5 anton 10506:
1.78 anton 10507: @item
10508: It is layered; you don't have to learn and use all features to use this
10509: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10510: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10511: are optional and independent of each other.
1.5 anton 10512:
1.78 anton 10513: @item
10514: An implementation in ANS Forth is available.
1.5 anton 10515:
1.78 anton 10516: @end itemize
1.5 anton 10517:
1.44 crook 10518:
1.78 anton 10519: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10520: @subsubsection Basic @file{objects.fs} Usage
10521: @cindex basic objects usage
10522: @cindex objects, basic usage
1.5 anton 10523:
1.78 anton 10524: You can define a class for graphical objects like this:
1.44 crook 10525:
1.78 anton 10526: @cindex @code{class} usage
10527: @cindex @code{end-class} usage
10528: @cindex @code{selector} usage
1.5 anton 10529: @example
1.78 anton 10530: object class \ "object" is the parent class
10531: selector draw ( x y graphical -- )
10532: end-class graphical
10533: @end example
10534:
10535: This code defines a class @code{graphical} with an
10536: operation @code{draw}. We can perform the operation
10537: @code{draw} on any @code{graphical} object, e.g.:
10538:
10539: @example
10540: 100 100 t-rex draw
1.26 crook 10541: @end example
1.5 anton 10542:
1.78 anton 10543: @noindent
10544: where @code{t-rex} is a word (say, a constant) that produces a
10545: graphical object.
10546:
10547: @comment TODO add a 2nd operation eg perimeter.. and use for
10548: @comment a concrete example
1.5 anton 10549:
1.78 anton 10550: @cindex abstract class
10551: How do we create a graphical object? With the present definitions,
10552: we cannot create a useful graphical object. The class
10553: @code{graphical} describes graphical objects in general, but not
10554: any concrete graphical object type (C++ users would call it an
10555: @emph{abstract class}); e.g., there is no method for the selector
10556: @code{draw} in the class @code{graphical}.
1.5 anton 10557:
1.78 anton 10558: For concrete graphical objects, we define child classes of the
10559: class @code{graphical}, e.g.:
1.5 anton 10560:
1.78 anton 10561: @cindex @code{overrides} usage
10562: @cindex @code{field} usage in class definition
1.26 crook 10563: @example
1.78 anton 10564: graphical class \ "graphical" is the parent class
10565: cell% field circle-radius
1.5 anton 10566:
1.78 anton 10567: :noname ( x y circle -- )
10568: circle-radius @@ draw-circle ;
10569: overrides draw
1.5 anton 10570:
1.78 anton 10571: :noname ( n-radius circle -- )
10572: circle-radius ! ;
10573: overrides construct
1.5 anton 10574:
1.78 anton 10575: end-class circle
10576: @end example
1.44 crook 10577:
1.78 anton 10578: Here we define a class @code{circle} as a child of @code{graphical},
10579: with field @code{circle-radius} (which behaves just like a field
10580: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10581: for the selectors @code{draw} and @code{construct} (@code{construct} is
10582: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10583:
1.78 anton 10584: Now we can create a circle on the heap (i.e.,
10585: @code{allocate}d memory) with:
1.44 crook 10586:
1.78 anton 10587: @cindex @code{heap-new} usage
1.5 anton 10588: @example
1.78 anton 10589: 50 circle heap-new constant my-circle
1.5 anton 10590: @end example
10591:
1.78 anton 10592: @noindent
10593: @code{heap-new} invokes @code{construct}, thus
10594: initializing the field @code{circle-radius} with 50. We can draw
10595: this new circle at (100,100) with:
1.5 anton 10596:
10597: @example
1.78 anton 10598: 100 100 my-circle draw
1.5 anton 10599: @end example
10600:
1.78 anton 10601: @cindex selector invocation, restrictions
10602: @cindex class definition, restrictions
10603: Note: You can only invoke a selector if the object on the TOS
10604: (the receiving object) belongs to the class where the selector was
10605: defined or one of its descendents; e.g., you can invoke
10606: @code{draw} only for objects belonging to @code{graphical}
10607: or its descendents (e.g., @code{circle}). Immediately before
10608: @code{end-class}, the search order has to be the same as
10609: immediately after @code{class}.
10610:
10611: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10612: @subsubsection The @file{object.fs} base class
10613: @cindex @code{object} class
10614:
10615: When you define a class, you have to specify a parent class. So how do
10616: you start defining classes? There is one class available from the start:
10617: @code{object}. It is ancestor for all classes and so is the
10618: only class that has no parent. It has two selectors: @code{construct}
10619: and @code{print}.
10620:
10621: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10622: @subsubsection Creating objects
10623: @cindex creating objects
10624: @cindex object creation
10625: @cindex object allocation options
10626:
10627: @cindex @code{heap-new} discussion
10628: @cindex @code{dict-new} discussion
10629: @cindex @code{construct} discussion
10630: You can create and initialize an object of a class on the heap with
10631: @code{heap-new} ( ... class -- object ) and in the dictionary
10632: (allocation with @code{allot}) with @code{dict-new} (
10633: ... class -- object ). Both words invoke @code{construct}, which
10634: consumes the stack items indicated by "..." above.
10635:
10636: @cindex @code{init-object} discussion
10637: @cindex @code{class-inst-size} discussion
10638: If you want to allocate memory for an object yourself, you can get its
10639: alignment and size with @code{class-inst-size 2@@} ( class --
10640: align size ). Once you have memory for an object, you can initialize
10641: it with @code{init-object} ( ... class object -- );
10642: @code{construct} does only a part of the necessary work.
10643:
10644: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10645: @subsubsection Object-Oriented Programming Style
10646: @cindex object-oriented programming style
10647: @cindex programming style, object-oriented
1.5 anton 10648:
1.78 anton 10649: This section is not exhaustive.
1.5 anton 10650:
1.78 anton 10651: @cindex stack effects of selectors
10652: @cindex selectors and stack effects
10653: In general, it is a good idea to ensure that all methods for the
10654: same selector have the same stack effect: when you invoke a selector,
10655: you often have no idea which method will be invoked, so, unless all
10656: methods have the same stack effect, you will not know the stack effect
10657: of the selector invocation.
1.5 anton 10658:
1.78 anton 10659: One exception to this rule is methods for the selector
10660: @code{construct}. We know which method is invoked, because we
10661: specify the class to be constructed at the same place. Actually, I
10662: defined @code{construct} as a selector only to give the users a
10663: convenient way to specify initialization. The way it is used, a
10664: mechanism different from selector invocation would be more natural
10665: (but probably would take more code and more space to explain).
1.5 anton 10666:
1.78 anton 10667: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10668: @subsubsection Class Binding
10669: @cindex class binding
10670: @cindex early binding
1.5 anton 10671:
1.78 anton 10672: @cindex late binding
10673: Normal selector invocations determine the method at run-time depending
10674: on the class of the receiving object. This run-time selection is called
10675: @i{late binding}.
1.5 anton 10676:
1.78 anton 10677: Sometimes it's preferable to invoke a different method. For example,
10678: you might want to use the simple method for @code{print}ing
10679: @code{object}s instead of the possibly long-winded @code{print} method
10680: of the receiver class. You can achieve this by replacing the invocation
10681: of @code{print} with:
1.5 anton 10682:
1.78 anton 10683: @cindex @code{[bind]} usage
1.5 anton 10684: @example
1.78 anton 10685: [bind] object print
1.5 anton 10686: @end example
10687:
1.78 anton 10688: @noindent
10689: in compiled code or:
10690:
10691: @cindex @code{bind} usage
1.5 anton 10692: @example
1.78 anton 10693: bind object print
1.5 anton 10694: @end example
10695:
1.78 anton 10696: @cindex class binding, alternative to
10697: @noindent
10698: in interpreted code. Alternatively, you can define the method with a
10699: name (e.g., @code{print-object}), and then invoke it through the
10700: name. Class binding is just a (often more convenient) way to achieve
10701: the same effect; it avoids name clutter and allows you to invoke
10702: methods directly without naming them first.
1.5 anton 10703:
1.78 anton 10704: @cindex superclass binding
10705: @cindex parent class binding
10706: A frequent use of class binding is this: When we define a method
10707: for a selector, we often want the method to do what the selector does
10708: in the parent class, and a little more. There is a special word for
10709: this purpose: @code{[parent]}; @code{[parent]
10710: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10711: selector}}, where @code{@emph{parent}} is the parent
10712: class of the current class. E.g., a method definition might look like:
1.44 crook 10713:
1.78 anton 10714: @cindex @code{[parent]} usage
10715: @example
10716: :noname
10717: dup [parent] foo \ do parent's foo on the receiving object
10718: ... \ do some more
10719: ; overrides foo
10720: @end example
1.6 pazsan 10721:
1.78 anton 10722: @cindex class binding as optimization
10723: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10724: March 1997), Andrew McKewan presents class binding as an optimization
10725: technique. I recommend not using it for this purpose unless you are in
10726: an emergency. Late binding is pretty fast with this model anyway, so the
10727: benefit of using class binding is small; the cost of using class binding
10728: where it is not appropriate is reduced maintainability.
1.44 crook 10729:
1.78 anton 10730: While we are at programming style questions: You should bind
10731: selectors only to ancestor classes of the receiving object. E.g., say,
10732: you know that the receiving object is of class @code{foo} or its
10733: descendents; then you should bind only to @code{foo} and its
10734: ancestors.
1.12 anton 10735:
1.78 anton 10736: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10737: @subsubsection Method conveniences
10738: @cindex method conveniences
1.44 crook 10739:
1.78 anton 10740: In a method you usually access the receiving object pretty often. If
10741: you define the method as a plain colon definition (e.g., with
10742: @code{:noname}), you may have to do a lot of stack
10743: gymnastics. To avoid this, you can define the method with @code{m:
10744: ... ;m}. E.g., you could define the method for
10745: @code{draw}ing a @code{circle} with
1.6 pazsan 10746:
1.78 anton 10747: @cindex @code{this} usage
10748: @cindex @code{m:} usage
10749: @cindex @code{;m} usage
10750: @example
10751: m: ( x y circle -- )
10752: ( x y ) this circle-radius @@ draw-circle ;m
10753: @end example
1.6 pazsan 10754:
1.78 anton 10755: @cindex @code{exit} in @code{m: ... ;m}
10756: @cindex @code{exitm} discussion
10757: @cindex @code{catch} in @code{m: ... ;m}
10758: When this method is executed, the receiver object is removed from the
10759: stack; you can access it with @code{this} (admittedly, in this
10760: example the use of @code{m: ... ;m} offers no advantage). Note
10761: that I specify the stack effect for the whole method (i.e. including
10762: the receiver object), not just for the code between @code{m:}
10763: and @code{;m}. You cannot use @code{exit} in
10764: @code{m:...;m}; instead, use
10765: @code{exitm}.@footnote{Moreover, for any word that calls
10766: @code{catch} and was defined before loading
10767: @code{objects.fs}, you have to redefine it like I redefined
10768: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10769:
1.78 anton 10770: @cindex @code{inst-var} usage
10771: You will frequently use sequences of the form @code{this
10772: @emph{field}} (in the example above: @code{this
10773: circle-radius}). If you use the field only in this way, you can
10774: define it with @code{inst-var} and eliminate the
10775: @code{this} before the field name. E.g., the @code{circle}
10776: class above could also be defined with:
1.6 pazsan 10777:
1.78 anton 10778: @example
10779: graphical class
10780: cell% inst-var radius
1.6 pazsan 10781:
1.78 anton 10782: m: ( x y circle -- )
10783: radius @@ draw-circle ;m
10784: overrides draw
1.6 pazsan 10785:
1.78 anton 10786: m: ( n-radius circle -- )
10787: radius ! ;m
10788: overrides construct
1.6 pazsan 10789:
1.78 anton 10790: end-class circle
10791: @end example
1.6 pazsan 10792:
1.78 anton 10793: @code{radius} can only be used in @code{circle} and its
10794: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10795:
1.78 anton 10796: @cindex @code{inst-value} usage
10797: You can also define fields with @code{inst-value}, which is
10798: to @code{inst-var} what @code{value} is to
10799: @code{variable}. You can change the value of such a field with
10800: @code{[to-inst]}. E.g., we could also define the class
10801: @code{circle} like this:
1.44 crook 10802:
1.78 anton 10803: @example
10804: graphical class
10805: inst-value radius
1.6 pazsan 10806:
1.78 anton 10807: m: ( x y circle -- )
10808: radius draw-circle ;m
10809: overrides draw
1.44 crook 10810:
1.78 anton 10811: m: ( n-radius circle -- )
10812: [to-inst] radius ;m
10813: overrides construct
1.6 pazsan 10814:
1.78 anton 10815: end-class circle
10816: @end example
1.6 pazsan 10817:
1.78 anton 10818: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10819:
1.78 anton 10820: @c Finally, you can define named methods with @code{:m}. One use of this
10821: @c feature is the definition of words that occur only in one class and are
10822: @c not intended to be overridden, but which still need method context
10823: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10824: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10825:
10826:
1.78 anton 10827: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10828: @subsubsection Classes and Scoping
10829: @cindex classes and scoping
10830: @cindex scoping and classes
1.6 pazsan 10831:
1.78 anton 10832: Inheritance is frequent, unlike structure extension. This exacerbates
10833: the problem with the field name convention (@pxref{Structure Naming
10834: Convention}): One always has to remember in which class the field was
10835: originally defined; changing a part of the class structure would require
10836: changes for renaming in otherwise unaffected code.
1.6 pazsan 10837:
1.78 anton 10838: @cindex @code{inst-var} visibility
10839: @cindex @code{inst-value} visibility
10840: To solve this problem, I added a scoping mechanism (which was not in my
10841: original charter): A field defined with @code{inst-var} (or
10842: @code{inst-value}) is visible only in the class where it is defined and in
10843: the descendent classes of this class. Using such fields only makes
10844: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10845:
1.78 anton 10846: This scoping mechanism allows us to use the unadorned field name,
10847: because name clashes with unrelated words become much less likely.
1.6 pazsan 10848:
1.78 anton 10849: @cindex @code{protected} discussion
10850: @cindex @code{private} discussion
10851: Once we have this mechanism, we can also use it for controlling the
10852: visibility of other words: All words defined after
10853: @code{protected} are visible only in the current class and its
10854: descendents. @code{public} restores the compilation
10855: (i.e. @code{current}) word list that was in effect before. If you
10856: have several @code{protected}s without an intervening
10857: @code{public} or @code{set-current}, @code{public}
10858: will restore the compilation word list in effect before the first of
10859: these @code{protected}s.
1.6 pazsan 10860:
1.78 anton 10861: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10862: @subsubsection Dividing classes
10863: @cindex Dividing classes
10864: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10865:
1.78 anton 10866: You may want to do the definition of methods separate from the
10867: definition of the class, its selectors, fields, and instance variables,
10868: i.e., separate the implementation from the definition. You can do this
10869: in the following way:
1.6 pazsan 10870:
1.78 anton 10871: @example
10872: graphical class
10873: inst-value radius
10874: end-class circle
1.6 pazsan 10875:
1.78 anton 10876: ... \ do some other stuff
1.6 pazsan 10877:
1.78 anton 10878: circle methods \ now we are ready
1.44 crook 10879:
1.78 anton 10880: m: ( x y circle -- )
10881: radius draw-circle ;m
10882: overrides draw
1.6 pazsan 10883:
1.78 anton 10884: m: ( n-radius circle -- )
10885: [to-inst] radius ;m
10886: overrides construct
1.44 crook 10887:
1.78 anton 10888: end-methods
10889: @end example
1.7 pazsan 10890:
1.78 anton 10891: You can use several @code{methods}...@code{end-methods} sections. The
10892: only things you can do to the class in these sections are: defining
10893: methods, and overriding the class's selectors. You must not define new
10894: selectors or fields.
1.7 pazsan 10895:
1.78 anton 10896: Note that you often have to override a selector before using it. In
10897: particular, you usually have to override @code{construct} with a new
10898: method before you can invoke @code{heap-new} and friends. E.g., you
10899: must not create a circle before the @code{overrides construct} sequence
10900: in the example above.
1.7 pazsan 10901:
1.78 anton 10902: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10903: @subsubsection Object Interfaces
10904: @cindex object interfaces
10905: @cindex interfaces for objects
1.7 pazsan 10906:
1.78 anton 10907: In this model you can only call selectors defined in the class of the
10908: receiving objects or in one of its ancestors. If you call a selector
10909: with a receiving object that is not in one of these classes, the
10910: result is undefined; if you are lucky, the program crashes
10911: immediately.
1.7 pazsan 10912:
1.78 anton 10913: @cindex selectors common to hardly-related classes
10914: Now consider the case when you want to have a selector (or several)
10915: available in two classes: You would have to add the selector to a
10916: common ancestor class, in the worst case to @code{object}. You
10917: may not want to do this, e.g., because someone else is responsible for
10918: this ancestor class.
1.7 pazsan 10919:
1.78 anton 10920: The solution for this problem is interfaces. An interface is a
10921: collection of selectors. If a class implements an interface, the
10922: selectors become available to the class and its descendents. A class
10923: can implement an unlimited number of interfaces. For the problem
10924: discussed above, we would define an interface for the selector(s), and
10925: both classes would implement the interface.
1.7 pazsan 10926:
1.78 anton 10927: As an example, consider an interface @code{storage} for
10928: writing objects to disk and getting them back, and a class
10929: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10930:
1.78 anton 10931: @cindex @code{interface} usage
10932: @cindex @code{end-interface} usage
10933: @cindex @code{implementation} usage
10934: @example
10935: interface
10936: selector write ( file object -- )
10937: selector read1 ( file object -- )
10938: end-interface storage
1.13 pazsan 10939:
1.78 anton 10940: bar class
10941: storage implementation
1.13 pazsan 10942:
1.78 anton 10943: ... overrides write
10944: ... overrides read1
10945: ...
10946: end-class foo
10947: @end example
1.13 pazsan 10948:
1.78 anton 10949: @noindent
10950: (I would add a word @code{read} @i{( file -- object )} that uses
10951: @code{read1} internally, but that's beyond the point illustrated
10952: here.)
1.13 pazsan 10953:
1.78 anton 10954: Note that you cannot use @code{protected} in an interface; and
10955: of course you cannot define fields.
1.13 pazsan 10956:
1.78 anton 10957: In the Neon model, all selectors are available for all classes;
10958: therefore it does not need interfaces. The price you pay in this model
10959: is slower late binding, and therefore, added complexity to avoid late
10960: binding.
1.13 pazsan 10961:
1.78 anton 10962: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10963: @subsubsection @file{objects.fs} Implementation
10964: @cindex @file{objects.fs} implementation
1.13 pazsan 10965:
1.78 anton 10966: @cindex @code{object-map} discussion
10967: An object is a piece of memory, like one of the data structures
10968: described with @code{struct...end-struct}. It has a field
10969: @code{object-map} that points to the method map for the object's
10970: class.
1.13 pazsan 10971:
1.78 anton 10972: @cindex method map
10973: @cindex virtual function table
10974: The @emph{method map}@footnote{This is Self terminology; in C++
10975: terminology: virtual function table.} is an array that contains the
10976: execution tokens (@i{xt}s) of the methods for the object's class. Each
10977: selector contains an offset into a method map.
1.13 pazsan 10978:
1.78 anton 10979: @cindex @code{selector} implementation, class
10980: @code{selector} is a defining word that uses
10981: @code{CREATE} and @code{DOES>}. The body of the
10982: selector contains the offset; the @code{DOES>} action for a
10983: class selector is, basically:
1.8 pazsan 10984:
10985: @example
1.78 anton 10986: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10987: @end example
10988:
1.78 anton 10989: Since @code{object-map} is the first field of the object, it
10990: does not generate any code. As you can see, calling a selector has a
10991: small, constant cost.
1.26 crook 10992:
1.78 anton 10993: @cindex @code{current-interface} discussion
10994: @cindex class implementation and representation
10995: A class is basically a @code{struct} combined with a method
10996: map. During the class definition the alignment and size of the class
10997: are passed on the stack, just as with @code{struct}s, so
10998: @code{field} can also be used for defining class
10999: fields. However, passing more items on the stack would be
11000: inconvenient, so @code{class} builds a data structure in memory,
11001: which is accessed through the variable
11002: @code{current-interface}. After its definition is complete, the
11003: class is represented on the stack by a pointer (e.g., as parameter for
11004: a child class definition).
1.26 crook 11005:
1.78 anton 11006: A new class starts off with the alignment and size of its parent,
11007: and a copy of the parent's method map. Defining new fields extends the
11008: size and alignment; likewise, defining new selectors extends the
11009: method map. @code{overrides} just stores a new @i{xt} in the method
11010: map at the offset given by the selector.
1.13 pazsan 11011:
1.78 anton 11012: @cindex class binding, implementation
11013: Class binding just gets the @i{xt} at the offset given by the selector
11014: from the class's method map and @code{compile,}s (in the case of
11015: @code{[bind]}) it.
1.13 pazsan 11016:
1.78 anton 11017: @cindex @code{this} implementation
11018: @cindex @code{catch} and @code{this}
11019: @cindex @code{this} and @code{catch}
11020: I implemented @code{this} as a @code{value}. At the
11021: start of an @code{m:...;m} method the old @code{this} is
11022: stored to the return stack and restored at the end; and the object on
11023: the TOS is stored @code{TO this}. This technique has one
11024: disadvantage: If the user does not leave the method via
11025: @code{;m}, but via @code{throw} or @code{exit},
11026: @code{this} is not restored (and @code{exit} may
11027: crash). To deal with the @code{throw} problem, I have redefined
11028: @code{catch} to save and restore @code{this}; the same
11029: should be done with any word that can catch an exception. As for
11030: @code{exit}, I simply forbid it (as a replacement, there is
11031: @code{exitm}).
1.13 pazsan 11032:
1.78 anton 11033: @cindex @code{inst-var} implementation
11034: @code{inst-var} is just the same as @code{field}, with
11035: a different @code{DOES>} action:
1.13 pazsan 11036: @example
1.78 anton 11037: @@ this +
1.8 pazsan 11038: @end example
1.78 anton 11039: Similar for @code{inst-value}.
1.8 pazsan 11040:
1.78 anton 11041: @cindex class scoping implementation
11042: Each class also has a word list that contains the words defined with
11043: @code{inst-var} and @code{inst-value}, and its protected
11044: words. It also has a pointer to its parent. @code{class} pushes
11045: the word lists of the class and all its ancestors onto the search order stack,
11046: and @code{end-class} drops them.
1.20 pazsan 11047:
1.78 anton 11048: @cindex interface implementation
11049: An interface is like a class without fields, parent and protected
11050: words; i.e., it just has a method map. If a class implements an
11051: interface, its method map contains a pointer to the method map of the
11052: interface. The positive offsets in the map are reserved for class
11053: methods, therefore interface map pointers have negative
11054: offsets. Interfaces have offsets that are unique throughout the
11055: system, unlike class selectors, whose offsets are only unique for the
11056: classes where the selector is available (invokable).
1.20 pazsan 11057:
1.78 anton 11058: This structure means that interface selectors have to perform one
11059: indirection more than class selectors to find their method. Their body
11060: contains the interface map pointer offset in the class method map, and
11061: the method offset in the interface method map. The
11062: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11063:
11064: @example
1.78 anton 11065: ( object selector-body )
11066: 2dup selector-interface @@ ( object selector-body object interface-offset )
11067: swap object-map @@ + @@ ( object selector-body map )
11068: swap selector-offset @@ + @@ execute
1.20 pazsan 11069: @end example
11070:
1.78 anton 11071: where @code{object-map} and @code{selector-offset} are
11072: first fields and generate no code.
1.20 pazsan 11073:
1.78 anton 11074: As a concrete example, consider the following code:
1.20 pazsan 11075:
11076: @example
1.78 anton 11077: interface
11078: selector if1sel1
11079: selector if1sel2
11080: end-interface if1
1.20 pazsan 11081:
1.78 anton 11082: object class
11083: if1 implementation
11084: selector cl1sel1
11085: cell% inst-var cl1iv1
1.20 pazsan 11086:
1.78 anton 11087: ' m1 overrides construct
11088: ' m2 overrides if1sel1
11089: ' m3 overrides if1sel2
11090: ' m4 overrides cl1sel2
11091: end-class cl1
1.20 pazsan 11092:
1.78 anton 11093: create obj1 object dict-new drop
11094: create obj2 cl1 dict-new drop
11095: @end example
1.20 pazsan 11096:
1.78 anton 11097: The data structure created by this code (including the data structure
11098: for @code{object}) is shown in the
11099: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11100: @comment TODO add this diagram..
1.20 pazsan 11101:
1.78 anton 11102: @node Objects Glossary, , Objects Implementation, Objects
11103: @subsubsection @file{objects.fs} Glossary
11104: @cindex @file{objects.fs} Glossary
1.20 pazsan 11105:
11106:
1.78 anton 11107: doc---objects-bind
11108: doc---objects-<bind>
11109: doc---objects-bind'
11110: doc---objects-[bind]
11111: doc---objects-class
11112: doc---objects-class->map
11113: doc---objects-class-inst-size
11114: doc---objects-class-override!
1.79 anton 11115: doc---objects-class-previous
11116: doc---objects-class>order
1.78 anton 11117: doc---objects-construct
11118: doc---objects-current'
11119: doc---objects-[current]
11120: doc---objects-current-interface
11121: doc---objects-dict-new
11122: doc---objects-end-class
11123: doc---objects-end-class-noname
11124: doc---objects-end-interface
11125: doc---objects-end-interface-noname
11126: doc---objects-end-methods
11127: doc---objects-exitm
11128: doc---objects-heap-new
11129: doc---objects-implementation
11130: doc---objects-init-object
11131: doc---objects-inst-value
11132: doc---objects-inst-var
11133: doc---objects-interface
11134: doc---objects-m:
11135: doc---objects-:m
11136: doc---objects-;m
11137: doc---objects-method
11138: doc---objects-methods
11139: doc---objects-object
11140: doc---objects-overrides
11141: doc---objects-[parent]
11142: doc---objects-print
11143: doc---objects-protected
11144: doc---objects-public
11145: doc---objects-selector
11146: doc---objects-this
11147: doc---objects-<to-inst>
11148: doc---objects-[to-inst]
11149: doc---objects-to-this
11150: doc---objects-xt-new
1.20 pazsan 11151:
11152:
1.78 anton 11153: @c -------------------------------------------------------------
11154: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11155: @subsection The @file{oof.fs} model
11156: @cindex oof
11157: @cindex object-oriented programming
1.20 pazsan 11158:
1.78 anton 11159: @cindex @file{objects.fs}
11160: @cindex @file{oof.fs}
1.20 pazsan 11161:
1.78 anton 11162: This section describes the @file{oof.fs} package.
1.20 pazsan 11163:
1.78 anton 11164: The package described in this section has been used in bigFORTH since 1991, and
11165: used for two large applications: a chromatographic system used to
11166: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11167:
1.78 anton 11168: You can find a description (in German) of @file{oof.fs} in @cite{Object
11169: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11170: 10(2), 1994.
1.20 pazsan 11171:
1.78 anton 11172: @menu
11173: * Properties of the OOF model::
11174: * Basic OOF Usage::
11175: * The OOF base class::
11176: * Class Declaration::
11177: * Class Implementation::
11178: @end menu
1.20 pazsan 11179:
1.78 anton 11180: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11181: @subsubsection Properties of the @file{oof.fs} model
11182: @cindex @file{oof.fs} properties
1.20 pazsan 11183:
1.78 anton 11184: @itemize @bullet
11185: @item
11186: This model combines object oriented programming with information
11187: hiding. It helps you writing large application, where scoping is
11188: necessary, because it provides class-oriented scoping.
1.20 pazsan 11189:
1.78 anton 11190: @item
11191: Named objects, object pointers, and object arrays can be created,
11192: selector invocation uses the ``object selector'' syntax. Selector invocation
11193: to objects and/or selectors on the stack is a bit less convenient, but
11194: possible.
1.44 crook 11195:
1.78 anton 11196: @item
11197: Selector invocation and instance variable usage of the active object is
11198: straightforward, since both make use of the active object.
1.44 crook 11199:
1.78 anton 11200: @item
11201: Late binding is efficient and easy to use.
1.20 pazsan 11202:
1.78 anton 11203: @item
11204: State-smart objects parse selectors. However, extensibility is provided
11205: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11206:
1.78 anton 11207: @item
11208: An implementation in ANS Forth is available.
1.20 pazsan 11209:
1.78 anton 11210: @end itemize
1.23 crook 11211:
11212:
1.78 anton 11213: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11214: @subsubsection Basic @file{oof.fs} Usage
11215: @cindex @file{oof.fs} usage
1.23 crook 11216:
1.78 anton 11217: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11218:
1.78 anton 11219: You can define a class for graphical objects like this:
1.23 crook 11220:
1.78 anton 11221: @cindex @code{class} usage
11222: @cindex @code{class;} usage
11223: @cindex @code{method} usage
11224: @example
11225: object class graphical \ "object" is the parent class
1.139 pazsan 11226: method draw ( x y -- )
1.78 anton 11227: class;
11228: @end example
1.23 crook 11229:
1.78 anton 11230: This code defines a class @code{graphical} with an
11231: operation @code{draw}. We can perform the operation
11232: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11233:
1.78 anton 11234: @example
11235: 100 100 t-rex draw
11236: @end example
1.23 crook 11237:
1.78 anton 11238: @noindent
11239: where @code{t-rex} is an object or object pointer, created with e.g.
11240: @code{graphical : t-rex}.
1.23 crook 11241:
1.78 anton 11242: @cindex abstract class
11243: How do we create a graphical object? With the present definitions,
11244: we cannot create a useful graphical object. The class
11245: @code{graphical} describes graphical objects in general, but not
11246: any concrete graphical object type (C++ users would call it an
11247: @emph{abstract class}); e.g., there is no method for the selector
11248: @code{draw} in the class @code{graphical}.
1.23 crook 11249:
1.78 anton 11250: For concrete graphical objects, we define child classes of the
11251: class @code{graphical}, e.g.:
1.23 crook 11252:
1.78 anton 11253: @example
11254: graphical class circle \ "graphical" is the parent class
11255: cell var circle-radius
11256: how:
11257: : draw ( x y -- )
11258: circle-radius @@ draw-circle ;
1.23 crook 11259:
1.139 pazsan 11260: : init ( n-radius -- )
1.78 anton 11261: circle-radius ! ;
11262: class;
11263: @end example
1.1 anton 11264:
1.78 anton 11265: Here we define a class @code{circle} as a child of @code{graphical},
11266: with a field @code{circle-radius}; it defines new methods for the
11267: selectors @code{draw} and @code{init} (@code{init} is defined in
11268: @code{object}, the parent class of @code{graphical}).
1.1 anton 11269:
1.78 anton 11270: Now we can create a circle in the dictionary with:
1.1 anton 11271:
1.78 anton 11272: @example
11273: 50 circle : my-circle
11274: @end example
1.21 crook 11275:
1.78 anton 11276: @noindent
11277: @code{:} invokes @code{init}, thus initializing the field
11278: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11279: with:
1.1 anton 11280:
1.78 anton 11281: @example
11282: 100 100 my-circle draw
11283: @end example
1.1 anton 11284:
1.78 anton 11285: @cindex selector invocation, restrictions
11286: @cindex class definition, restrictions
11287: Note: You can only invoke a selector if the receiving object belongs to
11288: the class where the selector was defined or one of its descendents;
11289: e.g., you can invoke @code{draw} only for objects belonging to
11290: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11291: mechanism will check if you try to invoke a selector that is not
11292: defined in this class hierarchy, so you'll get an error at compilation
11293: time.
1.1 anton 11294:
11295:
1.78 anton 11296: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11297: @subsubsection The @file{oof.fs} base class
11298: @cindex @file{oof.fs} base class
1.1 anton 11299:
1.78 anton 11300: When you define a class, you have to specify a parent class. So how do
11301: you start defining classes? There is one class available from the start:
11302: @code{object}. You have to use it as ancestor for all classes. It is the
11303: only class that has no parent. Classes are also objects, except that
11304: they don't have instance variables; class manipulation such as
11305: inheritance or changing definitions of a class is handled through
11306: selectors of the class @code{object}.
1.1 anton 11307:
1.78 anton 11308: @code{object} provides a number of selectors:
1.1 anton 11309:
1.78 anton 11310: @itemize @bullet
11311: @item
11312: @code{class} for subclassing, @code{definitions} to add definitions
11313: later on, and @code{class?} to get type informations (is the class a
11314: subclass of the class passed on the stack?).
1.1 anton 11315:
1.78 anton 11316: doc---object-class
11317: doc---object-definitions
11318: doc---object-class?
1.1 anton 11319:
11320:
1.26 crook 11321: @item
1.78 anton 11322: @code{init} and @code{dispose} as constructor and destructor of the
11323: object. @code{init} is invocated after the object's memory is allocated,
11324: while @code{dispose} also handles deallocation. Thus if you redefine
11325: @code{dispose}, you have to call the parent's dispose with @code{super
11326: dispose}, too.
11327:
11328: doc---object-init
11329: doc---object-dispose
11330:
1.1 anton 11331:
1.26 crook 11332: @item
1.78 anton 11333: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11334: @code{[]} to create named and unnamed objects and object arrays or
11335: object pointers.
11336:
11337: doc---object-new
11338: doc---object-new[]
11339: doc---object-:
11340: doc---object-ptr
11341: doc---object-asptr
11342: doc---object-[]
11343:
1.1 anton 11344:
1.26 crook 11345: @item
1.78 anton 11346: @code{::} and @code{super} for explicit scoping. You should use explicit
11347: scoping only for super classes or classes with the same set of instance
11348: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11349:
1.78 anton 11350: doc---object-::
11351: doc---object-super
1.21 crook 11352:
11353:
1.26 crook 11354: @item
1.78 anton 11355: @code{self} to get the address of the object
1.21 crook 11356:
1.78 anton 11357: doc---object-self
1.21 crook 11358:
11359:
1.78 anton 11360: @item
11361: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11362: pointers and instance defers.
1.21 crook 11363:
1.78 anton 11364: doc---object-bind
11365: doc---object-bound
11366: doc---object-link
11367: doc---object-is
1.21 crook 11368:
11369:
1.78 anton 11370: @item
11371: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11372: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11373:
1.78 anton 11374: doc---object-'
11375: doc---object-postpone
1.21 crook 11376:
11377:
1.78 anton 11378: @item
11379: @code{with} and @code{endwith} to select the active object from the
11380: stack, and enable its scope. Using @code{with} and @code{endwith}
11381: also allows you to create code using selector @code{postpone} without being
11382: trapped by the state-smart objects.
1.21 crook 11383:
1.78 anton 11384: doc---object-with
11385: doc---object-endwith
1.21 crook 11386:
11387:
1.78 anton 11388: @end itemize
1.21 crook 11389:
1.78 anton 11390: @node Class Declaration, Class Implementation, The OOF base class, OOF
11391: @subsubsection Class Declaration
11392: @cindex class declaration
1.21 crook 11393:
1.78 anton 11394: @itemize @bullet
11395: @item
11396: Instance variables
1.21 crook 11397:
1.78 anton 11398: doc---oof-var
1.21 crook 11399:
11400:
1.78 anton 11401: @item
11402: Object pointers
1.21 crook 11403:
1.78 anton 11404: doc---oof-ptr
11405: doc---oof-asptr
1.21 crook 11406:
11407:
1.78 anton 11408: @item
11409: Instance defers
1.21 crook 11410:
1.78 anton 11411: doc---oof-defer
1.21 crook 11412:
11413:
1.78 anton 11414: @item
11415: Method selectors
1.21 crook 11416:
1.78 anton 11417: doc---oof-early
11418: doc---oof-method
1.21 crook 11419:
11420:
1.78 anton 11421: @item
11422: Class-wide variables
1.21 crook 11423:
1.78 anton 11424: doc---oof-static
1.21 crook 11425:
11426:
1.78 anton 11427: @item
11428: End declaration
1.1 anton 11429:
1.78 anton 11430: doc---oof-how:
11431: doc---oof-class;
1.21 crook 11432:
11433:
1.78 anton 11434: @end itemize
1.21 crook 11435:
1.78 anton 11436: @c -------------------------------------------------------------
11437: @node Class Implementation, , Class Declaration, OOF
11438: @subsubsection Class Implementation
11439: @cindex class implementation
1.21 crook 11440:
1.78 anton 11441: @c -------------------------------------------------------------
11442: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11443: @subsection The @file{mini-oof.fs} model
11444: @cindex mini-oof
1.21 crook 11445:
1.78 anton 11446: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11447: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11448: and reduces to the bare minimum of features. This is based on a posting
11449: of Bernd Paysan in comp.lang.forth.
1.21 crook 11450:
1.78 anton 11451: @menu
11452: * Basic Mini-OOF Usage::
11453: * Mini-OOF Example::
11454: * Mini-OOF Implementation::
11455: @end menu
1.21 crook 11456:
1.78 anton 11457: @c -------------------------------------------------------------
11458: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11459: @subsubsection Basic @file{mini-oof.fs} Usage
11460: @cindex mini-oof usage
1.21 crook 11461:
1.78 anton 11462: There is a base class (@code{class}, which allocates one cell for the
11463: object pointer) plus seven other words: to define a method, a variable,
11464: a class; to end a class, to resolve binding, to allocate an object and
11465: to compile a class method.
11466: @comment TODO better description of the last one
1.26 crook 11467:
1.21 crook 11468:
1.78 anton 11469: doc-object
11470: doc-method
11471: doc-var
11472: doc-class
11473: doc-end-class
11474: doc-defines
11475: doc-new
11476: doc-::
1.21 crook 11477:
11478:
11479:
1.78 anton 11480: @c -------------------------------------------------------------
11481: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11482: @subsubsection Mini-OOF Example
11483: @cindex mini-oof example
1.1 anton 11484:
1.78 anton 11485: A short example shows how to use this package. This example, in slightly
11486: extended form, is supplied as @file{moof-exm.fs}
11487: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11488:
1.26 crook 11489: @example
1.78 anton 11490: object class
11491: method init
11492: method draw
11493: end-class graphical
1.26 crook 11494: @end example
1.20 pazsan 11495:
1.78 anton 11496: This code defines a class @code{graphical} with an
11497: operation @code{draw}. We can perform the operation
11498: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11499:
1.26 crook 11500: @example
1.78 anton 11501: 100 100 t-rex draw
1.26 crook 11502: @end example
1.12 anton 11503:
1.78 anton 11504: where @code{t-rex} is an object or object pointer, created with e.g.
11505: @code{graphical new Constant t-rex}.
1.12 anton 11506:
1.78 anton 11507: For concrete graphical objects, we define child classes of the
11508: class @code{graphical}, e.g.:
1.12 anton 11509:
1.26 crook 11510: @example
11511: graphical class
1.78 anton 11512: cell var circle-radius
11513: end-class circle \ "graphical" is the parent class
1.12 anton 11514:
1.78 anton 11515: :noname ( x y -- )
11516: circle-radius @@ draw-circle ; circle defines draw
11517: :noname ( r -- )
11518: circle-radius ! ; circle defines init
11519: @end example
1.12 anton 11520:
1.78 anton 11521: There is no implicit init method, so we have to define one. The creation
11522: code of the object now has to call init explicitely.
1.21 crook 11523:
1.78 anton 11524: @example
11525: circle new Constant my-circle
11526: 50 my-circle init
1.12 anton 11527: @end example
11528:
1.78 anton 11529: It is also possible to add a function to create named objects with
11530: automatic call of @code{init}, given that all objects have @code{init}
11531: on the same place:
1.38 anton 11532:
1.78 anton 11533: @example
11534: : new: ( .. o "name" -- )
11535: new dup Constant init ;
11536: 80 circle new: large-circle
11537: @end example
1.12 anton 11538:
1.78 anton 11539: We can draw this new circle at (100,100) with:
1.12 anton 11540:
1.78 anton 11541: @example
11542: 100 100 my-circle draw
11543: @end example
1.12 anton 11544:
1.78 anton 11545: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11546: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11547:
1.78 anton 11548: Object-oriented systems with late binding typically use a
11549: ``vtable''-approach: the first variable in each object is a pointer to a
11550: table, which contains the methods as function pointers. The vtable
11551: may also contain other information.
1.12 anton 11552:
1.79 anton 11553: So first, let's declare selectors:
1.37 anton 11554:
11555: @example
1.79 anton 11556: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11557: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11558: @end example
1.37 anton 11559:
1.79 anton 11560: During selector declaration, the number of selectors and instance
11561: variables is on the stack (in address units). @code{method} creates one
11562: selector and increments the selector number. To execute a selector, it
1.78 anton 11563: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11564: executes the method @i{xt} stored there. Each selector takes the object
11565: it is invoked with as top of stack parameter; it passes the parameters
11566: (including the object) unchanged to the appropriate method which should
1.78 anton 11567: consume that object.
1.37 anton 11568:
1.78 anton 11569: Now, we also have to declare instance variables
1.37 anton 11570:
1.78 anton 11571: @example
1.79 anton 11572: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11573: DOES> ( o -- addr ) @@ + ;
1.37 anton 11574: @end example
11575:
1.78 anton 11576: As before, a word is created with the current offset. Instance
11577: variables can have different sizes (cells, floats, doubles, chars), so
11578: all we do is take the size and add it to the offset. If your machine
11579: has alignment restrictions, put the proper @code{aligned} or
11580: @code{faligned} before the variable, to adjust the variable
11581: offset. That's why it is on the top of stack.
1.37 anton 11582:
1.78 anton 11583: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11584:
1.78 anton 11585: @example
11586: Create object 1 cells , 2 cells ,
1.79 anton 11587: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11588: @end example
1.12 anton 11589:
1.78 anton 11590: For inheritance, the vtable of the parent object has to be
11591: copied when a new, derived class is declared. This gives all the
11592: methods of the parent class, which can be overridden, though.
1.12 anton 11593:
1.78 anton 11594: @example
1.79 anton 11595: : end-class ( class selectors vars "name" -- )
1.78 anton 11596: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11597: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11598: @end example
1.12 anton 11599:
1.78 anton 11600: The first line creates the vtable, initialized with
11601: @code{noop}s. The second line is the inheritance mechanism, it
11602: copies the xts from the parent vtable.
1.12 anton 11603:
1.78 anton 11604: We still have no way to define new methods, let's do that now:
1.12 anton 11605:
1.26 crook 11606: @example
1.79 anton 11607: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11608: @end example
1.12 anton 11609:
1.78 anton 11610: To allocate a new object, we need a word, too:
1.12 anton 11611:
1.78 anton 11612: @example
11613: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11614: @end example
11615:
1.78 anton 11616: Sometimes derived classes want to access the method of the
11617: parent object. There are two ways to achieve this with Mini-OOF:
11618: first, you could use named words, and second, you could look up the
11619: vtable of the parent object.
1.12 anton 11620:
1.78 anton 11621: @example
11622: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11623: @end example
1.12 anton 11624:
11625:
1.78 anton 11626: Nothing can be more confusing than a good example, so here is
11627: one. First let's declare a text object (called
11628: @code{button}), that stores text and position:
1.12 anton 11629:
1.78 anton 11630: @example
11631: object class
11632: cell var text
11633: cell var len
11634: cell var x
11635: cell var y
11636: method init
11637: method draw
11638: end-class button
11639: @end example
1.12 anton 11640:
1.78 anton 11641: @noindent
11642: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11643:
1.26 crook 11644: @example
1.78 anton 11645: :noname ( o -- )
11646: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11647: button defines draw
11648: :noname ( addr u o -- )
11649: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11650: button defines init
1.26 crook 11651: @end example
1.12 anton 11652:
1.78 anton 11653: @noindent
11654: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11655: new data and no new selectors:
1.78 anton 11656:
11657: @example
11658: button class
11659: end-class bold-button
1.12 anton 11660:
1.78 anton 11661: : bold 27 emit ." [1m" ;
11662: : normal 27 emit ." [0m" ;
11663: @end example
1.1 anton 11664:
1.78 anton 11665: @noindent
11666: The class @code{bold-button} has a different draw method to
11667: @code{button}, but the new method is defined in terms of the draw method
11668: for @code{button}:
1.20 pazsan 11669:
1.78 anton 11670: @example
11671: :noname bold [ button :: draw ] normal ; bold-button defines draw
11672: @end example
1.21 crook 11673:
1.78 anton 11674: @noindent
1.79 anton 11675: Finally, create two objects and apply selectors:
1.21 crook 11676:
1.26 crook 11677: @example
1.78 anton 11678: button new Constant foo
11679: s" thin foo" foo init
11680: page
11681: foo draw
11682: bold-button new Constant bar
11683: s" fat bar" bar init
11684: 1 bar y !
11685: bar draw
1.26 crook 11686: @end example
1.21 crook 11687:
11688:
1.78 anton 11689: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11690: @subsection Comparison with other object models
11691: @cindex comparison of object models
11692: @cindex object models, comparison
11693:
11694: Many object-oriented Forth extensions have been proposed (@cite{A survey
11695: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11696: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11697: relation of the object models described here to two well-known and two
11698: closely-related (by the use of method maps) models. Andras Zsoter
11699: helped us with this section.
11700:
11701: @cindex Neon model
11702: The most popular model currently seems to be the Neon model (see
11703: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11704: 1997) by Andrew McKewan) but this model has a number of limitations
11705: @footnote{A longer version of this critique can be
11706: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11707: Dimensions, May 1997) by Anton Ertl.}:
11708:
11709: @itemize @bullet
11710: @item
11711: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11712: to pass objects on the stack.
1.21 crook 11713:
1.78 anton 11714: @item
11715: It requires that the selector parses the input stream (at
1.79 anton 11716: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11717: hard to find.
1.21 crook 11718:
1.78 anton 11719: @item
1.79 anton 11720: It allows using every selector on every object; this eliminates the
11721: need for interfaces, but makes it harder to create efficient
11722: implementations.
1.78 anton 11723: @end itemize
1.21 crook 11724:
1.78 anton 11725: @cindex Pountain's object-oriented model
11726: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11727: Press, London, 1987) by Dick Pountain. However, it is not really about
11728: object-oriented programming, because it hardly deals with late
11729: binding. Instead, it focuses on features like information hiding and
11730: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11731:
1.78 anton 11732: @cindex Zsoter's object-oriented model
1.79 anton 11733: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11734: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11735: describes a model that makes heavy use of an active object (like
11736: @code{this} in @file{objects.fs}): The active object is not only used
11737: for accessing all fields, but also specifies the receiving object of
11738: every selector invocation; you have to change the active object
11739: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11740: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11741: the method entry point is unnecessary with Zsoter's model, because the
11742: receiving object is the active object already. On the other hand, the
11743: explicit change is absolutely necessary in that model, because otherwise
11744: no one could ever change the active object. An ANS Forth implementation
11745: of this model is available through
11746: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11747:
1.78 anton 11748: @cindex @file{oof.fs}, differences to other models
11749: The @file{oof.fs} model combines information hiding and overloading
11750: resolution (by keeping names in various word lists) with object-oriented
11751: programming. It sets the active object implicitly on method entry, but
11752: also allows explicit changing (with @code{>o...o>} or with
11753: @code{with...endwith}). It uses parsing and state-smart objects and
11754: classes for resolving overloading and for early binding: the object or
11755: class parses the selector and determines the method from this. If the
11756: selector is not parsed by an object or class, it performs a call to the
11757: selector for the active object (late binding), like Zsoter's model.
11758: Fields are always accessed through the active object. The big
11759: disadvantage of this model is the parsing and the state-smartness, which
11760: reduces extensibility and increases the opportunities for subtle bugs;
11761: essentially, you are only safe if you never tick or @code{postpone} an
11762: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11763:
1.78 anton 11764: @cindex @file{mini-oof.fs}, differences to other models
11765: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11766: version of the @file{objects.fs} model, but syntactically it is a
11767: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11768:
11769:
1.78 anton 11770: @c -------------------------------------------------------------
1.150 anton 11771: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11772: @section Programming Tools
11773: @cindex programming tools
1.21 crook 11774:
1.78 anton 11775: @c !! move this and assembler down below OO stuff.
1.21 crook 11776:
1.78 anton 11777: @menu
1.150 anton 11778: * Examining:: Data and Code.
11779: * Forgetting words:: Usually before reloading.
1.78 anton 11780: * Debugging:: Simple and quick.
11781: * Assertions:: Making your programs self-checking.
11782: * Singlestep Debugger:: Executing your program word by word.
11783: @end menu
1.21 crook 11784:
1.78 anton 11785: @node Examining, Forgetting words, Programming Tools, Programming Tools
11786: @subsection Examining data and code
11787: @cindex examining data and code
11788: @cindex data examination
11789: @cindex code examination
1.44 crook 11790:
1.78 anton 11791: The following words inspect the stack non-destructively:
1.21 crook 11792:
1.78 anton 11793: doc-.s
11794: doc-f.s
1.158 anton 11795: doc-maxdepth-.s
1.44 crook 11796:
1.78 anton 11797: There is a word @code{.r} but it does @i{not} display the return stack!
11798: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11799:
1.78 anton 11800: doc-depth
11801: doc-fdepth
11802: doc-clearstack
1.124 anton 11803: doc-clearstacks
1.21 crook 11804:
1.78 anton 11805: The following words inspect memory.
1.21 crook 11806:
1.78 anton 11807: doc-?
11808: doc-dump
1.21 crook 11809:
1.78 anton 11810: And finally, @code{see} allows to inspect code:
1.21 crook 11811:
1.78 anton 11812: doc-see
11813: doc-xt-see
1.111 anton 11814: doc-simple-see
11815: doc-simple-see-range
1.182 anton 11816: doc-see-code
11817: doc-see-code-range
1.21 crook 11818:
1.78 anton 11819: @node Forgetting words, Debugging, Examining, Programming Tools
11820: @subsection Forgetting words
11821: @cindex words, forgetting
11822: @cindex forgeting words
1.21 crook 11823:
1.78 anton 11824: @c anton: other, maybe better places for this subsection: Defining Words;
11825: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11826:
1.78 anton 11827: Forth allows you to forget words (and everything that was alloted in the
11828: dictonary after them) in a LIFO manner.
1.21 crook 11829:
1.78 anton 11830: doc-marker
1.21 crook 11831:
1.78 anton 11832: The most common use of this feature is during progam development: when
11833: you change a source file, forget all the words it defined and load it
11834: again (since you also forget everything defined after the source file
11835: was loaded, you have to reload that, too). Note that effects like
11836: storing to variables and destroyed system words are not undone when you
11837: forget words. With a system like Gforth, that is fast enough at
11838: starting up and compiling, I find it more convenient to exit and restart
11839: Gforth, as this gives me a clean slate.
1.21 crook 11840:
1.78 anton 11841: Here's an example of using @code{marker} at the start of a source file
11842: that you are debugging; it ensures that you only ever have one copy of
11843: the file's definitions compiled at any time:
1.21 crook 11844:
1.78 anton 11845: @example
11846: [IFDEF] my-code
11847: my-code
11848: [ENDIF]
1.26 crook 11849:
1.78 anton 11850: marker my-code
11851: init-included-files
1.21 crook 11852:
1.78 anton 11853: \ .. definitions start here
11854: \ .
11855: \ .
11856: \ end
11857: @end example
1.21 crook 11858:
1.26 crook 11859:
1.78 anton 11860: @node Debugging, Assertions, Forgetting words, Programming Tools
11861: @subsection Debugging
11862: @cindex debugging
1.21 crook 11863:
1.78 anton 11864: Languages with a slow edit/compile/link/test development loop tend to
11865: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11866:
1.78 anton 11867: A much better (faster) way in fast-compiling languages is to add
11868: printing code at well-selected places, let the program run, look at
11869: the output, see where things went wrong, add more printing code, etc.,
11870: until the bug is found.
1.21 crook 11871:
1.78 anton 11872: The simple debugging aids provided in @file{debugs.fs}
11873: are meant to support this style of debugging.
1.21 crook 11874:
1.78 anton 11875: The word @code{~~} prints debugging information (by default the source
11876: location and the stack contents). It is easy to insert. If you use Emacs
11877: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11878: query-replace them with nothing). The deferred words
1.101 anton 11879: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11880: @code{~~}. The default source location output format works well with
11881: Emacs' compilation mode, so you can step through the program at the
11882: source level using @kbd{C-x `} (the advantage over a stepping debugger
11883: is that you can step in any direction and you know where the crash has
11884: happened or where the strange data has occurred).
1.21 crook 11885:
1.78 anton 11886: doc-~~
11887: doc-printdebugdata
1.101 anton 11888: doc-.debugline
1.21 crook 11889:
1.106 anton 11890: @cindex filenames in @code{~~} output
11891: @code{~~} (and assertions) will usually print the wrong file name if a
11892: marker is executed in the same file after their occurance. They will
11893: print @samp{*somewhere*} as file name if a marker is executed in the
11894: same file before their occurance.
11895:
11896:
1.78 anton 11897: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11898: @subsection Assertions
11899: @cindex assertions
1.21 crook 11900:
1.78 anton 11901: It is a good idea to make your programs self-checking, especially if you
11902: make an assumption that may become invalid during maintenance (for
11903: example, that a certain field of a data structure is never zero). Gforth
11904: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11905:
11906: @example
1.78 anton 11907: assert( @i{flag} )
1.26 crook 11908: @end example
11909:
1.78 anton 11910: The code between @code{assert(} and @code{)} should compute a flag, that
11911: should be true if everything is alright and false otherwise. It should
11912: not change anything else on the stack. The overall stack effect of the
11913: assertion is @code{( -- )}. E.g.
1.21 crook 11914:
1.26 crook 11915: @example
1.78 anton 11916: assert( 1 1 + 2 = ) \ what we learn in school
11917: assert( dup 0<> ) \ assert that the top of stack is not zero
11918: assert( false ) \ this code should not be reached
1.21 crook 11919: @end example
11920:
1.78 anton 11921: The need for assertions is different at different times. During
11922: debugging, we want more checking, in production we sometimes care more
11923: for speed. Therefore, assertions can be turned off, i.e., the assertion
11924: becomes a comment. Depending on the importance of an assertion and the
11925: time it takes to check it, you may want to turn off some assertions and
11926: keep others turned on. Gforth provides several levels of assertions for
11927: this purpose:
11928:
11929:
11930: doc-assert0(
11931: doc-assert1(
11932: doc-assert2(
11933: doc-assert3(
11934: doc-assert(
11935: doc-)
1.21 crook 11936:
11937:
1.78 anton 11938: The variable @code{assert-level} specifies the highest assertions that
11939: are turned on. I.e., at the default @code{assert-level} of one,
11940: @code{assert0(} and @code{assert1(} assertions perform checking, while
11941: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11942:
1.78 anton 11943: The value of @code{assert-level} is evaluated at compile-time, not at
11944: run-time. Therefore you cannot turn assertions on or off at run-time;
11945: you have to set the @code{assert-level} appropriately before compiling a
11946: piece of code. You can compile different pieces of code at different
11947: @code{assert-level}s (e.g., a trusted library at level 1 and
11948: newly-written code at level 3).
1.26 crook 11949:
11950:
1.78 anton 11951: doc-assert-level
1.26 crook 11952:
11953:
1.78 anton 11954: If an assertion fails, a message compatible with Emacs' compilation mode
11955: is produced and the execution is aborted (currently with @code{ABORT"}.
11956: If there is interest, we will introduce a special throw code. But if you
11957: intend to @code{catch} a specific condition, using @code{throw} is
11958: probably more appropriate than an assertion).
1.106 anton 11959:
11960: @cindex filenames in assertion output
11961: Assertions (and @code{~~}) will usually print the wrong file name if a
11962: marker is executed in the same file after their occurance. They will
11963: print @samp{*somewhere*} as file name if a marker is executed in the
11964: same file before their occurance.
1.44 crook 11965:
1.78 anton 11966: Definitions in ANS Forth for these assertion words are provided
11967: in @file{compat/assert.fs}.
1.26 crook 11968:
1.44 crook 11969:
1.78 anton 11970: @node Singlestep Debugger, , Assertions, Programming Tools
11971: @subsection Singlestep Debugger
11972: @cindex singlestep Debugger
11973: @cindex debugging Singlestep
1.44 crook 11974:
1.189 anton 11975: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 11976:
1.78 anton 11977: When you create a new word there's often the need to check whether it
11978: behaves correctly or not. You can do this by typing @code{dbg
11979: badword}. A debug session might look like this:
1.26 crook 11980:
1.78 anton 11981: @example
11982: : badword 0 DO i . LOOP ; ok
11983: 2 dbg badword
11984: : badword
11985: Scanning code...
1.44 crook 11986:
1.78 anton 11987: Nesting debugger ready!
1.44 crook 11988:
1.78 anton 11989: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11990: 400D4740 8049F68 DO -> [ 0 ]
11991: 400D4744 804A0C8 i -> [ 1 ] 00000
11992: 400D4748 400C5E60 . -> 0 [ 0 ]
11993: 400D474C 8049D0C LOOP -> [ 0 ]
11994: 400D4744 804A0C8 i -> [ 1 ] 00001
11995: 400D4748 400C5E60 . -> 1 [ 0 ]
11996: 400D474C 8049D0C LOOP -> [ 0 ]
11997: 400D4758 804B384 ; -> ok
11998: @end example
1.21 crook 11999:
1.78 anton 12000: Each line displayed is one step. You always have to hit return to
12001: execute the next word that is displayed. If you don't want to execute
12002: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12003: an overview what keys are available:
1.44 crook 12004:
1.78 anton 12005: @table @i
1.44 crook 12006:
1.78 anton 12007: @item @key{RET}
12008: Next; Execute the next word.
1.21 crook 12009:
1.78 anton 12010: @item n
12011: Nest; Single step through next word.
1.44 crook 12012:
1.78 anton 12013: @item u
12014: Unnest; Stop debugging and execute rest of word. If we got to this word
12015: with nest, continue debugging with the calling word.
1.44 crook 12016:
1.78 anton 12017: @item d
12018: Done; Stop debugging and execute rest.
1.21 crook 12019:
1.78 anton 12020: @item s
12021: Stop; Abort immediately.
1.44 crook 12022:
1.78 anton 12023: @end table
1.44 crook 12024:
1.78 anton 12025: Debugging large application with this mechanism is very difficult, because
12026: you have to nest very deeply into the program before the interesting part
12027: begins. This takes a lot of time.
1.26 crook 12028:
1.78 anton 12029: To do it more directly put a @code{BREAK:} command into your source code.
12030: When program execution reaches @code{BREAK:} the single step debugger is
12031: invoked and you have all the features described above.
1.44 crook 12032:
1.78 anton 12033: If you have more than one part to debug it is useful to know where the
12034: program has stopped at the moment. You can do this by the
12035: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12036: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12037:
1.26 crook 12038:
1.78 anton 12039: doc-dbg
12040: doc-break:
12041: doc-break"
1.44 crook 12042:
1.150 anton 12043: @c ------------------------------------------------------------
12044: @node C Interface, Assembler and Code Words, Programming Tools, Words
12045: @section C Interface
12046: @cindex C interface
12047: @cindex foreign language interface
12048: @cindex interface to C functions
12049:
1.178 anton 12050: Note that the C interface is not yet complete; callbacks are missing,
12051: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12052:
12053: @menu
12054: * Calling C Functions::
12055: * Declaring C Functions::
1.180 anton 12056: * Calling C function pointers::
1.150 anton 12057: * Callbacks::
1.178 anton 12058: * C interface internals::
1.155 anton 12059: * Low-Level C Interface Words::
1.150 anton 12060: @end menu
12061:
1.151 pazsan 12062: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12063: @subsection Calling C functions
1.155 anton 12064: @cindex C functions, calls to
12065: @cindex calling C functions
1.150 anton 12066:
1.151 pazsan 12067: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12068: can call it as follows: You push the arguments on the stack(s), and
12069: then call the word for the C function. The arguments have to be
12070: pushed in the same order as the arguments appear in the C
12071: documentation (i.e., the first argument is deepest on the stack).
12072: Integer and pointer arguments have to be pushed on the data stack,
12073: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12074: by the called C function.
1.150 anton 12075:
1.155 anton 12076: On returning from the C function, the return value, if any, resides on
12077: the appropriate stack: an integer return value is pushed on the data
12078: stack, an FP return value on the FP stack, and a void return value
12079: results in not pushing anything. Note that most C functions have a
12080: return value, even if that is often not used in C; in Forth, you have
12081: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12082:
1.177 anton 12083: The C interface automatically converts between the C type and the
12084: Forth type as necessary, on a best-effort basis (in some cases, there
12085: may be some loss).
1.150 anton 12086:
12087: As an example, consider the POSIX function @code{lseek()}:
12088:
12089: @example
12090: off_t lseek(int fd, off_t offset, int whence);
12091: @end example
12092:
12093: This function takes three integer arguments, and returns an integer
12094: argument, so a Forth call for setting the current file offset to the
12095: start of the file could look like this:
12096:
12097: @example
12098: fd @@ 0 SEEK_SET lseek -1 = if
12099: ... \ error handling
12100: then
12101: @end example
12102:
12103: You might be worried that an @code{off_t} does not fit into a cell, so
12104: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12105: of the return values. In that case, in your declaration of the
12106: function (@pxref{Declaring C Functions}) you should declare it to use
12107: double-cells for the off_t argument and return value, and maybe give
12108: the resulting Forth word a different name, like @code{dlseek}; the
12109: result could be called like this:
1.150 anton 12110:
12111: @example
12112: fd @@ 0. SEEK_SET dlseek -1. d= if
12113: ... \ error handling
12114: then
12115: @end example
12116:
12117: Passing and returning structs or unions is currently not supported by
12118: our interface@footnote{If you know the calling convention of your C
12119: compiler, you usually can call such functions in some way, but that
12120: way is usually not portable between platforms, and sometimes not even
12121: between C compilers.}.
12122:
1.177 anton 12123: Calling functions with a variable number of arguments (@emph{variadic}
12124: functions, e.g., @code{printf()}) is only supported by having you
12125: declare one function-calling word for each argument pattern, and
12126: calling the appropriate word for the desired pattern.
12127:
1.150 anton 12128:
1.155 anton 12129:
1.180 anton 12130: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12131: @subsection Declaring C Functions
1.155 anton 12132: @cindex C functions, declarations
12133: @cindex declaring C functions
1.150 anton 12134:
12135: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12136: it. The declaration consists of two parts:
12137:
12138: @table @b
12139:
12140: @item The C part
1.179 anton 12141: is the C declaration of the function, or more typically and portably,
12142: a C-style @code{#include} of a file that contains the declaration of
12143: the C function.
1.177 anton 12144:
12145: @item The Forth part
12146: declares the Forth types of the parameters and the Forth word name
12147: corresponding to the C function.
12148:
12149: @end table
12150:
12151: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12152: declarations are:
12153:
12154: @example
12155: \c #define _FILE_OFFSET_BITS 64
12156: \c #include <sys/types.h>
12157: \c #include <unistd.h>
12158: c-function lseek lseek n n n -- n
12159: c-function dlseek lseek n d n -- d
12160: @end example
12161:
1.178 anton 12162: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12163: of the line is ordinary C code. You can use as many lines of C
12164: declarations as you like, and they are visible for all further
12165: function declarations.
12166:
12167: The Forth part declares each interface word with @code{c-function},
12168: followed by the Forth name of the word, the C name of the called
12169: function, and the stack effect of the word. The stack effect contains
1.178 anton 12170: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12171: exactly one type for the return value. The possible types are:
12172:
12173: @table @code
12174:
12175: @item n
12176: single-cell integer
12177:
12178: @item a
12179: address (single-cell)
12180:
12181: @item d
12182: double-cell integer
12183:
12184: @item r
12185: floating-point value
12186:
12187: @item func
12188: C function pointer
12189:
12190: @item void
12191: no value (used as return type for void functions)
12192:
12193: @end table
12194:
12195: @cindex variadic C functions
12196:
12197: To deal with variadic C functions, you can declare one Forth word for
12198: every pattern you want to use, e.g.:
12199:
12200: @example
12201: \c #include <stdio.h>
12202: c-function printf-nr printf a n r -- n
12203: c-function printf-rn printf a r n -- n
12204: @end example
12205:
12206: Note that with C functions declared as variadic (or if you don't
12207: provide a prototype), the C interface has no C type to convert to, so
12208: no automatic conversion happens, which may lead to portability
12209: problems in some cases. In such cases you can perform the conversion
12210: explicitly on the C level, e.g., as follows:
12211:
12212: @example
1.178 anton 12213: \c #define printfll(s,ll) printf(s,(long long)ll)
12214: c-function printfll printfll a n -- n
1.177 anton 12215: @end example
12216:
12217: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12218: that casts (converts) the Forth single-cell integer into a
12219: C @code{long long} before calling @code{printf()}.
1.177 anton 12220:
12221: doc-\c
12222: doc-c-function
12223:
12224: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12225: dynamic linking. If these features are not available, there are
12226: other, less convenient and less portable C interfaces in @file{lib.fs}
12227: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12228: mostly incompatible with each other and with the documented C
12229: interface; you can find some examples for the @file{lib.fs} interface
12230: in @file{lib.fs}.
1.177 anton 12231:
12232:
1.180 anton 12233: @node Calling C function pointers, Callbacks, Declaring C Functions, C Interface
12234: @subsection Calling C function pointers from Forth
12235: @cindex C function pointers, calling from Forth
1.177 anton 12236:
1.180 anton 12237: If you come across a C function pointer (e.g., in some C-constructed
12238: structure) and want to call it from your Forth program, you can also
12239: use the features explained until now to achieve that, as follows:
1.150 anton 12240:
1.180 anton 12241: Let us assume that there is a C function pointer type @code{func1}
12242: defined in some header file @file{func1.h}, and you know that these
12243: functions take one integer argument and return an integer result; and
12244: you want to call functions through such pointers. Just define
1.155 anton 12245:
1.180 anton 12246: @example
12247: \c #include <func1.h>
12248: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12249: c-function call-func1 call_func1 n func -- n
12250: @end example
12251:
12252: and then you can call a function pointed to by, say @code{func1a} as
12253: follows:
12254:
12255: @example
12256: -5 func1a call-func1 .
12257: @end example
12258:
12259: In the C part, @code{call_func} is defined as a macro to avoid having
12260: to declare the exact parameter and return types, so the C compiler
12261: knows them from the declaration of @code{func1}.
12262:
12263: The Forth word @code{call-func1} is similar to @code{execute}, except
12264: that it takes a C @code{func1} pointer instead of a Forth execution
12265: token, and it is specific to @code{func1} pointers. For each type of
12266: function pointer you want to call from Forth, you have to define
12267: a separate calling word.
12268:
12269:
12270: @node Callbacks, C interface internals, Calling C function pointers, C Interface
1.150 anton 12271: @subsection Callbacks
1.155 anton 12272: @cindex Callback functions written in Forth
12273: @cindex C function pointers to Forth words
12274:
1.177 anton 12275: Callbacks are not yet supported by the documented C interface. You
12276: can use the undocumented @file{lib.fs} interface for callbacks.
12277:
1.155 anton 12278: In some cases you have to pass a function pointer to a C function,
12279: i.e., the library wants to call back to your application (and the
12280: pointed-to function is called a callback function). You can pass the
12281: address of an existing C function (that you get with @code{lib-sym},
12282: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12283: function, you probably want to define the function as a Forth word.
12284:
12285: @c I don't understand the existing callback interface from the example - anton
12286:
1.165 anton 12287:
12288: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12289: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12290: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12291: @c > > C-Funktionsadresse auf dem TOS).
12292: @c >
12293: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12294: @c > gesehen habe, wozu das gut ist.
12295: @c
12296: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12297: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12298: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12299: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12300: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12301: @c demselben Prototyp.
12302:
12303:
1.178 anton 12304: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12305: @subsection How the C interface works
12306:
12307: The documented C interface works by generating a C code out of the
12308: declarations.
12309:
12310: In particular, for every Forth word declared with @code{c-function},
12311: it generates a wrapper function in C that takes the Forth data from
12312: the Forth stacks, and calls the target C function with these data as
12313: arguments. The C compiler then performs an implicit conversion
12314: between the Forth type from the stack, and the C type for the
12315: parameter, which is given by the C function prototype. After the C
12316: function returns, the return value is likewise implicitly converted to
12317: a Forth type and written back on the stack.
12318:
12319: The @code{\c} lines are literally included in the C code (but without
12320: the @code{\c}), and provide the necessary declarations so that the C
12321: compiler knows the C types and has enough information to perform the
12322: conversion.
12323:
12324: These wrapper functions are eventually compiled and dynamically linked
12325: into Gforth, and then they can be called.
12326:
12327:
1.178 anton 12328: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12329: @subsection Low-Level C Interface Words
1.44 crook 12330:
1.155 anton 12331: doc-open-lib
12332: doc-lib-sym
1.177 anton 12333: doc-call-c
1.26 crook 12334:
1.78 anton 12335: @c -------------------------------------------------------------
1.150 anton 12336: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12337: @section Assembler and Code Words
12338: @cindex assembler
12339: @cindex code words
1.44 crook 12340:
1.78 anton 12341: @menu
12342: * Code and ;code::
12343: * Common Assembler:: Assembler Syntax
12344: * Common Disassembler::
12345: * 386 Assembler:: Deviations and special cases
12346: * Alpha Assembler:: Deviations and special cases
12347: * MIPS assembler:: Deviations and special cases
1.161 anton 12348: * PowerPC assembler:: Deviations and special cases
1.78 anton 12349: * Other assemblers:: How to write them
12350: @end menu
1.21 crook 12351:
1.78 anton 12352: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12353: @subsection @code{Code} and @code{;code}
1.26 crook 12354:
1.78 anton 12355: Gforth provides some words for defining primitives (words written in
12356: machine code), and for defining the machine-code equivalent of
12357: @code{DOES>}-based defining words. However, the machine-independent
12358: nature of Gforth poses a few problems: First of all, Gforth runs on
12359: several architectures, so it can provide no standard assembler. What's
12360: worse is that the register allocation not only depends on the processor,
12361: but also on the @code{gcc} version and options used.
1.44 crook 12362:
1.78 anton 12363: The words that Gforth offers encapsulate some system dependences (e.g.,
12364: the header structure), so a system-independent assembler may be used in
12365: Gforth. If you do not have an assembler, you can compile machine code
12366: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12367: because these words emit stuff in @i{data} space; it works because
12368: Gforth has unified code/data spaces. Assembler isn't likely to be
12369: portable anyway.}.
1.21 crook 12370:
1.44 crook 12371:
1.78 anton 12372: doc-assembler
12373: doc-init-asm
12374: doc-code
12375: doc-end-code
12376: doc-;code
12377: doc-flush-icache
1.44 crook 12378:
1.21 crook 12379:
1.78 anton 12380: If @code{flush-icache} does not work correctly, @code{code} words
12381: etc. will not work (reliably), either.
1.44 crook 12382:
1.78 anton 12383: The typical usage of these @code{code} words can be shown most easily by
12384: analogy to the equivalent high-level defining words:
1.44 crook 12385:
1.78 anton 12386: @example
12387: : foo code foo
12388: <high-level Forth words> <assembler>
12389: ; end-code
12390:
12391: : bar : bar
12392: <high-level Forth words> <high-level Forth words>
12393: CREATE CREATE
12394: <high-level Forth words> <high-level Forth words>
12395: DOES> ;code
12396: <high-level Forth words> <assembler>
12397: ; end-code
12398: @end example
1.21 crook 12399:
1.78 anton 12400: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12401:
1.78 anton 12402: @cindex registers of the inner interpreter
12403: In the assembly code you will want to refer to the inner interpreter's
12404: registers (e.g., the data stack pointer) and you may want to use other
12405: registers for temporary storage. Unfortunately, the register allocation
12406: is installation-dependent.
1.44 crook 12407:
1.78 anton 12408: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12409: (return stack pointer) may be in different places in @code{gforth} and
12410: @code{gforth-fast}, or different installations. This means that you
12411: cannot write a @code{NEXT} routine that works reliably on both versions
12412: or different installations; so for doing @code{NEXT}, I recommend
12413: jumping to @code{' noop >code-address}, which contains nothing but a
12414: @code{NEXT}.
1.21 crook 12415:
1.78 anton 12416: For general accesses to the inner interpreter's registers, the easiest
12417: solution is to use explicit register declarations (@pxref{Explicit Reg
12418: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12419: all of the inner interpreter's registers: You have to compile Gforth
12420: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12421: the appropriate declarations must be present in the @code{machine.h}
12422: file (see @code{mips.h} for an example; you can find a full list of all
12423: declarable register symbols with @code{grep register engine.c}). If you
12424: give explicit registers to all variables that are declared at the
12425: beginning of @code{engine()}, you should be able to use the other
12426: caller-saved registers for temporary storage. Alternatively, you can use
12427: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12428: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12429: reserve a register (however, this restriction on register allocation may
12430: slow Gforth significantly).
1.44 crook 12431:
1.78 anton 12432: If this solution is not viable (e.g., because @code{gcc} does not allow
12433: you to explicitly declare all the registers you need), you have to find
12434: out by looking at the code where the inner interpreter's registers
12435: reside and which registers can be used for temporary storage. You can
12436: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12437:
1.78 anton 12438: In any case, it is good practice to abstract your assembly code from the
12439: actual register allocation. E.g., if the data stack pointer resides in
12440: register @code{$17}, create an alias for this register called @code{sp},
12441: and use that in your assembly code.
1.21 crook 12442:
1.78 anton 12443: @cindex code words, portable
12444: Another option for implementing normal and defining words efficiently
12445: is to add the desired functionality to the source of Gforth. For normal
12446: words you just have to edit @file{primitives} (@pxref{Automatic
12447: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12448: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12449: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12450:
1.78 anton 12451: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12452: @subsection Common Assembler
1.44 crook 12453:
1.78 anton 12454: The assemblers in Gforth generally use a postfix syntax, i.e., the
12455: instruction name follows the operands.
1.21 crook 12456:
1.78 anton 12457: The operands are passed in the usual order (the same that is used in the
12458: manual of the architecture). Since they all are Forth words, they have
12459: to be separated by spaces; you can also use Forth words to compute the
12460: operands.
1.44 crook 12461:
1.78 anton 12462: The instruction names usually end with a @code{,}. This makes it easier
12463: to visually separate instructions if you put several of them on one
12464: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12465:
1.78 anton 12466: Registers are usually specified by number; e.g., (decimal) @code{11}
12467: specifies registers R11 and F11 on the Alpha architecture (which one,
12468: depends on the instruction). The usual names are also available, e.g.,
12469: @code{s2} for R11 on Alpha.
1.21 crook 12470:
1.78 anton 12471: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12472: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12473: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12474: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12475: conditions are specified in a way specific to each assembler.
1.1 anton 12476:
1.78 anton 12477: Note that the register assignments of the Gforth engine can change
12478: between Gforth versions, or even between different compilations of the
12479: same Gforth version (e.g., if you use a different GCC version). So if
12480: you want to refer to Gforth's registers (e.g., the stack pointer or
12481: TOS), I recommend defining your own words for refering to these
12482: registers, and using them later on; then you can easily adapt to a
12483: changed register assignment. The stability of the register assignment
12484: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12485:
1.100 anton 12486: The most common use of these registers is to dispatch to the next word
12487: (the @code{next} routine). A portable way to do this is to jump to
12488: @code{' noop >code-address} (of course, this is less efficient than
12489: integrating the @code{next} code and scheduling it well).
1.1 anton 12490:
1.96 anton 12491: Another difference between Gforth version is that the top of stack is
12492: kept in memory in @code{gforth} and, on most platforms, in a register in
12493: @code{gforth-fast}.
12494:
1.78 anton 12495: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12496: @subsection Common Disassembler
1.127 anton 12497: @cindex disassembler, general
12498: @cindex gdb disassembler
1.1 anton 12499:
1.78 anton 12500: You can disassemble a @code{code} word with @code{see}
12501: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12502:
1.127 anton 12503: doc-discode
1.44 crook 12504:
1.127 anton 12505: There are two kinds of disassembler for Gforth: The Forth disassembler
12506: (available on some CPUs) and the gdb disassembler (available on
12507: platforms with @command{gdb} and @command{mktemp}). If both are
12508: available, the Forth disassembler is used by default. If you prefer
12509: the gdb disassembler, say
12510:
12511: @example
12512: ' disasm-gdb is discode
12513: @end example
12514:
12515: If neither is available, @code{discode} performs @code{dump}.
12516:
12517: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12518: assembler (i.e., same syntax, etc.). It also includes additional
12519: information in comments. In particular, the address of the instruction
12520: is given in a comment before the instruction.
1.1 anton 12521:
1.127 anton 12522: The gdb disassembler produces output in the same format as the gdb
12523: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12524: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12525: the 386 and AMD64 architectures).
12526:
1.78 anton 12527: @code{See} may display more or less than the actual code of the word,
12528: because the recognition of the end of the code is unreliable. You can
1.127 anton 12529: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12530: the code word is not immediately followed by a named word. If you have
1.116 anton 12531: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12532: to ensure that the end is recognized.
1.21 crook 12533:
1.78 anton 12534: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12535: @subsection 386 Assembler
1.44 crook 12536:
1.78 anton 12537: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12538: available under GPL, and originally part of bigFORTH.
1.21 crook 12539:
1.78 anton 12540: The 386 disassembler included in Gforth was written by Andrew McKewan
12541: and is in the public domain.
1.21 crook 12542:
1.91 anton 12543: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12544:
1.78 anton 12545: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12546:
1.78 anton 12547: The assembler includes all instruction of the Athlon, i.e. 486 core
12548: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12549: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12550: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12551:
1.78 anton 12552: There are several prefixes to switch between different operation sizes,
12553: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12554: double-word accesses. Addressing modes can be switched with @code{.wa}
12555: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12556: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12557:
1.78 anton 12558: For floating point operations, the prefixes are @code{.fs} (IEEE
12559: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12560: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12561:
1.78 anton 12562: The MMX opcodes don't have size prefixes, they are spelled out like in
12563: the Intel assembler. Instead of move from and to memory, there are
12564: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12565:
1.78 anton 12566: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12567: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12568: e.g., @code{3 #}. Here are some examples of addressing modes in various
12569: syntaxes:
1.21 crook 12570:
1.26 crook 12571: @example
1.91 anton 12572: Gforth Intel (NASM) AT&T (gas) Name
12573: .w ax ax %ax register (16 bit)
12574: ax eax %eax register (32 bit)
12575: 3 # offset 3 $3 immediate
12576: 1000 #) byte ptr 1000 1000 displacement
12577: bx ) [ebx] (%ebx) base
12578: 100 di d) 100[edi] 100(%edi) base+displacement
12579: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12580: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12581: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12582: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12583: @end example
12584:
12585: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12586: @code{DI)} to enforce 32-bit displacement fields (useful for
12587: later patching).
1.21 crook 12588:
1.78 anton 12589: Some example of instructions are:
1.1 anton 12590:
12591: @example
1.78 anton 12592: ax bx mov \ move ebx,eax
12593: 3 # ax mov \ mov eax,3
1.137 pazsan 12594: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12595: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12596: .w ax bx mov \ mov bx,ax
1.1 anton 12597: @end example
12598:
1.78 anton 12599: The following forms are supported for binary instructions:
1.1 anton 12600:
12601: @example
1.78 anton 12602: <reg> <reg> <inst>
12603: <n> # <reg> <inst>
12604: <mem> <reg> <inst>
12605: <reg> <mem> <inst>
1.136 pazsan 12606: <n> # <mem> <inst>
1.1 anton 12607: @end example
12608:
1.136 pazsan 12609: The shift/rotate syntax is:
1.1 anton 12610:
1.26 crook 12611: @example
1.78 anton 12612: <reg/mem> 1 # shl \ shortens to shift without immediate
12613: <reg/mem> 4 # shl
12614: <reg/mem> cl shl
1.26 crook 12615: @end example
1.1 anton 12616:
1.78 anton 12617: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12618: the byte version.
1.1 anton 12619:
1.78 anton 12620: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12621: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12622: pc < >= <= >}. (Note that most of these words shadow some Forth words
12623: when @code{assembler} is in front of @code{forth} in the search path,
12624: e.g., in @code{code} words). Currently the control structure words use
12625: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12626: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12627:
1.78 anton 12628: Here is an example of a @code{code} word (assumes that the stack pointer
12629: is in esi and the TOS is in ebx):
1.21 crook 12630:
1.26 crook 12631: @example
1.78 anton 12632: code my+ ( n1 n2 -- n )
12633: 4 si D) bx add
12634: 4 # si add
12635: Next
12636: end-code
1.26 crook 12637: @end example
1.21 crook 12638:
1.161 anton 12639:
1.78 anton 12640: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12641: @subsection Alpha Assembler
1.21 crook 12642:
1.78 anton 12643: The Alpha assembler and disassembler were originally written by Bernd
12644: Thallner.
1.26 crook 12645:
1.78 anton 12646: The register names @code{a0}--@code{a5} are not available to avoid
12647: shadowing hex numbers.
1.2 jwilke 12648:
1.78 anton 12649: Immediate forms of arithmetic instructions are distinguished by a
12650: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12651: does not count as arithmetic instruction).
1.2 jwilke 12652:
1.78 anton 12653: You have to specify all operands to an instruction, even those that
12654: other assemblers consider optional, e.g., the destination register for
12655: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12656:
1.78 anton 12657: You can specify conditions for @code{if,} by removing the first @code{b}
12658: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12659:
1.26 crook 12660: @example
1.78 anton 12661: 11 fgt if, \ if F11>0e
12662: ...
12663: endif,
1.26 crook 12664: @end example
1.2 jwilke 12665:
1.78 anton 12666: @code{fbgt,} gives @code{fgt}.
12667:
1.161 anton 12668: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12669: @subsection MIPS assembler
1.2 jwilke 12670:
1.78 anton 12671: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12672:
1.78 anton 12673: Currently the assembler and disassembler only cover the MIPS-I
12674: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12675:
1.78 anton 12676: The register names @code{$a0}--@code{$a3} are not available to avoid
12677: shadowing hex numbers.
1.2 jwilke 12678:
1.78 anton 12679: Because there is no way to distinguish registers from immediate values,
12680: you have to explicitly use the immediate forms of instructions, i.e.,
12681: @code{addiu,}, not just @code{addu,} (@command{as} does this
12682: implicitly).
1.2 jwilke 12683:
1.78 anton 12684: If the architecture manual specifies several formats for the instruction
12685: (e.g., for @code{jalr,}), you usually have to use the one with more
12686: arguments (i.e., two for @code{jalr,}). When in doubt, see
12687: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12688:
1.78 anton 12689: Branches and jumps in the MIPS architecture have a delay slot. You have
12690: to fill it yourself (the simplest way is to use @code{nop,}), the
12691: assembler does not do it for you (unlike @command{as}). Even
12692: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12693: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12694: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12695:
1.78 anton 12696: Note that you must not put branches, jumps, or @code{li,} into the delay
12697: slot: @code{li,} may expand to several instructions, and control flow
12698: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12699:
1.78 anton 12700: For branches the argument specifying the target is a relative address;
12701: You have to add the address of the delay slot to get the absolute
12702: address.
1.1 anton 12703:
1.78 anton 12704: The MIPS architecture also has load delay slots and restrictions on
12705: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12706: yourself to satisfy these restrictions, the assembler does not do it for
12707: you.
1.1 anton 12708:
1.78 anton 12709: You can specify the conditions for @code{if,} etc. by taking a
12710: conditional branch and leaving away the @code{b} at the start and the
12711: @code{,} at the end. E.g.,
1.1 anton 12712:
1.26 crook 12713: @example
1.78 anton 12714: 4 5 eq if,
12715: ... \ do something if $4 equals $5
12716: then,
1.26 crook 12717: @end example
1.1 anton 12718:
1.161 anton 12719:
12720: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
12721: @subsection PowerPC assembler
12722:
1.162 anton 12723: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12724: Revucky.
12725:
1.162 anton 12726: This assembler does not follow the convention of ending mnemonic names
12727: with a ``,'', so some mnemonic names shadow regular Forth words (in
12728: particular: @code{and or xor fabs}); so if you want to use the Forth
12729: words, you have to make them visible first, e.g., with @code{also
12730: forth}.
12731:
1.161 anton 12732: Registers are referred to by their number, e.g., @code{9} means the
12733: integer register 9 or the FP register 9 (depending on the
12734: instruction).
12735:
12736: Because there is no way to distinguish registers from immediate values,
12737: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12738: @code{addi,}, not just @code{add,}.
1.161 anton 12739:
1.162 anton 12740: The assembler and disassembler usually support the most general form
1.161 anton 12741: of an instruction, but usually not the shorter forms (especially for
12742: branches).
12743:
12744:
12745:
12746: @node Other assemblers, , PowerPC assembler, Assembler and Code Words
1.78 anton 12747: @subsection Other assemblers
12748:
12749: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12750: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12751: an assembler already. If you are writing them from scratch, please use
12752: a similar syntax style as the one we use (i.e., postfix, commas at the
12753: end of the instruction names, @pxref{Common Assembler}); make the output
12754: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12755: similar to the style we used.
12756:
12757: Hints on implementation: The most important part is to have a good test
12758: suite that contains all instructions. Once you have that, the rest is
12759: easy. For actual coding you can take a look at
12760: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12761: the assembler and disassembler, avoiding redundancy and some potential
12762: bugs. You can also look at that file (and @pxref{Advanced does> usage
12763: example}) to get ideas how to factor a disassembler.
12764:
12765: Start with the disassembler, because it's easier to reuse data from the
12766: disassembler for the assembler than the other way round.
1.1 anton 12767:
1.78 anton 12768: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12769: how simple it can be.
1.1 anton 12770:
1.161 anton 12771:
12772:
12773:
1.78 anton 12774: @c -------------------------------------------------------------
12775: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12776: @section Threading Words
12777: @cindex threading words
1.1 anton 12778:
1.78 anton 12779: @cindex code address
12780: These words provide access to code addresses and other threading stuff
12781: in Gforth (and, possibly, other interpretive Forths). It more or less
12782: abstracts away the differences between direct and indirect threading
12783: (and, for direct threading, the machine dependences). However, at
12784: present this wordset is still incomplete. It is also pretty low-level;
12785: some day it will hopefully be made unnecessary by an internals wordset
12786: that abstracts implementation details away completely.
1.1 anton 12787:
1.78 anton 12788: The terminology used here stems from indirect threaded Forth systems; in
12789: such a system, the XT of a word is represented by the CFA (code field
12790: address) of a word; the CFA points to a cell that contains the code
12791: address. The code address is the address of some machine code that
12792: performs the run-time action of invoking the word (e.g., the
12793: @code{dovar:} routine pushes the address of the body of the word (a
12794: variable) on the stack
12795: ).
1.1 anton 12796:
1.78 anton 12797: @cindex code address
12798: @cindex code field address
12799: In an indirect threaded Forth, you can get the code address of @i{name}
12800: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12801: >code-address}, independent of the threading method.
1.1 anton 12802:
1.78 anton 12803: doc-threading-method
12804: doc->code-address
12805: doc-code-address!
1.1 anton 12806:
1.78 anton 12807: @cindex @code{does>}-handler
12808: @cindex @code{does>}-code
12809: For a word defined with @code{DOES>}, the code address usually points to
12810: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12811: routine (in Gforth on some platforms, it can also point to the dodoes
12812: routine itself). What you are typically interested in, though, is
12813: whether a word is a @code{DOES>}-defined word, and what Forth code it
12814: executes; @code{>does-code} tells you that.
1.1 anton 12815:
1.78 anton 12816: doc->does-code
1.1 anton 12817:
1.78 anton 12818: To create a @code{DOES>}-defined word with the following basic words,
12819: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12820: @code{/does-handler} aus behind you have to place your executable Forth
12821: code. Finally you have to create a word and modify its behaviour with
12822: @code{does-handler!}.
1.1 anton 12823:
1.78 anton 12824: doc-does-code!
12825: doc-does-handler!
12826: doc-/does-handler
1.1 anton 12827:
1.78 anton 12828: The code addresses produced by various defining words are produced by
12829: the following words:
1.1 anton 12830:
1.78 anton 12831: doc-docol:
12832: doc-docon:
12833: doc-dovar:
12834: doc-douser:
12835: doc-dodefer:
12836: doc-dofield:
1.1 anton 12837:
1.99 anton 12838: @cindex definer
12839: The following two words generalize @code{>code-address},
12840: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12841:
12842: doc->definer
12843: doc-definer!
12844:
1.26 crook 12845: @c -------------------------------------------------------------
1.78 anton 12846: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12847: @section Passing Commands to the Operating System
12848: @cindex operating system - passing commands
12849: @cindex shell commands
12850:
12851: Gforth allows you to pass an arbitrary string to the host operating
12852: system shell (if such a thing exists) for execution.
12853:
12854: doc-sh
12855: doc-system
12856: doc-$?
1.23 crook 12857: doc-getenv
1.44 crook 12858:
1.26 crook 12859: @c -------------------------------------------------------------
1.47 crook 12860: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12861: @section Keeping track of Time
12862: @cindex time-related words
12863:
12864: doc-ms
12865: doc-time&date
1.79 anton 12866: doc-utime
12867: doc-cputime
1.47 crook 12868:
12869:
12870: @c -------------------------------------------------------------
12871: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12872: @section Miscellaneous Words
12873: @cindex miscellaneous words
12874:
1.29 crook 12875: @comment TODO find homes for these
12876:
1.26 crook 12877: These section lists the ANS Forth words that are not documented
1.21 crook 12878: elsewhere in this manual. Ultimately, they all need proper homes.
12879:
1.68 anton 12880: doc-quit
1.44 crook 12881:
1.26 crook 12882: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12883: (@pxref{ANS conformance}):
1.21 crook 12884:
12885: @code{EDITOR}
12886: @code{EMIT?}
12887: @code{FORGET}
12888:
1.24 anton 12889: @c ******************************************************************
12890: @node Error messages, Tools, Words, Top
12891: @chapter Error messages
12892: @cindex error messages
12893: @cindex backtrace
12894:
12895: A typical Gforth error message looks like this:
12896:
12897: @example
1.86 anton 12898: in file included from \evaluated string/:-1
1.24 anton 12899: in file included from ./yyy.fs:1
12900: ./xxx.fs:4: Invalid memory address
1.134 anton 12901: >>>bar<<<
1.79 anton 12902: Backtrace:
1.25 anton 12903: $400E664C @@
12904: $400E6664 foo
1.24 anton 12905: @end example
12906:
12907: The message identifying the error is @code{Invalid memory address}. The
12908: error happened when text-interpreting line 4 of the file
12909: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12910: word on the line where the error happened, is pointed out (with
1.134 anton 12911: @code{>>>} and @code{<<<}).
1.24 anton 12912:
12913: The file containing the error was included in line 1 of @file{./yyy.fs},
12914: and @file{yyy.fs} was included from a non-file (in this case, by giving
12915: @file{yyy.fs} as command-line parameter to Gforth).
12916:
12917: At the end of the error message you find a return stack dump that can be
12918: interpreted as a backtrace (possibly empty). On top you find the top of
12919: the return stack when the @code{throw} happened, and at the bottom you
12920: find the return stack entry just above the return stack of the topmost
12921: text interpreter.
12922:
12923: To the right of most return stack entries you see a guess for the word
12924: that pushed that return stack entry as its return address. This gives a
12925: backtrace. In our case we see that @code{bar} called @code{foo}, and
12926: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12927: address} exception).
12928:
12929: Note that the backtrace is not perfect: We don't know which return stack
12930: entries are return addresses (so we may get false positives); and in
12931: some cases (e.g., for @code{abort"}) we cannot determine from the return
12932: address the word that pushed the return address, so for some return
12933: addresses you see no names in the return stack dump.
1.25 anton 12934:
12935: @cindex @code{catch} and backtraces
12936: The return stack dump represents the return stack at the time when a
12937: specific @code{throw} was executed. In programs that make use of
12938: @code{catch}, it is not necessarily clear which @code{throw} should be
12939: used for the return stack dump (e.g., consider one @code{throw} that
12940: indicates an error, which is caught, and during recovery another error
1.160 anton 12941: happens; which @code{throw} should be used for the stack dump?).
12942: Gforth presents the return stack dump for the first @code{throw} after
12943: the last executed (not returned-to) @code{catch} or @code{nothrow};
12944: this works well in the usual case. To get the right backtrace, you
12945: usually want to insert @code{nothrow} or @code{['] false catch drop}
12946: after a @code{catch} if the error is not rethrown.
1.25 anton 12947:
12948: @cindex @code{gforth-fast} and backtraces
12949: @cindex @code{gforth-fast}, difference from @code{gforth}
12950: @cindex backtraces with @code{gforth-fast}
12951: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12952: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12953: from primitives (e.g., invalid memory address, stack empty etc.);
12954: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12955: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12956: exception caused by a primitive in @code{gforth-fast}, you will
12957: typically see no return stack dump at all; however, if the exception is
12958: caught by @code{catch} (e.g., for restoring some state), and then
12959: @code{throw}n again, the return stack dump will be for the first such
12960: @code{throw}.
1.2 jwilke 12961:
1.5 anton 12962: @c ******************************************************************
1.24 anton 12963: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12964: @chapter Tools
12965:
12966: @menu
12967: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12968: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12969: @end menu
12970:
12971: See also @ref{Emacs and Gforth}.
12972:
1.126 pazsan 12973: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12974: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12975: @cindex @file{ans-report.fs}
12976: @cindex report the words used in your program
12977: @cindex words used in your program
12978:
12979: If you want to label a Forth program as ANS Forth Program, you must
12980: document which wordsets the program uses; for extension wordsets, it is
12981: helpful to list the words the program requires from these wordsets
12982: (because Forth systems are allowed to provide only some words of them).
12983:
12984: The @file{ans-report.fs} tool makes it easy for you to determine which
12985: words from which wordset and which non-ANS words your application
12986: uses. You simply have to include @file{ans-report.fs} before loading the
12987: program you want to check. After loading your program, you can get the
12988: report with @code{print-ans-report}. A typical use is to run this as
12989: batch job like this:
12990: @example
12991: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12992: @end example
12993:
12994: The output looks like this (for @file{compat/control.fs}):
12995: @example
12996: The program uses the following words
12997: from CORE :
12998: : POSTPONE THEN ; immediate ?dup IF 0=
12999: from BLOCK-EXT :
13000: \
13001: from FILE :
13002: (
13003: @end example
13004:
13005: @subsection Caveats
13006:
13007: Note that @file{ans-report.fs} just checks which words are used, not whether
13008: they are used in an ANS Forth conforming way!
13009:
13010: Some words are defined in several wordsets in the
13011: standard. @file{ans-report.fs} reports them for only one of the
13012: wordsets, and not necessarily the one you expect. It depends on usage
13013: which wordset is the right one to specify. E.g., if you only use the
13014: compilation semantics of @code{S"}, it is a Core word; if you also use
13015: its interpretation semantics, it is a File word.
1.124 anton 13016:
13017:
1.127 anton 13018: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13019: @section Stack depth changes during interpretation
13020: @cindex @file{depth-changes.fs}
13021: @cindex depth changes during interpretation
13022: @cindex stack depth changes during interpretation
13023: @cindex items on the stack after interpretation
13024:
13025: Sometimes you notice that, after loading a file, there are items left
13026: on the stack. The tool @file{depth-changes.fs} helps you find out
13027: quickly where in the file these stack items are coming from.
13028:
13029: The simplest way of using @file{depth-changes.fs} is to include it
13030: before the file(s) you want to check, e.g.:
13031:
13032: @example
13033: gforth depth-changes.fs my-file.fs
13034: @end example
13035:
13036: This will compare the stack depths of the data and FP stack at every
13037: empty line (in interpretation state) against these depths at the last
13038: empty line (in interpretation state). If the depths are not equal,
13039: the position in the file and the stack contents are printed with
13040: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13041: change has occured in the paragraph of non-empty lines before the
13042: indicated line. It is a good idea to leave an empty line at the end
13043: of the file, so the last paragraph is checked, too.
13044:
13045: Checking only at empty lines usually works well, but sometimes you
13046: have big blocks of non-empty lines (e.g., when building a big table),
13047: and you want to know where in this block the stack depth changed. You
13048: can check all interpreted lines with
13049:
13050: @example
13051: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13052: @end example
13053:
13054: This checks the stack depth at every end-of-line. So the depth change
13055: occured in the line reported by the @code{~~} (not in the line
13056: before).
13057:
13058: Note that, while this offers better accuracy in indicating where the
13059: stack depth changes, it will often report many intentional stack depth
13060: changes (e.g., when an interpreted computation stretches across
13061: several lines). You can suppress the checking of some lines by
13062: putting backslashes at the end of these lines (not followed by white
13063: space), and using
13064:
13065: @example
13066: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13067: @end example
1.1 anton 13068:
13069: @c ******************************************************************
1.65 anton 13070: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13071: @chapter ANS conformance
13072: @cindex ANS conformance of Gforth
13073:
13074: To the best of our knowledge, Gforth is an
13075:
13076: ANS Forth System
13077: @itemize @bullet
13078: @item providing the Core Extensions word set
13079: @item providing the Block word set
13080: @item providing the Block Extensions word set
13081: @item providing the Double-Number word set
13082: @item providing the Double-Number Extensions word set
13083: @item providing the Exception word set
13084: @item providing the Exception Extensions word set
13085: @item providing the Facility word set
1.40 anton 13086: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13087: @item providing the File Access word set
13088: @item providing the File Access Extensions word set
13089: @item providing the Floating-Point word set
13090: @item providing the Floating-Point Extensions word set
13091: @item providing the Locals word set
13092: @item providing the Locals Extensions word set
13093: @item providing the Memory-Allocation word set
13094: @item providing the Memory-Allocation Extensions word set (that one's easy)
13095: @item providing the Programming-Tools word set
13096: @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
13097: @item providing the Search-Order word set
13098: @item providing the Search-Order Extensions word set
13099: @item providing the String word set
13100: @item providing the String Extensions word set (another easy one)
13101: @end itemize
13102:
1.118 anton 13103: Gforth has the following environmental restrictions:
13104:
13105: @cindex environmental restrictions
13106: @itemize @bullet
13107: @item
13108: While processing the OS command line, if an exception is not caught,
13109: Gforth exits with a non-zero exit code instyead of performing QUIT.
13110:
13111: @item
13112: When an @code{throw} is performed after a @code{query}, Gforth does not
13113: allways restore the input source specification in effect at the
13114: corresponding catch.
13115:
13116: @end itemize
13117:
13118:
1.1 anton 13119: @cindex system documentation
13120: In addition, ANS Forth systems are required to document certain
13121: implementation choices. This chapter tries to meet these
13122: requirements. In many cases it gives a way to ask the system for the
13123: information instead of providing the information directly, in
13124: particular, if the information depends on the processor, the operating
13125: system or the installation options chosen, or if they are likely to
13126: change during the maintenance of Gforth.
13127:
13128: @comment The framework for the rest has been taken from pfe.
13129:
13130: @menu
13131: * The Core Words::
13132: * The optional Block word set::
13133: * The optional Double Number word set::
13134: * The optional Exception word set::
13135: * The optional Facility word set::
13136: * The optional File-Access word set::
13137: * The optional Floating-Point word set::
13138: * The optional Locals word set::
13139: * The optional Memory-Allocation word set::
13140: * The optional Programming-Tools word set::
13141: * The optional Search-Order word set::
13142: @end menu
13143:
13144:
13145: @c =====================================================================
13146: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13147: @comment node-name, next, previous, up
13148: @section The Core Words
13149: @c =====================================================================
13150: @cindex core words, system documentation
13151: @cindex system documentation, core words
13152:
13153: @menu
13154: * core-idef:: Implementation Defined Options
13155: * core-ambcond:: Ambiguous Conditions
13156: * core-other:: Other System Documentation
13157: @end menu
13158:
13159: @c ---------------------------------------------------------------------
13160: @node core-idef, core-ambcond, The Core Words, The Core Words
13161: @subsection Implementation Defined Options
13162: @c ---------------------------------------------------------------------
13163: @cindex core words, implementation-defined options
13164: @cindex implementation-defined options, core words
13165:
13166:
13167: @table @i
13168: @item (Cell) aligned addresses:
13169: @cindex cell-aligned addresses
13170: @cindex aligned addresses
13171: processor-dependent. Gforth's alignment words perform natural alignment
13172: (e.g., an address aligned for a datum of size 8 is divisible by
13173: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13174:
13175: @item @code{EMIT} and non-graphic characters:
13176: @cindex @code{EMIT} and non-graphic characters
13177: @cindex non-graphic characters and @code{EMIT}
13178: The character is output using the C library function (actually, macro)
13179: @code{putc}.
13180:
13181: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13182: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13183: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13184: @cindex @code{ACCEPT}, editing
13185: @cindex @code{EXPECT}, editing
13186: This is modeled on the GNU readline library (@pxref{Readline
13187: Interaction, , Command Line Editing, readline, The GNU Readline
13188: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13189: producing a full word completion every time you type it (instead of
1.28 crook 13190: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13191:
13192: @item character set:
13193: @cindex character set
13194: The character set of your computer and display device. Gforth is
13195: 8-bit-clean (but some other component in your system may make trouble).
13196:
13197: @item Character-aligned address requirements:
13198: @cindex character-aligned address requirements
13199: installation-dependent. Currently a character is represented by a C
13200: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13201: (Comments on that requested).
13202:
13203: @item character-set extensions and matching of names:
13204: @cindex character-set extensions and matching of names
1.26 crook 13205: @cindex case-sensitivity for name lookup
13206: @cindex name lookup, case-sensitivity
13207: @cindex locale and case-sensitivity
1.21 crook 13208: Any character except the ASCII NUL character can be used in a
1.1 anton 13209: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13210: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13211: function is probably influenced by the locale. E.g., the @code{C} locale
13212: does not know about accents and umlauts, so they are matched
13213: case-sensitively in that locale. For portability reasons it is best to
13214: write programs such that they work in the @code{C} locale. Then one can
13215: use libraries written by a Polish programmer (who might use words
13216: containing ISO Latin-2 encoded characters) and by a French programmer
13217: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13218: funny results for some of the words (which ones, depends on the font you
13219: are using)). Also, the locale you prefer may not be available in other
13220: operating systems. Hopefully, Unicode will solve these problems one day.
13221:
13222: @item conditions under which control characters match a space delimiter:
13223: @cindex space delimiters
13224: @cindex control characters as delimiters
1.117 anton 13225: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13226: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13227: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13228: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13229: interpreter (aka text interpreter) by default, treats all white-space
13230: characters as delimiters.
13231:
1.26 crook 13232: @item format of the control-flow stack:
13233: @cindex control-flow stack, format
13234: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13235: stack item in cells is given by the constant @code{cs-item-size}. At the
13236: time of this writing, an item consists of a (pointer to a) locals list
13237: (third), an address in the code (second), and a tag for identifying the
13238: item (TOS). The following tags are used: @code{defstart},
13239: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13240: @code{scopestart}.
13241:
13242: @item conversion of digits > 35
13243: @cindex digits > 35
13244: The characters @code{[\]^_'} are the digits with the decimal value
13245: 36@minus{}41. There is no way to input many of the larger digits.
13246:
13247: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13248: @cindex @code{EXPECT}, display after end of input
13249: @cindex @code{ACCEPT}, display after end of input
13250: The cursor is moved to the end of the entered string. If the input is
13251: terminated using the @kbd{Return} key, a space is typed.
13252:
13253: @item exception abort sequence of @code{ABORT"}:
13254: @cindex exception abort sequence of @code{ABORT"}
13255: @cindex @code{ABORT"}, exception abort sequence
13256: The error string is stored into the variable @code{"error} and a
13257: @code{-2 throw} is performed.
13258:
13259: @item input line terminator:
13260: @cindex input line terminator
13261: @cindex line terminator on input
1.26 crook 13262: @cindex newline character on input
1.1 anton 13263: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13264: lines. One of these characters is typically produced when you type the
13265: @kbd{Enter} or @kbd{Return} key.
13266:
13267: @item maximum size of a counted string:
13268: @cindex maximum size of a counted string
13269: @cindex counted string, maximum size
13270: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13271: on all platforms, but this may change.
1.1 anton 13272:
13273: @item maximum size of a parsed string:
13274: @cindex maximum size of a parsed string
13275: @cindex parsed string, maximum size
13276: Given by the constant @code{/line}. Currently 255 characters.
13277:
13278: @item maximum size of a definition name, in characters:
13279: @cindex maximum size of a definition name, in characters
13280: @cindex name, maximum length
1.113 anton 13281: MAXU/8
1.1 anton 13282:
13283: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13284: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13285: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13286: MAXU/8
1.1 anton 13287:
13288: @item method of selecting the user input device:
13289: @cindex user input device, method of selecting
13290: The user input device is the standard input. There is currently no way to
13291: change it from within Gforth. However, the input can typically be
13292: redirected in the command line that starts Gforth.
13293:
13294: @item method of selecting the user output device:
13295: @cindex user output device, method of selecting
13296: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13297: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13298: output when the user output device is a terminal, otherwise the output
13299: is buffered.
1.1 anton 13300:
13301: @item methods of dictionary compilation:
13302: What are we expected to document here?
13303:
13304: @item number of bits in one address unit:
13305: @cindex number of bits in one address unit
13306: @cindex address unit, size in bits
13307: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13308: platforms.
1.1 anton 13309:
13310: @item number representation and arithmetic:
13311: @cindex number representation and arithmetic
1.79 anton 13312: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13313:
13314: @item ranges for integer types:
13315: @cindex ranges for integer types
13316: @cindex integer types, ranges
13317: Installation-dependent. Make environmental queries for @code{MAX-N},
13318: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13319: unsigned (and positive) types is 0. The lower bound for signed types on
13320: two's complement and one's complement machines machines can be computed
13321: by adding 1 to the upper bound.
13322:
13323: @item read-only data space regions:
13324: @cindex read-only data space regions
13325: @cindex data-space, read-only regions
13326: The whole Forth data space is writable.
13327:
13328: @item size of buffer at @code{WORD}:
13329: @cindex size of buffer at @code{WORD}
13330: @cindex @code{WORD} buffer size
13331: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13332: shared with the pictured numeric output string. If overwriting
13333: @code{PAD} is acceptable, it is as large as the remaining dictionary
13334: space, although only as much can be sensibly used as fits in a counted
13335: string.
13336:
13337: @item size of one cell in address units:
13338: @cindex cell size
13339: @code{1 cells .}.
13340:
13341: @item size of one character in address units:
13342: @cindex char size
1.79 anton 13343: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13344:
13345: @item size of the keyboard terminal buffer:
13346: @cindex size of the keyboard terminal buffer
13347: @cindex terminal buffer, size
13348: Varies. You can determine the size at a specific time using @code{lp@@
13349: tib - .}. It is shared with the locals stack and TIBs of files that
13350: include the current file. You can change the amount of space for TIBs
13351: and locals stack at Gforth startup with the command line option
13352: @code{-l}.
13353:
13354: @item size of the pictured numeric output buffer:
13355: @cindex size of the pictured numeric output buffer
13356: @cindex pictured numeric output buffer, size
13357: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13358: shared with @code{WORD}.
13359:
13360: @item size of the scratch area returned by @code{PAD}:
13361: @cindex size of the scratch area returned by @code{PAD}
13362: @cindex @code{PAD} size
13363: The remainder of dictionary space. @code{unused pad here - - .}.
13364:
13365: @item system case-sensitivity characteristics:
13366: @cindex case-sensitivity characteristics
1.26 crook 13367: Dictionary searches are case-insensitive (except in
1.1 anton 13368: @code{TABLE}s). However, as explained above under @i{character-set
13369: extensions}, the matching for non-ASCII characters is determined by the
13370: locale you are using. In the default @code{C} locale all non-ASCII
13371: characters are matched case-sensitively.
13372:
13373: @item system prompt:
13374: @cindex system prompt
13375: @cindex prompt
13376: @code{ ok} in interpret state, @code{ compiled} in compile state.
13377:
13378: @item division rounding:
13379: @cindex division rounding
1.166 anton 13380: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13381: division (with the default installation of Gforth). You can check
13382: this with @code{s" floored" environment? drop .}. If you write
13383: programs that need a specific division rounding, best use
13384: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13385:
13386: @item values of @code{STATE} when true:
13387: @cindex @code{STATE} values
13388: -1.
13389:
13390: @item values returned after arithmetic overflow:
13391: On two's complement machines, arithmetic is performed modulo
13392: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13393: arithmetic (with appropriate mapping for signed types). Division by
13394: zero typically results in a @code{-55 throw} (Floating-point
13395: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13396: division overflow can result in these throws, or in @code{-11 throw};
13397: in @code{gforth-fast} division overflow and divide by zero may also
13398: result in returning bogus results without producing an exception.
1.1 anton 13399:
13400: @item whether the current definition can be found after @t{DOES>}:
13401: @cindex @t{DOES>}, visibility of current definition
13402: No.
13403:
13404: @end table
13405:
13406: @c ---------------------------------------------------------------------
13407: @node core-ambcond, core-other, core-idef, The Core Words
13408: @subsection Ambiguous conditions
13409: @c ---------------------------------------------------------------------
13410: @cindex core words, ambiguous conditions
13411: @cindex ambiguous conditions, core words
13412:
13413: @table @i
13414:
13415: @item a name is neither a word nor a number:
13416: @cindex name not found
1.26 crook 13417: @cindex undefined word
1.80 anton 13418: @code{-13 throw} (Undefined word).
1.1 anton 13419:
13420: @item a definition name exceeds the maximum length allowed:
1.26 crook 13421: @cindex word name too long
1.1 anton 13422: @code{-19 throw} (Word name too long)
13423:
13424: @item addressing a region not inside the various data spaces of the forth system:
13425: @cindex Invalid memory address
1.32 anton 13426: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13427: typically readable. Accessing other addresses gives results dependent on
13428: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13429: address).
13430:
13431: @item argument type incompatible with parameter:
1.26 crook 13432: @cindex argument type mismatch
1.1 anton 13433: This is usually not caught. Some words perform checks, e.g., the control
13434: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13435: mismatch).
13436:
13437: @item attempting to obtain the execution token of a word with undefined execution semantics:
13438: @cindex Interpreting a compile-only word, for @code{'} etc.
13439: @cindex execution token of words with undefined execution semantics
13440: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13441: get an execution token for @code{compile-only-error} (which performs a
13442: @code{-14 throw} when executed).
13443:
13444: @item dividing by zero:
13445: @cindex dividing by zero
13446: @cindex floating point unidentified fault, integer division
1.80 anton 13447: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13448: zero); on other systems, this typically results in a @code{-55 throw}
13449: (Floating-point unidentified fault).
1.1 anton 13450:
13451: @item insufficient data stack or return stack space:
13452: @cindex insufficient data stack or return stack space
13453: @cindex stack overflow
1.26 crook 13454: @cindex address alignment exception, stack overflow
1.1 anton 13455: @cindex Invalid memory address, stack overflow
13456: Depending on the operating system, the installation, and the invocation
13457: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13458: it is not checked. If it is checked, you typically get a @code{-3 throw}
13459: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13460: throw} (Invalid memory address) (depending on the platform and how you
13461: achieved the overflow) as soon as the overflow happens. If it is not
13462: checked, overflows typically result in mysterious illegal memory
13463: accesses, producing @code{-9 throw} (Invalid memory address) or
13464: @code{-23 throw} (Address alignment exception); they might also destroy
13465: the internal data structure of @code{ALLOCATE} and friends, resulting in
13466: various errors in these words.
1.1 anton 13467:
13468: @item insufficient space for loop control parameters:
13469: @cindex insufficient space for loop control parameters
1.80 anton 13470: Like other return stack overflows.
1.1 anton 13471:
13472: @item insufficient space in the dictionary:
13473: @cindex insufficient space in the dictionary
13474: @cindex dictionary overflow
1.12 anton 13475: If you try to allot (either directly with @code{allot}, or indirectly
13476: with @code{,}, @code{create} etc.) more memory than available in the
13477: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13478: to access memory beyond the end of the dictionary, the results are
13479: similar to stack overflows.
1.1 anton 13480:
13481: @item interpreting a word with undefined interpretation semantics:
13482: @cindex interpreting a word with undefined interpretation semantics
13483: @cindex Interpreting a compile-only word
13484: For some words, we have defined interpretation semantics. For the
13485: others: @code{-14 throw} (Interpreting a compile-only word).
13486:
13487: @item modifying the contents of the input buffer or a string literal:
13488: @cindex modifying the contents of the input buffer or a string literal
13489: These are located in writable memory and can be modified.
13490:
13491: @item overflow of the pictured numeric output string:
13492: @cindex overflow of the pictured numeric output string
13493: @cindex pictured numeric output string, overflow
1.24 anton 13494: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13495:
13496: @item parsed string overflow:
13497: @cindex parsed string overflow
13498: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13499:
13500: @item producing a result out of range:
13501: @cindex result out of range
13502: On two's complement machines, arithmetic is performed modulo
13503: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13504: arithmetic (with appropriate mapping for signed types). Division by
13505: zero typically results in a @code{-10 throw} (divide by zero) or
13506: @code{-55 throw} (floating point unidentified fault). Overflow on
13507: division may result in these errors or in @code{-11 throw} (result out
13508: of range). @code{Gforth-fast} may silently produce bogus results on
13509: division overflow or division by zero. @code{Convert} and
1.24 anton 13510: @code{>number} currently overflow silently.
1.1 anton 13511:
13512: @item reading from an empty data or return stack:
13513: @cindex stack empty
13514: @cindex stack underflow
1.24 anton 13515: @cindex return stack underflow
1.1 anton 13516: The data stack is checked by the outer (aka text) interpreter after
13517: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13518: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13519: depending on operating system, installation, and invocation. If they are
13520: caught by a check, they typically result in @code{-4 throw} (Stack
13521: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13522: (Invalid memory address), depending on the platform and which stack
13523: underflows and by how much. Note that even if the system uses checking
13524: (through the MMU), your program may have to underflow by a significant
13525: number of stack items to trigger the reaction (the reason for this is
13526: that the MMU, and therefore the checking, works with a page-size
13527: granularity). If there is no checking, the symptoms resulting from an
13528: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13529: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13530: (Invalid memory address) and Illegal Instruction (typically @code{-260
13531: throw}).
1.1 anton 13532:
13533: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13534: @cindex unexpected end of the input buffer
13535: @cindex zero-length string as a name
13536: @cindex Attempt to use zero-length string as a name
13537: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13538: use zero-length string as a name). Words like @code{'} probably will not
13539: find what they search. Note that it is possible to create zero-length
13540: names with @code{nextname} (should it not?).
13541:
13542: @item @code{>IN} greater than input buffer:
13543: @cindex @code{>IN} greater than input buffer
13544: The next invocation of a parsing word returns a string with length 0.
13545:
13546: @item @code{RECURSE} appears after @code{DOES>}:
13547: @cindex @code{RECURSE} appears after @code{DOES>}
13548: Compiles a recursive call to the defining word, not to the defined word.
13549:
13550: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13551: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13552: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13553: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13554: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13555: the end of the file was reached), its source-id may be
13556: reused. Therefore, restoring an input source specification referencing a
13557: closed file may lead to unpredictable results instead of a @code{-12
13558: THROW}.
13559:
13560: In the future, Gforth may be able to restore input source specifications
13561: from other than the current input source.
13562:
13563: @item data space containing definitions gets de-allocated:
13564: @cindex data space containing definitions gets de-allocated
13565: Deallocation with @code{allot} is not checked. This typically results in
13566: memory access faults or execution of illegal instructions.
13567:
13568: @item data space read/write with incorrect alignment:
13569: @cindex data space read/write with incorrect alignment
13570: @cindex alignment faults
1.26 crook 13571: @cindex address alignment exception
1.1 anton 13572: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13573: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13574: alignment turned on, incorrect alignment results in a @code{-9 throw}
13575: (Invalid memory address). There are reportedly some processors with
1.12 anton 13576: alignment restrictions that do not report violations.
1.1 anton 13577:
13578: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13579: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13580: Like other alignment errors.
13581:
13582: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13583: Like other stack underflows.
13584:
13585: @item loop control parameters not available:
13586: @cindex loop control parameters not available
13587: Not checked. The counted loop words simply assume that the top of return
13588: stack items are loop control parameters and behave accordingly.
13589:
13590: @item most recent definition does not have a name (@code{IMMEDIATE}):
13591: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13592: @cindex last word was headerless
13593: @code{abort" last word was headerless"}.
13594:
13595: @item name not defined by @code{VALUE} used by @code{TO}:
13596: @cindex name not defined by @code{VALUE} used by @code{TO}
13597: @cindex @code{TO} on non-@code{VALUE}s
13598: @cindex Invalid name argument, @code{TO}
13599: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13600: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13601:
13602: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13603: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13604: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13605: @code{-13 throw} (Undefined word)
13606:
13607: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13608: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13609: Gforth behaves as if they were of the same type. I.e., you can predict
13610: the behaviour by interpreting all parameters as, e.g., signed.
13611:
13612: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13613: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13614: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13615: compilation semantics of @code{TO}.
13616:
13617: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13618: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13619: @cindex @code{WORD}, string overflow
13620: Not checked. The string will be ok, but the count will, of course,
13621: contain only the least significant bits of the length.
13622:
13623: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13624: @cindex @code{LSHIFT}, large shift counts
13625: @cindex @code{RSHIFT}, large shift counts
13626: Processor-dependent. Typical behaviours are returning 0 and using only
13627: the low bits of the shift count.
13628:
13629: @item word not defined via @code{CREATE}:
13630: @cindex @code{>BODY} of non-@code{CREATE}d words
13631: @code{>BODY} produces the PFA of the word no matter how it was defined.
13632:
13633: @cindex @code{DOES>} of non-@code{CREATE}d words
13634: @code{DOES>} changes the execution semantics of the last defined word no
13635: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13636: @code{CREATE , DOES>}.
13637:
13638: @item words improperly used outside @code{<#} and @code{#>}:
13639: Not checked. As usual, you can expect memory faults.
13640:
13641: @end table
13642:
13643:
13644: @c ---------------------------------------------------------------------
13645: @node core-other, , core-ambcond, The Core Words
13646: @subsection Other system documentation
13647: @c ---------------------------------------------------------------------
13648: @cindex other system documentation, core words
13649: @cindex core words, other system documentation
13650:
13651: @table @i
13652: @item nonstandard words using @code{PAD}:
13653: @cindex @code{PAD} use by nonstandard words
13654: None.
13655:
13656: @item operator's terminal facilities available:
13657: @cindex operator's terminal facilities available
1.80 anton 13658: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13659: and you can give commands to Gforth interactively. The actual facilities
13660: available depend on how you invoke Gforth.
13661:
13662: @item program data space available:
13663: @cindex program data space available
13664: @cindex data space available
13665: @code{UNUSED .} gives the remaining dictionary space. The total
13666: dictionary space can be specified with the @code{-m} switch
13667: (@pxref{Invoking Gforth}) when Gforth starts up.
13668:
13669: @item return stack space available:
13670: @cindex return stack space available
13671: You can compute the total return stack space in cells with
13672: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13673: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13674:
13675: @item stack space available:
13676: @cindex stack space available
13677: You can compute the total data stack space in cells with
13678: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13679: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13680:
13681: @item system dictionary space required, in address units:
13682: @cindex system dictionary space required, in address units
13683: Type @code{here forthstart - .} after startup. At the time of this
13684: writing, this gives 80080 (bytes) on a 32-bit system.
13685: @end table
13686:
13687:
13688: @c =====================================================================
13689: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13690: @section The optional Block word set
13691: @c =====================================================================
13692: @cindex system documentation, block words
13693: @cindex block words, system documentation
13694:
13695: @menu
13696: * block-idef:: Implementation Defined Options
13697: * block-ambcond:: Ambiguous Conditions
13698: * block-other:: Other System Documentation
13699: @end menu
13700:
13701:
13702: @c ---------------------------------------------------------------------
13703: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13704: @subsection Implementation Defined Options
13705: @c ---------------------------------------------------------------------
13706: @cindex implementation-defined options, block words
13707: @cindex block words, implementation-defined options
13708:
13709: @table @i
13710: @item the format for display by @code{LIST}:
13711: @cindex @code{LIST} display format
13712: First the screen number is displayed, then 16 lines of 64 characters,
13713: each line preceded by the line number.
13714:
13715: @item the length of a line affected by @code{\}:
13716: @cindex length of a line affected by @code{\}
13717: @cindex @code{\}, line length in blocks
13718: 64 characters.
13719: @end table
13720:
13721:
13722: @c ---------------------------------------------------------------------
13723: @node block-ambcond, block-other, block-idef, The optional Block word set
13724: @subsection Ambiguous conditions
13725: @c ---------------------------------------------------------------------
13726: @cindex block words, ambiguous conditions
13727: @cindex ambiguous conditions, block words
13728:
13729: @table @i
13730: @item correct block read was not possible:
13731: @cindex block read not possible
13732: Typically results in a @code{throw} of some OS-derived value (between
13733: -512 and -2048). If the blocks file was just not long enough, blanks are
13734: supplied for the missing portion.
13735:
13736: @item I/O exception in block transfer:
13737: @cindex I/O exception in block transfer
13738: @cindex block transfer, I/O exception
13739: Typically results in a @code{throw} of some OS-derived value (between
13740: -512 and -2048).
13741:
13742: @item invalid block number:
13743: @cindex invalid block number
13744: @cindex block number invalid
13745: @code{-35 throw} (Invalid block number)
13746:
13747: @item a program directly alters the contents of @code{BLK}:
13748: @cindex @code{BLK}, altering @code{BLK}
13749: The input stream is switched to that other block, at the same
13750: position. If the storing to @code{BLK} happens when interpreting
13751: non-block input, the system will get quite confused when the block ends.
13752:
13753: @item no current block buffer for @code{UPDATE}:
13754: @cindex @code{UPDATE}, no current block buffer
13755: @code{UPDATE} has no effect.
13756:
13757: @end table
13758:
13759: @c ---------------------------------------------------------------------
13760: @node block-other, , block-ambcond, The optional Block word set
13761: @subsection Other system documentation
13762: @c ---------------------------------------------------------------------
13763: @cindex other system documentation, block words
13764: @cindex block words, other system documentation
13765:
13766: @table @i
13767: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13768: No restrictions (yet).
13769:
13770: @item the number of blocks available for source and data:
13771: depends on your disk space.
13772:
13773: @end table
13774:
13775:
13776: @c =====================================================================
13777: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13778: @section The optional Double Number word set
13779: @c =====================================================================
13780: @cindex system documentation, double words
13781: @cindex double words, system documentation
13782:
13783: @menu
13784: * double-ambcond:: Ambiguous Conditions
13785: @end menu
13786:
13787:
13788: @c ---------------------------------------------------------------------
13789: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13790: @subsection Ambiguous conditions
13791: @c ---------------------------------------------------------------------
13792: @cindex double words, ambiguous conditions
13793: @cindex ambiguous conditions, double words
13794:
13795: @table @i
1.29 crook 13796: @item @i{d} outside of range of @i{n} in @code{D>S}:
13797: @cindex @code{D>S}, @i{d} out of range of @i{n}
13798: The least significant cell of @i{d} is produced.
1.1 anton 13799:
13800: @end table
13801:
13802:
13803: @c =====================================================================
13804: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13805: @section The optional Exception word set
13806: @c =====================================================================
13807: @cindex system documentation, exception words
13808: @cindex exception words, system documentation
13809:
13810: @menu
13811: * exception-idef:: Implementation Defined Options
13812: @end menu
13813:
13814:
13815: @c ---------------------------------------------------------------------
13816: @node exception-idef, , The optional Exception word set, The optional Exception word set
13817: @subsection Implementation Defined Options
13818: @c ---------------------------------------------------------------------
13819: @cindex implementation-defined options, exception words
13820: @cindex exception words, implementation-defined options
13821:
13822: @table @i
13823: @item @code{THROW}-codes used in the system:
13824: @cindex @code{THROW}-codes used in the system
13825: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13826: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13827: codes -512@minus{}-2047 are used for OS errors (for file and memory
13828: allocation operations). The mapping from OS error numbers to throw codes
13829: is -512@minus{}@code{errno}. One side effect of this mapping is that
13830: undefined OS errors produce a message with a strange number; e.g.,
13831: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13832: @end table
13833:
13834: @c =====================================================================
13835: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13836: @section The optional Facility word set
13837: @c =====================================================================
13838: @cindex system documentation, facility words
13839: @cindex facility words, system documentation
13840:
13841: @menu
13842: * facility-idef:: Implementation Defined Options
13843: * facility-ambcond:: Ambiguous Conditions
13844: @end menu
13845:
13846:
13847: @c ---------------------------------------------------------------------
13848: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13849: @subsection Implementation Defined Options
13850: @c ---------------------------------------------------------------------
13851: @cindex implementation-defined options, facility words
13852: @cindex facility words, implementation-defined options
13853:
13854: @table @i
13855: @item encoding of keyboard events (@code{EKEY}):
13856: @cindex keyboard events, encoding in @code{EKEY}
13857: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13858: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13859: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13860: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13861: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13862: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13863:
1.1 anton 13864:
13865: @item duration of a system clock tick:
13866: @cindex duration of a system clock tick
13867: @cindex clock tick duration
13868: System dependent. With respect to @code{MS}, the time is specified in
13869: microseconds. How well the OS and the hardware implement this, is
13870: another question.
13871:
13872: @item repeatability to be expected from the execution of @code{MS}:
13873: @cindex repeatability to be expected from the execution of @code{MS}
13874: @cindex @code{MS}, repeatability to be expected
13875: System dependent. On Unix, a lot depends on load. If the system is
13876: lightly loaded, and the delay is short enough that Gforth does not get
13877: swapped out, the performance should be acceptable. Under MS-DOS and
13878: other single-tasking systems, it should be good.
13879:
13880: @end table
13881:
13882:
13883: @c ---------------------------------------------------------------------
13884: @node facility-ambcond, , facility-idef, The optional Facility word set
13885: @subsection Ambiguous conditions
13886: @c ---------------------------------------------------------------------
13887: @cindex facility words, ambiguous conditions
13888: @cindex ambiguous conditions, facility words
13889:
13890: @table @i
13891: @item @code{AT-XY} can't be performed on user output device:
13892: @cindex @code{AT-XY} can't be performed on user output device
13893: Largely terminal dependent. No range checks are done on the arguments.
13894: No errors are reported. You may see some garbage appearing, you may see
13895: simply nothing happen.
13896:
13897: @end table
13898:
13899:
13900: @c =====================================================================
13901: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13902: @section The optional File-Access word set
13903: @c =====================================================================
13904: @cindex system documentation, file words
13905: @cindex file words, system documentation
13906:
13907: @menu
13908: * file-idef:: Implementation Defined Options
13909: * file-ambcond:: Ambiguous Conditions
13910: @end menu
13911:
13912: @c ---------------------------------------------------------------------
13913: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13914: @subsection Implementation Defined Options
13915: @c ---------------------------------------------------------------------
13916: @cindex implementation-defined options, file words
13917: @cindex file words, implementation-defined options
13918:
13919: @table @i
13920: @item file access methods used:
13921: @cindex file access methods used
13922: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13923: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13924: @code{wb}): The file is cleared, if it exists, and created, if it does
13925: not (with both @code{open-file} and @code{create-file}). Under Unix
13926: @code{create-file} creates a file with 666 permissions modified by your
13927: umask.
13928:
13929: @item file exceptions:
13930: @cindex file exceptions
13931: The file words do not raise exceptions (except, perhaps, memory access
13932: faults when you pass illegal addresses or file-ids).
13933:
13934: @item file line terminator:
13935: @cindex file line terminator
13936: System-dependent. Gforth uses C's newline character as line
13937: terminator. What the actual character code(s) of this are is
13938: system-dependent.
13939:
13940: @item file name format:
13941: @cindex file name format
13942: System dependent. Gforth just uses the file name format of your OS.
13943:
13944: @item information returned by @code{FILE-STATUS}:
13945: @cindex @code{FILE-STATUS}, returned information
13946: @code{FILE-STATUS} returns the most powerful file access mode allowed
13947: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13948: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13949: along with the returned mode.
13950:
13951: @item input file state after an exception when including source:
13952: @cindex exception when including source
13953: All files that are left via the exception are closed.
13954:
1.29 crook 13955: @item @i{ior} values and meaning:
13956: @cindex @i{ior} values and meaning
1.68 anton 13957: @cindex @i{wior} values and meaning
1.29 crook 13958: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13959: intended as throw codes. They typically are in the range
13960: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13961: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13962:
13963: @item maximum depth of file input nesting:
13964: @cindex maximum depth of file input nesting
13965: @cindex file input nesting, maximum depth
13966: limited by the amount of return stack, locals/TIB stack, and the number
13967: of open files available. This should not give you troubles.
13968:
13969: @item maximum size of input line:
13970: @cindex maximum size of input line
13971: @cindex input line size, maximum
13972: @code{/line}. Currently 255.
13973:
13974: @item methods of mapping block ranges to files:
13975: @cindex mapping block ranges to files
13976: @cindex files containing blocks
13977: @cindex blocks in files
13978: By default, blocks are accessed in the file @file{blocks.fb} in the
13979: current working directory. The file can be switched with @code{USE}.
13980:
13981: @item number of string buffers provided by @code{S"}:
13982: @cindex @code{S"}, number of string buffers
13983: 1
13984:
13985: @item size of string buffer used by @code{S"}:
13986: @cindex @code{S"}, size of string buffer
13987: @code{/line}. currently 255.
13988:
13989: @end table
13990:
13991: @c ---------------------------------------------------------------------
13992: @node file-ambcond, , file-idef, The optional File-Access word set
13993: @subsection Ambiguous conditions
13994: @c ---------------------------------------------------------------------
13995: @cindex file words, ambiguous conditions
13996: @cindex ambiguous conditions, file words
13997:
13998: @table @i
13999: @item attempting to position a file outside its boundaries:
14000: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14001: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14002: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14003:
14004: @item attempting to read from file positions not yet written:
14005: @cindex reading from file positions not yet written
14006: End-of-file, i.e., zero characters are read and no error is reported.
14007:
1.29 crook 14008: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14009: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14010: An appropriate exception may be thrown, but a memory fault or other
14011: problem is more probable.
14012:
1.29 crook 14013: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14014: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14015: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14016: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14017: thrown.
14018:
14019: @item named file cannot be opened (@code{INCLUDED}):
14020: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14021: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14022:
14023: @item requesting an unmapped block number:
14024: @cindex unmapped block numbers
14025: There are no unmapped legal block numbers. On some operating systems,
14026: writing a block with a large number may overflow the file system and
14027: have an error message as consequence.
14028:
14029: @item using @code{source-id} when @code{blk} is non-zero:
14030: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14031: @code{source-id} performs its function. Typically it will give the id of
14032: the source which loaded the block. (Better ideas?)
14033:
14034: @end table
14035:
14036:
14037: @c =====================================================================
14038: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14039: @section The optional Floating-Point word set
14040: @c =====================================================================
14041: @cindex system documentation, floating-point words
14042: @cindex floating-point words, system documentation
14043:
14044: @menu
14045: * floating-idef:: Implementation Defined Options
14046: * floating-ambcond:: Ambiguous Conditions
14047: @end menu
14048:
14049:
14050: @c ---------------------------------------------------------------------
14051: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14052: @subsection Implementation Defined Options
14053: @c ---------------------------------------------------------------------
14054: @cindex implementation-defined options, floating-point words
14055: @cindex floating-point words, implementation-defined options
14056:
14057: @table @i
14058: @item format and range of floating point numbers:
14059: @cindex format and range of floating point numbers
14060: @cindex floating point numbers, format and range
14061: System-dependent; the @code{double} type of C.
14062:
1.29 crook 14063: @item results of @code{REPRESENT} when @i{float} is out of range:
14064: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14065: System dependent; @code{REPRESENT} is implemented using the C library
14066: function @code{ecvt()} and inherits its behaviour in this respect.
14067:
14068: @item rounding or truncation of floating-point numbers:
14069: @cindex rounding of floating-point numbers
14070: @cindex truncation of floating-point numbers
14071: @cindex floating-point numbers, rounding or truncation
14072: System dependent; the rounding behaviour is inherited from the hosting C
14073: compiler. IEEE-FP-based (i.e., most) systems by default round to
14074: nearest, and break ties by rounding to even (i.e., such that the last
14075: bit of the mantissa is 0).
14076:
14077: @item size of floating-point stack:
14078: @cindex floating-point stack size
14079: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14080: the floating-point stack (in floats). You can specify this on startup
14081: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14082:
14083: @item width of floating-point stack:
14084: @cindex floating-point stack width
14085: @code{1 floats}.
14086:
14087: @end table
14088:
14089:
14090: @c ---------------------------------------------------------------------
14091: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14092: @subsection Ambiguous conditions
14093: @c ---------------------------------------------------------------------
14094: @cindex floating-point words, ambiguous conditions
14095: @cindex ambiguous conditions, floating-point words
14096:
14097: @table @i
14098: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14099: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14100: System-dependent. Typically results in a @code{-23 THROW} like other
14101: alignment violations.
14102:
14103: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14104: @cindex @code{f@@} used with an address that is not float aligned
14105: @cindex @code{f!} used with an address that is not float aligned
14106: System-dependent. Typically results in a @code{-23 THROW} like other
14107: alignment violations.
14108:
14109: @item floating-point result out of range:
14110: @cindex floating-point result out of range
1.80 anton 14111: System-dependent. Can result in a @code{-43 throw} (floating point
14112: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14113: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14114: unidentified fault), or can produce a special value representing, e.g.,
14115: Infinity.
14116:
14117: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14118: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14119: System-dependent. Typically results in an alignment fault like other
14120: alignment violations.
14121:
1.35 anton 14122: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14123: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14124: The floating-point number is converted into decimal nonetheless.
14125:
14126: @item Both arguments are equal to zero (@code{FATAN2}):
14127: @cindex @code{FATAN2}, both arguments are equal to zero
14128: System-dependent. @code{FATAN2} is implemented using the C library
14129: function @code{atan2()}.
14130:
1.29 crook 14131: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14132: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14133: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14134: because of small errors and the tan will be a very large (or very small)
14135: but finite number.
14136:
1.29 crook 14137: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14138: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14139: The result is rounded to the nearest float.
14140:
14141: @item dividing by zero:
14142: @cindex dividing by zero, floating-point
14143: @cindex floating-point dividing by zero
14144: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14145: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14146: (floating point divide by zero) or @code{-55 throw} (Floating-point
14147: unidentified fault).
1.1 anton 14148:
14149: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14150: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14151: System dependent. On IEEE-FP based systems the number is converted into
14152: an infinity.
14153:
1.29 crook 14154: @item @i{float}<1 (@code{FACOSH}):
14155: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14156: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14157: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14158:
1.29 crook 14159: @item @i{float}=<-1 (@code{FLNP1}):
14160: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14161: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14162: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14163: negative infinity for @i{float}=-1).
1.1 anton 14164:
1.29 crook 14165: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14166: @cindex @code{FLN}, @i{float}=<0
14167: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14168: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14169: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14170: negative infinity for @i{float}=0).
1.1 anton 14171:
1.29 crook 14172: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14173: @cindex @code{FASINH}, @i{float}<0
14174: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14175: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14176: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14177: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14178: C library?).
1.1 anton 14179:
1.29 crook 14180: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14181: @cindex @code{FACOS}, |@i{float}|>1
14182: @cindex @code{FASIN}, |@i{float}|>1
14183: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14184: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14185: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14186:
1.29 crook 14187: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14188: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14189: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14190: Platform-dependent; typically, some double number is produced and no
14191: error is reported.
1.1 anton 14192:
14193: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14194: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14195: @code{Precision} characters of the numeric output area are used. If
14196: @code{precision} is too high, these words will smash the data or code
14197: close to @code{here}.
1.1 anton 14198: @end table
14199:
14200: @c =====================================================================
14201: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14202: @section The optional Locals word set
14203: @c =====================================================================
14204: @cindex system documentation, locals words
14205: @cindex locals words, system documentation
14206:
14207: @menu
14208: * locals-idef:: Implementation Defined Options
14209: * locals-ambcond:: Ambiguous Conditions
14210: @end menu
14211:
14212:
14213: @c ---------------------------------------------------------------------
14214: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14215: @subsection Implementation Defined Options
14216: @c ---------------------------------------------------------------------
14217: @cindex implementation-defined options, locals words
14218: @cindex locals words, implementation-defined options
14219:
14220: @table @i
14221: @item maximum number of locals in a definition:
14222: @cindex maximum number of locals in a definition
14223: @cindex locals, maximum number in a definition
14224: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14225: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14226: characters. The number of locals in a definition is bounded by the size
14227: of locals-buffer, which contains the names of the locals.
14228:
14229: @end table
14230:
14231:
14232: @c ---------------------------------------------------------------------
14233: @node locals-ambcond, , locals-idef, The optional Locals word set
14234: @subsection Ambiguous conditions
14235: @c ---------------------------------------------------------------------
14236: @cindex locals words, ambiguous conditions
14237: @cindex ambiguous conditions, locals words
14238:
14239: @table @i
14240: @item executing a named local in interpretation state:
14241: @cindex local in interpretation state
14242: @cindex Interpreting a compile-only word, for a local
14243: Locals have no interpretation semantics. If you try to perform the
14244: interpretation semantics, you will get a @code{-14 throw} somewhere
14245: (Interpreting a compile-only word). If you perform the compilation
14246: semantics, the locals access will be compiled (irrespective of state).
14247:
1.29 crook 14248: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14249: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14250: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14251: @cindex Invalid name argument, @code{TO}
14252: @code{-32 throw} (Invalid name argument)
14253:
14254: @end table
14255:
14256:
14257: @c =====================================================================
14258: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14259: @section The optional Memory-Allocation word set
14260: @c =====================================================================
14261: @cindex system documentation, memory-allocation words
14262: @cindex memory-allocation words, system documentation
14263:
14264: @menu
14265: * memory-idef:: Implementation Defined Options
14266: @end menu
14267:
14268:
14269: @c ---------------------------------------------------------------------
14270: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14271: @subsection Implementation Defined Options
14272: @c ---------------------------------------------------------------------
14273: @cindex implementation-defined options, memory-allocation words
14274: @cindex memory-allocation words, implementation-defined options
14275:
14276: @table @i
1.29 crook 14277: @item values and meaning of @i{ior}:
14278: @cindex @i{ior} values and meaning
14279: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14280: intended as throw codes. They typically are in the range
14281: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14282: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14283:
14284: @end table
14285:
14286: @c =====================================================================
14287: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14288: @section The optional Programming-Tools word set
14289: @c =====================================================================
14290: @cindex system documentation, programming-tools words
14291: @cindex programming-tools words, system documentation
14292:
14293: @menu
14294: * programming-idef:: Implementation Defined Options
14295: * programming-ambcond:: Ambiguous Conditions
14296: @end menu
14297:
14298:
14299: @c ---------------------------------------------------------------------
14300: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14301: @subsection Implementation Defined Options
14302: @c ---------------------------------------------------------------------
14303: @cindex implementation-defined options, programming-tools words
14304: @cindex programming-tools words, implementation-defined options
14305:
14306: @table @i
14307: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14308: @cindex @code{;CODE} ending sequence
14309: @cindex @code{CODE} ending sequence
14310: @code{END-CODE}
14311:
14312: @item manner of processing input following @code{;CODE} and @code{CODE}:
14313: @cindex @code{;CODE}, processing input
14314: @cindex @code{CODE}, processing input
14315: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14316: the input is processed by the text interpreter, (starting) in interpret
14317: state.
14318:
14319: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14320: @cindex @code{ASSEMBLER}, search order capability
14321: The ANS Forth search order word set.
14322:
14323: @item source and format of display by @code{SEE}:
14324: @cindex @code{SEE}, source and format of output
1.80 anton 14325: The source for @code{see} is the executable code used by the inner
1.1 anton 14326: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14327: (and on some platforms, assembly code for primitives) as well as
14328: possible.
1.1 anton 14329:
14330: @end table
14331:
14332: @c ---------------------------------------------------------------------
14333: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14334: @subsection Ambiguous conditions
14335: @c ---------------------------------------------------------------------
14336: @cindex programming-tools words, ambiguous conditions
14337: @cindex ambiguous conditions, programming-tools words
14338:
14339: @table @i
14340:
1.21 crook 14341: @item deleting the compilation word list (@code{FORGET}):
14342: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14343: Not implemented (yet).
14344:
1.29 crook 14345: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14346: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14347: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14348: @cindex control-flow stack underflow
14349: This typically results in an @code{abort"} with a descriptive error
14350: message (may change into a @code{-22 throw} (Control structure mismatch)
14351: in the future). You may also get a memory access error. If you are
14352: unlucky, this ambiguous condition is not caught.
14353:
1.29 crook 14354: @item @i{name} can't be found (@code{FORGET}):
14355: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14356: Not implemented (yet).
14357:
1.29 crook 14358: @item @i{name} not defined via @code{CREATE}:
14359: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14360: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14361: the execution semantics of the last defined word no matter how it was
14362: defined.
14363:
14364: @item @code{POSTPONE} applied to @code{[IF]}:
14365: @cindex @code{POSTPONE} applied to @code{[IF]}
14366: @cindex @code{[IF]} and @code{POSTPONE}
14367: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14368: equivalent to @code{[IF]}.
14369:
14370: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14371: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14372: Continue in the same state of conditional compilation in the next outer
14373: input source. Currently there is no warning to the user about this.
14374:
14375: @item removing a needed definition (@code{FORGET}):
14376: @cindex @code{FORGET}, removing a needed definition
14377: Not implemented (yet).
14378:
14379: @end table
14380:
14381:
14382: @c =====================================================================
14383: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14384: @section The optional Search-Order word set
14385: @c =====================================================================
14386: @cindex system documentation, search-order words
14387: @cindex search-order words, system documentation
14388:
14389: @menu
14390: * search-idef:: Implementation Defined Options
14391: * search-ambcond:: Ambiguous Conditions
14392: @end menu
14393:
14394:
14395: @c ---------------------------------------------------------------------
14396: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14397: @subsection Implementation Defined Options
14398: @c ---------------------------------------------------------------------
14399: @cindex implementation-defined options, search-order words
14400: @cindex search-order words, implementation-defined options
14401:
14402: @table @i
14403: @item maximum number of word lists in search order:
14404: @cindex maximum number of word lists in search order
14405: @cindex search order, maximum depth
14406: @code{s" wordlists" environment? drop .}. Currently 16.
14407:
14408: @item minimum search order:
14409: @cindex minimum search order
14410: @cindex search order, minimum
14411: @code{root root}.
14412:
14413: @end table
14414:
14415: @c ---------------------------------------------------------------------
14416: @node search-ambcond, , search-idef, The optional Search-Order word set
14417: @subsection Ambiguous conditions
14418: @c ---------------------------------------------------------------------
14419: @cindex search-order words, ambiguous conditions
14420: @cindex ambiguous conditions, search-order words
14421:
14422: @table @i
1.21 crook 14423: @item changing the compilation word list (during compilation):
14424: @cindex changing the compilation word list (during compilation)
14425: @cindex compilation word list, change before definition ends
14426: The word is entered into the word list that was the compilation word list
1.1 anton 14427: at the start of the definition. Any changes to the name field (e.g.,
14428: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14429: are applied to the latest defined word (as reported by @code{latest} or
14430: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14431:
14432: @item search order empty (@code{previous}):
14433: @cindex @code{previous}, search order empty
1.26 crook 14434: @cindex vocstack empty, @code{previous}
1.1 anton 14435: @code{abort" Vocstack empty"}.
14436:
14437: @item too many word lists in search order (@code{also}):
14438: @cindex @code{also}, too many word lists in search order
1.26 crook 14439: @cindex vocstack full, @code{also}
1.1 anton 14440: @code{abort" Vocstack full"}.
14441:
14442: @end table
14443:
14444: @c ***************************************************************
1.65 anton 14445: @node Standard vs Extensions, Model, ANS conformance, Top
14446: @chapter Should I use Gforth extensions?
14447: @cindex Gforth extensions
14448:
14449: As you read through the rest of this manual, you will see documentation
14450: for @i{Standard} words, and documentation for some appealing Gforth
14451: @i{extensions}. You might ask yourself the question: @i{``Should I
14452: restrict myself to the standard, or should I use the extensions?''}
14453:
14454: The answer depends on the goals you have for the program you are working
14455: on:
14456:
14457: @itemize @bullet
14458:
14459: @item Is it just for yourself or do you want to share it with others?
14460:
14461: @item
14462: If you want to share it, do the others all use Gforth?
14463:
14464: @item
14465: If it is just for yourself, do you want to restrict yourself to Gforth?
14466:
14467: @end itemize
14468:
14469: If restricting the program to Gforth is ok, then there is no reason not
14470: to use extensions. It is still a good idea to keep to the standard
14471: where it is easy, in case you want to reuse these parts in another
14472: program that you want to be portable.
14473:
14474: If you want to be able to port the program to other Forth systems, there
14475: are the following points to consider:
14476:
14477: @itemize @bullet
14478:
14479: @item
14480: Most Forth systems that are being maintained support the ANS Forth
14481: standard. So if your program complies with the standard, it will be
14482: portable among many systems.
14483:
14484: @item
14485: A number of the Gforth extensions can be implemented in ANS Forth using
14486: public-domain files provided in the @file{compat/} directory. These are
14487: mentioned in the text in passing. There is no reason not to use these
14488: extensions, your program will still be ANS Forth compliant; just include
14489: the appropriate compat files with your program.
14490:
14491: @item
14492: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14493: analyse your program and determine what non-Standard words it relies
14494: upon. However, it does not check whether you use standard words in a
14495: non-standard way.
14496:
14497: @item
14498: Some techniques are not standardized by ANS Forth, and are hard or
14499: impossible to implement in a standard way, but can be implemented in
14500: most Forth systems easily, and usually in similar ways (e.g., accessing
14501: word headers). Forth has a rich historical precedent for programmers
14502: taking advantage of implementation-dependent features of their tools
14503: (for example, relying on a knowledge of the dictionary
14504: structure). Sometimes these techniques are necessary to extract every
14505: last bit of performance from the hardware, sometimes they are just a
14506: programming shorthand.
14507:
14508: @item
14509: Does using a Gforth extension save more work than the porting this part
14510: to other Forth systems (if any) will cost?
14511:
14512: @item
14513: Is the additional functionality worth the reduction in portability and
14514: the additional porting problems?
14515:
14516: @end itemize
14517:
14518: In order to perform these consideratios, you need to know what's
14519: standard and what's not. This manual generally states if something is
1.81 anton 14520: non-standard, but the authoritative source is the
14521: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14522: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14523: into the thought processes of the technical committee.
14524:
14525: Note also that portability between Forth systems is not the only
14526: portability issue; there is also the issue of portability between
14527: different platforms (processor/OS combinations).
14528:
14529: @c ***************************************************************
14530: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14531: @chapter Model
14532:
14533: This chapter has yet to be written. It will contain information, on
14534: which internal structures you can rely.
14535:
14536: @c ***************************************************************
14537: @node Integrating Gforth, Emacs and Gforth, Model, Top
14538: @chapter Integrating Gforth into C programs
14539:
14540: This is not yet implemented.
14541:
14542: Several people like to use Forth as scripting language for applications
14543: that are otherwise written in C, C++, or some other language.
14544:
14545: The Forth system ATLAST provides facilities for embedding it into
14546: applications; unfortunately it has several disadvantages: most
14547: importantly, it is not based on ANS Forth, and it is apparently dead
14548: (i.e., not developed further and not supported). The facilities
1.21 crook 14549: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14550: making the switch should not be hard.
14551:
14552: We also tried to design the interface such that it can easily be
14553: implemented by other Forth systems, so that we may one day arrive at a
14554: standardized interface. Such a standard interface would allow you to
14555: replace the Forth system without having to rewrite C code.
14556:
14557: You embed the Gforth interpreter by linking with the library
14558: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14559: global symbols in this library that belong to the interface, have the
14560: prefix @code{forth_}. (Global symbols that are used internally have the
14561: prefix @code{gforth_}).
14562:
14563: You can include the declarations of Forth types and the functions and
14564: variables of the interface with @code{#include <forth.h>}.
14565:
14566: Types.
14567:
14568: Variables.
14569:
14570: Data and FP Stack pointer. Area sizes.
14571:
14572: functions.
14573:
14574: forth_init(imagefile)
14575: forth_evaluate(string) exceptions?
14576: forth_goto(address) (or forth_execute(xt)?)
14577: forth_continue() (a corountining mechanism)
14578:
14579: Adding primitives.
14580:
14581: No checking.
14582:
14583: Signals?
14584:
14585: Accessing the Stacks
14586:
1.26 crook 14587: @c ******************************************************************
1.1 anton 14588: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14589: @chapter Emacs and Gforth
14590: @cindex Emacs and Gforth
14591:
14592: @cindex @file{gforth.el}
14593: @cindex @file{forth.el}
14594: @cindex Rydqvist, Goran
1.107 dvdkhlng 14595: @cindex Kuehling, David
1.1 anton 14596: @cindex comment editing commands
14597: @cindex @code{\}, editing with Emacs
14598: @cindex debug tracer editing commands
14599: @cindex @code{~~}, removal with Emacs
14600: @cindex Forth mode in Emacs
1.107 dvdkhlng 14601:
1.1 anton 14602: Gforth comes with @file{gforth.el}, an improved version of
14603: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14604: improvements are:
14605:
14606: @itemize @bullet
14607: @item
1.107 dvdkhlng 14608: A better handling of indentation.
14609: @item
14610: A custom hilighting engine for Forth-code.
1.26 crook 14611: @item
14612: Comment paragraph filling (@kbd{M-q})
14613: @item
14614: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14615: @item
14616: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14617: @item
14618: Support of the @code{info-lookup} feature for looking up the
14619: documentation of a word.
1.107 dvdkhlng 14620: @item
14621: Support for reading and writing blocks files.
1.26 crook 14622: @end itemize
14623:
1.107 dvdkhlng 14624: To get a basic description of these features, enter Forth mode and
14625: type @kbd{C-h m}.
1.1 anton 14626:
14627: @cindex source location of error or debugging output in Emacs
14628: @cindex error output, finding the source location in Emacs
14629: @cindex debugging output, finding the source location in Emacs
14630: In addition, Gforth supports Emacs quite well: The source code locations
14631: given in error messages, debugging output (from @code{~~}) and failed
14632: assertion messages are in the right format for Emacs' compilation mode
14633: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14634: Manual}) so the source location corresponding to an error or other
14635: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14636: @kbd{C-c C-c} for the error under the cursor).
14637:
1.107 dvdkhlng 14638: @cindex viewing the documentation of a word in Emacs
14639: @cindex context-sensitive help
14640: Moreover, for words documented in this manual, you can look up the
14641: glossary entry quickly by using @kbd{C-h TAB}
14642: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14643: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14644: later and does not work for words containing @code{:}.
14645:
14646: @menu
14647: * Installing gforth.el:: Making Emacs aware of Forth.
14648: * Emacs Tags:: Viewing the source of a word in Emacs.
14649: * Hilighting:: Making Forth code look prettier.
14650: * Auto-Indentation:: Customizing auto-indentation.
14651: * Blocks Files:: Reading and writing blocks files.
14652: @end menu
14653:
14654: @c ----------------------------------
1.109 anton 14655: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14656: @section Installing gforth.el
14657: @cindex @file{.emacs}
14658: @cindex @file{gforth.el}, installation
14659: To make the features from @file{gforth.el} available in Emacs, add
14660: the following lines to your @file{.emacs} file:
14661:
14662: @example
14663: (autoload 'forth-mode "gforth.el")
14664: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14665: auto-mode-alist))
14666: (autoload 'forth-block-mode "gforth.el")
14667: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14668: auto-mode-alist))
14669: (add-hook 'forth-mode-hook (function (lambda ()
14670: ;; customize variables here:
14671: (setq forth-indent-level 4)
14672: (setq forth-minor-indent-level 2)
14673: (setq forth-hilight-level 3)
14674: ;;; ...
14675: )))
14676: @end example
14677:
14678: @c ----------------------------------
14679: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14680: @section Emacs Tags
1.1 anton 14681: @cindex @file{TAGS} file
14682: @cindex @file{etags.fs}
14683: @cindex viewing the source of a word in Emacs
1.43 anton 14684: @cindex @code{require}, placement in files
14685: @cindex @code{include}, placement in files
1.107 dvdkhlng 14686: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14687: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14688: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14689: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14690: several tags files at the same time (e.g., one for the Gforth sources
14691: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14692: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14693: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14694: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14695: with @file{etags.fs}, you should avoid putting definitions both before
14696: and after @code{require} etc., otherwise you will see the same file
14697: visited several times by commands like @code{tags-search}.
1.1 anton 14698:
1.107 dvdkhlng 14699: @c ----------------------------------
14700: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14701: @section Hilighting
14702: @cindex hilighting Forth code in Emacs
14703: @cindex highlighting Forth code in Emacs
14704: @file{gforth.el} comes with a custom source hilighting engine. When
14705: you open a file in @code{forth-mode}, it will be completely parsed,
14706: assigning faces to keywords, comments, strings etc. While you edit
14707: the file, modified regions get parsed and updated on-the-fly.
14708:
14709: Use the variable `forth-hilight-level' to change the level of
14710: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14711: you set the hilighting level to 0, the parser will still work in the
14712: background, collecting information about whether regions of text are
14713: ``compiled'' or ``interpreted''. Those information are required for
14714: auto-indentation to work properly. Set `forth-disable-parser' to
14715: non-nil if your computer is too slow to handle parsing. This will
14716: have an impact on the smartness of the auto-indentation engine,
14717: though.
14718:
14719: Sometimes Forth sources define new features that should be hilighted,
14720: new control structures, defining-words etc. You can use the variable
14721: `forth-custom-words' to make @code{forth-mode} hilight additional
14722: words and constructs. See the docstring of `forth-words' for details
14723: (in Emacs, type @kbd{C-h v forth-words}).
14724:
14725: `forth-custom-words' is meant to be customized in your
14726: @file{.emacs} file. To customize hilighing in a file-specific manner,
14727: set `forth-local-words' in a local-variables section at the end of
14728: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14729:
14730: Example:
14731: @example
14732: 0 [IF]
14733: Local Variables:
14734: forth-local-words:
14735: ((("t:") definition-starter (font-lock-keyword-face . 1)
14736: "[ \t\n]" t name (font-lock-function-name-face . 3))
14737: ((";t") definition-ender (font-lock-keyword-face . 1)))
14738: End:
14739: [THEN]
14740: @end example
14741:
14742: @c ----------------------------------
14743: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14744: @section Auto-Indentation
14745: @cindex auto-indentation of Forth code in Emacs
14746: @cindex indentation of Forth code in Emacs
14747: @code{forth-mode} automatically tries to indent lines in a smart way,
14748: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14749:
14750: Simple customization can be achieved by setting
14751: `forth-indent-level' and `forth-minor-indent-level' in your
14752: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14753: per default by multiples of 4 columns. To use the more traditional
14754: 3-column indentation, add the following lines to your @file{.emacs}:
14755:
14756: @example
14757: (add-hook 'forth-mode-hook (function (lambda ()
14758: ;; customize variables here:
14759: (setq forth-indent-level 3)
14760: (setq forth-minor-indent-level 1)
14761: )))
14762: @end example
14763:
14764: If you want indentation to recognize non-default words, customize it
14765: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14766: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14767: v forth-indent-words}).
14768:
14769: To customize indentation in a file-specific manner, set
14770: `forth-local-indent-words' in a local-variables section at the end of
14771: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14772: Emacs Manual}).
14773:
14774: Example:
14775: @example
14776: 0 [IF]
14777: Local Variables:
14778: forth-local-indent-words:
14779: ((("t:") (0 . 2) (0 . 2))
14780: ((";t") (-2 . 0) (0 . -2)))
14781: End:
14782: [THEN]
14783: @end example
14784:
14785: @c ----------------------------------
1.109 anton 14786: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14787: @section Blocks Files
14788: @cindex blocks files, use with Emacs
14789: @code{forth-mode} Autodetects blocks files by checking whether the
14790: length of the first line exceeds 1023 characters. It then tries to
14791: convert the file into normal text format. When you save the file, it
14792: will be written to disk as normal stream-source file.
14793:
14794: If you want to write blocks files, use @code{forth-blocks-mode}. It
14795: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14796:
1.107 dvdkhlng 14797: @itemize @bullet
14798: @item
14799: Files are written to disk in blocks file format.
14800: @item
14801: Screen numbers are displayed in the mode line (enumerated beginning
14802: with the value of `forth-block-base')
14803: @item
14804: Warnings are displayed when lines exceed 64 characters.
14805: @item
14806: The beginning of the currently edited block is marked with an
14807: overlay-arrow.
14808: @end itemize
1.41 anton 14809:
1.107 dvdkhlng 14810: There are some restrictions you should be aware of. When you open a
14811: blocks file that contains tabulator or newline characters, these
14812: characters will be translated into spaces when the file is written
14813: back to disk. If tabs or newlines are encountered during blocks file
14814: reading, an error is output to the echo area. So have a look at the
14815: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14816:
1.107 dvdkhlng 14817: Please consult the docstring of @code{forth-blocks-mode} for more
14818: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14819:
1.26 crook 14820: @c ******************************************************************
1.1 anton 14821: @node Image Files, Engine, Emacs and Gforth, Top
14822: @chapter Image Files
1.26 crook 14823: @cindex image file
14824: @cindex @file{.fi} files
1.1 anton 14825: @cindex precompiled Forth code
14826: @cindex dictionary in persistent form
14827: @cindex persistent form of dictionary
14828:
14829: An image file is a file containing an image of the Forth dictionary,
14830: i.e., compiled Forth code and data residing in the dictionary. By
14831: convention, we use the extension @code{.fi} for image files.
14832:
14833: @menu
1.18 anton 14834: * Image Licensing Issues:: Distribution terms for images.
14835: * Image File Background:: Why have image files?
1.67 anton 14836: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14837: * Data-Relocatable Image Files:: are better.
1.67 anton 14838: * Fully Relocatable Image Files:: better yet.
1.18 anton 14839: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14840: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14841: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14842: @end menu
14843:
1.18 anton 14844: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14845: @section Image Licensing Issues
14846: @cindex license for images
14847: @cindex image license
14848:
14849: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14850: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14851: original image; i.e., according to copyright law it is a derived work of
14852: the original image.
14853:
14854: Since Gforth is distributed under the GNU GPL, the newly created image
14855: falls under the GNU GPL, too. In particular, this means that if you
14856: distribute the image, you have to make all of the sources for the image
1.113 anton 14857: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14858: GNU General Public License (Section 3)}.
14859:
14860: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14861: contains only code compiled from the sources you gave it; if none of
14862: these sources is under the GPL, the terms discussed above do not apply
14863: to the image. However, if your image needs an engine (a gforth binary)
14864: that is under the GPL, you should make sure that you distribute both in
14865: a way that is at most a @emph{mere aggregation}, if you don't want the
14866: terms of the GPL to apply to the image.
14867:
14868: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14869: @section Image File Background
14870: @cindex image file background
14871:
1.80 anton 14872: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14873: definitions written in Forth. Since the Forth compiler itself belongs to
14874: those definitions, it is not possible to start the system with the
1.80 anton 14875: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14876: code as an image file in nearly executable form. When Gforth starts up,
14877: a C routine loads the image file into memory, optionally relocates the
14878: addresses, then sets up the memory (stacks etc.) according to
14879: information in the image file, and (finally) starts executing Forth
14880: code.
1.1 anton 14881:
14882: The image file variants represent different compromises between the
14883: goals of making it easy to generate image files and making them
14884: portable.
14885:
14886: @cindex relocation at run-time
1.26 crook 14887: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14888: run-time. This avoids many of the complications discussed below (image
14889: files are data relocatable without further ado), but costs performance
14890: (one addition per memory access).
14891:
14892: @cindex relocation at load-time
1.26 crook 14893: By contrast, the Gforth loader performs relocation at image load time. The
14894: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14895: appropriate code-field addresses (or code addresses in the case of
14896: direct threading).
14897:
14898: There are three kinds of image files, with different degrees of
14899: relocatability: non-relocatable, data-relocatable, and fully relocatable
14900: image files.
14901:
14902: @cindex image file loader
14903: @cindex relocating loader
14904: @cindex loader for image files
14905: These image file variants have several restrictions in common; they are
14906: caused by the design of the image file loader:
14907:
14908: @itemize @bullet
14909: @item
14910: There is only one segment; in particular, this means, that an image file
14911: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14912: them). The contents of the stacks are not represented, either.
1.1 anton 14913:
14914: @item
14915: The only kinds of relocation supported are: adding the same offset to
14916: all cells that represent data addresses; and replacing special tokens
14917: with code addresses or with pieces of machine code.
14918:
14919: If any complex computations involving addresses are performed, the
14920: results cannot be represented in the image file. Several applications that
14921: use such computations come to mind:
14922: @itemize @minus
14923: @item
14924: Hashing addresses (or data structures which contain addresses) for table
14925: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14926: purpose, you will have no problem, because the hash tables are
14927: recomputed automatically when the system is started. If you use your own
14928: hash tables, you will have to do something similar.
14929:
14930: @item
14931: There's a cute implementation of doubly-linked lists that uses
14932: @code{XOR}ed addresses. You could represent such lists as singly-linked
14933: in the image file, and restore the doubly-linked representation on
14934: startup.@footnote{In my opinion, though, you should think thrice before
14935: using a doubly-linked list (whatever implementation).}
14936:
14937: @item
14938: The code addresses of run-time routines like @code{docol:} cannot be
14939: represented in the image file (because their tokens would be replaced by
14940: machine code in direct threaded implementations). As a workaround,
14941: compute these addresses at run-time with @code{>code-address} from the
14942: executions tokens of appropriate words (see the definitions of
1.80 anton 14943: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14944:
14945: @item
14946: On many architectures addresses are represented in machine code in some
14947: shifted or mangled form. You cannot put @code{CODE} words that contain
14948: absolute addresses in this form in a relocatable image file. Workarounds
14949: are representing the address in some relative form (e.g., relative to
14950: the CFA, which is present in some register), or loading the address from
14951: a place where it is stored in a non-mangled form.
14952: @end itemize
14953: @end itemize
14954:
14955: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14956: @section Non-Relocatable Image Files
14957: @cindex non-relocatable image files
1.26 crook 14958: @cindex image file, non-relocatable
1.1 anton 14959:
14960: These files are simple memory dumps of the dictionary. They are specific
14961: to the executable (i.e., @file{gforth} file) they were created
14962: with. What's worse, they are specific to the place on which the
14963: dictionary resided when the image was created. Now, there is no
14964: guarantee that the dictionary will reside at the same place the next
14965: time you start Gforth, so there's no guarantee that a non-relocatable
14966: image will work the next time (Gforth will complain instead of crashing,
14967: though).
14968:
14969: You can create a non-relocatable image file with
14970:
1.44 crook 14971:
1.1 anton 14972: doc-savesystem
14973:
1.44 crook 14974:
1.1 anton 14975: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14976: @section Data-Relocatable Image Files
14977: @cindex data-relocatable image files
1.26 crook 14978: @cindex image file, data-relocatable
1.1 anton 14979:
14980: These files contain relocatable data addresses, but fixed code addresses
14981: (instead of tokens). They are specific to the executable (i.e.,
14982: @file{gforth} file) they were created with. For direct threading on some
14983: architectures (e.g., the i386), data-relocatable images do not work. You
14984: get a data-relocatable image, if you use @file{gforthmi} with a
14985: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14986: Relocatable Image Files}).
14987:
14988: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14989: @section Fully Relocatable Image Files
14990: @cindex fully relocatable image files
1.26 crook 14991: @cindex image file, fully relocatable
1.1 anton 14992:
14993: @cindex @file{kern*.fi}, relocatability
14994: @cindex @file{gforth.fi}, relocatability
14995: These image files have relocatable data addresses, and tokens for code
14996: addresses. They can be used with different binaries (e.g., with and
14997: without debugging) on the same machine, and even across machines with
14998: the same data formats (byte order, cell size, floating point
14999: format). However, they are usually specific to the version of Gforth
15000: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
15001: are fully relocatable.
15002:
15003: There are two ways to create a fully relocatable image file:
15004:
15005: @menu
1.29 crook 15006: * gforthmi:: The normal way
1.1 anton 15007: * cross.fs:: The hard way
15008: @end menu
15009:
15010: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15011: @subsection @file{gforthmi}
15012: @cindex @file{comp-i.fs}
15013: @cindex @file{gforthmi}
15014:
15015: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15016: image @i{file} that contains everything you would load by invoking
15017: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15018: @example
1.29 crook 15019: gforthmi @i{file} @i{options}
1.1 anton 15020: @end example
15021:
15022: E.g., if you want to create an image @file{asm.fi} that has the file
15023: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15024: like this:
15025:
15026: @example
15027: gforthmi asm.fi asm.fs
15028: @end example
15029:
1.27 crook 15030: @file{gforthmi} is implemented as a sh script and works like this: It
15031: produces two non-relocatable images for different addresses and then
15032: compares them. Its output reflects this: first you see the output (if
1.62 crook 15033: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15034: files, then you see the output of the comparing program: It displays the
15035: offset used for data addresses and the offset used for code addresses;
1.1 anton 15036: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15037: image files, it displays a line like this:
1.1 anton 15038:
15039: @example
15040: 78DC BFFFFA50 BFFFFA40
15041: @end example
15042:
15043: This means that at offset $78dc from @code{forthstart}, one input image
15044: contains $bffffa50, and the other contains $bffffa40. Since these cells
15045: cannot be represented correctly in the output image, you should examine
15046: these places in the dictionary and verify that these cells are dead
15047: (i.e., not read before they are written).
1.39 anton 15048:
15049: @cindex --application, @code{gforthmi} option
15050: If you insert the option @code{--application} in front of the image file
15051: name, you will get an image that uses the @code{--appl-image} option
15052: instead of the @code{--image-file} option (@pxref{Invoking
15053: Gforth}). When you execute such an image on Unix (by typing the image
15054: name as command), the Gforth engine will pass all options to the image
15055: instead of trying to interpret them as engine options.
1.1 anton 15056:
1.27 crook 15057: If you type @file{gforthmi} with no arguments, it prints some usage
15058: instructions.
15059:
1.1 anton 15060: @cindex @code{savesystem} during @file{gforthmi}
15061: @cindex @code{bye} during @file{gforthmi}
15062: @cindex doubly indirect threaded code
1.44 crook 15063: @cindex environment variables
15064: @cindex @code{GFORTHD} -- environment variable
15065: @cindex @code{GFORTH} -- environment variable
1.1 anton 15066: @cindex @code{gforth-ditc}
1.29 crook 15067: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 15068: words @code{savesystem} and @code{bye} must be visible. A special doubly
15069: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 15070: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 15071: this executable through the environment variable @code{GFORTHD}
15072: (default: @file{gforth-ditc}); if you pass a version that is not doubly
15073: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 15074: data-relocatable image (because there is no code address offset). The
15075: normal @file{gforth} executable is used for creating the relocatable
15076: image; you can pass the exact filename of this executable through the
15077: environment variable @code{GFORTH}.
1.1 anton 15078:
15079: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15080: @subsection @file{cross.fs}
15081: @cindex @file{cross.fs}
15082: @cindex cross-compiler
15083: @cindex metacompiler
1.47 crook 15084: @cindex target compiler
1.1 anton 15085:
15086: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15087: programming language (@pxref{Cross Compiler}).
1.1 anton 15088:
1.47 crook 15089: @code{cross} allows you to create image files for machines with
1.1 anton 15090: different data sizes and data formats than the one used for generating
15091: the image file. You can also use it to create an application image that
15092: does not contain a Forth compiler. These features are bought with
15093: restrictions and inconveniences in programming. E.g., addresses have to
15094: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15095: order to make the code relocatable.
15096:
15097:
15098: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15099: @section Stack and Dictionary Sizes
15100: @cindex image file, stack and dictionary sizes
15101: @cindex dictionary size default
15102: @cindex stack size default
15103:
15104: If you invoke Gforth with a command line flag for the size
15105: (@pxref{Invoking Gforth}), the size you specify is stored in the
15106: dictionary. If you save the dictionary with @code{savesystem} or create
15107: an image with @file{gforthmi}, this size will become the default
15108: for the resulting image file. E.g., the following will create a
1.21 crook 15109: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15110:
15111: @example
15112: gforthmi gforth.fi -m 1M
15113: @end example
15114:
15115: In other words, if you want to set the default size for the dictionary
15116: and the stacks of an image, just invoke @file{gforthmi} with the
15117: appropriate options when creating the image.
15118:
15119: @cindex stack size, cache-friendly
15120: Note: For cache-friendly behaviour (i.e., good performance), you should
15121: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15122: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15123: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15124:
15125: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15126: @section Running Image Files
15127: @cindex running image files
15128: @cindex invoking image files
15129: @cindex image file invocation
15130:
15131: @cindex -i, invoke image file
15132: @cindex --image file, invoke image file
1.29 crook 15133: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15134: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15135: @example
1.29 crook 15136: gforth -i @i{image}
1.1 anton 15137: @end example
15138:
15139: @cindex executable image file
1.26 crook 15140: @cindex image file, executable
1.1 anton 15141: If your operating system supports starting scripts with a line of the
15142: form @code{#! ...}, you just have to type the image file name to start
15143: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15144: just a convention). I.e., to run Gforth with the image file @i{image},
15145: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15146: This works because every @code{.fi} file starts with a line of this
15147: format:
15148:
15149: @example
15150: #! /usr/local/bin/gforth-0.4.0 -i
15151: @end example
15152:
15153: The file and pathname for the Gforth engine specified on this line is
15154: the specific Gforth executable that it was built against; i.e. the value
15155: of the environment variable @code{GFORTH} at the time that
15156: @file{gforthmi} was executed.
1.1 anton 15157:
1.27 crook 15158: You can make use of the same shell capability to make a Forth source
15159: file into an executable. For example, if you place this text in a file:
1.26 crook 15160:
15161: @example
15162: #! /usr/local/bin/gforth
15163:
15164: ." Hello, world" CR
15165: bye
15166: @end example
15167:
15168: @noindent
1.27 crook 15169: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15170: directly from the command line. The sequence @code{#!} is used in two
15171: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15172: system@footnote{The Unix kernel actually recognises two types of files:
15173: executable files and files of data, where the data is processed by an
15174: interpreter that is specified on the ``interpreter line'' -- the first
15175: line of the file, starting with the sequence #!. There may be a small
15176: limit (e.g., 32) on the number of characters that may be specified on
15177: the interpreter line.} secondly it is treated as a comment character by
15178: Gforth. Because of the second usage, a space is required between
1.80 anton 15179: @code{#!} and the path to the executable (moreover, some Unixes
15180: require the sequence @code{#! /}).
1.27 crook 15181:
15182: The disadvantage of this latter technique, compared with using
1.80 anton 15183: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15184: compiled on-the-fly, each time the program is invoked.
1.26 crook 15185:
1.1 anton 15186: doc-#!
15187:
1.44 crook 15188:
1.1 anton 15189: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15190: @section Modifying the Startup Sequence
15191: @cindex startup sequence for image file
15192: @cindex image file initialization sequence
15193: @cindex initialization sequence of image file
15194:
1.120 anton 15195: You can add your own initialization to the startup sequence of an image
15196: through the deferred word @code{'cold}. @code{'cold} is invoked just
15197: before the image-specific command line processing (i.e., loading files
15198: and evaluating (@code{-e}) strings) starts.
1.1 anton 15199:
15200: A sequence for adding your initialization usually looks like this:
15201:
15202: @example
15203: :noname
15204: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15205: ... \ your stuff
15206: ; IS 'cold
15207: @end example
15208:
1.157 anton 15209: After @code{'cold}, Gforth processes the image options
15210: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15211: another deferred word. This normally prints Gforth's startup message
15212: and does nothing else.
15213:
1.1 anton 15214: @cindex turnkey image files
1.26 crook 15215: @cindex image file, turnkey applications
1.157 anton 15216: So, if you want to make a turnkey image (i.e., an image for an
15217: application instead of an extended Forth system), you can do this in
15218: two ways:
15219:
15220: @itemize @bullet
15221:
15222: @item
15223: If you want to do your interpretation of the OS command-line
15224: arguments, hook into @code{'cold}. In that case you probably also
15225: want to build the image with @code{gforthmi --application}
15226: (@pxref{gforthmi}) to keep the engine from processing OS command line
15227: options. You can then do your own command-line processing with
15228: @code{next-arg}
15229:
15230: @item
15231: If you want to have the normal Gforth processing of OS command-line
15232: arguments, hook into @code{bootmessage}.
15233:
15234: @end itemize
15235:
15236: In either case, you probably do not want the word that you execute in
15237: these hooks to exit normally, but use @code{bye} or @code{throw}.
15238: Otherwise the Gforth startup process would continue and eventually
15239: present the Forth command line to the user.
1.26 crook 15240:
15241: doc-'cold
1.157 anton 15242: doc-bootmessage
1.44 crook 15243:
1.1 anton 15244: @c ******************************************************************
1.113 anton 15245: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15246: @chapter Engine
15247: @cindex engine
15248: @cindex virtual machine
15249:
1.26 crook 15250: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15251: may be helpful for finding your way in the Gforth sources.
15252:
1.109 anton 15253: The ideas in this section have also been published in the following
15254: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15255: Forth-Tagung '93; M. Anton Ertl,
15256: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15257: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15258: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15259: Threaded code variations and optimizations (extended version)}},
15260: Forth-Tagung '02.
1.1 anton 15261:
15262: @menu
15263: * Portability::
15264: * Threading::
15265: * Primitives::
15266: * Performance::
15267: @end menu
15268:
15269: @node Portability, Threading, Engine, Engine
15270: @section Portability
15271: @cindex engine portability
15272:
1.26 crook 15273: An important goal of the Gforth Project is availability across a wide
15274: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15275: achieved this goal by manually coding the engine in assembly language
15276: for several then-popular processors. This approach is very
15277: labor-intensive and the results are short-lived due to progress in
15278: computer architecture.
1.1 anton 15279:
15280: @cindex C, using C for the engine
15281: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15282: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15283: particularly popular for UNIX-based Forths due to the large variety of
15284: architectures of UNIX machines. Unfortunately an implementation in C
15285: does not mix well with the goals of efficiency and with using
15286: traditional techniques: Indirect or direct threading cannot be expressed
15287: in C, and switch threading, the fastest technique available in C, is
15288: significantly slower. Another problem with C is that it is very
15289: cumbersome to express double integer arithmetic.
15290:
15291: @cindex GNU C for the engine
15292: @cindex long long
15293: Fortunately, there is a portable language that does not have these
15294: limitations: GNU C, the version of C processed by the GNU C compiler
15295: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15296: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15297: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15298: threading possible, its @code{long long} type (@pxref{Long Long, ,
15299: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15300: double numbers on many systems. GNU C is freely available on all
1.1 anton 15301: important (and many unimportant) UNIX machines, VMS, 80386s running
15302: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15303: on all these machines.
15304:
15305: Writing in a portable language has the reputation of producing code that
15306: is slower than assembly. For our Forth engine we repeatedly looked at
15307: the code produced by the compiler and eliminated most compiler-induced
15308: inefficiencies by appropriate changes in the source code.
15309:
15310: @cindex explicit register declarations
15311: @cindex --enable-force-reg, configuration flag
15312: @cindex -DFORCE_REG
15313: However, register allocation cannot be portably influenced by the
15314: programmer, leading to some inefficiencies on register-starved
15315: machines. We use explicit register declarations (@pxref{Explicit Reg
15316: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15317: improve the speed on some machines. They are turned on by using the
15318: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15319: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15320: machine, but also on the compiler version: On some machines some
15321: compiler versions produce incorrect code when certain explicit register
15322: declarations are used. So by default @code{-DFORCE_REG} is not used.
15323:
15324: @node Threading, Primitives, Portability, Engine
15325: @section Threading
15326: @cindex inner interpreter implementation
15327: @cindex threaded code implementation
15328:
15329: @cindex labels as values
15330: GNU C's labels as values extension (available since @code{gcc-2.0},
15331: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15332: makes it possible to take the address of @i{label} by writing
15333: @code{&&@i{label}}. This address can then be used in a statement like
15334: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15335: @code{goto x}.
15336:
1.26 crook 15337: @cindex @code{NEXT}, indirect threaded
1.1 anton 15338: @cindex indirect threaded inner interpreter
15339: @cindex inner interpreter, indirect threaded
1.26 crook 15340: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15341: @example
15342: cfa = *ip++;
15343: ca = *cfa;
15344: goto *ca;
15345: @end example
15346: @cindex instruction pointer
15347: For those unfamiliar with the names: @code{ip} is the Forth instruction
15348: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15349: execution token and points to the code field of the next word to be
15350: executed; The @code{ca} (code address) fetched from there points to some
15351: executable code, e.g., a primitive or the colon definition handler
15352: @code{docol}.
15353:
1.26 crook 15354: @cindex @code{NEXT}, direct threaded
1.1 anton 15355: @cindex direct threaded inner interpreter
15356: @cindex inner interpreter, direct threaded
15357: Direct threading is even simpler:
15358: @example
15359: ca = *ip++;
15360: goto *ca;
15361: @end example
15362:
15363: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15364: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15365:
15366: @menu
15367: * Scheduling::
15368: * Direct or Indirect Threaded?::
1.109 anton 15369: * Dynamic Superinstructions::
1.1 anton 15370: * DOES>::
15371: @end menu
15372:
15373: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15374: @subsection Scheduling
15375: @cindex inner interpreter optimization
15376:
15377: There is a little complication: Pipelined and superscalar processors,
15378: i.e., RISC and some modern CISC machines can process independent
15379: instructions while waiting for the results of an instruction. The
15380: compiler usually reorders (schedules) the instructions in a way that
15381: achieves good usage of these delay slots. However, on our first tries
15382: the compiler did not do well on scheduling primitives. E.g., for
15383: @code{+} implemented as
15384: @example
15385: n=sp[0]+sp[1];
15386: sp++;
15387: sp[0]=n;
15388: NEXT;
15389: @end example
1.81 anton 15390: the @code{NEXT} comes strictly after the other code, i.e., there is
15391: nearly no scheduling. After a little thought the problem becomes clear:
15392: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15393: addresses (and the version of @code{gcc} we used would not know it even
15394: if it was possible), so it could not move the load of the cfa above the
15395: store to the TOS. Indeed the pointers could be the same, if code on or
15396: very near the top of stack were executed. In the interest of speed we
15397: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15398: in scheduling: @code{NEXT} is divided into several parts:
15399: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15400: like:
1.1 anton 15401: @example
1.81 anton 15402: NEXT_P0;
1.1 anton 15403: n=sp[0]+sp[1];
15404: sp++;
15405: NEXT_P1;
15406: sp[0]=n;
15407: NEXT_P2;
15408: @end example
15409:
1.81 anton 15410: There are various schemes that distribute the different operations of
15411: NEXT between these parts in several ways; in general, different schemes
15412: perform best on different processors. We use a scheme for most
15413: architectures that performs well for most processors of this
1.109 anton 15414: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15415: the scheme on installation time.
15416:
1.1 anton 15417:
1.109 anton 15418: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15419: @subsection Direct or Indirect Threaded?
15420: @cindex threading, direct or indirect?
15421:
1.109 anton 15422: Threaded forth code consists of references to primitives (simple machine
15423: code routines like @code{+}) and to non-primitives (e.g., colon
15424: definitions, variables, constants); for a specific class of
15425: non-primitives (e.g., variables) there is one code routine (e.g.,
15426: @code{dovar}), but each variable needs a separate reference to its data.
15427:
15428: Traditionally Forth has been implemented as indirect threaded code,
15429: because this allows to use only one cell to reference a non-primitive
15430: (basically you point to the data, and find the code address there).
15431:
15432: @cindex primitive-centric threaded code
15433: However, threaded code in Gforth (since 0.6.0) uses two cells for
15434: non-primitives, one for the code address, and one for the data address;
15435: the data pointer is an immediate argument for the virtual machine
15436: instruction represented by the code address. We call this
15437: @emph{primitive-centric} threaded code, because all code addresses point
15438: to simple primitives. E.g., for a variable, the code address is for
15439: @code{lit} (also used for integer literals like @code{99}).
15440:
15441: Primitive-centric threaded code allows us to use (faster) direct
15442: threading as dispatch method, completely portably (direct threaded code
15443: in Gforth before 0.6.0 required architecture-specific code). It also
15444: eliminates the performance problems related to I-cache consistency that
15445: 386 implementations have with direct threaded code, and allows
15446: additional optimizations.
15447:
15448: @cindex hybrid direct/indirect threaded code
15449: There is a catch, however: the @var{xt} parameter of @code{execute} can
15450: occupy only one cell, so how do we pass non-primitives with their code
15451: @emph{and} data addresses to them? Our answer is to use indirect
15452: threaded dispatch for @code{execute} and other words that use a
15453: single-cell xt. So, normal threaded code in colon definitions uses
15454: direct threading, and @code{execute} and similar words, which dispatch
15455: to xts on the data stack, use indirect threaded code. We call this
15456: @emph{hybrid direct/indirect} threaded code.
15457:
15458: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15459: @cindex gforth engine
15460: @cindex gforth-fast engine
15461: The engines @command{gforth} and @command{gforth-fast} use hybrid
15462: direct/indirect threaded code. This means that with these engines you
15463: cannot use @code{,} to compile an xt. Instead, you have to use
15464: @code{compile,}.
15465:
15466: @cindex gforth-itc engine
1.115 anton 15467: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15468: This engine uses plain old indirect threaded code. It still compiles in
15469: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15470: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15471: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15472: and execute @code{' , is compile,}. Your program can check if it is
15473: running on a hybrid direct/indirect threaded engine or a pure indirect
15474: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15475:
15476:
15477: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15478: @subsection Dynamic Superinstructions
15479: @cindex Dynamic superinstructions with replication
15480: @cindex Superinstructions
15481: @cindex Replication
15482:
15483: The engines @command{gforth} and @command{gforth-fast} use another
15484: optimization: Dynamic superinstructions with replication. As an
15485: example, consider the following colon definition:
15486:
15487: @example
15488: : squared ( n1 -- n2 )
15489: dup * ;
15490: @end example
15491:
15492: Gforth compiles this into the threaded code sequence
15493:
15494: @example
15495: dup
15496: *
15497: ;s
15498: @end example
15499:
15500: In normal direct threaded code there is a code address occupying one
15501: cell for each of these primitives. Each code address points to a
15502: machine code routine, and the interpreter jumps to this machine code in
15503: order to execute the primitive. The routines for these three
15504: primitives are (in @command{gforth-fast} on the 386):
15505:
15506: @example
15507: Code dup
15508: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15509: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15510: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15511: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15512: end-code
15513: Code *
15514: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15515: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15516: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15517: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15518: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15519: end-code
15520: Code ;s
15521: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15522: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15523: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15524: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15525: end-code
15526: @end example
15527:
15528: With dynamic superinstructions and replication the compiler does not
15529: just lay down the threaded code, but also copies the machine code
15530: fragments, usually without the jump at the end.
15531:
15532: @example
15533: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15534: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15535: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15536: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15537: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15538: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15539: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15540: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15541: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15542: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15543: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15544: @end example
15545:
15546: Only when a threaded-code control-flow change happens (e.g., in
15547: @code{;s}), the jump is appended. This optimization eliminates many of
15548: these jumps and makes the rest much more predictable. The speedup
15549: depends on the processor and the application; on the Athlon and Pentium
15550: III this optimization typically produces a speedup by a factor of 2.
15551:
15552: The code addresses in the direct-threaded code are set to point to the
15553: appropriate points in the copied machine code, in this example like
15554: this:
1.1 anton 15555:
1.109 anton 15556: @example
15557: primitive code address
15558: dup $4057D27D
15559: * $4057D286
15560: ;s $4057D292
15561: @end example
15562:
15563: Thus there can be threaded-code jumps to any place in this piece of
15564: code. This also simplifies decompilation quite a bit.
15565:
15566: @cindex --no-dynamic command-line option
15567: @cindex --no-super command-line option
15568: You can disable this optimization with @option{--no-dynamic}. You can
15569: use the copying without eliminating the jumps (i.e., dynamic
15570: replication, but without superinstructions) with @option{--no-super};
15571: this gives the branch prediction benefit alone; the effect on
1.110 anton 15572: performance depends on the CPU; on the Athlon and Pentium III the
15573: speedup is a little less than for dynamic superinstructions with
15574: replication.
15575:
15576: @cindex patching threaded code
15577: One use of these options is if you want to patch the threaded code.
15578: With superinstructions, many of the dispatch jumps are eliminated, so
15579: patching often has no effect. These options preserve all the dispatch
15580: jumps.
1.109 anton 15581:
15582: @cindex --dynamic command-line option
1.110 anton 15583: On some machines dynamic superinstructions are disabled by default,
15584: because it is unsafe on these machines. However, if you feel
15585: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15586:
15587: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15588: @subsection DOES>
15589: @cindex @code{DOES>} implementation
15590:
1.26 crook 15591: @cindex @code{dodoes} routine
15592: @cindex @code{DOES>}-code
1.1 anton 15593: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15594: the chunk of code executed by every word defined by a
1.109 anton 15595: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15596: this is only needed if the xt of the word is @code{execute}d. The main
15597: problem here is: How to find the Forth code to be executed, i.e. the
15598: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15599: solutions:
1.1 anton 15600:
1.21 crook 15601: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15602: @code{DOES>}-code address is stored in the cell after the code address
15603: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15604: illegal in the Forth-79 and all later standards, because in fig-Forth
15605: this address lies in the body (which is illegal in these
15606: standards). However, by making the code field larger for all words this
15607: solution becomes legal again. We use this approach. Leaving a cell
15608: unused in most words is a bit wasteful, but on the machines we are
15609: targeting this is hardly a problem.
15610:
1.1 anton 15611:
15612: @node Primitives, Performance, Threading, Engine
15613: @section Primitives
15614: @cindex primitives, implementation
15615: @cindex virtual machine instructions, implementation
15616:
15617: @menu
15618: * Automatic Generation::
15619: * TOS Optimization::
15620: * Produced code::
15621: @end menu
15622:
15623: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15624: @subsection Automatic Generation
15625: @cindex primitives, automatic generation
15626:
15627: @cindex @file{prims2x.fs}
1.109 anton 15628:
1.1 anton 15629: Since the primitives are implemented in a portable language, there is no
15630: longer any need to minimize the number of primitives. On the contrary,
15631: having many primitives has an advantage: speed. In order to reduce the
15632: number of errors in primitives and to make programming them easier, we
1.109 anton 15633: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15634: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15635: generates most (and sometimes all) of the C code for a primitive from
15636: the stack effect notation. The source for a primitive has the following
15637: form:
1.1 anton 15638:
15639: @cindex primitive source format
15640: @format
1.58 anton 15641: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15642: [@code{""}@i{glossary entry}@code{""}]
15643: @i{C code}
1.1 anton 15644: [@code{:}
1.29 crook 15645: @i{Forth code}]
1.1 anton 15646: @end format
15647:
15648: The items in brackets are optional. The category and glossary fields
15649: are there for generating the documentation, the Forth code is there
15650: for manual implementations on machines without GNU C. E.g., the source
15651: for the primitive @code{+} is:
15652: @example
1.58 anton 15653: + ( n1 n2 -- n ) core plus
1.1 anton 15654: n = n1+n2;
15655: @end example
15656:
15657: This looks like a specification, but in fact @code{n = n1+n2} is C
15658: code. Our primitive generation tool extracts a lot of information from
15659: the stack effect notations@footnote{We use a one-stack notation, even
15660: though we have separate data and floating-point stacks; The separate
15661: notation can be generated easily from the unified notation.}: The number
15662: of items popped from and pushed on the stack, their type, and by what
15663: name they are referred to in the C code. It then generates a C code
15664: prelude and postlude for each primitive. The final C code for @code{+}
15665: looks like this:
15666:
15667: @example
1.46 pazsan 15668: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15669: /* */ /* documentation */
1.81 anton 15670: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15671: @{
15672: DEF_CA /* definition of variable ca (indirect threading) */
15673: Cell n1; /* definitions of variables */
15674: Cell n2;
15675: Cell n;
1.81 anton 15676: NEXT_P0; /* NEXT part 0 */
1.1 anton 15677: n1 = (Cell) sp[1]; /* input */
15678: n2 = (Cell) TOS;
15679: sp += 1; /* stack adjustment */
15680: @{
15681: n = n1+n2; /* C code taken from the source */
15682: @}
15683: NEXT_P1; /* NEXT part 1 */
15684: TOS = (Cell)n; /* output */
15685: NEXT_P2; /* NEXT part 2 */
15686: @}
15687: @end example
15688:
15689: This looks long and inefficient, but the GNU C compiler optimizes quite
15690: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15691: HP RISC machines: Defining the @code{n}s does not produce any code, and
15692: using them as intermediate storage also adds no cost.
15693:
1.26 crook 15694: There are also other optimizations that are not illustrated by this
15695: example: assignments between simple variables are usually for free (copy
1.1 anton 15696: propagation). If one of the stack items is not used by the primitive
15697: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15698: (dead code elimination). On the other hand, there are some things that
15699: the compiler does not do, therefore they are performed by
15700: @file{prims2x.fs}: The compiler does not optimize code away that stores
15701: a stack item to the place where it just came from (e.g., @code{over}).
15702:
15703: While programming a primitive is usually easy, there are a few cases
15704: where the programmer has to take the actions of the generator into
15705: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15706: fall through to @code{NEXT}.
1.109 anton 15707:
15708: For more information
1.1 anton 15709:
15710: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15711: @subsection TOS Optimization
15712: @cindex TOS optimization for primitives
15713: @cindex primitives, keeping the TOS in a register
15714:
15715: An important optimization for stack machine emulators, e.g., Forth
15716: engines, is keeping one or more of the top stack items in
1.29 crook 15717: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15718: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15719: @itemize @bullet
15720: @item
1.29 crook 15721: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15722: due to fewer loads from and stores to the stack.
1.29 crook 15723: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15724: @i{y<n}, due to additional moves between registers.
1.1 anton 15725: @end itemize
15726:
15727: @cindex -DUSE_TOS
15728: @cindex -DUSE_NO_TOS
15729: In particular, keeping one item in a register is never a disadvantage,
15730: if there are enough registers. Keeping two items in registers is a
15731: disadvantage for frequent words like @code{?branch}, constants,
15732: variables, literals and @code{i}. Therefore our generator only produces
15733: code that keeps zero or one items in registers. The generated C code
15734: covers both cases; the selection between these alternatives is made at
15735: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15736: code for @code{+} is just a simple variable name in the one-item case,
15737: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15738: GNU C compiler tries to keep simple variables like @code{TOS} in
15739: registers, and it usually succeeds, if there are enough registers.
15740:
15741: @cindex -DUSE_FTOS
15742: @cindex -DUSE_NO_FTOS
15743: The primitive generator performs the TOS optimization for the
15744: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15745: operations the benefit of this optimization is even larger:
15746: floating-point operations take quite long on most processors, but can be
15747: performed in parallel with other operations as long as their results are
15748: not used. If the FP-TOS is kept in a register, this works. If
15749: it is kept on the stack, i.e., in memory, the store into memory has to
15750: wait for the result of the floating-point operation, lengthening the
15751: execution time of the primitive considerably.
15752:
15753: The TOS optimization makes the automatic generation of primitives a
15754: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15755: @code{TOS} is not sufficient. There are some special cases to
15756: consider:
15757: @itemize @bullet
15758: @item In the case of @code{dup ( w -- w w )} the generator must not
15759: eliminate the store to the original location of the item on the stack,
15760: if the TOS optimization is turned on.
15761: @item Primitives with stack effects of the form @code{--}
1.29 crook 15762: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15763: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15764: must load the TOS from the stack at the end. But for the null stack
15765: effect @code{--} no stores or loads should be generated.
15766: @end itemize
15767:
15768: @node Produced code, , TOS Optimization, Primitives
15769: @subsection Produced code
15770: @cindex primitives, assembly code listing
15771:
15772: @cindex @file{engine.s}
15773: To see what assembly code is produced for the primitives on your machine
15774: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15775: look at the resulting file @file{engine.s}. Alternatively, you can also
15776: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15777:
15778: @node Performance, , Primitives, Engine
15779: @section Performance
15780: @cindex performance of some Forth interpreters
15781: @cindex engine performance
15782: @cindex benchmarking Forth systems
15783: @cindex Gforth performance
15784:
15785: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15786: impossible to write a significantly faster threaded-code engine.
1.1 anton 15787:
15788: On register-starved machines like the 386 architecture processors
15789: improvements are possible, because @code{gcc} does not utilize the
15790: registers as well as a human, even with explicit register declarations;
15791: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15792: and hand-tuned it for the 486; this system is 1.19 times faster on the
15793: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15794: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15795: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15796: registers fit in real registers (and we can even afford to use the TOS
15797: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15798: earlier results. And dynamic superinstructions provide another speedup
15799: (but only around a factor 1.2 on the 486).
1.1 anton 15800:
15801: @cindex Win32Forth performance
15802: @cindex NT Forth performance
15803: @cindex eforth performance
15804: @cindex ThisForth performance
15805: @cindex PFE performance
15806: @cindex TILE performance
1.81 anton 15807: The potential advantage of assembly language implementations is not
1.112 anton 15808: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15809: (direct threaded, compiled with @code{gcc-2.95.1} and
15810: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15811: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15812: (with and without peephole (aka pinhole) optimization of the threaded
15813: code); all these systems were written in assembly language. We also
15814: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15815: with @code{gcc-2.6.3} with the default configuration for Linux:
15816: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15817: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15818: employs peephole optimization of the threaded code) and TILE (compiled
15819: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15820: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15821: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15822: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15823: then extended it to run the benchmarks, added the peephole optimizer,
15824: ran the benchmarks and reported the results.
1.40 anton 15825:
1.1 anton 15826: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15827: matrix multiplication come from the Stanford integer benchmarks and have
15828: been translated into Forth by Martin Fraeman; we used the versions
15829: included in the TILE Forth package, but with bigger data set sizes; and
15830: a recursive Fibonacci number computation for benchmarking calling
15831: performance. The following table shows the time taken for the benchmarks
15832: scaled by the time taken by Gforth (in other words, it shows the speedup
15833: factor that Gforth achieved over the other systems).
15834:
15835: @example
1.112 anton 15836: relative Win32- NT eforth This-
15837: time Gforth Forth Forth eforth +opt PFE Forth TILE
15838: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15839: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15840: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15841: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15842: @end example
15843:
1.26 crook 15844: You may be quite surprised by the good performance of Gforth when
15845: compared with systems written in assembly language. One important reason
15846: for the disappointing performance of these other systems is probably
15847: that they are not written optimally for the 486 (e.g., they use the
15848: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15849: but costly method for relocating the Forth image: like @code{cforth}, it
15850: computes the actual addresses at run time, resulting in two address
15851: computations per @code{NEXT} (@pxref{Image File Background}).
15852:
1.1 anton 15853: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15854: explained with the self-imposed restriction of the latter systems to
15855: standard C, which makes efficient threading impossible (however, the
1.4 anton 15856: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15857: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15858: Moreover, current C compilers have a hard time optimizing other aspects
15859: of the ThisForth and the TILE source.
15860:
1.26 crook 15861: The performance of Gforth on 386 architecture processors varies widely
15862: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15863: allocate any of the virtual machine registers into real machine
15864: registers by itself and would not work correctly with explicit register
1.112 anton 15865: declarations, giving a significantly slower engine (on a 486DX2/66
15866: running the Sieve) than the one measured above.
1.1 anton 15867:
1.26 crook 15868: Note that there have been several releases of Win32Forth since the
15869: release presented here, so the results presented above may have little
1.40 anton 15870: predictive value for the performance of Win32Forth today (results for
15871: the current release on an i486DX2/66 are welcome).
1.1 anton 15872:
15873: @cindex @file{Benchres}
1.66 anton 15874: In
15875: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15876: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15877: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15878: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15879: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15880: than the version used here. You can find a newer version of these
15881: measurements at
1.47 crook 15882: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15883: find numbers for Gforth on various machines in @file{Benchres}.
15884:
1.26 crook 15885: @c ******************************************************************
1.113 anton 15886: @c @node Binding to System Library, Cross Compiler, Engine, Top
15887: @c @chapter Binding to System Library
1.13 pazsan 15888:
1.113 anton 15889: @c ****************************************************************
15890: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15891: @chapter Cross Compiler
1.47 crook 15892: @cindex @file{cross.fs}
15893: @cindex cross-compiler
15894: @cindex metacompiler
15895: @cindex target compiler
1.13 pazsan 15896:
1.46 pazsan 15897: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15898: mostly written in Forth, including crucial parts like the outer
15899: interpreter and compiler, it needs compiled Forth code to get
15900: started. The cross compiler allows to create new images for other
15901: architectures, even running under another Forth system.
1.13 pazsan 15902:
15903: @menu
1.67 anton 15904: * Using the Cross Compiler::
15905: * How the Cross Compiler Works::
1.13 pazsan 15906: @end menu
15907:
1.21 crook 15908: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15909: @section Using the Cross Compiler
1.46 pazsan 15910:
15911: The cross compiler uses a language that resembles Forth, but isn't. The
15912: main difference is that you can execute Forth code after definition,
15913: while you usually can't execute the code compiled by cross, because the
15914: code you are compiling is typically for a different computer than the
15915: one you are compiling on.
15916:
1.81 anton 15917: @c anton: This chapter is somewhat different from waht I would expect: I
15918: @c would expect an explanation of the cross language and how to create an
15919: @c application image with it. The section explains some aspects of
15920: @c creating a Gforth kernel.
15921:
1.46 pazsan 15922: The Makefile is already set up to allow you to create kernels for new
15923: architectures with a simple make command. The generic kernels using the
15924: GCC compiled virtual machine are created in the normal build process
15925: with @code{make}. To create a embedded Gforth executable for e.g. the
15926: 8086 processor (running on a DOS machine), type
15927:
15928: @example
15929: make kernl-8086.fi
15930: @end example
15931:
15932: This will use the machine description from the @file{arch/8086}
15933: directory to create a new kernel. A machine file may look like that:
15934:
15935: @example
15936: \ Parameter for target systems 06oct92py
15937:
15938: 4 Constant cell \ cell size in bytes
15939: 2 Constant cell<< \ cell shift to bytes
15940: 5 Constant cell>bit \ cell shift to bits
15941: 8 Constant bits/char \ bits per character
15942: 8 Constant bits/byte \ bits per byte [default: 8]
15943: 8 Constant float \ bytes per float
15944: 8 Constant /maxalign \ maximum alignment in bytes
15945: false Constant bigendian \ byte order
15946: ( true=big, false=little )
15947:
15948: include machpc.fs \ feature list
15949: @end example
15950:
15951: This part is obligatory for the cross compiler itself, the feature list
15952: is used by the kernel to conditionally compile some features in and out,
15953: depending on whether the target supports these features.
15954:
15955: There are some optional features, if you define your own primitives,
15956: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15957: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15958: @code{prims-include} includes primitives, and @code{>boot} prepares for
15959: booting.
15960:
15961: @example
15962: : asm-include ." Include assembler" cr
15963: s" arch/8086/asm.fs" included ;
15964:
15965: : prims-include ." Include primitives" cr
15966: s" arch/8086/prim.fs" included ;
15967:
15968: : >boot ." Prepare booting" cr
15969: s" ' boot >body into-forth 1+ !" evaluate ;
15970: @end example
15971:
15972: These words are used as sort of macro during the cross compilation in
1.81 anton 15973: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15974: be possible --- but more complicated --- to write a new kernel project
15975: file, too.
15976:
15977: @file{kernel/main.fs} expects the machine description file name on the
15978: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15979: @code{mach-file} leaves a counted string on the stack, or
15980: @code{machine-file} leaves an address, count pair of the filename on the
15981: stack.
15982:
15983: The feature list is typically controlled using @code{SetValue}, generic
15984: files that are used by several projects can use @code{DefaultValue}
15985: instead. Both functions work like @code{Value}, when the value isn't
15986: defined, but @code{SetValue} works like @code{to} if the value is
15987: defined, and @code{DefaultValue} doesn't set anything, if the value is
15988: defined.
15989:
15990: @example
15991: \ generic mach file for pc gforth 03sep97jaw
15992:
15993: true DefaultValue NIL \ relocating
15994:
15995: >ENVIRON
15996:
15997: true DefaultValue file \ controls the presence of the
15998: \ file access wordset
15999: true DefaultValue OS \ flag to indicate a operating system
16000:
16001: true DefaultValue prims \ true: primitives are c-code
16002:
16003: true DefaultValue floating \ floating point wordset is present
16004:
16005: true DefaultValue glocals \ gforth locals are present
16006: \ will be loaded
16007: true DefaultValue dcomps \ double number comparisons
16008:
16009: true DefaultValue hash \ hashing primitives are loaded/present
16010:
16011: true DefaultValue xconds \ used together with glocals,
16012: \ special conditionals supporting gforths'
16013: \ local variables
16014: true DefaultValue header \ save a header information
16015:
16016: true DefaultValue backtrace \ enables backtrace code
16017:
16018: false DefaultValue ec
16019: false DefaultValue crlf
16020:
16021: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16022:
16023: &16 KB DefaultValue stack-size
16024: &15 KB &512 + DefaultValue fstack-size
16025: &15 KB DefaultValue rstack-size
16026: &14 KB &512 + DefaultValue lstack-size
16027: @end example
1.13 pazsan 16028:
1.48 anton 16029: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16030: @section How the Cross Compiler Works
1.13 pazsan 16031:
16032: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16033: @appendix Bugs
1.1 anton 16034: @cindex bug reporting
16035:
1.21 crook 16036: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16037:
1.103 anton 16038: If you find a bug, please submit a bug report through
16039: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16040:
16041: @itemize @bullet
16042: @item
1.81 anton 16043: A program (or a sequence of keyboard commands) that reproduces the bug.
16044: @item
16045: A description of what you think constitutes the buggy behaviour.
16046: @item
1.21 crook 16047: The Gforth version used (it is announced at the start of an
16048: interactive Gforth session).
16049: @item
16050: The machine and operating system (on Unix
16051: systems @code{uname -a} will report this information).
16052: @item
1.81 anton 16053: The installation options (you can find the configure options at the
16054: start of @file{config.status}) and configuration (@code{configure}
16055: output or @file{config.cache}).
1.21 crook 16056: @item
16057: A complete list of changes (if any) you (or your installer) have made to the
16058: Gforth sources.
16059: @end itemize
1.1 anton 16060:
16061: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16062: to Report Bugs, gcc.info, GNU C Manual}.
16063:
16064:
1.21 crook 16065: @node Origin, Forth-related information, Bugs, Top
16066: @appendix Authors and Ancestors of Gforth
1.1 anton 16067:
16068: @section Authors and Contributors
16069: @cindex authors of Gforth
16070: @cindex contributors to Gforth
16071:
16072: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16073: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16074: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16075: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16076: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16077: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16078: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16079: working on automatic support for calling C libraries. Helpful comments
16080: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16081: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16082: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16083: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16084: comments from many others; thank you all, sorry for not listing you
16085: here (but digging through my mailbox to extract your names is on my
16086: to-do list).
1.1 anton 16087:
16088: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16089: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16090: was developed across the Internet, and its authors did not meet
1.20 pazsan 16091: physically for the first 4 years of development.
1.1 anton 16092:
16093: @section Pedigree
1.26 crook 16094: @cindex pedigree of Gforth
1.1 anton 16095:
1.81 anton 16096: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16097: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16098:
1.20 pazsan 16099: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16100: 32 bit native code version of VolksForth for the Atari ST, written
16101: mostly by Dietrich Weineck.
16102:
1.81 anton 16103: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16104: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16105: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16106:
1.147 anton 16107: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16108: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16109:
16110: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16111: 1979. Robert Selzer and Bill Ragsdale developed the original
16112: implementation of fig-Forth for the 6502 based on microForth.
16113:
16114: The principal architect of microForth was Dean Sanderson. microForth was
16115: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16116: the 1802, and subsequently implemented on the 8080, the 6800 and the
16117: Z80.
16118:
16119: All earlier Forth systems were custom-made, usually by Charles Moore,
16120: who discovered (as he puts it) Forth during the late 60s. The first full
16121: Forth existed in 1971.
16122:
1.81 anton 16123: A part of the information in this section comes from
16124: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16125: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16126: Charles H. Moore, presented at the HOPL-II conference and preprinted
16127: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16128: genealogical information about Forth there. For a more general (and
16129: graphical) Forth family tree look see
16130: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16131: Forth Family Tree and Timeline}.
1.1 anton 16132:
1.81 anton 16133: @c ------------------------------------------------------------------
1.113 anton 16134: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16135: @appendix Other Forth-related information
16136: @cindex Forth-related information
16137:
1.81 anton 16138: @c anton: I threw most of this stuff out, because it can be found through
16139: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16140:
16141: @cindex comp.lang.forth
16142: @cindex frequently asked questions
1.81 anton 16143: There is an active news group (comp.lang.forth) discussing Forth
16144: (including Gforth) and Forth-related issues. Its
16145: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16146: (frequently asked questions and their answers) contains a lot of
16147: information on Forth. You should read it before posting to
16148: comp.lang.forth.
1.21 crook 16149:
1.81 anton 16150: The ANS Forth standard is most usable in its
16151: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16152:
1.113 anton 16153: @c ---------------------------------------------------
16154: @node Licenses, Word Index, Forth-related information, Top
16155: @appendix Licenses
16156:
16157: @menu
16158: * GNU Free Documentation License:: License for copying this manual.
1.192 ! anton 16159: * Copying:: GPL (for copying this software).
1.113 anton 16160: @end menu
16161:
1.192 ! anton 16162: @node GNU Free Documentation License, Copying, Licenses, Licenses
! 16163: @appendixsec GNU Free Documentation License
1.113 anton 16164: @include fdl.texi
16165:
1.192 ! anton 16166: @node Copying, , GNU Free Documentation License, Licenses
! 16167: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16168: @include gpl.texi
16169:
16170:
16171:
1.81 anton 16172: @c ------------------------------------------------------------------
1.113 anton 16173: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16174: @unnumbered Word Index
16175:
1.26 crook 16176: This index is a list of Forth words that have ``glossary'' entries
16177: within this manual. Each word is listed with its stack effect and
16178: wordset.
1.1 anton 16179:
16180: @printindex fn
16181:
1.81 anton 16182: @c anton: the name index seems superfluous given the word and concept indices.
16183:
16184: @c @node Name Index, Concept Index, Word Index, Top
16185: @c @unnumbered Name Index
1.41 anton 16186:
1.81 anton 16187: @c This index is a list of Forth words that have ``glossary'' entries
16188: @c within this manual.
1.41 anton 16189:
1.81 anton 16190: @c @printindex ky
1.41 anton 16191:
1.113 anton 16192: @c -------------------------------------------------------
1.81 anton 16193: @node Concept Index, , Word Index, Top
1.1 anton 16194: @unnumbered Concept and Word Index
16195:
1.26 crook 16196: Not all entries listed in this index are present verbatim in the
16197: text. This index also duplicates, in abbreviated form, all of the words
16198: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16199:
16200: @printindex cp
16201:
16202: @bye
1.81 anton 16203:
16204:
1.1 anton 16205:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>