Annotation of gforth/doc/gforth.ds, revision 1.230
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.230 ! anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008,2009,2010 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.204 anton 148: * Startup speed:: When 14ms is not fast enough ...
1.48 anton 149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.190 anton 177: * Floating Point Tutorial::
1.87 anton 178: * Files Tutorial::
1.48 anton 179: * Interpretation and Compilation Semantics and Immediacy Tutorial::
180: * Execution Tokens Tutorial::
181: * Exceptions Tutorial::
182: * Defining Words Tutorial::
183: * Arrays and Records Tutorial::
184: * POSTPONE Tutorial::
185: * Literal Tutorial::
186: * Advanced macros Tutorial::
187: * Compilation Tokens Tutorial::
188: * Wordlists and Search Order Tutorial::
1.29 crook 189:
1.24 anton 190: An Introduction to ANS Forth
191:
1.67 anton 192: * Introducing the Text Interpreter::
193: * Stacks and Postfix notation::
194: * Your first definition::
195: * How does that work?::
196: * Forth is written in Forth::
197: * Review - elements of a Forth system::
198: * Where to go next::
199: * Exercises::
1.24 anton 200:
1.12 anton 201: Forth Words
202:
203: * Notation::
1.65 anton 204: * Case insensitivity::
205: * Comments::
206: * Boolean Flags::
1.12 anton 207: * Arithmetic::
208: * Stack Manipulation::
209: * Memory::
210: * Control Structures::
211: * Defining Words::
1.65 anton 212: * Interpretation and Compilation Semantics::
1.47 crook 213: * Tokens for Words::
1.81 anton 214: * Compiling words::
1.65 anton 215: * The Text Interpreter::
1.111 anton 216: * The Input Stream::
1.65 anton 217: * Word Lists::
218: * Environmental Queries::
1.12 anton 219: * Files::
220: * Blocks::
221: * Other I/O::
1.121 anton 222: * OS command line arguments::
1.78 anton 223: * Locals::
224: * Structures::
225: * Object-oriented Forth::
1.12 anton 226: * Programming Tools::
1.150 anton 227: * C Interface::
1.12 anton 228: * Assembler and Code Words::
229: * Threading Words::
1.65 anton 230: * Passing Commands to the OS::
231: * Keeping track of Time::
232: * Miscellaneous Words::
1.12 anton 233:
234: Arithmetic
235:
236: * Single precision::
1.67 anton 237: * Double precision:: Double-cell integer arithmetic
1.12 anton 238: * Bitwise operations::
1.67 anton 239: * Numeric comparison::
1.32 anton 240: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 241: * Floating Point::
242:
243: Stack Manipulation
244:
245: * Data stack::
246: * Floating point stack::
247: * Return stack::
248: * Locals stack::
249: * Stack pointer manipulation::
250:
251: Memory
252:
1.32 anton 253: * Memory model::
254: * Dictionary allocation::
255: * Heap Allocation::
256: * Memory Access::
257: * Address arithmetic::
258: * Memory Blocks::
1.12 anton 259:
260: Control Structures
261:
1.41 anton 262: * Selection:: IF ... ELSE ... ENDIF
263: * Simple Loops:: BEGIN ...
1.32 anton 264: * Counted Loops:: DO
1.67 anton 265: * Arbitrary control structures::
266: * Calls and returns::
1.12 anton 267: * Exception Handling::
268:
269: Defining Words
270:
1.67 anton 271: * CREATE::
1.44 crook 272: * Variables:: Variables and user variables
1.67 anton 273: * Constants::
1.44 crook 274: * Values:: Initialised variables
1.67 anton 275: * Colon Definitions::
1.44 crook 276: * Anonymous Definitions:: Definitions without names
1.71 anton 277: * Supplying names:: Passing definition names as strings
1.67 anton 278: * User-defined Defining Words::
1.170 pazsan 279: * Deferred Words:: Allow forward references
1.67 anton 280: * Aliases::
1.47 crook 281:
1.63 anton 282: User-defined Defining Words
283:
284: * CREATE..DOES> applications::
285: * CREATE..DOES> details::
286: * Advanced does> usage example::
1.155 anton 287: * Const-does>::
1.63 anton 288:
1.47 crook 289: Interpretation and Compilation Semantics
290:
1.67 anton 291: * Combined words::
1.12 anton 292:
1.71 anton 293: Tokens for Words
294:
295: * Execution token:: represents execution/interpretation semantics
296: * Compilation token:: represents compilation semantics
297: * Name token:: represents named words
298:
1.82 anton 299: Compiling words
300:
301: * Literals:: Compiling data values
302: * Macros:: Compiling words
303:
1.21 crook 304: The Text Interpreter
305:
1.67 anton 306: * Input Sources::
307: * Number Conversion::
308: * Interpret/Compile states::
309: * Interpreter Directives::
1.21 crook 310:
1.26 crook 311: Word Lists
312:
1.75 anton 313: * Vocabularies::
1.67 anton 314: * Why use word lists?::
1.75 anton 315: * Word list example::
1.26 crook 316:
317: Files
318:
1.48 anton 319: * Forth source files::
320: * General files::
1.167 anton 321: * Redirection::
1.48 anton 322: * Search Paths::
323:
324: Search Paths
325:
1.75 anton 326: * Source Search Paths::
1.26 crook 327: * General Search Paths::
328:
329: Other I/O
330:
1.32 anton 331: * Simple numeric output:: Predefined formats
332: * Formatted numeric output:: Formatted (pictured) output
333: * String Formats:: How Forth stores strings in memory
1.67 anton 334: * Displaying characters and strings:: Other stuff
1.178 anton 335: * Terminal output:: Cursor positioning etc.
1.181 anton 336: * Single-key input::
337: * Line input and conversion::
1.112 anton 338: * Pipes:: How to create your own pipes
1.149 pazsan 339: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 340:
341: Locals
342:
343: * Gforth locals::
344: * ANS Forth locals::
345:
346: Gforth locals
347:
348: * Where are locals visible by name?::
349: * How long do locals live?::
1.78 anton 350: * Locals programming style::
351: * Locals implementation::
1.26 crook 352:
1.12 anton 353: Structures
354:
355: * Why explicit structure support?::
356: * Structure Usage::
357: * Structure Naming Convention::
358: * Structure Implementation::
359: * Structure Glossary::
1.183 anton 360: * Forth200x Structures::
1.12 anton 361:
362: Object-oriented Forth
363:
1.48 anton 364: * Why object-oriented programming?::
365: * Object-Oriented Terminology::
366: * Objects::
367: * OOF::
368: * Mini-OOF::
1.23 crook 369: * Comparison with other object models::
1.12 anton 370:
1.24 anton 371: The @file{objects.fs} model
1.12 anton 372:
373: * Properties of the Objects model::
374: * Basic Objects Usage::
1.41 anton 375: * The Objects base class::
1.12 anton 376: * Creating objects::
377: * Object-Oriented Programming Style::
378: * Class Binding::
379: * Method conveniences::
380: * Classes and Scoping::
1.41 anton 381: * Dividing classes::
1.12 anton 382: * Object Interfaces::
383: * Objects Implementation::
384: * Objects Glossary::
385:
1.24 anton 386: The @file{oof.fs} model
1.12 anton 387:
1.67 anton 388: * Properties of the OOF model::
389: * Basic OOF Usage::
390: * The OOF base class::
391: * Class Declaration::
392: * Class Implementation::
1.12 anton 393:
1.24 anton 394: The @file{mini-oof.fs} model
1.23 crook 395:
1.48 anton 396: * Basic Mini-OOF Usage::
397: * Mini-OOF Example::
398: * Mini-OOF Implementation::
1.23 crook 399:
1.78 anton 400: Programming Tools
401:
1.150 anton 402: * Examining:: Data and Code.
403: * Forgetting words:: Usually before reloading.
1.78 anton 404: * Debugging:: Simple and quick.
405: * Assertions:: Making your programs self-checking.
406: * Singlestep Debugger:: Executing your program word by word.
407:
1.155 anton 408: C Interface
409:
410: * Calling C Functions::
411: * Declaring C Functions::
1.180 anton 412: * Calling C function pointers::
1.196 anton 413: * Defining library interfaces::
414: * Declaring OS-level libraries::
1.155 anton 415: * Callbacks::
1.178 anton 416: * C interface internals::
1.155 anton 417: * Low-Level C Interface Words::
418:
1.78 anton 419: Assembler and Code Words
420:
1.221 anton 421: * Assembler Definitions:: Definitions in assembly language
1.78 anton 422: * Common Assembler:: Assembler Syntax
423: * Common Disassembler::
424: * 386 Assembler:: Deviations and special cases
1.221 anton 425: * AMD64 Assembler::
1.78 anton 426: * Alpha Assembler:: Deviations and special cases
427: * MIPS assembler:: Deviations and special cases
1.167 anton 428: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 429: * ARM Assembler:: Deviations and special cases
1.78 anton 430: * Other assemblers:: How to write them
431:
1.12 anton 432: Tools
433:
434: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 435: * Stack depth changes:: Where does this stack item come from?
1.12 anton 436:
437: ANS conformance
438:
439: * The Core Words::
440: * The optional Block word set::
441: * The optional Double Number word set::
442: * The optional Exception word set::
443: * The optional Facility word set::
444: * The optional File-Access word set::
445: * The optional Floating-Point word set::
446: * The optional Locals word set::
447: * The optional Memory-Allocation word set::
448: * The optional Programming-Tools word set::
449: * The optional Search-Order word set::
450:
451: The Core Words
452:
453: * core-idef:: Implementation Defined Options
454: * core-ambcond:: Ambiguous Conditions
455: * core-other:: Other System Documentation
456:
457: The optional Block word set
458:
459: * block-idef:: Implementation Defined Options
460: * block-ambcond:: Ambiguous Conditions
461: * block-other:: Other System Documentation
462:
463: The optional Double Number word set
464:
465: * double-ambcond:: Ambiguous Conditions
466:
467: The optional Exception word set
468:
469: * exception-idef:: Implementation Defined Options
470:
471: The optional Facility word set
472:
473: * facility-idef:: Implementation Defined Options
474: * facility-ambcond:: Ambiguous Conditions
475:
476: The optional File-Access word set
477:
478: * file-idef:: Implementation Defined Options
479: * file-ambcond:: Ambiguous Conditions
480:
481: The optional Floating-Point word set
482:
483: * floating-idef:: Implementation Defined Options
484: * floating-ambcond:: Ambiguous Conditions
485:
486: The optional Locals word set
487:
488: * locals-idef:: Implementation Defined Options
489: * locals-ambcond:: Ambiguous Conditions
490:
491: The optional Memory-Allocation word set
492:
493: * memory-idef:: Implementation Defined Options
494:
495: The optional Programming-Tools word set
496:
497: * programming-idef:: Implementation Defined Options
498: * programming-ambcond:: Ambiguous Conditions
499:
500: The optional Search-Order word set
501:
502: * search-idef:: Implementation Defined Options
503: * search-ambcond:: Ambiguous Conditions
504:
1.109 anton 505: Emacs and Gforth
506:
507: * Installing gforth.el:: Making Emacs aware of Forth.
508: * Emacs Tags:: Viewing the source of a word in Emacs.
509: * Hilighting:: Making Forth code look prettier.
510: * Auto-Indentation:: Customizing auto-indentation.
511: * Blocks Files:: Reading and writing blocks files.
512:
1.12 anton 513: Image Files
514:
1.24 anton 515: * Image Licensing Issues:: Distribution terms for images.
516: * Image File Background:: Why have image files?
1.67 anton 517: * Non-Relocatable Image Files:: don't always work.
1.24 anton 518: * Data-Relocatable Image Files:: are better.
1.67 anton 519: * Fully Relocatable Image Files:: better yet.
1.24 anton 520: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 521: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 522: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 523:
524: Fully Relocatable Image Files
525:
1.27 crook 526: * gforthmi:: The normal way
1.12 anton 527: * cross.fs:: The hard way
528:
529: Engine
530:
531: * Portability::
532: * Threading::
533: * Primitives::
534: * Performance::
535:
536: Threading
537:
538: * Scheduling::
539: * Direct or Indirect Threaded?::
1.109 anton 540: * Dynamic Superinstructions::
1.12 anton 541: * DOES>::
542:
543: Primitives
544:
545: * Automatic Generation::
546: * TOS Optimization::
547: * Produced code::
1.13 pazsan 548:
549: Cross Compiler
550:
1.67 anton 551: * Using the Cross Compiler::
552: * How the Cross Compiler Works::
1.13 pazsan 553:
1.113 anton 554: Licenses
555:
556: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 557: * Copying:: GPL (for copying this software).
1.113 anton 558:
1.24 anton 559: @end detailmenu
1.1 anton 560: @end menu
561:
1.113 anton 562: @c ----------------------------------------------------------
1.1 anton 563: @iftex
564: @unnumbered Preface
565: @cindex Preface
1.21 crook 566: This manual documents Gforth. Some introductory material is provided for
567: readers who are unfamiliar with Forth or who are migrating to Gforth
568: from other Forth compilers. However, this manual is primarily a
569: reference manual.
1.1 anton 570: @end iftex
571:
1.28 crook 572: @comment TODO much more blurb here.
1.26 crook 573:
574: @c ******************************************************************
1.113 anton 575: @node Goals, Gforth Environment, Top, Top
1.26 crook 576: @comment node-name, next, previous, up
577: @chapter Goals of Gforth
578: @cindex goals of the Gforth project
579: The goal of the Gforth Project is to develop a standard model for
580: ANS Forth. This can be split into several subgoals:
581:
582: @itemize @bullet
583: @item
584: Gforth should conform to the ANS Forth Standard.
585: @item
586: It should be a model, i.e. it should define all the
587: implementation-dependent things.
588: @item
589: It should become standard, i.e. widely accepted and used. This goal
590: is the most difficult one.
591: @end itemize
592:
593: To achieve these goals Gforth should be
594: @itemize @bullet
595: @item
596: Similar to previous models (fig-Forth, F83)
597: @item
598: Powerful. It should provide for all the things that are considered
599: necessary today and even some that are not yet considered necessary.
600: @item
601: Efficient. It should not get the reputation of being exceptionally
602: slow.
603: @item
604: Free.
605: @item
606: Available on many machines/easy to port.
607: @end itemize
608:
609: Have we achieved these goals? Gforth conforms to the ANS Forth
610: standard. It may be considered a model, but we have not yet documented
611: which parts of the model are stable and which parts we are likely to
612: change. It certainly has not yet become a de facto standard, but it
613: appears to be quite popular. It has some similarities to and some
614: differences from previous models. It has some powerful features, but not
615: yet everything that we envisioned. We certainly have achieved our
1.65 anton 616: execution speed goals (@pxref{Performance})@footnote{However, in 1998
617: the bar was raised when the major commercial Forth vendors switched to
618: native code compilers.}. It is free and available on many machines.
1.29 crook 619:
1.26 crook 620: @c ******************************************************************
1.48 anton 621: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 622: @chapter Gforth Environment
623: @cindex Gforth environment
1.21 crook 624:
1.45 crook 625: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 626: material in this chapter.
1.21 crook 627:
628: @menu
1.29 crook 629: * Invoking Gforth:: Getting in
630: * Leaving Gforth:: Getting out
631: * Command-line editing::
1.48 anton 632: * Environment variables:: that affect how Gforth starts up
1.29 crook 633: * Gforth Files:: What gets installed and where
1.112 anton 634: * Gforth in pipes::
1.204 anton 635: * Startup speed:: When 14ms is not fast enough ...
1.21 crook 636: @end menu
637:
1.49 anton 638: For related information about the creation of images see @ref{Image Files}.
1.29 crook 639:
1.21 crook 640: @comment ----------------------------------------------
1.48 anton 641: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 642: @section Invoking Gforth
643: @cindex invoking Gforth
644: @cindex running Gforth
645: @cindex command-line options
646: @cindex options on the command line
647: @cindex flags on the command line
1.21 crook 648:
1.30 anton 649: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 650: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 651: will usually just say @code{gforth} -- this automatically loads the
652: default image file @file{gforth.fi}. In many other cases the default
653: Gforth image will be invoked like this:
1.21 crook 654: @example
1.30 anton 655: gforth [file | -e forth-code] ...
1.21 crook 656: @end example
1.29 crook 657: @noindent
658: This interprets the contents of the files and the Forth code in the order they
659: are given.
1.21 crook 660:
1.109 anton 661: In addition to the @command{gforth} engine, there is also an engine
662: called @command{gforth-fast}, which is faster, but gives less
663: informative error messages (@pxref{Error messages}) and may catch some
1.166 anton 664: errors (in particular, stack underflows and integer division errors)
665: later or not at all. You should use it for debugged,
1.109 anton 666: performance-critical programs.
667:
668: Moreover, there is an engine called @command{gforth-itc}, which is
669: useful in some backwards-compatibility situations (@pxref{Direct or
670: Indirect Threaded?}).
1.30 anton 671:
1.29 crook 672: In general, the command line looks like this:
1.21 crook 673:
674: @example
1.30 anton 675: gforth[-fast] [engine options] [image options]
1.21 crook 676: @end example
677:
1.30 anton 678: The engine options must come before the rest of the command
1.29 crook 679: line. They are:
1.26 crook 680:
1.29 crook 681: @table @code
682: @cindex -i, command-line option
683: @cindex --image-file, command-line option
684: @item --image-file @i{file}
685: @itemx -i @i{file}
686: Loads the Forth image @i{file} instead of the default
687: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 688:
1.39 anton 689: @cindex --appl-image, command-line option
690: @item --appl-image @i{file}
691: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 692: to the image (instead of processing them as engine options). This is
693: useful for building executable application images on Unix, built with
1.39 anton 694: @code{gforthmi --application ...}.
695:
1.29 crook 696: @cindex --path, command-line option
697: @cindex -p, command-line option
698: @item --path @i{path}
699: @itemx -p @i{path}
700: Uses @i{path} for searching the image file and Forth source code files
701: instead of the default in the environment variable @code{GFORTHPATH} or
702: the path specified at installation time (e.g.,
703: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
704: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 705:
1.29 crook 706: @cindex --dictionary-size, command-line option
707: @cindex -m, command-line option
708: @cindex @i{size} parameters for command-line options
709: @cindex size of the dictionary and the stacks
710: @item --dictionary-size @i{size}
711: @itemx -m @i{size}
712: Allocate @i{size} space for the Forth dictionary space instead of
713: using the default specified in the image (typically 256K). The
714: @i{size} specification for this and subsequent options consists of
715: an integer and a unit (e.g.,
716: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
717: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
718: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
719: @code{e} is used.
1.21 crook 720:
1.29 crook 721: @cindex --data-stack-size, command-line option
722: @cindex -d, command-line option
723: @item --data-stack-size @i{size}
724: @itemx -d @i{size}
725: Allocate @i{size} space for the data stack instead of using the
726: default specified in the image (typically 16K).
1.21 crook 727:
1.29 crook 728: @cindex --return-stack-size, command-line option
729: @cindex -r, command-line option
730: @item --return-stack-size @i{size}
731: @itemx -r @i{size}
732: Allocate @i{size} space for the return stack instead of using the
733: default specified in the image (typically 15K).
1.21 crook 734:
1.29 crook 735: @cindex --fp-stack-size, command-line option
736: @cindex -f, command-line option
737: @item --fp-stack-size @i{size}
738: @itemx -f @i{size}
739: Allocate @i{size} space for the floating point stack instead of
740: using the default specified in the image (typically 15.5K). In this case
741: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 742:
1.48 anton 743: @cindex --locals-stack-size, command-line option
744: @cindex -l, command-line option
745: @item --locals-stack-size @i{size}
746: @itemx -l @i{size}
747: Allocate @i{size} space for the locals stack instead of using the
748: default specified in the image (typically 14.5K).
749:
1.176 anton 750: @cindex --vm-commit, command-line option
751: @cindex overcommit memory for dictionary and stacks
752: @cindex memory overcommit for dictionary and stacks
753: @item --vm-commit
754: Normally, Gforth tries to start up even if there is not enough virtual
755: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
756: on OSs that support it); so you can ask for a really big dictionary
757: and/or stacks, and as long as you don't use more virtual memory than
758: is available, everything will be fine (but if you use more, processes
759: get killed). With this option you just use the default allocation
760: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
761: means that you cannot and should not ask for as big dictionary and
762: stacks, but once Gforth successfully starts up, out-of-memory won't
763: kill it.
764:
1.48 anton 765: @cindex -h, command-line option
766: @cindex --help, command-line option
767: @item --help
768: @itemx -h
769: Print a message about the command-line options
770:
771: @cindex -v, command-line option
772: @cindex --version, command-line option
773: @item --version
774: @itemx -v
775: Print version and exit
776:
777: @cindex --debug, command-line option
778: @item --debug
779: Print some information useful for debugging on startup.
780:
781: @cindex --offset-image, command-line option
782: @item --offset-image
783: Start the dictionary at a slightly different position than would be used
784: otherwise (useful for creating data-relocatable images,
785: @pxref{Data-Relocatable Image Files}).
786:
787: @cindex --no-offset-im, command-line option
788: @item --no-offset-im
789: Start the dictionary at the normal position.
790:
791: @cindex --clear-dictionary, command-line option
792: @item --clear-dictionary
793: Initialize all bytes in the dictionary to 0 before loading the image
794: (@pxref{Data-Relocatable Image Files}).
795:
796: @cindex --die-on-signal, command-line-option
797: @item --die-on-signal
798: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
799: or the segmentation violation SIGSEGV) by translating it into a Forth
800: @code{THROW}. With this option, Gforth exits if it receives such a
801: signal. This option is useful when the engine and/or the image might be
802: severely broken (such that it causes another signal before recovering
803: from the first); this option avoids endless loops in such cases.
1.109 anton 804:
1.119 anton 805: @cindex --no-dynamic, command-line option
806: @cindex --dynamic, command-line option
1.109 anton 807: @item --no-dynamic
808: @item --dynamic
809: Disable or enable dynamic superinstructions with replication
810: (@pxref{Dynamic Superinstructions}).
811:
1.119 anton 812: @cindex --no-super, command-line option
1.109 anton 813: @item --no-super
1.110 anton 814: Disable dynamic superinstructions, use just dynamic replication; this is
815: useful if you want to patch threaded code (@pxref{Dynamic
816: Superinstructions}).
1.119 anton 817:
818: @cindex --ss-number, command-line option
819: @item --ss-number=@var{N}
820: Use only the first @var{N} static superinstructions compiled into the
821: engine (default: use them all; note that only @code{gforth-fast} has
822: any). This option is useful for measuring the performance impact of
823: static superinstructions.
824:
825: @cindex --ss-min-..., command-line options
826: @item --ss-min-codesize
827: @item --ss-min-ls
828: @item --ss-min-lsu
829: @item --ss-min-nexts
830: Use specified metric for determining the cost of a primitive or static
831: superinstruction for static superinstruction selection. @code{Codesize}
832: is the native code size of the primive or static superinstruction,
833: @code{ls} is the number of loads and stores, @code{lsu} is the number of
834: loads, stores, and updates, and @code{nexts} is the number of dispatches
835: (not taking dynamic superinstructions into account), i.e. every
836: primitive or static superinstruction has cost 1. Default:
837: @code{codesize} if you use dynamic code generation, otherwise
838: @code{nexts}.
839:
840: @cindex --ss-greedy, command-line option
841: @item --ss-greedy
842: This option is useful for measuring the performance impact of static
843: superinstructions. By default, an optimal shortest-path algorithm is
844: used for selecting static superinstructions. With @option{--ss-greedy}
845: this algorithm is modified to assume that anything after the static
846: superinstruction currently under consideration is not combined into
847: static superinstructions. With @option{--ss-min-nexts} this produces
848: the same result as a greedy algorithm that always selects the longest
849: superinstruction available at the moment. E.g., if there are
850: superinstructions AB and BCD, then for the sequence A B C D the optimal
851: algorithm will select A BCD and the greedy algorithm will select AB C D.
852:
853: @cindex --print-metrics, command-line option
854: @item --print-metrics
855: Prints some metrics used during static superinstruction selection:
856: @code{code size} is the actual size of the dynamically generated code.
857: @code{Metric codesize} is the sum of the codesize metrics as seen by
858: static superinstruction selection; there is a difference from @code{code
859: size}, because not all primitives and static superinstructions are
860: compiled into dynamically generated code, and because of markers. The
861: other metrics correspond to the @option{ss-min-...} options. This
862: option is useful for evaluating the effects of the @option{--ss-...}
863: options.
1.109 anton 864:
1.48 anton 865: @end table
866:
867: @cindex loading files at startup
868: @cindex executing code on startup
869: @cindex batch processing with Gforth
870: As explained above, the image-specific command-line arguments for the
871: default image @file{gforth.fi} consist of a sequence of filenames and
872: @code{-e @var{forth-code}} options that are interpreted in the sequence
873: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 874: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
875: option takes only one argument; if you want to evaluate more Forth
876: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 877: after processing the command line (instead of entering interactive mode)
1.121 anton 878: append @code{-e bye} to the command line. You can also process the
879: command-line arguments with a Forth program (@pxref{OS command line
880: arguments}).
1.48 anton 881:
882: @cindex versions, invoking other versions of Gforth
883: If you have several versions of Gforth installed, @code{gforth} will
884: invoke the version that was installed last. @code{gforth-@i{version}}
885: invokes a specific version. If your environment contains the variable
886: @code{GFORTHPATH}, you may want to override it by using the
887: @code{--path} option.
888:
889: Not yet implemented:
890: On startup the system first executes the system initialization file
891: (unless the option @code{--no-init-file} is given; note that the system
892: resulting from using this option may not be ANS Forth conformant). Then
893: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 894: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 895: then in @file{~}, then in the normal path (see above).
896:
897:
898:
899: @comment ----------------------------------------------
900: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
901: @section Leaving Gforth
902: @cindex Gforth - leaving
903: @cindex leaving Gforth
904:
905: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
906: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
907: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 908: data are discarded. For ways of saving the state of the system before
909: leaving Gforth see @ref{Image Files}.
1.48 anton 910:
911: doc-bye
912:
913:
914: @comment ----------------------------------------------
1.65 anton 915: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 916: @section Command-line editing
917: @cindex command-line editing
918:
919: Gforth maintains a history file that records every line that you type to
920: the text interpreter. This file is preserved between sessions, and is
921: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
922: repeatedly you can recall successively older commands from this (or
923: previous) session(s). The full list of command-line editing facilities is:
924:
925: @itemize @bullet
926: @item
927: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
928: commands from the history buffer.
929: @item
930: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
931: from the history buffer.
932: @item
933: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
934: @item
935: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
936: @item
937: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
938: closing up the line.
939: @item
940: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
941: @item
942: @kbd{Ctrl-a} to move the cursor to the start of the line.
943: @item
944: @kbd{Ctrl-e} to move the cursor to the end of the line.
945: @item
946: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
947: line.
948: @item
949: @key{TAB} to step through all possible full-word completions of the word
950: currently being typed.
951: @item
1.65 anton 952: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
953: using @code{bye}).
954: @item
955: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
956: character under the cursor.
1.48 anton 957: @end itemize
958:
959: When editing, displayable characters are inserted to the left of the
960: cursor position; the line is always in ``insert'' (as opposed to
961: ``overstrike'') mode.
962:
963: @cindex history file
964: @cindex @file{.gforth-history}
965: On Unix systems, the history file is @file{~/.gforth-history} by
966: default@footnote{i.e. it is stored in the user's home directory.}. You
967: can find out the name and location of your history file using:
968:
969: @example
970: history-file type \ Unix-class systems
971:
972: history-file type \ Other systems
973: history-dir type
974: @end example
975:
976: If you enter long definitions by hand, you can use a text editor to
977: paste them out of the history file into a Forth source file for reuse at
978: a later time.
979:
980: Gforth never trims the size of the history file, so you should do this
981: periodically, if necessary.
982:
983: @comment this is all defined in history.fs
984: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
985: @comment chosen?
986:
987:
988: @comment ----------------------------------------------
1.65 anton 989: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 990: @section Environment variables
991: @cindex environment variables
992:
993: Gforth uses these environment variables:
994:
995: @itemize @bullet
996: @item
997: @cindex @code{GFORTHHIST} -- environment variable
998: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
999: open/create the history file, @file{.gforth-history}. Default:
1000: @code{$HOME}.
1001:
1002: @item
1003: @cindex @code{GFORTHPATH} -- environment variable
1004: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1005: for Forth source-code files.
1006:
1007: @item
1.147 anton 1008: @cindex @code{LANG} -- environment variable
1009: @code{LANG} -- see @code{LC_CTYPE}
1010:
1011: @item
1012: @cindex @code{LC_ALL} -- environment variable
1013: @code{LC_ALL} -- see @code{LC_CTYPE}
1014:
1015: @item
1016: @cindex @code{LC_CTYPE} -- environment variable
1017: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1018: startup, Gforth uses the UTF-8 encoding for strings internally and
1019: expects its input and produces its output in UTF-8 encoding, otherwise
1020: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1021: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1022: that is unset, in @code{LANG}.
1023:
1024: @item
1.129 anton 1025: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1026:
1027: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1028: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1029: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1030: and the command are directly concatenated, so if a space between them is
1031: necessary, append it to the prefix.
1032:
1033: @item
1.48 anton 1034: @cindex @code{GFORTH} -- environment variable
1.49 anton 1035: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1036:
1037: @item
1038: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1039: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1040:
1041: @item
1042: @cindex @code{TMP}, @code{TEMP} - environment variable
1043: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1044: location for the history file.
1045: @end itemize
1046:
1047: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1048: @comment mentioning these.
1049:
1050: All the Gforth environment variables default to sensible values if they
1051: are not set.
1052:
1053:
1054: @comment ----------------------------------------------
1.112 anton 1055: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1056: @section Gforth files
1057: @cindex Gforth files
1058:
1059: When you install Gforth on a Unix system, it installs files in these
1060: locations by default:
1061:
1062: @itemize @bullet
1063: @item
1064: @file{/usr/local/bin/gforth}
1065: @item
1066: @file{/usr/local/bin/gforthmi}
1067: @item
1068: @file{/usr/local/man/man1/gforth.1} - man page.
1069: @item
1070: @file{/usr/local/info} - the Info version of this manual.
1071: @item
1072: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1073: @item
1074: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1075: @item
1076: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1077: @item
1078: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1079: @end itemize
1080:
1081: You can select different places for installation by using
1082: @code{configure} options (listed with @code{configure --help}).
1083:
1084: @comment ----------------------------------------------
1.112 anton 1085: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1086: @section Gforth in pipes
1087: @cindex pipes, Gforth as part of
1088:
1089: Gforth can be used in pipes created elsewhere (described here). It can
1090: also create pipes on its own (@pxref{Pipes}).
1091:
1092: @cindex input from pipes
1093: If you pipe into Gforth, your program should read with @code{read-file}
1094: or @code{read-line} from @code{stdin} (@pxref{General files}).
1095: @code{Key} does not recognize the end of input. Words like
1096: @code{accept} echo the input and are therefore usually not useful for
1097: reading from a pipe. You have to invoke the Forth program with an OS
1098: command-line option, as you have no chance to use the Forth command line
1099: (the text interpreter would try to interpret the pipe input).
1100:
1101: @cindex output in pipes
1102: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1103:
1104: @cindex silent exiting from Gforth
1105: When you write to a pipe that has been closed at the other end, Gforth
1106: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1107: into the exception @code{broken-pipe-error}. If your application does
1108: not catch that exception, the system catches it and exits, usually
1109: silently (unless you were working on the Forth command line; then it
1110: prints an error message and exits). This is usually the desired
1111: behaviour.
1112:
1113: If you do not like this behaviour, you have to catch the exception
1114: yourself, and react to it.
1115:
1116: Here's an example of an invocation of Gforth that is usable in a pipe:
1117:
1118: @example
1119: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1120: type repeat ; foo bye"
1121: @end example
1122:
1123: This example just copies the input verbatim to the output. A very
1124: simple pipe containing this example looks like this:
1125:
1126: @example
1127: cat startup.fs |
1128: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1129: type repeat ; foo bye"|
1130: head
1131: @end example
1132:
1133: @cindex stderr and pipes
1134: Pipes involving Gforth's @code{stderr} output do not work.
1135:
1136: @comment ----------------------------------------------
1137: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1138: @section Startup speed
1139: @cindex Startup speed
1140: @cindex speed, startup
1141:
1142: If Gforth is used for CGI scripts or in shell scripts, its startup
1.204 anton 1143: speed may become a problem. On a 3GHz Core 2 Duo E8400 under 64-bit
1144: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
1145: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
1146: with about 3.4ms user time and 1.2ms system time, because it subsumes
1147: some of the options discussed below).
1.48 anton 1148:
1149: If startup speed is a problem, you may consider the following ways to
1150: improve it; or you may consider ways to reduce the number of startups
1.204 anton 1151: (for example, by using Fast-CGI). Note that the first steps below
1152: improve the startup time at the cost of run-time (including
1153: compile-time), so whether they are profitable depends on the balance
1154: of these times in your application.
1155:
1156: An easy step that influences Gforth startup speed is the use of a
1157: number of options that increase run-time, but decrease image-loading
1158: time.
1159:
1160: The first of these that you should try is @code{--ss-number=0
1161: --ss-states=1} because this option buys relatively little run-time
1162: speedup and costs quite a bit of time at startup. @code{gforth-fast
1163: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
1164: system time.
1.48 anton 1165:
1.204 anton 1166: The next option is @code{--no-dynamic} which has a substantial impact
1167: on run-time (about a factor of 2 on several platforms), but still
1168: makes startup speed a little faster: @code{gforth-fast --ss-number=0
1169: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
1170: system time.
1171:
1172: The next step to improve startup speed is to use a data-relocatable
1173: image (@pxref{Data-Relocatable Image Files}). This avoids the
1174: relocation cost for the code in the image (but not for the data).
1175: Note that the image is then specific to the particular binary you are
1176: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
1177: the particular build). You create the data-relocatable image that
1178: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
1179: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
1180: required here or the image will not work). And you run it with
1181: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
1182: above don't matter here, because they only come into play on
1183: relocatable code). @code{gforth-fast -i gforthdr.fi -e bye} takes
1184: about 1.1ms user and 1.2ms system time.
1185:
1186: One step further is to avoid all relocation cost and part of the
1187: copy-on-write cost through using a non-relocatable image
1188: (@pxref{Non-Relocatable Image Files}). However, this has the
1189: disadvantage that it does not work on operating systems with address
1190: space randomization (the default in, e.g., Linux nowadays), or if the
1191: dictionary moves for any other reason (e.g., because of a change of
1192: the OS kernel or an updated library), so we cannot really recommend
1193: it. You create a non-relocatable image with @code{gforth-fast
1194: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
1195: is required here, too). And you run it with @code{gforth-fast -i
1196: gforthnr.fi ... -e bye} (again the flags discussed above don't
1197: matter). @code{gforth-fast -i gforthdr.fi -e bye} takes
1198: about 0.9ms user and 0.9ms system time.
1199:
1200: If the script you want to execute contains a significant amount of
1201: code, it may be profitable to compile it into the image to avoid the
1202: cost of compiling it at startup time.
1.48 anton 1203:
1204: @c ******************************************************************
1205: @node Tutorial, Introduction, Gforth Environment, Top
1206: @chapter Forth Tutorial
1207: @cindex Tutorial
1208: @cindex Forth Tutorial
1209:
1.67 anton 1210: @c Topics from nac's Introduction that could be mentioned:
1211: @c press <ret> after each line
1212: @c Prompt
1213: @c numbers vs. words in dictionary on text interpretation
1214: @c what happens on redefinition
1215: @c parsing words (in particular, defining words)
1216:
1.83 anton 1217: The difference of this chapter from the Introduction
1218: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1219: be used while sitting in front of a computer, and covers much more
1220: material, but does not explain how the Forth system works.
1221:
1.62 crook 1222: This tutorial can be used with any ANS-compliant Forth; any
1.206 anton 1223: Gforth-specific features are marked as such and you can skip them if
1224: you work with another Forth. This tutorial does not explain all
1225: features of Forth, just enough to get you started and give you some
1226: ideas about the facilities available in Forth. Read the rest of the
1227: manual when you are through this.
1.48 anton 1228:
1229: The intended way to use this tutorial is that you work through it while
1230: sitting in front of the console, take a look at the examples and predict
1231: what they will do, then try them out; if the outcome is not as expected,
1232: find out why (e.g., by trying out variations of the example), so you
1233: understand what's going on. There are also some assignments that you
1234: should solve.
1235:
1236: This tutorial assumes that you have programmed before and know what,
1237: e.g., a loop is.
1238:
1239: @c !! explain compat library
1240:
1241: @menu
1242: * Starting Gforth Tutorial::
1243: * Syntax Tutorial::
1244: * Crash Course Tutorial::
1245: * Stack Tutorial::
1246: * Arithmetics Tutorial::
1247: * Stack Manipulation Tutorial::
1248: * Using files for Forth code Tutorial::
1249: * Comments Tutorial::
1250: * Colon Definitions Tutorial::
1251: * Decompilation Tutorial::
1252: * Stack-Effect Comments Tutorial::
1253: * Types Tutorial::
1254: * Factoring Tutorial::
1255: * Designing the stack effect Tutorial::
1256: * Local Variables Tutorial::
1257: * Conditional execution Tutorial::
1258: * Flags and Comparisons Tutorial::
1259: * General Loops Tutorial::
1260: * Counted loops Tutorial::
1261: * Recursion Tutorial::
1262: * Leaving definitions or loops Tutorial::
1263: * Return Stack Tutorial::
1264: * Memory Tutorial::
1265: * Characters and Strings Tutorial::
1266: * Alignment Tutorial::
1.190 anton 1267: * Floating Point Tutorial::
1.87 anton 1268: * Files Tutorial::
1.48 anton 1269: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1270: * Execution Tokens Tutorial::
1271: * Exceptions Tutorial::
1272: * Defining Words Tutorial::
1273: * Arrays and Records Tutorial::
1274: * POSTPONE Tutorial::
1275: * Literal Tutorial::
1276: * Advanced macros Tutorial::
1277: * Compilation Tokens Tutorial::
1278: * Wordlists and Search Order Tutorial::
1279: @end menu
1280:
1281: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1282: @section Starting Gforth
1.66 anton 1283: @cindex starting Gforth tutorial
1.48 anton 1284: You can start Gforth by typing its name:
1285:
1286: @example
1287: gforth
1288: @end example
1289:
1290: That puts you into interactive mode; you can leave Gforth by typing
1291: @code{bye}. While in Gforth, you can edit the command line and access
1292: the command line history with cursor keys, similar to bash.
1293:
1294:
1295: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1296: @section Syntax
1.66 anton 1297: @cindex syntax tutorial
1.48 anton 1298:
1.171 anton 1299: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1300: space). Words are separated by white space. E.g., each of the
1301: following lines contains exactly one word:
1302:
1303: @example
1304: word
1305: !@@#$%^&*()
1306: 1234567890
1307: 5!a
1308: @end example
1309:
1.205 anton 1310: A frequent beginner's error is to leave out necessary white space,
1.48 anton 1311: resulting in an error like @samp{Undefined word}; so if you see such an
1312: error, check if you have put spaces wherever necessary.
1313:
1314: @example
1315: ." hello, world" \ correct
1316: ."hello, world" \ gives an "Undefined word" error
1317: @end example
1318:
1.65 anton 1319: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1320: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1321: your system is case-sensitive, you may have to type all the examples
1322: given here in upper case.
1323:
1324:
1325: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1326: @section Crash Course
1327:
1.209 anton 1328: Forth does not prevent you from shooting yourself in the foot. Let's
1329: try a few ways to crash Gforth:
1.48 anton 1330:
1331: @example
1332: 0 0 !
1333: here execute
1334: ' catch >body 20 erase abort
1335: ' (quit) >body 20 erase
1336: @end example
1337:
1.209 anton 1338: The last two examples are guaranteed to destroy important parts of
1339: Gforth (and most other systems), so you better leave Gforth afterwards
1340: (if it has not finished by itself). On some systems you may have to
1341: kill gforth from outside (e.g., in Unix with @code{kill}).
1342:
1343: You will find out later what these lines do and then you will get an
1344: idea why they produce crashes.
1.48 anton 1345:
1346: Now that you know how to produce crashes (and that there's not much to
1347: them), let's learn how to produce meaningful programs.
1348:
1349:
1350: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1351: @section Stack
1.66 anton 1352: @cindex stack tutorial
1.48 anton 1353:
1354: The most obvious feature of Forth is the stack. When you type in a
1.205 anton 1355: number, it is pushed on the stack. You can display the contents of the
1.48 anton 1356: stack with @code{.s}.
1357:
1358: @example
1359: 1 2 .s
1360: 3 .s
1361: @end example
1362:
1363: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1364: appear in @code{.s} output as they appeared in the input.
1365:
1.205 anton 1366: You can print the top element of the stack with @code{.}.
1.48 anton 1367:
1368: @example
1369: 1 2 3 . . .
1370: @end example
1371:
1372: In general, words consume their stack arguments (@code{.s} is an
1373: exception).
1374:
1.141 anton 1375: @quotation Assignment
1.48 anton 1376: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1377: @end quotation
1.48 anton 1378:
1379:
1380: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1381: @section Arithmetics
1.66 anton 1382: @cindex arithmetics tutorial
1.48 anton 1383:
1384: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1385: operate on the top two stack items:
1386:
1387: @example
1.67 anton 1388: 2 2 .s
1389: + .s
1390: .
1.48 anton 1391: 2 1 - .
1392: 7 3 mod .
1393: @end example
1394:
1395: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1396: as in the corresponding infix expression (this is generally the case in
1397: Forth).
1398:
1399: Parentheses are superfluous (and not available), because the order of
1400: the words unambiguously determines the order of evaluation and the
1401: operands:
1402:
1403: @example
1404: 3 4 + 5 * .
1405: 3 4 5 * + .
1406: @end example
1407:
1.141 anton 1408: @quotation Assignment
1.48 anton 1409: What are the infix expressions corresponding to the Forth code above?
1410: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1411: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1412: @end quotation
1.48 anton 1413:
1414: To change the sign, use @code{negate}:
1415:
1416: @example
1417: 2 negate .
1418: @end example
1419:
1.141 anton 1420: @quotation Assignment
1.48 anton 1421: Convert -(-3)*4-5 to Forth.
1.141 anton 1422: @end quotation
1.48 anton 1423:
1424: @code{/mod} performs both @code{/} and @code{mod}.
1425:
1426: @example
1427: 7 3 /mod . .
1428: @end example
1429:
1.66 anton 1430: Reference: @ref{Arithmetic}.
1431:
1432:
1.48 anton 1433: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1434: @section Stack Manipulation
1.66 anton 1435: @cindex stack manipulation tutorial
1.48 anton 1436:
1437: Stack manipulation words rearrange the data on the stack.
1438:
1439: @example
1440: 1 .s drop .s
1441: 1 .s dup .s drop drop .s
1442: 1 2 .s over .s drop drop drop
1443: 1 2 .s swap .s drop drop
1444: 1 2 3 .s rot .s drop drop drop
1445: @end example
1446:
1447: These are the most important stack manipulation words. There are also
1448: variants that manipulate twice as many stack items:
1449:
1450: @example
1451: 1 2 3 4 .s 2swap .s 2drop 2drop
1452: @end example
1453:
1454: Two more stack manipulation words are:
1455:
1456: @example
1457: 1 2 .s nip .s drop
1458: 1 2 .s tuck .s 2drop drop
1459: @end example
1460:
1.141 anton 1461: @quotation Assignment
1.48 anton 1462: Replace @code{nip} and @code{tuck} with combinations of other stack
1463: manipulation words.
1464:
1465: @example
1466: Given: How do you get:
1467: 1 2 3 3 2 1
1468: 1 2 3 1 2 3 2
1469: 1 2 3 1 2 3 3
1470: 1 2 3 1 3 3
1471: 1 2 3 2 1 3
1472: 1 2 3 4 4 3 2 1
1473: 1 2 3 1 2 3 1 2 3
1474: 1 2 3 4 1 2 3 4 1 2
1475: 1 2 3
1476: 1 2 3 1 2 3 4
1477: 1 2 3 1 3
1478: @end example
1.141 anton 1479: @end quotation
1.48 anton 1480:
1481: @example
1482: 5 dup * .
1483: @end example
1484:
1.141 anton 1485: @quotation Assignment
1.48 anton 1486: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1487: Write a piece of Forth code that expects two numbers on the stack
1488: (@var{a} and @var{b}, with @var{b} on top) and computes
1489: @code{(a-b)(a+1)}.
1.141 anton 1490: @end quotation
1.48 anton 1491:
1.66 anton 1492: Reference: @ref{Stack Manipulation}.
1493:
1494:
1.48 anton 1495: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1496: @section Using files for Forth code
1.66 anton 1497: @cindex loading Forth code, tutorial
1498: @cindex files containing Forth code, tutorial
1.48 anton 1499:
1500: While working at the Forth command line is convenient for one-line
1501: examples and short one-off code, you probably want to store your source
1502: code in files for convenient editing and persistence. You can use your
1503: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1504: Gforth}) to create @var{file.fs} and use
1.48 anton 1505:
1506: @example
1.102 anton 1507: s" @var{file.fs}" included
1.48 anton 1508: @end example
1509:
1510: to load it into your Forth system. The file name extension I use for
1511: Forth files is @samp{.fs}.
1512:
1513: You can easily start Gforth with some files loaded like this:
1514:
1515: @example
1.102 anton 1516: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1517: @end example
1518:
1519: If an error occurs during loading these files, Gforth terminates,
1520: whereas an error during @code{INCLUDED} within Gforth usually gives you
1521: a Gforth command line. Starting the Forth system every time gives you a
1522: clean start every time, without interference from the results of earlier
1523: tries.
1524:
1525: I often put all the tests in a file, then load the code and run the
1526: tests with
1527:
1528: @example
1.102 anton 1529: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1530: @end example
1531:
1532: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1533: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1534: restart this command without ado.
1535:
1536: The advantage of this approach is that the tests can be repeated easily
1537: every time the program ist changed, making it easy to catch bugs
1538: introduced by the change.
1539:
1.66 anton 1540: Reference: @ref{Forth source files}.
1541:
1.48 anton 1542:
1543: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1544: @section Comments
1.66 anton 1545: @cindex comments tutorial
1.48 anton 1546:
1547: @example
1548: \ That's a comment; it ends at the end of the line
1549: ( Another comment; it ends here: ) .s
1550: @end example
1551:
1552: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1553: separated with white space from the following text.
1554:
1555: @example
1556: \This gives an "Undefined word" error
1557: @end example
1558:
1559: The first @code{)} ends a comment started with @code{(}, so you cannot
1560: nest @code{(}-comments; and you cannot comment out text containing a
1561: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1562: avoid @code{)} in word names.}.
1563:
1564: I use @code{\}-comments for descriptive text and for commenting out code
1565: of one or more line; I use @code{(}-comments for describing the stack
1566: effect, the stack contents, or for commenting out sub-line pieces of
1567: code.
1568:
1569: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1570: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1571: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1572: with @kbd{M-q}.
1573:
1.66 anton 1574: Reference: @ref{Comments}.
1575:
1.48 anton 1576:
1577: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1578: @section Colon Definitions
1.66 anton 1579: @cindex colon definitions, tutorial
1580: @cindex definitions, tutorial
1581: @cindex procedures, tutorial
1582: @cindex functions, tutorial
1.48 anton 1583:
1584: are similar to procedures and functions in other programming languages.
1585:
1586: @example
1587: : squared ( n -- n^2 )
1588: dup * ;
1589: 5 squared .
1590: 7 squared .
1591: @end example
1592:
1593: @code{:} starts the colon definition; its name is @code{squared}. The
1594: following comment describes its stack effect. The words @code{dup *}
1595: are not executed, but compiled into the definition. @code{;} ends the
1596: colon definition.
1597:
1598: The newly-defined word can be used like any other word, including using
1599: it in other definitions:
1600:
1601: @example
1602: : cubed ( n -- n^3 )
1603: dup squared * ;
1604: -5 cubed .
1605: : fourth-power ( n -- n^4 )
1606: squared squared ;
1607: 3 fourth-power .
1608: @end example
1609:
1.141 anton 1610: @quotation Assignment
1.48 anton 1611: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1612: @code{/mod} in terms of other Forth words, and check if they work (hint:
1613: test your tests on the originals first). Don't let the
1614: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1615: @end quotation
1.48 anton 1616:
1.66 anton 1617: Reference: @ref{Colon Definitions}.
1618:
1.48 anton 1619:
1620: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1621: @section Decompilation
1.66 anton 1622: @cindex decompilation tutorial
1623: @cindex see tutorial
1.48 anton 1624:
1625: You can decompile colon definitions with @code{see}:
1626:
1627: @example
1628: see squared
1629: see cubed
1630: @end example
1631:
1632: In Gforth @code{see} shows you a reconstruction of the source code from
1633: the executable code. Informations that were present in the source, but
1634: not in the executable code, are lost (e.g., comments).
1635:
1.65 anton 1636: You can also decompile the predefined words:
1637:
1638: @example
1639: see .
1640: see +
1641: @end example
1642:
1643:
1.48 anton 1644: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1645: @section Stack-Effect Comments
1.66 anton 1646: @cindex stack-effect comments, tutorial
1647: @cindex --, tutorial
1.48 anton 1648: By convention the comment after the name of a definition describes the
1.171 anton 1649: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1650: the stack before the execution of the definition, i.e., the parameters
1651: that are passed into the colon definition; the part behind the @samp{--}
1652: is the state of the stack after the execution of the definition, i.e.,
1653: the results of the definition. The stack comment only shows the top
1654: stack items that the definition accesses and/or changes.
1655:
1656: You should put a correct stack effect on every definition, even if it is
1657: just @code{( -- )}. You should also add some descriptive comment to
1658: more complicated words (I usually do this in the lines following
1659: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1660: you have to work through every definition before you can understand
1.48 anton 1661: any).
1662:
1.141 anton 1663: @quotation Assignment
1.48 anton 1664: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1665: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1666: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1667: are done, you can compare your stack effects to those in this manual
1.48 anton 1668: (@pxref{Word Index}).
1.141 anton 1669: @end quotation
1.48 anton 1670:
1671: Sometimes programmers put comments at various places in colon
1672: definitions that describe the contents of the stack at that place (stack
1673: comments); i.e., they are like the first part of a stack-effect
1674: comment. E.g.,
1675:
1676: @example
1677: : cubed ( n -- n^3 )
1678: dup squared ( n n^2 ) * ;
1679: @end example
1680:
1681: In this case the stack comment is pretty superfluous, because the word
1682: is simple enough. If you think it would be a good idea to add such a
1683: comment to increase readability, you should also consider factoring the
1684: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1685: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1686: however, if you decide not to refactor it, then having such a comment is
1687: better than not having it.
1688:
1689: The names of the stack items in stack-effect and stack comments in the
1690: standard, in this manual, and in many programs specify the type through
1691: a type prefix, similar to Fortran and Hungarian notation. The most
1692: frequent prefixes are:
1693:
1694: @table @code
1695: @item n
1696: signed integer
1697: @item u
1698: unsigned integer
1699: @item c
1700: character
1701: @item f
1702: Boolean flags, i.e. @code{false} or @code{true}.
1703: @item a-addr,a-
1704: Cell-aligned address
1705: @item c-addr,c-
1706: Char-aligned address (note that a Char may have two bytes in Windows NT)
1707: @item xt
1708: Execution token, same size as Cell
1709: @item w,x
1710: Cell, can contain an integer or an address. It usually takes 32, 64 or
1711: 16 bits (depending on your platform and Forth system). A cell is more
1712: commonly known as machine word, but the term @emph{word} already means
1713: something different in Forth.
1714: @item d
1715: signed double-cell integer
1716: @item ud
1717: unsigned double-cell integer
1718: @item r
1719: Float (on the FP stack)
1720: @end table
1721:
1722: You can find a more complete list in @ref{Notation}.
1723:
1.141 anton 1724: @quotation Assignment
1.48 anton 1725: Write stack-effect comments for all definitions you have written up to
1726: now.
1.141 anton 1727: @end quotation
1.48 anton 1728:
1729:
1730: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1731: @section Types
1.66 anton 1732: @cindex types tutorial
1.48 anton 1733:
1734: In Forth the names of the operations are not overloaded; so similar
1735: operations on different types need different names; e.g., @code{+} adds
1736: integers, and you have to use @code{f+} to add floating-point numbers.
1737: The following prefixes are often used for related operations on
1738: different types:
1739:
1740: @table @code
1741: @item (none)
1742: signed integer
1743: @item u
1744: unsigned integer
1745: @item c
1746: character
1747: @item d
1748: signed double-cell integer
1749: @item ud, du
1750: unsigned double-cell integer
1751: @item 2
1752: two cells (not-necessarily double-cell numbers)
1753: @item m, um
1754: mixed single-cell and double-cell operations
1755: @item f
1756: floating-point (note that in stack comments @samp{f} represents flags,
1.210 anton 1757: and @samp{r} represents FP numbers; also, you need to include the
1758: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
1.48 anton 1759: @end table
1760:
1761: If there are no differences between the signed and the unsigned variant
1762: (e.g., for @code{+}), there is only the prefix-less variant.
1763:
1764: Forth does not perform type checking, neither at compile time, nor at
1.210 anton 1765: run time. If you use the wrong operation, the data are interpreted
1.48 anton 1766: incorrectly:
1767:
1768: @example
1769: -1 u.
1770: @end example
1771:
1772: If you have only experience with type-checked languages until now, and
1773: have heard how important type-checking is, don't panic! In my
1774: experience (and that of other Forthers), type errors in Forth code are
1775: usually easy to find (once you get used to it), the increased vigilance
1776: of the programmer tends to catch some harder errors in addition to most
1777: type errors, and you never have to work around the type system, so in
1778: most situations the lack of type-checking seems to be a win (projects to
1779: add type checking to Forth have not caught on).
1780:
1781:
1782: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1783: @section Factoring
1.66 anton 1784: @cindex factoring tutorial
1.48 anton 1785:
1786: If you try to write longer definitions, you will soon find it hard to
1787: keep track of the stack contents. Therefore, good Forth programmers
1788: tend to write only short definitions (e.g., three lines). The art of
1789: finding meaningful short definitions is known as factoring (as in
1790: factoring polynomials).
1791:
1792: Well-factored programs offer additional advantages: smaller, more
1793: general words, are easier to test and debug and can be reused more and
1794: better than larger, specialized words.
1795:
1796: So, if you run into difficulties with stack management, when writing
1797: code, try to define meaningful factors for the word, and define the word
1798: in terms of those. Even if a factor contains only two words, it is
1799: often helpful.
1800:
1.65 anton 1801: Good factoring is not easy, and it takes some practice to get the knack
1802: for it; but even experienced Forth programmers often don't find the
1803: right solution right away, but only when rewriting the program. So, if
1804: you don't come up with a good solution immediately, keep trying, don't
1805: despair.
1.48 anton 1806:
1807: @c example !!
1808:
1809:
1810: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1811: @section Designing the stack effect
1.66 anton 1812: @cindex Stack effect design, tutorial
1813: @cindex design of stack effects, tutorial
1.48 anton 1814:
1815: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1816: function; and since there is only one result, you don't have to deal with
1.48 anton 1817: the order of results, either.
1818:
1.117 anton 1819: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1820: parameter and result order of a definition is important and should be
1821: designed well. The general guideline is to design the stack effect such
1822: that the word is simple to use in most cases, even if that complicates
1823: the implementation of the word. Some concrete rules are:
1824:
1825: @itemize @bullet
1826:
1827: @item
1828: Words consume all of their parameters (e.g., @code{.}).
1829:
1830: @item
1831: If there is a convention on the order of parameters (e.g., from
1832: mathematics or another programming language), stick with it (e.g.,
1833: @code{-}).
1834:
1835: @item
1836: If one parameter usually requires only a short computation (e.g., it is
1837: a constant), pass it on the top of the stack. Conversely, parameters
1838: that usually require a long sequence of code to compute should be passed
1839: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1840: read, because the reader does not need to keep track of the bottom item
1.48 anton 1841: through a long sequence of code (or, alternatively, through stack
1.49 anton 1842: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1843: address on top of the stack because it is usually simpler to compute
1844: than the stored value (often the address is just a variable).
1845:
1846: @item
1847: Similarly, results that are usually consumed quickly should be returned
1848: on the top of stack, whereas a result that is often used in long
1849: computations should be passed as bottom result. E.g., the file words
1850: like @code{open-file} return the error code on the top of stack, because
1851: it is usually consumed quickly by @code{throw}; moreover, the error code
1852: has to be checked before doing anything with the other results.
1853:
1854: @end itemize
1855:
1856: These rules are just general guidelines, don't lose sight of the overall
1857: goal to make the words easy to use. E.g., if the convention rule
1858: conflicts with the computation-length rule, you might decide in favour
1859: of the convention if the word will be used rarely, and in favour of the
1860: computation-length rule if the word will be used frequently (because
1861: with frequent use the cost of breaking the computation-length rule would
1862: be quite high, and frequent use makes it easier to remember an
1863: unconventional order).
1864:
1865: @c example !! structure package
1866:
1.65 anton 1867:
1.48 anton 1868: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1869: @section Local Variables
1.66 anton 1870: @cindex local variables, tutorial
1.48 anton 1871:
1872: You can define local variables (@emph{locals}) in a colon definition:
1873:
1874: @example
1875: : swap @{ a b -- b a @}
1876: b a ;
1877: 1 2 swap .s 2drop
1878: @end example
1879:
1880: (If your Forth system does not support this syntax, include
1.187 anton 1881: @file{compat/anslocal.fs} first).
1.48 anton 1882:
1883: In this example @code{@{ a b -- b a @}} is the locals definition; it
1884: takes two cells from the stack, puts the top of stack in @code{b} and
1885: the next stack element in @code{a}. @code{--} starts a comment ending
1886: with @code{@}}. After the locals definition, using the name of the
1887: local will push its value on the stack. You can leave the comment
1888: part (@code{-- b a}) away:
1889:
1890: @example
1891: : swap ( x1 x2 -- x2 x1 )
1892: @{ a b @} b a ;
1893: @end example
1894:
1895: In Gforth you can have several locals definitions, anywhere in a colon
1896: definition; in contrast, in a standard program you can have only one
1897: locals definition per colon definition, and that locals definition must
1.163 anton 1898: be outside any control structure.
1.48 anton 1899:
1900: With locals you can write slightly longer definitions without running
1901: into stack trouble. However, I recommend trying to write colon
1902: definitions without locals for exercise purposes to help you gain the
1903: essential factoring skills.
1904:
1.141 anton 1905: @quotation Assignment
1.48 anton 1906: Rewrite your definitions until now with locals
1.141 anton 1907: @end quotation
1.48 anton 1908:
1.66 anton 1909: Reference: @ref{Locals}.
1910:
1.48 anton 1911:
1912: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1913: @section Conditional execution
1.66 anton 1914: @cindex conditionals, tutorial
1915: @cindex if, tutorial
1.48 anton 1916:
1917: In Forth you can use control structures only inside colon definitions.
1918: An @code{if}-structure looks like this:
1919:
1920: @example
1921: : abs ( n1 -- +n2 )
1922: dup 0 < if
1923: negate
1924: endif ;
1925: 5 abs .
1926: -5 abs .
1927: @end example
1928:
1929: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1930: the following code is performed, otherwise execution continues after the
1.51 pazsan 1931: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1932: elements and produces a flag:
1.48 anton 1933:
1934: @example
1935: 1 2 < .
1936: 2 1 < .
1937: 1 1 < .
1938: @end example
1939:
1940: Actually the standard name for @code{endif} is @code{then}. This
1941: tutorial presents the examples using @code{endif}, because this is often
1942: less confusing for people familiar with other programming languages
1943: where @code{then} has a different meaning. If your system does not have
1944: @code{endif}, define it with
1945:
1946: @example
1947: : endif postpone then ; immediate
1948: @end example
1949:
1950: You can optionally use an @code{else}-part:
1951:
1952: @example
1953: : min ( n1 n2 -- n )
1954: 2dup < if
1955: drop
1956: else
1957: nip
1958: endif ;
1959: 2 3 min .
1960: 3 2 min .
1961: @end example
1962:
1.141 anton 1963: @quotation Assignment
1.48 anton 1964: Write @code{min} without @code{else}-part (hint: what's the definition
1965: of @code{nip}?).
1.141 anton 1966: @end quotation
1.48 anton 1967:
1.66 anton 1968: Reference: @ref{Selection}.
1969:
1.48 anton 1970:
1971: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1972: @section Flags and Comparisons
1.66 anton 1973: @cindex flags tutorial
1974: @cindex comparison tutorial
1.48 anton 1975:
1976: In a false-flag all bits are clear (0 when interpreted as integer). In
1977: a canonical true-flag all bits are set (-1 as a twos-complement signed
1978: integer); in many contexts (e.g., @code{if}) any non-zero value is
1979: treated as true flag.
1980:
1981: @example
1982: false .
1983: true .
1984: true hex u. decimal
1985: @end example
1986:
1987: Comparison words produce canonical flags:
1988:
1989: @example
1990: 1 1 = .
1991: 1 0= .
1992: 0 1 < .
1993: 0 0 < .
1994: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1995: -1 1 < .
1996: @end example
1997:
1.66 anton 1998: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1999: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
2000: these combinations are standard (for details see the standard,
2001: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 2002:
1.171 anton 2003: You can use @code{and or xor invert} as operations on canonical flags.
2004: Actually they are bitwise operations:
1.48 anton 2005:
2006: @example
2007: 1 2 and .
2008: 1 2 or .
2009: 1 3 xor .
2010: 1 invert .
2011: @end example
2012:
2013: You can convert a zero/non-zero flag into a canonical flag with
2014: @code{0<>} (and complement it on the way with @code{0=}).
2015:
2016: @example
2017: 1 0= .
2018: 1 0<> .
2019: @end example
2020:
1.65 anton 2021: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2022: operation of the Boolean operations to avoid @code{if}s:
2023:
2024: @example
2025: : foo ( n1 -- n2 )
2026: 0= if
2027: 14
2028: else
2029: 0
2030: endif ;
2031: 0 foo .
2032: 1 foo .
2033:
2034: : foo ( n1 -- n2 )
2035: 0= 14 and ;
2036: 0 foo .
2037: 1 foo .
2038: @end example
2039:
1.141 anton 2040: @quotation Assignment
1.48 anton 2041: Write @code{min} without @code{if}.
1.141 anton 2042: @end quotation
1.48 anton 2043:
1.66 anton 2044: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2045: @ref{Bitwise operations}.
2046:
1.48 anton 2047:
2048: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2049: @section General Loops
1.66 anton 2050: @cindex loops, indefinite, tutorial
1.48 anton 2051:
2052: The endless loop is the most simple one:
2053:
2054: @example
2055: : endless ( -- )
2056: 0 begin
2057: dup . 1+
2058: again ;
2059: endless
2060: @end example
2061:
2062: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2063: does nothing at run-time, @code{again} jumps back to @code{begin}.
2064:
2065: A loop with one exit at any place looks like this:
2066:
2067: @example
2068: : log2 ( +n1 -- n2 )
2069: \ logarithmus dualis of n1>0, rounded down to the next integer
2070: assert( dup 0> )
2071: 2/ 0 begin
2072: over 0> while
2073: 1+ swap 2/ swap
2074: repeat
2075: nip ;
2076: 7 log2 .
2077: 8 log2 .
2078: @end example
2079:
2080: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2081: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2082: continues behind the @code{while}. @code{Repeat} jumps back to
2083: @code{begin}, just like @code{again}.
2084:
1.211 anton 2085: In Forth there are a number of combinations/abbreviations, like
2086: @code{1+}. However, @code{2/} is not one of them; it shifts its
2087: argument right by one bit (arithmetic shift right), and viewed as
2088: division that always rounds towards negative infinity (floored
2089: division). In contrast, @code{/} rounds towards zero on some systems
2090: (not on default installations of gforth (>=0.7.0), however).
1.48 anton 2091:
2092: @example
1.211 anton 2093: -5 2 / . \ -2 or -3
2094: -5 2/ . \ -3
1.48 anton 2095: @end example
2096:
2097: @code{assert(} is no standard word, but you can get it on systems other
1.198 anton 2098: than Gforth by including @file{compat/assert.fs}. You can see what it
1.48 anton 2099: does by trying
2100:
2101: @example
2102: 0 log2 .
2103: @end example
2104:
2105: Here's a loop with an exit at the end:
2106:
2107: @example
2108: : log2 ( +n1 -- n2 )
2109: \ logarithmus dualis of n1>0, rounded down to the next integer
2110: assert( dup 0 > )
2111: -1 begin
2112: 1+ swap 2/ swap
2113: over 0 <=
2114: until
2115: nip ;
2116: @end example
2117:
2118: @code{Until} consumes a flag; if it is non-zero, execution continues at
2119: the @code{begin}, otherwise after the @code{until}.
2120:
1.141 anton 2121: @quotation Assignment
1.48 anton 2122: Write a definition for computing the greatest common divisor.
1.141 anton 2123: @end quotation
1.48 anton 2124:
1.66 anton 2125: Reference: @ref{Simple Loops}.
2126:
1.48 anton 2127:
2128: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2129: @section Counted loops
1.66 anton 2130: @cindex loops, counted, tutorial
1.48 anton 2131:
2132: @example
2133: : ^ ( n1 u -- n )
1.171 anton 2134: \ n = the uth power of n1
1.48 anton 2135: 1 swap 0 u+do
2136: over *
2137: loop
2138: nip ;
2139: 3 2 ^ .
2140: 4 3 ^ .
2141: @end example
2142:
2143: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2144: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2145: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2146: times (or not at all, if @code{u3-u4<0}).
2147:
2148: You can see the stack effect design rules at work in the stack effect of
2149: the loop start words: Since the start value of the loop is more
2150: frequently constant than the end value, the start value is passed on
2151: the top-of-stack.
2152:
2153: You can access the counter of a counted loop with @code{i}:
2154:
2155: @example
2156: : fac ( u -- u! )
2157: 1 swap 1+ 1 u+do
2158: i *
2159: loop ;
2160: 5 fac .
2161: 7 fac .
2162: @end example
2163:
2164: There is also @code{+do}, which expects signed numbers (important for
2165: deciding whether to enter the loop).
2166:
1.141 anton 2167: @quotation Assignment
1.48 anton 2168: Write a definition for computing the nth Fibonacci number.
1.141 anton 2169: @end quotation
1.48 anton 2170:
1.65 anton 2171: You can also use increments other than 1:
2172:
2173: @example
2174: : up2 ( n1 n2 -- )
2175: +do
2176: i .
2177: 2 +loop ;
2178: 10 0 up2
2179:
2180: : down2 ( n1 n2 -- )
2181: -do
2182: i .
2183: 2 -loop ;
2184: 0 10 down2
2185: @end example
1.48 anton 2186:
1.66 anton 2187: Reference: @ref{Counted Loops}.
2188:
1.48 anton 2189:
2190: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2191: @section Recursion
1.66 anton 2192: @cindex recursion tutorial
1.48 anton 2193:
2194: Usually the name of a definition is not visible in the definition; but
2195: earlier definitions are usually visible:
2196:
2197: @example
1.166 anton 2198: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2199: : / ( n1 n2 -- n )
2200: dup 0= if
2201: -10 throw \ report division by zero
2202: endif
2203: / \ old version
2204: ;
2205: 1 0 /
2206: @end example
2207:
2208: For recursive definitions you can use @code{recursive} (non-standard) or
2209: @code{recurse}:
2210:
2211: @example
2212: : fac1 ( n -- n! ) recursive
2213: dup 0> if
2214: dup 1- fac1 *
2215: else
2216: drop 1
2217: endif ;
2218: 7 fac1 .
2219:
2220: : fac2 ( n -- n! )
2221: dup 0> if
2222: dup 1- recurse *
2223: else
2224: drop 1
2225: endif ;
2226: 8 fac2 .
2227: @end example
2228:
1.141 anton 2229: @quotation Assignment
1.48 anton 2230: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2231: @end quotation
1.48 anton 2232:
1.66 anton 2233: Reference (including indirect recursion): @xref{Calls and returns}.
2234:
1.48 anton 2235:
2236: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2237: @section Leaving definitions or loops
1.66 anton 2238: @cindex leaving definitions, tutorial
2239: @cindex leaving loops, tutorial
1.48 anton 2240:
2241: @code{EXIT} exits the current definition right away. For every counted
2242: loop that is left in this way, an @code{UNLOOP} has to be performed
2243: before the @code{EXIT}:
2244:
2245: @c !! real examples
2246: @example
2247: : ...
2248: ... u+do
2249: ... if
2250: ... unloop exit
2251: endif
2252: ...
2253: loop
2254: ... ;
2255: @end example
2256:
2257: @code{LEAVE} leaves the innermost counted loop right away:
2258:
2259: @example
2260: : ...
2261: ... u+do
2262: ... if
2263: ... leave
2264: endif
2265: ...
2266: loop
2267: ... ;
2268: @end example
2269:
1.65 anton 2270: @c !! example
1.48 anton 2271:
1.66 anton 2272: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2273:
2274:
1.48 anton 2275: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2276: @section Return Stack
1.66 anton 2277: @cindex return stack tutorial
1.48 anton 2278:
2279: In addition to the data stack Forth also has a second stack, the return
2280: stack; most Forth systems store the return addresses of procedure calls
2281: there (thus its name). Programmers can also use this stack:
2282:
2283: @example
2284: : foo ( n1 n2 -- )
2285: .s
2286: >r .s
1.50 anton 2287: r@@ .
1.48 anton 2288: >r .s
1.50 anton 2289: r@@ .
1.48 anton 2290: r> .
1.50 anton 2291: r@@ .
1.48 anton 2292: r> . ;
2293: 1 2 foo
2294: @end example
2295:
2296: @code{>r} takes an element from the data stack and pushes it onto the
2297: return stack; conversely, @code{r>} moves an elementm from the return to
2298: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2299: on the data stack.
1.48 anton 2300:
2301: Forth programmers usually use the return stack for storing data
2302: temporarily, if using the data stack alone would be too complex, and
2303: factoring and locals are not an option:
2304:
2305: @example
2306: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2307: rot >r rot r> ;
2308: @end example
2309:
2310: The return address of the definition and the loop control parameters of
2311: counted loops usually reside on the return stack, so you have to take
2312: all items, that you have pushed on the return stack in a colon
2313: definition or counted loop, from the return stack before the definition
2314: or loop ends. You cannot access items that you pushed on the return
2315: stack outside some definition or loop within the definition of loop.
2316:
2317: If you miscount the return stack items, this usually ends in a crash:
2318:
2319: @example
2320: : crash ( n -- )
2321: >r ;
2322: 5 crash
2323: @end example
2324:
2325: You cannot mix using locals and using the return stack (according to the
2326: standard; Gforth has no problem). However, they solve the same
2327: problems, so this shouldn't be an issue.
2328:
1.141 anton 2329: @quotation Assignment
1.48 anton 2330: Can you rewrite any of the definitions you wrote until now in a better
2331: way using the return stack?
1.141 anton 2332: @end quotation
1.48 anton 2333:
1.66 anton 2334: Reference: @ref{Return stack}.
2335:
1.48 anton 2336:
2337: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2338: @section Memory
1.66 anton 2339: @cindex memory access/allocation tutorial
1.48 anton 2340:
2341: You can create a global variable @code{v} with
2342:
2343: @example
2344: variable v ( -- addr )
2345: @end example
2346:
2347: @code{v} pushes the address of a cell in memory on the stack. This cell
2348: was reserved by @code{variable}. You can use @code{!} (store) to store
2349: values into this cell and @code{@@} (fetch) to load the value from the
2350: stack into memory:
2351:
2352: @example
2353: v .
2354: 5 v ! .s
1.50 anton 2355: v @@ .
1.48 anton 2356: @end example
2357:
1.65 anton 2358: You can see a raw dump of memory with @code{dump}:
2359:
2360: @example
2361: v 1 cells .s dump
2362: @end example
2363:
2364: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2365: generally, address units (aus)) that @code{n1 cells} occupy. You can
2366: also reserve more memory:
1.48 anton 2367:
2368: @example
2369: create v2 20 cells allot
1.65 anton 2370: v2 20 cells dump
1.48 anton 2371: @end example
2372:
1.212 anton 2373: creates a variable-like word @code{v2} and reserves 20 uninitialized
2374: cells; the address pushed by @code{v2} points to the start of these 20
2375: cells (@pxref{CREATE}). You can use address arithmetic to access
2376: these cells:
1.48 anton 2377:
2378: @example
2379: 3 v2 5 cells + !
1.65 anton 2380: v2 20 cells dump
1.48 anton 2381: @end example
2382:
2383: You can reserve and initialize memory with @code{,}:
2384:
2385: @example
2386: create v3
2387: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2388: v3 @@ .
2389: v3 cell+ @@ .
2390: v3 2 cells + @@ .
1.65 anton 2391: v3 5 cells dump
1.48 anton 2392: @end example
2393:
1.141 anton 2394: @quotation Assignment
1.48 anton 2395: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2396: @code{u} cells, with the first of these cells at @code{addr}, the next
2397: one at @code{addr cell+} etc.
1.141 anton 2398: @end quotation
1.48 anton 2399:
1.214 anton 2400: The difference between @code{variable} and @code{create} is that
2401: @code{variable} allots a cell, and that you cannot allot additional
2402: memory to a variable in standard Forth.
2403:
1.48 anton 2404: You can also reserve memory without creating a new word:
2405:
2406: @example
1.60 anton 2407: here 10 cells allot .
2408: here .
1.48 anton 2409: @end example
2410:
1.211 anton 2411: The first @code{here} pushes the start address of the memory area, the
2412: second @code{here} the address after the dictionary area. You should
2413: store the start address somewhere, or you will have a hard time
2414: finding the memory area again.
1.48 anton 2415:
2416: @code{Allot} manages dictionary memory. The dictionary memory contains
2417: the system's data structures for words etc. on Gforth and most other
2418: Forth systems. It is managed like a stack: You can free the memory that
2419: you have just @code{allot}ed with
2420:
2421: @example
2422: -10 cells allot
1.60 anton 2423: here .
1.48 anton 2424: @end example
2425:
2426: Note that you cannot do this if you have created a new word in the
2427: meantime (because then your @code{allot}ed memory is no longer on the
2428: top of the dictionary ``stack'').
2429:
2430: Alternatively, you can use @code{allocate} and @code{free} which allow
2431: freeing memory in any order:
2432:
2433: @example
2434: 10 cells allocate throw .s
2435: 20 cells allocate throw .s
2436: swap
2437: free throw
2438: free throw
2439: @end example
2440:
2441: The @code{throw}s deal with errors (e.g., out of memory).
2442:
1.65 anton 2443: And there is also a
2444: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2445: garbage collector}, which eliminates the need to @code{free} memory
2446: explicitly.
1.48 anton 2447:
1.66 anton 2448: Reference: @ref{Memory}.
2449:
1.48 anton 2450:
2451: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2452: @section Characters and Strings
1.66 anton 2453: @cindex strings tutorial
2454: @cindex characters tutorial
1.48 anton 2455:
2456: On the stack characters take up a cell, like numbers. In memory they
2457: have their own size (one 8-bit byte on most systems), and therefore
2458: require their own words for memory access:
2459:
2460: @example
2461: create v4
2462: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2463: v4 4 chars + c@@ .
1.65 anton 2464: v4 5 chars dump
1.48 anton 2465: @end example
2466:
2467: The preferred representation of strings on the stack is @code{addr
2468: u-count}, where @code{addr} is the address of the first character and
2469: @code{u-count} is the number of characters in the string.
2470:
2471: @example
2472: v4 5 type
2473: @end example
2474:
2475: You get a string constant with
2476:
2477: @example
2478: s" hello, world" .s
2479: type
2480: @end example
2481:
2482: Make sure you have a space between @code{s"} and the string; @code{s"}
2483: is a normal Forth word and must be delimited with white space (try what
2484: happens when you remove the space).
2485:
2486: However, this interpretive use of @code{s"} is quite restricted: the
2487: string exists only until the next call of @code{s"} (some Forth systems
2488: keep more than one of these strings, but usually they still have a
1.62 crook 2489: limited lifetime).
1.48 anton 2490:
2491: @example
2492: s" hello," s" world" .s
2493: type
2494: type
2495: @end example
2496:
1.62 crook 2497: You can also use @code{s"} in a definition, and the resulting
2498: strings then live forever (well, for as long as the definition):
1.48 anton 2499:
2500: @example
2501: : foo s" hello," s" world" ;
2502: foo .s
2503: type
2504: type
2505: @end example
2506:
1.141 anton 2507: @quotation Assignment
1.48 anton 2508: @code{Emit ( c -- )} types @code{c} as character (not a number).
2509: Implement @code{type ( addr u -- )}.
1.141 anton 2510: @end quotation
1.48 anton 2511:
1.66 anton 2512: Reference: @ref{Memory Blocks}.
2513:
2514:
1.190 anton 2515: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2516: @section Alignment
1.66 anton 2517: @cindex alignment tutorial
2518: @cindex memory alignment tutorial
1.48 anton 2519:
2520: On many processors cells have to be aligned in memory, if you want to
2521: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2522: not require alignment, access to aligned cells is faster).
1.48 anton 2523:
2524: @code{Create} aligns @code{here} (i.e., the place where the next
2525: allocation will occur, and that the @code{create}d word points to).
2526: Likewise, the memory produced by @code{allocate} starts at an aligned
2527: address. Adding a number of @code{cells} to an aligned address produces
2528: another aligned address.
2529:
2530: However, address arithmetic involving @code{char+} and @code{chars} can
2531: create an address that is not cell-aligned. @code{Aligned ( addr --
2532: a-addr )} produces the next aligned address:
2533:
2534: @example
1.50 anton 2535: v3 char+ aligned .s @@ .
2536: v3 char+ .s @@ .
1.48 anton 2537: @end example
2538:
2539: Similarly, @code{align} advances @code{here} to the next aligned
2540: address:
2541:
2542: @example
2543: create v5 97 c,
2544: here .
2545: align here .
2546: 1000 ,
2547: @end example
2548:
2549: Note that you should use aligned addresses even if your processor does
2550: not require them, if you want your program to be portable.
2551:
1.66 anton 2552: Reference: @ref{Address arithmetic}.
2553:
1.190 anton 2554: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2555: @section Floating Point
2556: @cindex floating point tutorial
2557: @cindex FP tutorial
2558:
2559: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2560: might expect, but there are a few things worth noting:
2561:
2562: The first point is not specific to Forth, but so important and yet not
2563: universally known that I mention it here: FP numbers are not reals.
2564: Many properties (e.g., arithmetic laws) that reals have and that one
2565: expects of all kinds of numbers do not hold for FP numbers. If you
2566: want to use FP computations, you should learn about their problems and
2567: how to avoid them; a good starting point is @cite{David Goldberg,
2568: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2569: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2570: Computing Surveys 23(1):5@minus{}48, March 1991}.
2571:
2572: In Forth source code literal FP numbers need an exponent, e.g.,
1.210 anton 2573: @code{1e0}; this can also be written shorter as @code{1e}, longer as
2574: @code{+1.0e+0}, and many variations in between. The reason for this is
2575: that, for historical reasons, Forth interprets a decimal point alone
2576: (e.g., @code{1.}) as indicating a double-cell integer. Examples:
2577:
2578: @example
2579: 2e 2e f+ f.
2580: @end example
2581:
2582: Another requirement for literal FP numbers is that the current base is
1.190 anton 2583: decimal; with a hex base @code{1e} is interpreted as an integer.
2584:
2585: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2586: ANS Forth system may implement the FP stack on the data stack, but
2587: virtually all systems implement a separate FP stack; and programming
2588: in a way that accommodates all models is so cumbersome that nobody
2589: does it.} One advantage of this model is that cells are not in the
2590: way when accessing FP values, and vice versa. Forth has a set of
2591: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2592: frot} and (non-standard) @code{fnip ftuck fpick}.
2593:
2594: FP arithmetic words are prefixed with @code{F}. There is the usual
2595: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2596: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2597: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2598: computation results are usually inaccurate, so exact comparison is
2599: usually a mistake, and one should use approximate comparison.
2600: Unfortunately, @code{f~}, the standard word for that purpose, is not
2601: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2602: well.
2603:
2604: And of course there are words for accessing FP numbers in memory
2605: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2606: faligned}). There are also variants of these words with an @code{sf}
2607: and @code{df} prefix for accessing IEEE format single-precision and
2608: double-precision numbers in memory; their main purpose is for
2609: accessing external FP data (e.g., that has been read from or will be
2610: written to a file).
2611:
2612: Here is an example of a dot-product word and its use:
2613:
2614: @example
2615: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2616: >r swap 2swap swap 0e r> 0 ?DO
2617: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2618: LOOP
2619: 2drop 2drop ;
1.48 anton 2620:
1.190 anton 2621: create v 1.23e f, 4.56e f, 7.89e f,
2622:
2623: v 1 floats v 1 floats 3 v* f.
2624: @end example
2625:
2626: @quotation Assignment
2627: Write a program to solve a quadratic equation. Then read @cite{Henry
2628: G. Baker,
2629: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2630: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2631: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2632: program. Finally, find a test case where the original and the
2633: improved version produce different results.
2634: @end quotation
2635:
2636: Reference: @ref{Floating Point}; @ref{Floating point stack};
2637: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2638: arithmetic}.
2639:
2640: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84 pazsan 2641: @section Files
2642: @cindex files tutorial
2643:
2644: This section gives a short introduction into how to use files inside
2645: Forth. It's broken up into five easy steps:
2646:
2647: @enumerate 1
2648: @item Opened an ASCII text file for input
2649: @item Opened a file for output
2650: @item Read input file until string matched (or some other condition matched)
2651: @item Wrote some lines from input ( modified or not) to output
2652: @item Closed the files.
2653: @end enumerate
2654:
1.153 anton 2655: Reference: @ref{General files}.
2656:
1.84 pazsan 2657: @subsection Open file for input
2658:
2659: @example
2660: s" foo.in" r/o open-file throw Value fd-in
2661: @end example
2662:
2663: @subsection Create file for output
2664:
2665: @example
2666: s" foo.out" w/o create-file throw Value fd-out
2667: @end example
2668:
2669: The available file modes are r/o for read-only access, r/w for
2670: read-write access, and w/o for write-only access. You could open both
2671: files with r/w, too, if you like. All file words return error codes; for
2672: most applications, it's best to pass there error codes with @code{throw}
2673: to the outer error handler.
2674:
2675: If you want words for opening and assigning, define them as follows:
2676:
2677: @example
2678: 0 Value fd-in
2679: 0 Value fd-out
2680: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2681: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2682: @end example
2683:
2684: Usage example:
2685:
2686: @example
2687: s" foo.in" open-input
2688: s" foo.out" open-output
2689: @end example
2690:
2691: @subsection Scan file for a particular line
2692:
2693: @example
2694: 256 Constant max-line
2695: Create line-buffer max-line 2 + allot
2696:
2697: : scan-file ( addr u -- )
2698: begin
2699: line-buffer max-line fd-in read-line throw
2700: while
2701: >r 2dup line-buffer r> compare 0=
2702: until
2703: else
2704: drop
2705: then
2706: 2drop ;
2707: @end example
2708:
2709: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2710: the buffer at addr, and returns the number of bytes read, a flag that is
2711: false when the end of file is reached, and an error code.
1.84 pazsan 2712:
2713: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2714: returns zero if both strings are equal. It returns a positive number if
2715: the first string is lexically greater, a negative if the second string
2716: is lexically greater.
2717:
2718: We haven't seen this loop here; it has two exits. Since the @code{while}
2719: exits with the number of bytes read on the stack, we have to clean up
2720: that separately; that's after the @code{else}.
2721:
2722: Usage example:
2723:
2724: @example
2725: s" The text I search is here" scan-file
2726: @end example
2727:
2728: @subsection Copy input to output
2729:
2730: @example
2731: : copy-file ( -- )
2732: begin
2733: line-buffer max-line fd-in read-line throw
2734: while
1.194 anton 2735: line-buffer swap fd-out write-line throw
1.229 anton 2736: repeat
2737: drop ;
1.84 pazsan 2738: @end example
1.194 anton 2739: @c !! does not handle long lines, no newline at end of file
1.84 pazsan 2740:
2741: @subsection Close files
2742:
2743: @example
2744: fd-in close-file throw
2745: fd-out close-file throw
2746: @end example
2747:
2748: Likewise, you can put that into definitions, too:
2749:
2750: @example
2751: : close-input ( -- ) fd-in close-file throw ;
2752: : close-output ( -- ) fd-out close-file throw ;
2753: @end example
2754:
1.141 anton 2755: @quotation Assignment
1.84 pazsan 2756: How could you modify @code{copy-file} so that it copies until a second line is
2757: matched? Can you write a program that extracts a section of a text file,
2758: given the line that starts and the line that terminates that section?
1.141 anton 2759: @end quotation
1.84 pazsan 2760:
2761: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2762: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2763: @cindex semantics tutorial
2764: @cindex interpretation semantics tutorial
2765: @cindex compilation semantics tutorial
2766: @cindex immediate, tutorial
1.48 anton 2767:
2768: When a word is compiled, it behaves differently from being interpreted.
2769: E.g., consider @code{+}:
2770:
2771: @example
2772: 1 2 + .
2773: : foo + ;
2774: @end example
2775:
2776: These two behaviours are known as compilation and interpretation
2777: semantics. For normal words (e.g., @code{+}), the compilation semantics
2778: is to append the interpretation semantics to the currently defined word
2779: (@code{foo} in the example above). I.e., when @code{foo} is executed
2780: later, the interpretation semantics of @code{+} (i.e., adding two
2781: numbers) will be performed.
2782:
2783: However, there are words with non-default compilation semantics, e.g.,
2784: the control-flow words like @code{if}. You can use @code{immediate} to
2785: change the compilation semantics of the last defined word to be equal to
2786: the interpretation semantics:
2787:
2788: @example
2789: : [FOO] ( -- )
2790: 5 . ; immediate
2791:
2792: [FOO]
2793: : bar ( -- )
2794: [FOO] ;
2795: bar
2796: see bar
2797: @end example
2798:
1.198 anton 2799: Two conventions to mark words with non-default compilation semantics are
1.48 anton 2800: names with brackets (more frequently used) and to write them all in
2801: upper case (less frequently used).
2802:
2803: In Gforth (and many other systems) you can also remove the
2804: interpretation semantics with @code{compile-only} (the compilation
2805: semantics is derived from the original interpretation semantics):
2806:
2807: @example
2808: : flip ( -- )
2809: 6 . ; compile-only \ but not immediate
2810: flip
2811:
2812: : flop ( -- )
2813: flip ;
2814: flop
2815: @end example
2816:
2817: In this example the interpretation semantics of @code{flop} is equal to
2818: the original interpretation semantics of @code{flip}.
2819:
2820: The text interpreter has two states: in interpret state, it performs the
2821: interpretation semantics of words it encounters; in compile state, it
2822: performs the compilation semantics of these words.
2823:
2824: Among other things, @code{:} switches into compile state, and @code{;}
2825: switches back to interpret state. They contain the factors @code{]}
2826: (switch to compile state) and @code{[} (switch to interpret state), that
2827: do nothing but switch the state.
2828:
2829: @example
2830: : xxx ( -- )
2831: [ 5 . ]
2832: ;
2833:
2834: xxx
2835: see xxx
2836: @end example
2837:
2838: These brackets are also the source of the naming convention mentioned
2839: above.
2840:
1.66 anton 2841: Reference: @ref{Interpretation and Compilation Semantics}.
2842:
1.48 anton 2843:
2844: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2845: @section Execution Tokens
1.66 anton 2846: @cindex execution tokens tutorial
2847: @cindex XT tutorial
1.48 anton 2848:
2849: @code{' word} gives you the execution token (XT) of a word. The XT is a
2850: cell representing the interpretation semantics of a word. You can
2851: execute this semantics with @code{execute}:
2852:
2853: @example
2854: ' + .s
2855: 1 2 rot execute .
2856: @end example
2857:
2858: The XT is similar to a function pointer in C. However, parameter
2859: passing through the stack makes it a little more flexible:
2860:
2861: @example
2862: : map-array ( ... addr u xt -- ... )
1.50 anton 2863: \ executes xt ( ... x -- ... ) for every element of the array starting
2864: \ at addr and containing u elements
1.48 anton 2865: @{ xt @}
2866: cells over + swap ?do
1.50 anton 2867: i @@ xt execute
1.48 anton 2868: 1 cells +loop ;
2869:
2870: create a 3 , 4 , 2 , -1 , 4 ,
2871: a 5 ' . map-array .s
2872: 0 a 5 ' + map-array .
2873: s" max-n" environment? drop .s
2874: a 5 ' min map-array .
2875: @end example
2876:
2877: You can use map-array with the XTs of words that consume one element
2878: more than they produce. In theory you can also use it with other XTs,
2879: but the stack effect then depends on the size of the array, which is
2880: hard to understand.
2881:
1.51 pazsan 2882: Since XTs are cell-sized, you can store them in memory and manipulate
2883: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2884: word with @code{compile,}:
2885:
2886: @example
2887: : foo1 ( n1 n2 -- n )
2888: [ ' + compile, ] ;
1.229 anton 2889: see foo1
1.48 anton 2890: @end example
2891:
2892: This is non-standard, because @code{compile,} has no compilation
2893: semantics in the standard, but it works in good Forth systems. For the
2894: broken ones, use
2895:
2896: @example
2897: : [compile,] compile, ; immediate
2898:
2899: : foo1 ( n1 n2 -- n )
2900: [ ' + ] [compile,] ;
2901: see foo
2902: @end example
2903:
2904: @code{'} is a word with default compilation semantics; it parses the
2905: next word when its interpretation semantics are executed, not during
2906: compilation:
2907:
2908: @example
2909: : foo ( -- xt )
2910: ' ;
2911: see foo
2912: : bar ( ... "word" -- ... )
2913: ' execute ;
2914: see bar
1.60 anton 2915: 1 2 bar + .
1.48 anton 2916: @end example
2917:
2918: You often want to parse a word during compilation and compile its XT so
2919: it will be pushed on the stack at run-time. @code{[']} does this:
2920:
2921: @example
2922: : xt-+ ( -- xt )
2923: ['] + ;
2924: see xt-+
2925: 1 2 xt-+ execute .
2926: @end example
2927:
2928: Many programmers tend to see @code{'} and the word it parses as one
2929: unit, and expect it to behave like @code{[']} when compiled, and are
2930: confused by the actual behaviour. If you are, just remember that the
2931: Forth system just takes @code{'} as one unit and has no idea that it is
2932: a parsing word (attempts to convenience programmers in this issue have
2933: usually resulted in even worse pitfalls, see
1.66 anton 2934: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2935: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2936:
2937: Note that the state of the interpreter does not come into play when
1.51 pazsan 2938: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2939: compile state, it still gives you the interpretation semantics. And
2940: whatever that state is, @code{execute} performs the semantics
1.66 anton 2941: represented by the XT (i.e., for XTs produced with @code{'} the
2942: interpretation semantics).
2943:
2944: Reference: @ref{Tokens for Words}.
1.48 anton 2945:
2946:
2947: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2948: @section Exceptions
1.66 anton 2949: @cindex exceptions tutorial
1.48 anton 2950:
2951: @code{throw ( n -- )} causes an exception unless n is zero.
2952:
2953: @example
2954: 100 throw .s
2955: 0 throw .s
2956: @end example
2957:
2958: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2959: it catches exceptions and pushes the number of the exception on the
2960: stack (or 0, if the xt executed without exception). If there was an
2961: exception, the stacks have the same depth as when entering @code{catch}:
2962:
2963: @example
2964: .s
2965: 3 0 ' / catch .s
2966: 3 2 ' / catch .s
2967: @end example
2968:
1.141 anton 2969: @quotation Assignment
1.48 anton 2970: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2971: @end quotation
1.48 anton 2972:
2973: @code{Throw} always jumps to the dynamically next enclosing
2974: @code{catch}, even if it has to leave several call levels to achieve
2975: this:
2976:
2977: @example
2978: : foo 100 throw ;
2979: : foo1 foo ." after foo" ;
1.51 pazsan 2980: : bar ['] foo1 catch ;
1.60 anton 2981: bar .
1.48 anton 2982: @end example
2983:
2984: It is often important to restore a value upon leaving a definition, even
2985: if the definition is left through an exception. You can ensure this
2986: like this:
2987:
2988: @example
2989: : ...
2990: save-x
1.51 pazsan 2991: ['] word-changing-x catch ( ... n )
1.48 anton 2992: restore-x
2993: ( ... n ) throw ;
2994: @end example
2995:
1.172 anton 2996: However, this is still not safe against, e.g., the user pressing
2997: @kbd{Ctrl-C} when execution is between the @code{catch} and
2998: @code{restore-x}.
2999:
3000: Gforth provides an alternative exception handling syntax that is safe
3001: against such cases: @code{try ... restore ... endtry}. If the code
3002: between @code{try} and @code{endtry} has an exception, the stack
3003: depths are restored, the exception number is pushed on the stack, and
3004: the execution continues right after @code{restore}.
1.48 anton 3005:
1.172 anton 3006: The safer equivalent to the restoration code above is
1.48 anton 3007:
3008: @example
3009: : ...
3010: save-x
3011: try
1.92 anton 3012: word-changing-x 0
1.172 anton 3013: restore
3014: restore-x
3015: endtry
1.48 anton 3016: throw ;
3017: @end example
3018:
1.66 anton 3019: Reference: @ref{Exception Handling}.
3020:
1.48 anton 3021:
3022: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3023: @section Defining Words
1.66 anton 3024: @cindex defining words tutorial
3025: @cindex does> tutorial
3026: @cindex create...does> tutorial
3027:
3028: @c before semantics?
1.48 anton 3029:
3030: @code{:}, @code{create}, and @code{variable} are definition words: They
3031: define other words. @code{Constant} is another definition word:
3032:
3033: @example
3034: 5 constant foo
3035: foo .
3036: @end example
3037:
3038: You can also use the prefixes @code{2} (double-cell) and @code{f}
3039: (floating point) with @code{variable} and @code{constant}.
3040:
3041: You can also define your own defining words. E.g.:
3042:
3043: @example
3044: : variable ( "name" -- )
3045: create 0 , ;
3046: @end example
3047:
3048: You can also define defining words that create words that do something
3049: other than just producing their address:
3050:
3051: @example
3052: : constant ( n "name" -- )
3053: create ,
3054: does> ( -- n )
1.50 anton 3055: ( addr ) @@ ;
1.48 anton 3056:
3057: 5 constant foo
3058: foo .
3059: @end example
3060:
3061: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3062: @code{does>} replaces @code{;}, but it also does something else: It
3063: changes the last defined word such that it pushes the address of the
3064: body of the word and then performs the code after the @code{does>}
3065: whenever it is called.
3066:
3067: In the example above, @code{constant} uses @code{,} to store 5 into the
3068: body of @code{foo}. When @code{foo} executes, it pushes the address of
3069: the body onto the stack, then (in the code after the @code{does>})
3070: fetches the 5 from there.
3071:
3072: The stack comment near the @code{does>} reflects the stack effect of the
3073: defined word, not the stack effect of the code after the @code{does>}
3074: (the difference is that the code expects the address of the body that
3075: the stack comment does not show).
3076:
3077: You can use these definition words to do factoring in cases that involve
3078: (other) definition words. E.g., a field offset is always added to an
3079: address. Instead of defining
3080:
3081: @example
3082: 2 cells constant offset-field1
3083: @end example
3084:
3085: and using this like
3086:
3087: @example
3088: ( addr ) offset-field1 +
3089: @end example
3090:
3091: you can define a definition word
3092:
3093: @example
3094: : simple-field ( n "name" -- )
3095: create ,
3096: does> ( n1 -- n1+n )
1.50 anton 3097: ( addr ) @@ + ;
1.48 anton 3098: @end example
1.21 crook 3099:
1.48 anton 3100: Definition and use of field offsets now look like this:
1.21 crook 3101:
1.48 anton 3102: @example
3103: 2 cells simple-field field1
1.60 anton 3104: create mystruct 4 cells allot
3105: mystruct .s field1 .s drop
1.48 anton 3106: @end example
1.21 crook 3107:
1.48 anton 3108: If you want to do something with the word without performing the code
3109: after the @code{does>}, you can access the body of a @code{create}d word
3110: with @code{>body ( xt -- addr )}:
1.21 crook 3111:
1.48 anton 3112: @example
3113: : value ( n "name" -- )
3114: create ,
3115: does> ( -- n1 )
1.50 anton 3116: @@ ;
1.48 anton 3117: : to ( n "name" -- )
3118: ' >body ! ;
1.21 crook 3119:
1.48 anton 3120: 5 value foo
3121: foo .
3122: 7 to foo
3123: foo .
3124: @end example
1.21 crook 3125:
1.141 anton 3126: @quotation Assignment
1.48 anton 3127: Define @code{defer ( "name" -- )}, which creates a word that stores an
3128: XT (at the start the XT of @code{abort}), and upon execution
3129: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3130: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3131: recursion is one application of @code{defer}.
1.141 anton 3132: @end quotation
1.29 crook 3133:
1.66 anton 3134: Reference: @ref{User-defined Defining Words}.
3135:
3136:
1.48 anton 3137: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3138: @section Arrays and Records
1.66 anton 3139: @cindex arrays tutorial
3140: @cindex records tutorial
3141: @cindex structs tutorial
1.29 crook 3142:
1.48 anton 3143: Forth has no standard words for defining data structures such as arrays
3144: and records (structs in C terminology), but you can build them yourself
3145: based on address arithmetic. You can also define words for defining
3146: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3147:
1.48 anton 3148: One of the first projects a Forth newcomer sets out upon when learning
3149: about defining words is an array defining word (possibly for
3150: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3151: learn something from it. However, don't be disappointed when you later
3152: learn that you have little use for these words (inappropriate use would
1.198 anton 3153: be even worse). I have not found a set of useful array words yet;
1.48 anton 3154: the needs are just too diverse, and named, global arrays (the result of
3155: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3156: consider how to pass them as parameters). Another such project is a set
3157: of words to help dealing with strings.
1.29 crook 3158:
1.48 anton 3159: On the other hand, there is a useful set of record words, and it has
3160: been defined in @file{compat/struct.fs}; these words are predefined in
3161: Gforth. They are explained in depth elsewhere in this manual (see
3162: @pxref{Structures}). The @code{simple-field} example above is
3163: simplified variant of fields in this package.
1.21 crook 3164:
3165:
1.48 anton 3166: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3167: @section @code{POSTPONE}
1.66 anton 3168: @cindex postpone tutorial
1.21 crook 3169:
1.48 anton 3170: You can compile the compilation semantics (instead of compiling the
3171: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3172:
1.48 anton 3173: @example
3174: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3175: POSTPONE + ; immediate
1.48 anton 3176: : foo ( n1 n2 -- n )
3177: MY-+ ;
3178: 1 2 foo .
3179: see foo
3180: @end example
1.21 crook 3181:
1.48 anton 3182: During the definition of @code{foo} the text interpreter performs the
3183: compilation semantics of @code{MY-+}, which performs the compilation
3184: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3185:
3186: This example also displays separate stack comments for the compilation
3187: semantics and for the stack effect of the compiled code. For words with
3188: default compilation semantics these stack effects are usually not
3189: displayed; the stack effect of the compilation semantics is always
3190: @code{( -- )} for these words, the stack effect for the compiled code is
3191: the stack effect of the interpretation semantics.
3192:
3193: Note that the state of the interpreter does not come into play when
3194: performing the compilation semantics in this way. You can also perform
3195: it interpretively, e.g.:
3196:
3197: @example
3198: : foo2 ( n1 n2 -- n )
3199: [ MY-+ ] ;
3200: 1 2 foo .
3201: see foo
3202: @end example
1.21 crook 3203:
1.48 anton 3204: However, there are some broken Forth systems where this does not always
1.62 crook 3205: work, and therefore this practice was been declared non-standard in
1.48 anton 3206: 1999.
3207: @c !! repair.fs
3208:
3209: Here is another example for using @code{POSTPONE}:
1.44 crook 3210:
1.48 anton 3211: @example
3212: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3213: POSTPONE negate POSTPONE + ; immediate compile-only
3214: : bar ( n1 n2 -- n )
3215: MY-- ;
3216: 2 1 bar .
3217: see bar
3218: @end example
1.21 crook 3219:
1.48 anton 3220: You can define @code{ENDIF} in this way:
1.21 crook 3221:
1.48 anton 3222: @example
3223: : ENDIF ( Compilation: orig -- )
3224: POSTPONE then ; immediate
3225: @end example
1.21 crook 3226:
1.141 anton 3227: @quotation Assignment
1.48 anton 3228: Write @code{MY-2DUP} that has compilation semantics equivalent to
3229: @code{2dup}, but compiles @code{over over}.
1.141 anton 3230: @end quotation
1.29 crook 3231:
1.66 anton 3232: @c !! @xref{Macros} for reference
3233:
3234:
1.48 anton 3235: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3236: @section @code{Literal}
1.66 anton 3237: @cindex literal tutorial
1.29 crook 3238:
1.48 anton 3239: You cannot @code{POSTPONE} numbers:
1.21 crook 3240:
1.48 anton 3241: @example
3242: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3243: @end example
3244:
1.48 anton 3245: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3246:
1.48 anton 3247: @example
3248: : [FOO] ( compilation: --; run-time: -- n )
3249: 500 POSTPONE literal ; immediate
1.29 crook 3250:
1.60 anton 3251: : flip [FOO] ;
1.48 anton 3252: flip .
3253: see flip
3254: @end example
1.29 crook 3255:
1.48 anton 3256: @code{LITERAL} consumes a number at compile-time (when it's compilation
3257: semantics are executed) and pushes it at run-time (when the code it
3258: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3259: number computed at compile time into the current word:
1.29 crook 3260:
1.48 anton 3261: @example
3262: : bar ( -- n )
3263: [ 2 2 + ] literal ;
3264: see bar
3265: @end example
1.29 crook 3266:
1.141 anton 3267: @quotation Assignment
1.48 anton 3268: Write @code{]L} which allows writing the example above as @code{: bar (
3269: -- n ) [ 2 2 + ]L ;}
1.141 anton 3270: @end quotation
1.48 anton 3271:
1.66 anton 3272: @c !! @xref{Macros} for reference
3273:
1.48 anton 3274:
3275: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3276: @section Advanced macros
1.66 anton 3277: @cindex macros, advanced tutorial
3278: @cindex run-time code generation, tutorial
1.48 anton 3279:
1.66 anton 3280: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3281: Execution Tokens}. It frequently performs @code{execute}, a relatively
3282: expensive operation in some Forth implementations. You can use
1.48 anton 3283: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3284: and produce a word that contains the word to be performed directly:
3285:
3286: @c use ]] ... [[
3287: @example
3288: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3289: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3290: \ array beginning at addr and containing u elements
3291: @{ xt @}
3292: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3293: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3294: 1 cells POSTPONE literal POSTPONE +loop ;
3295:
3296: : sum-array ( addr u -- n )
3297: 0 rot rot [ ' + compile-map-array ] ;
3298: see sum-array
3299: a 5 sum-array .
3300: @end example
3301:
3302: You can use the full power of Forth for generating the code; here's an
3303: example where the code is generated in a loop:
3304:
3305: @example
3306: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3307: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3308: POSTPONE tuck POSTPONE @@
1.48 anton 3309: POSTPONE literal POSTPONE * POSTPONE +
3310: POSTPONE swap POSTPONE cell+ ;
3311:
3312: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3313: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3314: 0 postpone literal postpone swap
3315: [ ' compile-vmul-step compile-map-array ]
3316: postpone drop ;
3317: see compile-vmul
3318:
3319: : a-vmul ( addr -- n )
1.51 pazsan 3320: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3321: [ a 5 compile-vmul ] ;
3322: see a-vmul
3323: a a-vmul .
3324: @end example
3325:
3326: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3327: also use @code{map-array} instead (try it now!).
1.48 anton 3328:
3329: You can use this technique for efficient multiplication of large
3330: matrices. In matrix multiplication, you multiply every line of one
3331: matrix with every column of the other matrix. You can generate the code
3332: for one line once, and use it for every column. The only downside of
3333: this technique is that it is cumbersome to recover the memory consumed
3334: by the generated code when you are done (and in more complicated cases
3335: it is not possible portably).
3336:
1.66 anton 3337: @c !! @xref{Macros} for reference
3338:
3339:
1.48 anton 3340: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3341: @section Compilation Tokens
1.66 anton 3342: @cindex compilation tokens, tutorial
3343: @cindex CT, tutorial
1.48 anton 3344:
3345: This section is Gforth-specific. You can skip it.
3346:
3347: @code{' word compile,} compiles the interpretation semantics. For words
3348: with default compilation semantics this is the same as performing the
3349: compilation semantics. To represent the compilation semantics of other
3350: words (e.g., words like @code{if} that have no interpretation
3351: semantics), Gforth has the concept of a compilation token (CT,
3352: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3353: You can perform the compilation semantics represented by a CT with
3354: @code{execute}:
1.29 crook 3355:
1.48 anton 3356: @example
3357: : foo2 ( n1 n2 -- n )
3358: [ comp' + execute ] ;
3359: see foo
3360: @end example
1.29 crook 3361:
1.48 anton 3362: You can compile the compilation semantics represented by a CT with
3363: @code{postpone,}:
1.30 anton 3364:
1.48 anton 3365: @example
3366: : foo3 ( -- )
3367: [ comp' + postpone, ] ;
3368: see foo3
3369: @end example
1.30 anton 3370:
1.51 pazsan 3371: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3372: @code{comp'} is particularly useful for words that have no
3373: interpretation semantics:
1.29 crook 3374:
1.30 anton 3375: @example
1.48 anton 3376: ' if
1.60 anton 3377: comp' if .s 2drop
1.30 anton 3378: @end example
3379:
1.66 anton 3380: Reference: @ref{Tokens for Words}.
3381:
1.29 crook 3382:
1.48 anton 3383: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3384: @section Wordlists and Search Order
1.66 anton 3385: @cindex wordlists tutorial
3386: @cindex search order, tutorial
1.48 anton 3387:
3388: The dictionary is not just a memory area that allows you to allocate
3389: memory with @code{allot}, it also contains the Forth words, arranged in
3390: several wordlists. When searching for a word in a wordlist,
3391: conceptually you start searching at the youngest and proceed towards
3392: older words (in reality most systems nowadays use hash-tables); i.e., if
3393: you define a word with the same name as an older word, the new word
3394: shadows the older word.
3395:
3396: Which wordlists are searched in which order is determined by the search
3397: order. You can display the search order with @code{order}. It displays
3398: first the search order, starting with the wordlist searched first, then
3399: it displays the wordlist that will contain newly defined words.
1.21 crook 3400:
1.48 anton 3401: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3402:
1.48 anton 3403: @example
3404: wordlist constant mywords
3405: @end example
1.21 crook 3406:
1.48 anton 3407: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3408: defined words (the @emph{current} wordlist):
1.21 crook 3409:
1.48 anton 3410: @example
3411: mywords set-current
3412: order
3413: @end example
1.26 crook 3414:
1.48 anton 3415: Gforth does not display a name for the wordlist in @code{mywords}
3416: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3417:
1.48 anton 3418: You can get the current wordlist with @code{get-current ( -- wid)}. If
3419: you want to put something into a specific wordlist without overall
3420: effect on the current wordlist, this typically looks like this:
1.21 crook 3421:
1.48 anton 3422: @example
3423: get-current mywords set-current ( wid )
3424: create someword
3425: ( wid ) set-current
3426: @end example
1.21 crook 3427:
1.48 anton 3428: You can write the search order with @code{set-order ( wid1 .. widn n --
3429: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3430: searched wordlist is topmost.
1.21 crook 3431:
1.48 anton 3432: @example
3433: get-order mywords swap 1+ set-order
3434: order
3435: @end example
1.21 crook 3436:
1.48 anton 3437: Yes, the order of wordlists in the output of @code{order} is reversed
3438: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3439:
1.141 anton 3440: @quotation Assignment
1.48 anton 3441: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3442: wordlist to the search order. Define @code{previous ( -- )}, which
3443: removes the first searched wordlist from the search order. Experiment
3444: with boundary conditions (you will see some crashes or situations that
3445: are hard or impossible to leave).
1.141 anton 3446: @end quotation
1.21 crook 3447:
1.48 anton 3448: The search order is a powerful foundation for providing features similar
3449: to Modula-2 modules and C++ namespaces. However, trying to modularize
3450: programs in this way has disadvantages for debugging and reuse/factoring
3451: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3452: though). These disadvantages are not so clear in other
1.82 anton 3453: languages/programming environments, because these languages are not so
1.48 anton 3454: strong in debugging and reuse.
1.21 crook 3455:
1.66 anton 3456: @c !! example
3457:
3458: Reference: @ref{Word Lists}.
1.21 crook 3459:
1.29 crook 3460: @c ******************************************************************
1.48 anton 3461: @node Introduction, Words, Tutorial, Top
1.29 crook 3462: @comment node-name, next, previous, up
3463: @chapter An Introduction to ANS Forth
3464: @cindex Forth - an introduction
1.21 crook 3465:
1.83 anton 3466: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3467: that it is slower-paced in its examples, but uses them to dive deep into
3468: explaining Forth internals (not covered by the Tutorial). Apart from
3469: that, this chapter covers far less material. It is suitable for reading
3470: without using a computer.
3471:
1.29 crook 3472: The primary purpose of this manual is to document Gforth. However, since
3473: Forth is not a widely-known language and there is a lack of up-to-date
3474: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3475: material. For other sources of Forth-related
3476: information, see @ref{Forth-related information}.
1.21 crook 3477:
1.29 crook 3478: The examples in this section should work on any ANS Forth; the
3479: output shown was produced using Gforth. Each example attempts to
3480: reproduce the exact output that Gforth produces. If you try out the
3481: examples (and you should), what you should type is shown @kbd{like this}
3482: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3483: that, where the example shows @key{RET} it means that you should
1.29 crook 3484: press the ``carriage return'' key. Unfortunately, some output formats for
3485: this manual cannot show the difference between @kbd{this} and
3486: @code{this} which will make trying out the examples harder (but not
3487: impossible).
1.21 crook 3488:
1.29 crook 3489: Forth is an unusual language. It provides an interactive development
3490: environment which includes both an interpreter and compiler. Forth
3491: programming style encourages you to break a problem down into many
3492: @cindex factoring
3493: small fragments (@dfn{factoring}), and then to develop and test each
3494: fragment interactively. Forth advocates assert that breaking the
3495: edit-compile-test cycle used by conventional programming languages can
3496: lead to great productivity improvements.
1.21 crook 3497:
1.29 crook 3498: @menu
1.67 anton 3499: * Introducing the Text Interpreter::
3500: * Stacks and Postfix notation::
3501: * Your first definition::
3502: * How does that work?::
3503: * Forth is written in Forth::
3504: * Review - elements of a Forth system::
3505: * Where to go next::
3506: * Exercises::
1.29 crook 3507: @end menu
1.21 crook 3508:
1.29 crook 3509: @comment ----------------------------------------------
3510: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3511: @section Introducing the Text Interpreter
3512: @cindex text interpreter
3513: @cindex outer interpreter
1.21 crook 3514:
1.30 anton 3515: @c IMO this is too detailed and the pace is too slow for
3516: @c an introduction. If you know German, take a look at
3517: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3518: @c to see how I do it - anton
3519:
1.44 crook 3520: @c nac-> Where I have accepted your comments 100% and modified the text
3521: @c accordingly, I have deleted your comments. Elsewhere I have added a
3522: @c response like this to attempt to rationalise what I have done. Of
3523: @c course, this is a very clumsy mechanism for something that would be
3524: @c done far more efficiently over a beer. Please delete any dialogue
3525: @c you consider closed.
3526:
1.29 crook 3527: When you invoke the Forth image, you will see a startup banner printed
3528: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3529: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3530: its command line interpreter, which is called the @dfn{Text Interpreter}
3531: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3532: about the text interpreter as you read through this chapter, for more
3533: detail @pxref{The Text Interpreter}).
1.21 crook 3534:
1.29 crook 3535: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3536: input. Type a number and press the @key{RET} key:
1.21 crook 3537:
1.26 crook 3538: @example
1.30 anton 3539: @kbd{45@key{RET}} ok
1.26 crook 3540: @end example
1.21 crook 3541:
1.29 crook 3542: Rather than give you a prompt to invite you to input something, the text
3543: interpreter prints a status message @i{after} it has processed a line
3544: of input. The status message in this case (``@code{ ok}'' followed by
3545: carriage-return) indicates that the text interpreter was able to process
3546: all of your input successfully. Now type something illegal:
3547:
3548: @example
1.30 anton 3549: @kbd{qwer341@key{RET}}
1.134 anton 3550: *the terminal*:2: Undefined word
3551: >>>qwer341<<<
3552: Backtrace:
3553: $2A95B42A20 throw
3554: $2A95B57FB8 no.extensions
1.29 crook 3555: @end example
1.23 crook 3556:
1.134 anton 3557: The exact text, other than the ``Undefined word'' may differ slightly
3558: on your system, but the effect is the same; when the text interpreter
1.29 crook 3559: detects an error, it discards any remaining text on a line, resets
1.134 anton 3560: certain internal state and prints an error message. For a detailed
3561: description of error messages see @ref{Error messages}.
1.23 crook 3562:
1.29 crook 3563: The text interpreter waits for you to press carriage-return, and then
3564: processes your input line. Starting at the beginning of the line, it
3565: breaks the line into groups of characters separated by spaces. For each
3566: group of characters in turn, it makes two attempts to do something:
1.23 crook 3567:
1.29 crook 3568: @itemize @bullet
3569: @item
1.44 crook 3570: @cindex name dictionary
1.29 crook 3571: It tries to treat it as a command. It does this by searching a @dfn{name
3572: dictionary}. If the group of characters matches an entry in the name
3573: dictionary, the name dictionary provides the text interpreter with
3574: information that allows the text interpreter perform some actions. In
3575: Forth jargon, we say that the group
3576: @cindex word
3577: @cindex definition
3578: @cindex execution token
3579: @cindex xt
3580: of characters names a @dfn{word}, that the dictionary search returns an
3581: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3582: word, and that the text interpreter executes the xt. Often, the terms
3583: @dfn{word} and @dfn{definition} are used interchangeably.
3584: @item
3585: If the text interpreter fails to find a match in the name dictionary, it
3586: tries to treat the group of characters as a number in the current number
3587: base (when you start up Forth, the current number base is base 10). If
3588: the group of characters legitimately represents a number, the text
3589: interpreter pushes the number onto a stack (we'll learn more about that
3590: in the next section).
3591: @end itemize
1.23 crook 3592:
1.29 crook 3593: If the text interpreter is unable to do either of these things with any
3594: group of characters, it discards the group of characters and the rest of
3595: the line, then prints an error message. If the text interpreter reaches
3596: the end of the line without error, it prints the status message ``@code{ ok}''
3597: followed by carriage-return.
1.21 crook 3598:
1.29 crook 3599: This is the simplest command we can give to the text interpreter:
1.23 crook 3600:
3601: @example
1.30 anton 3602: @key{RET} ok
1.23 crook 3603: @end example
1.21 crook 3604:
1.29 crook 3605: The text interpreter did everything we asked it to do (nothing) without
3606: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3607: command:
1.21 crook 3608:
1.23 crook 3609: @example
1.30 anton 3610: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3611: *the terminal*:3: Undefined word
3612: 12 dup >>>fred<<< dup
3613: Backtrace:
3614: $2A95B42A20 throw
3615: $2A95B57FB8 no.extensions
1.23 crook 3616: @end example
1.21 crook 3617:
1.29 crook 3618: When you press the carriage-return key, the text interpreter starts to
3619: work its way along the line:
1.21 crook 3620:
1.29 crook 3621: @itemize @bullet
3622: @item
3623: When it gets to the space after the @code{2}, it takes the group of
3624: characters @code{12} and looks them up in the name
3625: dictionary@footnote{We can't tell if it found them or not, but assume
3626: for now that it did not}. There is no match for this group of characters
3627: in the name dictionary, so it tries to treat them as a number. It is
3628: able to do this successfully, so it puts the number, 12, ``on the stack''
3629: (whatever that means).
3630: @item
3631: The text interpreter resumes scanning the line and gets the next group
3632: of characters, @code{dup}. It looks it up in the name dictionary and
3633: (you'll have to take my word for this) finds it, and executes the word
3634: @code{dup} (whatever that means).
3635: @item
3636: Once again, the text interpreter resumes scanning the line and gets the
3637: group of characters @code{fred}. It looks them up in the name
3638: dictionary, but can't find them. It tries to treat them as a number, but
3639: they don't represent any legal number.
3640: @end itemize
1.21 crook 3641:
1.29 crook 3642: At this point, the text interpreter gives up and prints an error
3643: message. The error message shows exactly how far the text interpreter
3644: got in processing the line. In particular, it shows that the text
3645: interpreter made no attempt to do anything with the final character
3646: group, @code{dup}, even though we have good reason to believe that the
3647: text interpreter would have no problem looking that word up and
3648: executing it a second time.
1.21 crook 3649:
3650:
1.29 crook 3651: @comment ----------------------------------------------
3652: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3653: @section Stacks, postfix notation and parameter passing
3654: @cindex text interpreter
3655: @cindex outer interpreter
1.21 crook 3656:
1.29 crook 3657: In procedural programming languages (like C and Pascal), the
3658: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3659: functions or procedures are called with @dfn{explicit parameters}. For
3660: example, in C we might write:
1.21 crook 3661:
1.23 crook 3662: @example
1.29 crook 3663: total = total + new_volume(length,height,depth);
1.23 crook 3664: @end example
1.21 crook 3665:
1.23 crook 3666: @noindent
1.29 crook 3667: where new_volume is a function-call to another piece of code, and total,
3668: length, height and depth are all variables. length, height and depth are
3669: parameters to the function-call.
1.21 crook 3670:
1.29 crook 3671: In Forth, the equivalent of the function or procedure is the
3672: @dfn{definition} and parameters are implicitly passed between
3673: definitions using a shared stack that is visible to the
3674: programmer. Although Forth does support variables, the existence of the
3675: stack means that they are used far less often than in most other
3676: programming languages. When the text interpreter encounters a number, it
3677: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3678: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3679: used for any operation is implied unambiguously by the operation being
3680: performed. The stack used for all integer operations is called the @dfn{data
3681: stack} and, since this is the stack used most commonly, references to
3682: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3683:
1.29 crook 3684: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3685:
1.23 crook 3686: @example
1.30 anton 3687: @kbd{1 2 3@key{RET}} ok
1.23 crook 3688: @end example
1.21 crook 3689:
1.29 crook 3690: Then this instructs the text interpreter to placed three numbers on the
3691: (data) stack. An analogy for the behaviour of the stack is to take a
3692: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3693: the table. The 3 was the last card onto the pile (``last-in'') and if
3694: you take a card off the pile then, unless you're prepared to fiddle a
3695: bit, the card that you take off will be the 3 (``first-out''). The
3696: number that will be first-out of the stack is called the @dfn{top of
3697: stack}, which
3698: @cindex TOS definition
3699: is often abbreviated to @dfn{TOS}.
1.21 crook 3700:
1.29 crook 3701: To understand how parameters are passed in Forth, consider the
3702: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3703: be surprised to learn that this definition performs addition. More
3704: precisely, it adds two number together and produces a result. Where does
3705: it get the two numbers from? It takes the top two numbers off the
3706: stack. Where does it place the result? On the stack. You can act-out the
3707: behaviour of @code{+} with your playing cards like this:
1.21 crook 3708:
3709: @itemize @bullet
3710: @item
1.29 crook 3711: Pick up two cards from the stack on the table
1.21 crook 3712: @item
1.29 crook 3713: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3714: numbers''
1.21 crook 3715: @item
1.29 crook 3716: Decide that the answer is 5
1.21 crook 3717: @item
1.29 crook 3718: Shuffle the two cards back into the pack and find a 5
1.21 crook 3719: @item
1.29 crook 3720: Put a 5 on the remaining ace that's on the table.
1.21 crook 3721: @end itemize
3722:
1.29 crook 3723: If you don't have a pack of cards handy but you do have Forth running,
3724: you can use the definition @code{.s} to show the current state of the stack,
3725: without affecting the stack. Type:
1.21 crook 3726:
3727: @example
1.124 anton 3728: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3729: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3730: @end example
3731:
1.124 anton 3732: The text interpreter looks up the word @code{clearstacks} and executes
3733: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3734: left on it by earlier examples. The text interpreter pushes each of the
3735: three numbers in turn onto the stack. Finally, the text interpreter
3736: looks up the word @code{.s} and executes it. The effect of executing
3737: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3738: followed by a list of all the items on the stack; the item on the far
3739: right-hand side is the TOS.
1.21 crook 3740:
1.29 crook 3741: You can now type:
1.21 crook 3742:
1.29 crook 3743: @example
1.30 anton 3744: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3745: @end example
1.21 crook 3746:
1.29 crook 3747: @noindent
3748: which is correct; there are now 2 items on the stack and the result of
3749: the addition is 5.
1.23 crook 3750:
1.29 crook 3751: If you're playing with cards, try doing a second addition: pick up the
3752: two cards, work out that their sum is 6, shuffle them into the pack,
3753: look for a 6 and place that on the table. You now have just one item on
3754: the stack. What happens if you try to do a third addition? Pick up the
3755: first card, pick up the second card -- ah! There is no second card. This
3756: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3757: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3758: Underflow or an Invalid Memory Address error).
1.23 crook 3759:
1.29 crook 3760: The opposite situation to a stack underflow is a @dfn{stack overflow},
3761: which simply accepts that there is a finite amount of storage space
3762: reserved for the stack. To stretch the playing card analogy, if you had
3763: enough packs of cards and you piled the cards up on the table, you would
3764: eventually be unable to add another card; you'd hit the ceiling. Gforth
3765: allows you to set the maximum size of the stacks. In general, the only
3766: time that you will get a stack overflow is because a definition has a
3767: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3768:
1.29 crook 3769: There's one final use for the playing card analogy. If you model your
3770: stack using a pack of playing cards, the maximum number of items on
3771: your stack will be 52 (I assume you didn't use the Joker). The maximum
3772: @i{value} of any item on the stack is 13 (the King). In fact, the only
3773: possible numbers are positive integer numbers 1 through 13; you can't
3774: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3775: think about some of the cards, you can accommodate different
3776: numbers. For example, you could think of the Jack as representing 0,
3777: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3778: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3779: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3780:
1.29 crook 3781: In that analogy, the limit was the amount of information that a single
3782: stack entry could hold, and Forth has a similar limit. In Forth, the
3783: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3784: implementation dependent and affects the maximum value that a stack
3785: entry can hold. A Standard Forth provides a cell size of at least
3786: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3787:
1.29 crook 3788: Forth does not do any type checking for you, so you are free to
3789: manipulate and combine stack items in any way you wish. A convenient way
3790: of treating stack items is as 2's complement signed integers, and that
3791: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3792:
1.29 crook 3793: @example
1.30 anton 3794: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3795: @end example
1.21 crook 3796:
1.29 crook 3797: If you use numbers and definitions like @code{+} in order to turn Forth
3798: into a great big pocket calculator, you will realise that it's rather
3799: different from a normal calculator. Rather than typing 2 + 3 = you had
3800: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3801: result). The terminology used to describe this difference is to say that
3802: your calculator uses @dfn{Infix Notation} (parameters and operators are
3803: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3804: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3805:
1.29 crook 3806: Whilst postfix notation might look confusing to begin with, it has
3807: several important advantages:
1.21 crook 3808:
1.23 crook 3809: @itemize @bullet
3810: @item
1.29 crook 3811: it is unambiguous
1.23 crook 3812: @item
1.29 crook 3813: it is more concise
1.23 crook 3814: @item
1.29 crook 3815: it fits naturally with a stack-based system
1.23 crook 3816: @end itemize
1.21 crook 3817:
1.29 crook 3818: To examine these claims in more detail, consider these sums:
1.21 crook 3819:
1.29 crook 3820: @example
3821: 6 + 5 * 4 =
3822: 4 * 5 + 6 =
3823: @end example
1.21 crook 3824:
1.29 crook 3825: If you're just learning maths or your maths is very rusty, you will
3826: probably come up with the answer 44 for the first and 26 for the
3827: second. If you are a bit of a whizz at maths you will remember the
3828: @i{convention} that multiplication takes precendence over addition, and
3829: you'd come up with the answer 26 both times. To explain the answer 26
3830: to someone who got the answer 44, you'd probably rewrite the first sum
3831: like this:
1.21 crook 3832:
1.29 crook 3833: @example
3834: 6 + (5 * 4) =
3835: @end example
1.21 crook 3836:
1.29 crook 3837: If what you really wanted was to perform the addition before the
3838: multiplication, you would have to use parentheses to force it.
1.21 crook 3839:
1.29 crook 3840: If you did the first two sums on a pocket calculator you would probably
3841: get the right answers, unless you were very cautious and entered them using
3842: these keystroke sequences:
1.21 crook 3843:
1.29 crook 3844: 6 + 5 = * 4 =
3845: 4 * 5 = + 6 =
1.21 crook 3846:
1.29 crook 3847: Postfix notation is unambiguous because the order that the operators
3848: are applied is always explicit; that also means that parentheses are
3849: never required. The operators are @i{active} (the act of quoting the
3850: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3851:
1.29 crook 3852: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3853: equivalent ways:
1.26 crook 3854:
3855: @example
1.29 crook 3856: 6 5 4 * + or:
3857: 5 4 * 6 +
1.26 crook 3858: @end example
1.23 crook 3859:
1.29 crook 3860: An important thing that you should notice about this notation is that
3861: the @i{order} of the numbers does not change; if you want to subtract
3862: 2 from 10 you type @code{10 2 -}.
1.1 anton 3863:
1.29 crook 3864: The reason that Forth uses postfix notation is very simple to explain: it
3865: makes the implementation extremely simple, and it follows naturally from
3866: using the stack as a mechanism for passing parameters. Another way of
3867: thinking about this is to realise that all Forth definitions are
3868: @i{active}; they execute as they are encountered by the text
3869: interpreter. The result of this is that the syntax of Forth is trivially
3870: simple.
1.1 anton 3871:
3872:
3873:
1.29 crook 3874: @comment ----------------------------------------------
3875: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3876: @section Your first Forth definition
3877: @cindex first definition
1.1 anton 3878:
1.29 crook 3879: Until now, the examples we've seen have been trivial; we've just been
3880: using Forth as a bigger-than-pocket calculator. Also, each calculation
3881: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3882: again@footnote{That's not quite true. If you press the up-arrow key on
3883: your keyboard you should be able to scroll back to any earlier command,
3884: edit it and re-enter it.} In this section we'll see how to add new
3885: words to Forth's vocabulary.
1.1 anton 3886:
1.29 crook 3887: The easiest way to create a new word is to use a @dfn{colon
3888: definition}. We'll define a few and try them out before worrying too
3889: much about how they work. Try typing in these examples; be careful to
3890: copy the spaces accurately:
1.1 anton 3891:
1.29 crook 3892: @example
3893: : add-two 2 + . ;
3894: : greet ." Hello and welcome" ;
3895: : demo 5 add-two ;
3896: @end example
1.1 anton 3897:
1.29 crook 3898: @noindent
3899: Now try them out:
1.1 anton 3900:
1.29 crook 3901: @example
1.30 anton 3902: @kbd{greet@key{RET}} Hello and welcome ok
3903: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3904: @kbd{4 add-two@key{RET}} 6 ok
3905: @kbd{demo@key{RET}} 7 ok
3906: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3907: @end example
1.1 anton 3908:
1.29 crook 3909: The first new thing that we've introduced here is the pair of words
3910: @code{:} and @code{;}. These are used to start and terminate a new
3911: definition, respectively. The first word after the @code{:} is the name
3912: for the new definition.
1.1 anton 3913:
1.29 crook 3914: As you can see from the examples, a definition is built up of words that
3915: have already been defined; Forth makes no distinction between
3916: definitions that existed when you started the system up, and those that
3917: you define yourself.
1.1 anton 3918:
1.29 crook 3919: The examples also introduce the words @code{.} (dot), @code{."}
3920: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3921: the stack and displays it. It's like @code{.s} except that it only
3922: displays the top item of the stack and it is destructive; after it has
3923: executed, the number is no longer on the stack. There is always one
3924: space printed after the number, and no spaces before it. Dot-quote
3925: defines a string (a sequence of characters) that will be printed when
3926: the word is executed. The string can contain any printable characters
3927: except @code{"}. A @code{"} has a special function; it is not a Forth
3928: word but it acts as a delimiter (the way that delimiters work is
3929: described in the next section). Finally, @code{dup} duplicates the value
3930: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3931:
1.29 crook 3932: We already know that the text interpreter searches through the
3933: dictionary to locate names. If you've followed the examples earlier, you
3934: will already have a definition called @code{add-two}. Lets try modifying
3935: it by typing in a new definition:
1.1 anton 3936:
1.29 crook 3937: @example
1.30 anton 3938: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3939: @end example
1.5 anton 3940:
1.29 crook 3941: Forth recognised that we were defining a word that already exists, and
3942: printed a message to warn us of that fact. Let's try out the new
3943: definition:
1.5 anton 3944:
1.29 crook 3945: @example
1.30 anton 3946: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3947: @end example
1.1 anton 3948:
1.29 crook 3949: @noindent
3950: All that we've actually done here, though, is to create a new
3951: definition, with a particular name. The fact that there was already a
3952: definition with the same name did not make any difference to the way
3953: that the new definition was created (except that Forth printed a warning
3954: message). The old definition of add-two still exists (try @code{demo}
3955: again to see that this is true). Any new definition will use the new
3956: definition of @code{add-two}, but old definitions continue to use the
3957: version that already existed at the time that they were @code{compiled}.
1.1 anton 3958:
1.29 crook 3959: Before you go on to the next section, try defining and redefining some
3960: words of your own.
1.1 anton 3961:
1.29 crook 3962: @comment ----------------------------------------------
3963: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3964: @section How does that work?
3965: @cindex parsing words
1.1 anton 3966:
1.30 anton 3967: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3968:
3969: @c Is it a good idea to talk about the interpretation semantics of a
3970: @c number? We don't have an xt to go along with it. - anton
3971:
3972: @c Now that I have eliminated execution semantics, I wonder if it would not
3973: @c be better to keep them (or add run-time semantics), to make it easier to
3974: @c explain what compilation semantics usually does. - anton
3975:
1.44 crook 3976: @c nac-> I removed the term ``default compilation sematics'' from the
3977: @c introductory chapter. Removing ``execution semantics'' was making
3978: @c everything simpler to explain, then I think the use of this term made
3979: @c everything more complex again. I replaced it with ``default
3980: @c semantics'' (which is used elsewhere in the manual) by which I mean
3981: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3982: @c flag set''.
3983:
3984: @c anton: I have eliminated default semantics (except in one place where it
3985: @c means "default interpretation and compilation semantics"), because it
3986: @c makes no sense in the presence of combined words. I reverted to
3987: @c "execution semantics" where necessary.
3988:
3989: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3990: @c section (and, unusually for me, I think I even made it shorter!). See
3991: @c what you think -- I know I have not addressed your primary concern
3992: @c that it is too heavy-going for an introduction. From what I understood
3993: @c of your course notes it looks as though they might be a good framework.
3994: @c Things that I've tried to capture here are some things that came as a
3995: @c great revelation here when I first understood them. Also, I like the
3996: @c fact that a very simple code example shows up almost all of the issues
3997: @c that you need to understand to see how Forth works. That's unique and
3998: @c worthwhile to emphasise.
3999:
1.83 anton 4000: @c anton: I think it's a good idea to present the details, especially those
4001: @c that you found to be a revelation, and probably the tutorial tries to be
4002: @c too superficial and does not get some of the things across that make
4003: @c Forth special. I do believe that most of the time these things should
4004: @c be discussed at the end of a section or in separate sections instead of
4005: @c in the middle of a section (e.g., the stuff you added in "User-defined
4006: @c defining words" leads in a completely different direction from the rest
4007: @c of the section).
4008:
1.29 crook 4009: Now we're going to take another look at the definition of @code{add-two}
4010: from the previous section. From our knowledge of the way that the text
4011: interpreter works, we would have expected this result when we tried to
4012: define @code{add-two}:
1.21 crook 4013:
1.29 crook 4014: @example
1.44 crook 4015: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 4016: *the terminal*:4: Undefined word
4017: : >>>add-two<<< 2 + . ;
1.29 crook 4018: @end example
1.28 crook 4019:
1.29 crook 4020: The reason that this didn't happen is bound up in the way that @code{:}
4021: works. The word @code{:} does two special things. The first special
4022: thing that it does prevents the text interpreter from ever seeing the
4023: characters @code{add-two}. The text interpreter uses a variable called
4024: @cindex modifying >IN
1.44 crook 4025: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 4026: input line. When it encounters the word @code{:} it behaves in exactly
4027: the same way as it does for any other word; it looks it up in the name
4028: dictionary, finds its xt and executes it. When @code{:} executes, it
4029: looks at the input buffer, finds the word @code{add-two} and advances the
4030: value of @code{>IN} to point past it. It then does some other stuff
4031: associated with creating the new definition (including creating an entry
4032: for @code{add-two} in the name dictionary). When the execution of @code{:}
4033: completes, control returns to the text interpreter, which is oblivious
4034: to the fact that it has been tricked into ignoring part of the input
4035: line.
1.21 crook 4036:
1.29 crook 4037: @cindex parsing words
4038: Words like @code{:} -- words that advance the value of @code{>IN} and so
4039: prevent the text interpreter from acting on the whole of the input line
4040: -- are called @dfn{parsing words}.
1.21 crook 4041:
1.29 crook 4042: @cindex @code{state} - effect on the text interpreter
4043: @cindex text interpreter - effect of state
4044: The second special thing that @code{:} does is change the value of a
4045: variable called @code{state}, which affects the way that the text
4046: interpreter behaves. When Gforth starts up, @code{state} has the value
4047: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4048: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4049: the text interpreter is said to be @dfn{compiling}.
4050:
4051: In this example, the text interpreter is compiling when it processes the
4052: string ``@code{2 + . ;}''. It still breaks the string down into
4053: character sequences in the same way. However, instead of pushing the
4054: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4055: into the definition of @code{add-two} that will make the number @code{2} get
4056: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4057: the behaviours of @code{+} and @code{.} are also compiled into the
4058: definition.
4059:
4060: One category of words don't get compiled. These so-called @dfn{immediate
4061: words} get executed (performed @i{now}) regardless of whether the text
4062: interpreter is interpreting or compiling. The word @code{;} is an
4063: immediate word. Rather than being compiled into the definition, it
4064: executes. Its effect is to terminate the current definition, which
4065: includes changing the value of @code{state} back to 0.
4066:
4067: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4068: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4069: definition.
1.28 crook 4070:
1.30 anton 4071: In Forth, every word or number can be described in terms of two
1.29 crook 4072: properties:
1.28 crook 4073:
4074: @itemize @bullet
4075: @item
1.29 crook 4076: @cindex interpretation semantics
1.44 crook 4077: Its @dfn{interpretation semantics} describe how it will behave when the
4078: text interpreter encounters it in @dfn{interpret} state. The
4079: interpretation semantics of a word are represented by an @dfn{execution
4080: token}.
1.28 crook 4081: @item
1.29 crook 4082: @cindex compilation semantics
1.44 crook 4083: Its @dfn{compilation semantics} describe how it will behave when the
4084: text interpreter encounters it in @dfn{compile} state. The compilation
4085: semantics of a word are represented in an implementation-dependent way;
4086: Gforth uses a @dfn{compilation token}.
1.29 crook 4087: @end itemize
4088:
4089: @noindent
4090: Numbers are always treated in a fixed way:
4091:
4092: @itemize @bullet
1.28 crook 4093: @item
1.44 crook 4094: When the number is @dfn{interpreted}, its behaviour is to push the
4095: number onto the stack.
1.28 crook 4096: @item
1.30 anton 4097: When the number is @dfn{compiled}, a piece of code is appended to the
4098: current definition that pushes the number when it runs. (In other words,
4099: the compilation semantics of a number are to postpone its interpretation
4100: semantics until the run-time of the definition that it is being compiled
4101: into.)
1.29 crook 4102: @end itemize
4103:
1.44 crook 4104: Words don't behave in such a regular way, but most have @i{default
4105: semantics} which means that they behave like this:
1.29 crook 4106:
4107: @itemize @bullet
1.28 crook 4108: @item
1.30 anton 4109: The @dfn{interpretation semantics} of the word are to do something useful.
4110: @item
1.29 crook 4111: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4112: @dfn{interpretation semantics} to the current definition (so that its
4113: run-time behaviour is to do something useful).
1.28 crook 4114: @end itemize
4115:
1.30 anton 4116: @cindex immediate words
1.44 crook 4117: The actual behaviour of any particular word can be controlled by using
4118: the words @code{immediate} and @code{compile-only} when the word is
4119: defined. These words set flags in the name dictionary entry of the most
4120: recently defined word, and these flags are retrieved by the text
4121: interpreter when it finds the word in the name dictionary.
4122:
4123: A word that is marked as @dfn{immediate} has compilation semantics that
4124: are identical to its interpretation semantics. In other words, it
4125: behaves like this:
1.29 crook 4126:
4127: @itemize @bullet
4128: @item
1.30 anton 4129: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4130: @item
1.30 anton 4131: The @dfn{compilation semantics} of the word are to do something useful
4132: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4133: @end itemize
1.28 crook 4134:
1.44 crook 4135: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4136: performing the interpretation semantics of the word directly; an attempt
4137: to do so will generate an error. It is never necessary to use
4138: @code{compile-only} (and it is not even part of ANS Forth, though it is
4139: provided by many implementations) but it is good etiquette to apply it
4140: to a word that will not behave correctly (and might have unexpected
4141: side-effects) in interpret state. For example, it is only legal to use
4142: the conditional word @code{IF} within a definition. If you forget this
4143: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4144: @code{compile-only} allows the text interpreter to generate a helpful
4145: error message rather than subjecting you to the consequences of your
4146: folly.
4147:
1.29 crook 4148: This example shows the difference between an immediate and a
4149: non-immediate word:
1.28 crook 4150:
1.29 crook 4151: @example
4152: : show-state state @@ . ;
4153: : show-state-now show-state ; immediate
4154: : word1 show-state ;
4155: : word2 show-state-now ;
1.28 crook 4156: @end example
1.23 crook 4157:
1.29 crook 4158: The word @code{immediate} after the definition of @code{show-state-now}
4159: makes that word an immediate word. These definitions introduce a new
4160: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4161: variable, and leaves it on the stack. Therefore, the behaviour of
4162: @code{show-state} is to print a number that represents the current value
4163: of @code{state}.
1.28 crook 4164:
1.29 crook 4165: When you execute @code{word1}, it prints the number 0, indicating that
4166: the system is interpreting. When the text interpreter compiled the
4167: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4168: compilation semantics are to append its interpretation semantics to the
1.29 crook 4169: current definition. When you execute @code{word1}, it performs the
1.30 anton 4170: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4171: (and therefore @code{show-state}) are executed, the system is
4172: interpreting.
1.28 crook 4173:
1.30 anton 4174: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4175: you should have seen the number -1 printed, followed by ``@code{
4176: ok}''. When the text interpreter compiled the definition of
4177: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4178: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4179: semantics. It is executed straight away (even before the text
4180: interpreter has moved on to process another group of characters; the
4181: @code{;} in this example). The effect of executing it are to display the
4182: value of @code{state} @i{at the time that the definition of}
4183: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4184: system is compiling at this time. If you execute @code{word2} it does
4185: nothing at all.
1.28 crook 4186:
1.29 crook 4187: @cindex @code{."}, how it works
4188: Before leaving the subject of immediate words, consider the behaviour of
4189: @code{."} in the definition of @code{greet}, in the previous
4190: section. This word is both a parsing word and an immediate word. Notice
4191: that there is a space between @code{."} and the start of the text
4192: @code{Hello and welcome}, but that there is no space between the last
4193: letter of @code{welcome} and the @code{"} character. The reason for this
4194: is that @code{."} is a Forth word; it must have a space after it so that
4195: the text interpreter can identify it. The @code{"} is not a Forth word;
4196: it is a @dfn{delimiter}. The examples earlier show that, when the string
4197: is displayed, there is neither a space before the @code{H} nor after the
4198: @code{e}. Since @code{."} is an immediate word, it executes at the time
4199: that @code{greet} is defined. When it executes, its behaviour is to
4200: search forward in the input line looking for the delimiter. When it
4201: finds the delimiter, it updates @code{>IN} to point past the
4202: delimiter. It also compiles some magic code into the definition of
4203: @code{greet}; the xt of a run-time routine that prints a text string. It
4204: compiles the string @code{Hello and welcome} into memory so that it is
4205: available to be printed later. When the text interpreter gains control,
4206: the next word it finds in the input stream is @code{;} and so it
4207: terminates the definition of @code{greet}.
1.28 crook 4208:
4209:
4210: @comment ----------------------------------------------
1.29 crook 4211: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4212: @section Forth is written in Forth
4213: @cindex structure of Forth programs
4214:
4215: When you start up a Forth compiler, a large number of definitions
4216: already exist. In Forth, you develop a new application using bottom-up
4217: programming techniques to create new definitions that are defined in
4218: terms of existing definitions. As you create each definition you can
4219: test and debug it interactively.
4220:
4221: If you have tried out the examples in this section, you will probably
4222: have typed them in by hand; when you leave Gforth, your definitions will
4223: be lost. You can avoid this by using a text editor to enter Forth source
4224: code into a file, and then loading code from the file using
1.49 anton 4225: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4226: processed by the text interpreter, just as though you had typed it in by
4227: hand@footnote{Actually, there are some subtle differences -- see
4228: @ref{The Text Interpreter}.}.
4229:
4230: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4231: files for program entry (@pxref{Blocks}).
1.28 crook 4232:
1.29 crook 4233: In common with many, if not most, Forth compilers, most of Gforth is
4234: actually written in Forth. All of the @file{.fs} files in the
4235: installation directory@footnote{For example,
1.30 anton 4236: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4237: study to see examples of Forth programming.
1.28 crook 4238:
1.29 crook 4239: Gforth maintains a history file that records every line that you type to
4240: the text interpreter. This file is preserved between sessions, and is
4241: used to provide a command-line recall facility. If you enter long
4242: definitions by hand, you can use a text editor to paste them out of the
4243: history file into a Forth source file for reuse at a later time
1.49 anton 4244: (for more information @pxref{Command-line editing}).
1.28 crook 4245:
4246:
4247: @comment ----------------------------------------------
1.29 crook 4248: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4249: @section Review - elements of a Forth system
4250: @cindex elements of a Forth system
1.28 crook 4251:
1.29 crook 4252: To summarise this chapter:
1.28 crook 4253:
4254: @itemize @bullet
4255: @item
1.29 crook 4256: Forth programs use @dfn{factoring} to break a problem down into small
4257: fragments called @dfn{words} or @dfn{definitions}.
4258: @item
4259: Forth program development is an interactive process.
4260: @item
4261: The main command loop that accepts input, and controls both
4262: interpretation and compilation, is called the @dfn{text interpreter}
4263: (also known as the @dfn{outer interpreter}).
4264: @item
4265: Forth has a very simple syntax, consisting of words and numbers
4266: separated by spaces or carriage-return characters. Any additional syntax
4267: is imposed by @dfn{parsing words}.
4268: @item
4269: Forth uses a stack to pass parameters between words. As a result, it
4270: uses postfix notation.
4271: @item
4272: To use a word that has previously been defined, the text interpreter
4273: searches for the word in the @dfn{name dictionary}.
4274: @item
1.30 anton 4275: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4276: @item
1.29 crook 4277: The text interpreter uses the value of @code{state} to select between
4278: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4279: semantics} of a word that it encounters.
1.28 crook 4280: @item
1.30 anton 4281: The relationship between the @dfn{interpretation semantics} and
4282: @dfn{compilation semantics} for a word
1.29 crook 4283: depend upon the way in which the word was defined (for example, whether
4284: it is an @dfn{immediate} word).
1.28 crook 4285: @item
1.29 crook 4286: Forth definitions can be implemented in Forth (called @dfn{high-level
4287: definitions}) or in some other way (usually a lower-level language and
4288: as a result often called @dfn{low-level definitions}, @dfn{code
4289: definitions} or @dfn{primitives}).
1.28 crook 4290: @item
1.29 crook 4291: Many Forth systems are implemented mainly in Forth.
1.28 crook 4292: @end itemize
4293:
4294:
1.29 crook 4295: @comment ----------------------------------------------
1.48 anton 4296: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4297: @section Where To Go Next
4298: @cindex where to go next
1.28 crook 4299:
1.29 crook 4300: Amazing as it may seem, if you have read (and understood) this far, you
4301: know almost all the fundamentals about the inner workings of a Forth
4302: system. You certainly know enough to be able to read and understand the
4303: rest of this manual and the ANS Forth document, to learn more about the
4304: facilities that Forth in general and Gforth in particular provide. Even
4305: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4306: However, that's not a good idea just yet... better to try writing some
1.29 crook 4307: programs in Gforth.
1.28 crook 4308:
1.29 crook 4309: Forth has such a rich vocabulary that it can be hard to know where to
4310: start in learning it. This section suggests a few sets of words that are
4311: enough to write small but useful programs. Use the word index in this
4312: document to learn more about each word, then try it out and try to write
4313: small definitions using it. Start by experimenting with these words:
1.28 crook 4314:
4315: @itemize @bullet
4316: @item
1.29 crook 4317: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4318: @item
4319: Comparison: @code{MIN MAX =}
4320: @item
4321: Logic: @code{AND OR XOR NOT}
4322: @item
4323: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4324: @item
1.29 crook 4325: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4326: @item
1.29 crook 4327: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4328: @item
1.29 crook 4329: Defining words: @code{: ; CREATE}
1.28 crook 4330: @item
1.29 crook 4331: Memory allocation words: @code{ALLOT ,}
1.28 crook 4332: @item
1.29 crook 4333: Tools: @code{SEE WORDS .S MARKER}
4334: @end itemize
4335:
4336: When you have mastered those, go on to:
4337:
4338: @itemize @bullet
1.28 crook 4339: @item
1.29 crook 4340: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4341: @item
1.29 crook 4342: Memory access: @code{@@ !}
1.28 crook 4343: @end itemize
1.23 crook 4344:
1.29 crook 4345: When you have mastered these, there's nothing for it but to read through
4346: the whole of this manual and find out what you've missed.
4347:
4348: @comment ----------------------------------------------
1.48 anton 4349: @node Exercises, , Where to go next, Introduction
1.29 crook 4350: @section Exercises
4351: @cindex exercises
4352:
4353: TODO: provide a set of programming excercises linked into the stuff done
4354: already and into other sections of the manual. Provide solutions to all
4355: the exercises in a .fs file in the distribution.
4356:
4357: @c Get some inspiration from Starting Forth and Kelly&Spies.
4358:
4359: @c excercises:
4360: @c 1. take inches and convert to feet and inches.
4361: @c 2. take temperature and convert from fahrenheight to celcius;
4362: @c may need to care about symmetric vs floored??
4363: @c 3. take input line and do character substitution
4364: @c to encipher or decipher
4365: @c 4. as above but work on a file for in and out
4366: @c 5. take input line and convert to pig-latin
4367: @c
4368: @c thing of sets of things to exercise then come up with
4369: @c problems that need those things.
4370:
4371:
1.26 crook 4372: @c ******************************************************************
1.29 crook 4373: @node Words, Error messages, Introduction, Top
1.1 anton 4374: @chapter Forth Words
1.26 crook 4375: @cindex words
1.1 anton 4376:
4377: @menu
4378: * Notation::
1.65 anton 4379: * Case insensitivity::
4380: * Comments::
4381: * Boolean Flags::
1.1 anton 4382: * Arithmetic::
4383: * Stack Manipulation::
1.5 anton 4384: * Memory::
1.1 anton 4385: * Control Structures::
4386: * Defining Words::
1.65 anton 4387: * Interpretation and Compilation Semantics::
1.47 crook 4388: * Tokens for Words::
1.81 anton 4389: * Compiling words::
1.65 anton 4390: * The Text Interpreter::
1.111 anton 4391: * The Input Stream::
1.65 anton 4392: * Word Lists::
4393: * Environmental Queries::
1.12 anton 4394: * Files::
4395: * Blocks::
4396: * Other I/O::
1.121 anton 4397: * OS command line arguments::
1.78 anton 4398: * Locals::
4399: * Structures::
4400: * Object-oriented Forth::
1.12 anton 4401: * Programming Tools::
1.150 anton 4402: * C Interface::
1.12 anton 4403: * Assembler and Code Words::
4404: * Threading Words::
1.65 anton 4405: * Passing Commands to the OS::
4406: * Keeping track of Time::
4407: * Miscellaneous Words::
1.1 anton 4408: @end menu
4409:
1.65 anton 4410: @node Notation, Case insensitivity, Words, Words
1.1 anton 4411: @section Notation
4412: @cindex notation of glossary entries
4413: @cindex format of glossary entries
4414: @cindex glossary notation format
4415: @cindex word glossary entry format
4416:
4417: The Forth words are described in this section in the glossary notation
1.67 anton 4418: that has become a de-facto standard for Forth texts:
1.1 anton 4419:
4420: @format
1.29 crook 4421: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4422: @end format
1.29 crook 4423: @i{Description}
1.1 anton 4424:
4425: @table @var
4426: @item word
1.28 crook 4427: The name of the word.
1.1 anton 4428:
4429: @item Stack effect
4430: @cindex stack effect
1.29 crook 4431: The stack effect is written in the notation @code{@i{before} --
4432: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4433: stack entries before and after the execution of the word. The rest of
4434: the stack is not touched by the word. The top of stack is rightmost,
4435: i.e., a stack sequence is written as it is typed in. Note that Gforth
4436: uses a separate floating point stack, but a unified stack
1.29 crook 4437: notation. Also, return stack effects are not shown in @i{stack
4438: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4439: the type and/or the function of the item. See below for a discussion of
4440: the types.
4441:
4442: All words have two stack effects: A compile-time stack effect and a
4443: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4444: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4445: this standard behaviour, or the word does other unusual things at
4446: compile time, both stack effects are shown; otherwise only the run-time
4447: stack effect is shown.
4448:
1.211 anton 4449: Also note that in code templates or examples there can be comments in
4450: parentheses that display the stack picture at this point; there is no
4451: @code{--} in these places, because there is no before-after situation.
4452:
1.1 anton 4453: @cindex pronounciation of words
4454: @item pronunciation
4455: How the word is pronounced.
4456:
4457: @cindex wordset
1.67 anton 4458: @cindex environment wordset
1.1 anton 4459: @item wordset
1.21 crook 4460: The ANS Forth standard is divided into several word sets. A standard
4461: system need not support all of them. Therefore, in theory, the fewer
4462: word sets your program uses the more portable it will be. However, we
4463: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4464: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4465: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4466: describes words that will work in future releases of Gforth;
4467: @code{gforth-internal} words are more volatile. Environmental query
4468: strings are also displayed like words; you can recognize them by the
1.21 crook 4469: @code{environment} in the word set field.
1.1 anton 4470:
4471: @item Description
4472: A description of the behaviour of the word.
4473: @end table
4474:
4475: @cindex types of stack items
4476: @cindex stack item types
4477: The type of a stack item is specified by the character(s) the name
4478: starts with:
4479:
4480: @table @code
4481: @item f
4482: @cindex @code{f}, stack item type
4483: Boolean flags, i.e. @code{false} or @code{true}.
4484: @item c
4485: @cindex @code{c}, stack item type
4486: Char
4487: @item w
4488: @cindex @code{w}, stack item type
4489: Cell, can contain an integer or an address
4490: @item n
4491: @cindex @code{n}, stack item type
4492: signed integer
4493: @item u
4494: @cindex @code{u}, stack item type
4495: unsigned integer
4496: @item d
4497: @cindex @code{d}, stack item type
4498: double sized signed integer
4499: @item ud
4500: @cindex @code{ud}, stack item type
4501: double sized unsigned integer
4502: @item r
4503: @cindex @code{r}, stack item type
4504: Float (on the FP stack)
1.21 crook 4505: @item a-
1.1 anton 4506: @cindex @code{a_}, stack item type
4507: Cell-aligned address
1.21 crook 4508: @item c-
1.1 anton 4509: @cindex @code{c_}, stack item type
4510: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4511: @item f-
1.1 anton 4512: @cindex @code{f_}, stack item type
4513: Float-aligned address
1.21 crook 4514: @item df-
1.1 anton 4515: @cindex @code{df_}, stack item type
4516: Address aligned for IEEE double precision float
1.21 crook 4517: @item sf-
1.1 anton 4518: @cindex @code{sf_}, stack item type
4519: Address aligned for IEEE single precision float
4520: @item xt
4521: @cindex @code{xt}, stack item type
4522: Execution token, same size as Cell
4523: @item wid
4524: @cindex @code{wid}, stack item type
1.21 crook 4525: Word list ID, same size as Cell
1.68 anton 4526: @item ior, wior
4527: @cindex ior type description
4528: @cindex wior type description
4529: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4530: @item f83name
4531: @cindex @code{f83name}, stack item type
4532: Pointer to a name structure
4533: @item "
4534: @cindex @code{"}, stack item type
1.12 anton 4535: string in the input stream (not on the stack). The terminating character
4536: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4537: quotes.
4538: @end table
4539:
1.65 anton 4540: @comment ----------------------------------------------
4541: @node Case insensitivity, Comments, Notation, Words
4542: @section Case insensitivity
4543: @cindex case sensitivity
4544: @cindex upper and lower case
4545:
4546: Gforth is case-insensitive; you can enter definitions and invoke
4547: Standard words using upper, lower or mixed case (however,
4548: @pxref{core-idef, Implementation-defined options, Implementation-defined
4549: options}).
4550:
4551: ANS Forth only @i{requires} implementations to recognise Standard words
4552: when they are typed entirely in upper case. Therefore, a Standard
4553: program must use upper case for all Standard words. You can use whatever
4554: case you like for words that you define, but in a Standard program you
4555: have to use the words in the same case that you defined them.
4556:
4557: Gforth supports case sensitivity through @code{table}s (case-sensitive
4558: wordlists, @pxref{Word Lists}).
4559:
4560: Two people have asked how to convert Gforth to be case-sensitive; while
4561: we think this is a bad idea, you can change all wordlists into tables
4562: like this:
4563:
4564: @example
4565: ' table-find forth-wordlist wordlist-map @ !
4566: @end example
4567:
4568: Note that you now have to type the predefined words in the same case
4569: that we defined them, which are varying. You may want to convert them
4570: to your favourite case before doing this operation (I won't explain how,
4571: because if you are even contemplating doing this, you'd better have
4572: enough knowledge of Forth systems to know this already).
4573:
4574: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4575: @section Comments
1.26 crook 4576: @cindex comments
1.21 crook 4577:
1.29 crook 4578: Forth supports two styles of comment; the traditional @i{in-line} comment,
4579: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4580:
1.44 crook 4581:
1.23 crook 4582: doc-(
1.21 crook 4583: doc-\
1.23 crook 4584: doc-\G
1.21 crook 4585:
1.44 crook 4586:
1.21 crook 4587: @node Boolean Flags, Arithmetic, Comments, Words
4588: @section Boolean Flags
1.26 crook 4589: @cindex Boolean flags
1.21 crook 4590:
4591: A Boolean flag is cell-sized. A cell with all bits clear represents the
4592: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4593: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4594: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4595: @c on and off to Memory?
4596: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4597:
1.21 crook 4598: doc-true
4599: doc-false
1.29 crook 4600: doc-on
4601: doc-off
1.21 crook 4602:
1.44 crook 4603:
1.21 crook 4604: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4605: @section Arithmetic
4606: @cindex arithmetic words
4607:
4608: @cindex division with potentially negative operands
4609: Forth arithmetic is not checked, i.e., you will not hear about integer
4610: overflow on addition or multiplication, you may hear about division by
4611: zero if you are lucky. The operator is written after the operands, but
4612: the operands are still in the original order. I.e., the infix @code{2-1}
4613: corresponds to @code{2 1 -}. Forth offers a variety of division
4614: operators. If you perform division with potentially negative operands,
4615: you do not want to use @code{/} or @code{/mod} with its undefined
4616: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4617: former, @pxref{Mixed precision}).
1.26 crook 4618: @comment TODO discuss the different division forms and the std approach
1.1 anton 4619:
4620: @menu
4621: * Single precision::
1.67 anton 4622: * Double precision:: Double-cell integer arithmetic
1.1 anton 4623: * Bitwise operations::
1.67 anton 4624: * Numeric comparison::
1.29 crook 4625: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4626: * Floating Point::
4627: @end menu
4628:
1.67 anton 4629: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4630: @subsection Single precision
4631: @cindex single precision arithmetic words
4632:
1.67 anton 4633: @c !! cell undefined
4634:
4635: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4636: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4637: treat them. For the rules used by the text interpreter for recognising
4638: single-precision integers see @ref{Number Conversion}.
1.21 crook 4639:
1.67 anton 4640: These words are all defined for signed operands, but some of them also
4641: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4642: @code{*}.
1.44 crook 4643:
1.1 anton 4644: doc-+
1.21 crook 4645: doc-1+
1.128 anton 4646: doc-under+
1.1 anton 4647: doc--
1.21 crook 4648: doc-1-
1.1 anton 4649: doc-*
4650: doc-/
4651: doc-mod
4652: doc-/mod
4653: doc-negate
4654: doc-abs
4655: doc-min
4656: doc-max
1.27 crook 4657: doc-floored
1.1 anton 4658:
1.44 crook 4659:
1.67 anton 4660: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4661: @subsection Double precision
4662: @cindex double precision arithmetic words
4663:
1.49 anton 4664: For the rules used by the text interpreter for
4665: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4666:
4667: A double precision number is represented by a cell pair, with the most
1.67 anton 4668: significant cell at the TOS. It is trivial to convert an unsigned single
4669: to a double: simply push a @code{0} onto the TOS. Since numbers are
4670: represented by Gforth using 2's complement arithmetic, converting a
4671: signed single to a (signed) double requires sign-extension across the
4672: most significant cell. This can be achieved using @code{s>d}. The moral
4673: of the story is that you cannot convert a number without knowing whether
4674: it represents an unsigned or a signed number.
1.21 crook 4675:
1.67 anton 4676: These words are all defined for signed operands, but some of them also
4677: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4678:
1.21 crook 4679: doc-s>d
1.67 anton 4680: doc-d>s
1.21 crook 4681: doc-d+
4682: doc-d-
4683: doc-dnegate
4684: doc-dabs
4685: doc-dmin
4686: doc-dmax
4687:
1.44 crook 4688:
1.67 anton 4689: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4690: @subsection Bitwise operations
4691: @cindex bitwise operation words
4692:
4693:
4694: doc-and
4695: doc-or
4696: doc-xor
4697: doc-invert
4698: doc-lshift
4699: doc-rshift
4700: doc-2*
4701: doc-d2*
4702: doc-2/
4703: doc-d2/
4704:
4705:
4706: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4707: @subsection Numeric comparison
4708: @cindex numeric comparison words
4709:
1.67 anton 4710: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4711: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4712:
1.28 crook 4713: doc-<
4714: doc-<=
4715: doc-<>
4716: doc-=
4717: doc->
4718: doc->=
4719:
1.21 crook 4720: doc-0<
1.23 crook 4721: doc-0<=
1.21 crook 4722: doc-0<>
4723: doc-0=
1.23 crook 4724: doc-0>
4725: doc-0>=
1.28 crook 4726:
4727: doc-u<
4728: doc-u<=
1.44 crook 4729: @c u<> and u= exist but are the same as <> and =
1.31 anton 4730: @c doc-u<>
4731: @c doc-u=
1.28 crook 4732: doc-u>
4733: doc-u>=
4734:
4735: doc-within
4736:
4737: doc-d<
4738: doc-d<=
4739: doc-d<>
4740: doc-d=
4741: doc-d>
4742: doc-d>=
1.23 crook 4743:
1.21 crook 4744: doc-d0<
1.23 crook 4745: doc-d0<=
4746: doc-d0<>
1.21 crook 4747: doc-d0=
1.23 crook 4748: doc-d0>
4749: doc-d0>=
4750:
1.21 crook 4751: doc-du<
1.28 crook 4752: doc-du<=
1.44 crook 4753: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4754: @c doc-du<>
4755: @c doc-du=
1.28 crook 4756: doc-du>
4757: doc-du>=
1.1 anton 4758:
1.44 crook 4759:
1.21 crook 4760: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4761: @subsection Mixed precision
4762: @cindex mixed precision arithmetic words
4763:
1.44 crook 4764:
1.1 anton 4765: doc-m+
4766: doc-*/
4767: doc-*/mod
4768: doc-m*
4769: doc-um*
4770: doc-m*/
4771: doc-um/mod
4772: doc-fm/mod
4773: doc-sm/rem
4774:
1.44 crook 4775:
1.21 crook 4776: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4777: @subsection Floating Point
4778: @cindex floating point arithmetic words
4779:
1.49 anton 4780: For the rules used by the text interpreter for
4781: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4782:
1.67 anton 4783: Gforth has a separate floating point stack, but the documentation uses
4784: the unified notation.@footnote{It's easy to generate the separate
4785: notation from that by just separating the floating-point numbers out:
4786: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4787: r3 )}.}
1.1 anton 4788:
4789: @cindex floating-point arithmetic, pitfalls
4790: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4791: unwary (e.g., floating point addition is not associative) and even a
4792: few for the wary. You should not use them unless you know what you are
4793: doing or you don't care that the results you get are totally bogus. If
4794: you want to learn about the problems of floating point numbers (and
4795: how to avoid them), you might start with @cite{David Goldberg,
4796: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4797: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4798: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4799:
1.44 crook 4800:
1.21 crook 4801: doc-d>f
4802: doc-f>d
1.1 anton 4803: doc-f+
4804: doc-f-
4805: doc-f*
4806: doc-f/
4807: doc-fnegate
4808: doc-fabs
4809: doc-fmax
4810: doc-fmin
4811: doc-floor
4812: doc-fround
4813: doc-f**
4814: doc-fsqrt
4815: doc-fexp
4816: doc-fexpm1
4817: doc-fln
4818: doc-flnp1
4819: doc-flog
4820: doc-falog
1.32 anton 4821: doc-f2*
4822: doc-f2/
4823: doc-1/f
4824: doc-precision
4825: doc-set-precision
4826:
4827: @cindex angles in trigonometric operations
4828: @cindex trigonometric operations
4829: Angles in floating point operations are given in radians (a full circle
4830: has 2 pi radians).
4831:
1.1 anton 4832: doc-fsin
4833: doc-fcos
4834: doc-fsincos
4835: doc-ftan
4836: doc-fasin
4837: doc-facos
4838: doc-fatan
4839: doc-fatan2
4840: doc-fsinh
4841: doc-fcosh
4842: doc-ftanh
4843: doc-fasinh
4844: doc-facosh
4845: doc-fatanh
1.21 crook 4846: doc-pi
1.28 crook 4847:
1.32 anton 4848: @cindex equality of floats
4849: @cindex floating-point comparisons
1.31 anton 4850: One particular problem with floating-point arithmetic is that comparison
4851: for equality often fails when you would expect it to succeed. For this
4852: reason approximate equality is often preferred (but you still have to
1.67 anton 4853: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4854: differently from what you might expect. The comparison words are:
1.31 anton 4855:
4856: doc-f~rel
4857: doc-f~abs
1.68 anton 4858: doc-f~
1.31 anton 4859: doc-f=
4860: doc-f<>
4861:
4862: doc-f<
4863: doc-f<=
4864: doc-f>
4865: doc-f>=
4866:
1.21 crook 4867: doc-f0<
1.28 crook 4868: doc-f0<=
4869: doc-f0<>
1.21 crook 4870: doc-f0=
1.28 crook 4871: doc-f0>
4872: doc-f0>=
4873:
1.1 anton 4874:
4875: @node Stack Manipulation, Memory, Arithmetic, Words
4876: @section Stack Manipulation
4877: @cindex stack manipulation words
4878:
4879: @cindex floating-point stack in the standard
1.21 crook 4880: Gforth maintains a number of separate stacks:
4881:
1.29 crook 4882: @cindex data stack
4883: @cindex parameter stack
1.21 crook 4884: @itemize @bullet
4885: @item
1.29 crook 4886: A data stack (also known as the @dfn{parameter stack}) -- for
4887: characters, cells, addresses, and double cells.
1.21 crook 4888:
1.29 crook 4889: @cindex floating-point stack
1.21 crook 4890: @item
1.44 crook 4891: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4892:
1.29 crook 4893: @cindex return stack
1.21 crook 4894: @item
1.44 crook 4895: A return stack -- for holding the return addresses of colon
1.32 anton 4896: definitions and other (non-FP) data.
1.21 crook 4897:
1.29 crook 4898: @cindex locals stack
1.21 crook 4899: @item
1.44 crook 4900: A locals stack -- for holding local variables.
1.21 crook 4901: @end itemize
4902:
1.1 anton 4903: @menu
4904: * Data stack::
4905: * Floating point stack::
4906: * Return stack::
4907: * Locals stack::
4908: * Stack pointer manipulation::
4909: @end menu
4910:
4911: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4912: @subsection Data stack
4913: @cindex data stack manipulation words
4914: @cindex stack manipulations words, data stack
4915:
1.44 crook 4916:
1.1 anton 4917: doc-drop
4918: doc-nip
4919: doc-dup
4920: doc-over
4921: doc-tuck
4922: doc-swap
1.21 crook 4923: doc-pick
1.1 anton 4924: doc-rot
4925: doc--rot
4926: doc-?dup
4927: doc-roll
4928: doc-2drop
4929: doc-2nip
4930: doc-2dup
4931: doc-2over
4932: doc-2tuck
4933: doc-2swap
4934: doc-2rot
4935:
1.44 crook 4936:
1.1 anton 4937: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4938: @subsection Floating point stack
4939: @cindex floating-point stack manipulation words
4940: @cindex stack manipulation words, floating-point stack
4941:
1.32 anton 4942: Whilst every sane Forth has a separate floating-point stack, it is not
4943: strictly required; an ANS Forth system could theoretically keep
4944: floating-point numbers on the data stack. As an additional difficulty,
4945: you don't know how many cells a floating-point number takes. It is
4946: reportedly possible to write words in a way that they work also for a
4947: unified stack model, but we do not recommend trying it. Instead, just
4948: say that your program has an environmental dependency on a separate
4949: floating-point stack.
4950:
4951: doc-floating-stack
4952:
1.1 anton 4953: doc-fdrop
4954: doc-fnip
4955: doc-fdup
4956: doc-fover
4957: doc-ftuck
4958: doc-fswap
1.21 crook 4959: doc-fpick
1.1 anton 4960: doc-frot
4961:
1.44 crook 4962:
1.1 anton 4963: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4964: @subsection Return stack
4965: @cindex return stack manipulation words
4966: @cindex stack manipulation words, return stack
4967:
1.32 anton 4968: @cindex return stack and locals
4969: @cindex locals and return stack
4970: A Forth system is allowed to keep local variables on the
4971: return stack. This is reasonable, as local variables usually eliminate
4972: the need to use the return stack explicitly. So, if you want to produce
4973: a standard compliant program and you are using local variables in a
4974: word, forget about return stack manipulations in that word (refer to the
4975: standard document for the exact rules).
4976:
1.1 anton 4977: doc->r
4978: doc-r>
4979: doc-r@
4980: doc-rdrop
4981: doc-2>r
4982: doc-2r>
4983: doc-2r@
4984: doc-2rdrop
4985:
1.44 crook 4986:
1.1 anton 4987: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4988: @subsection Locals stack
4989:
1.78 anton 4990: Gforth uses an extra locals stack. It is described, along with the
4991: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4992:
1.1 anton 4993: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4994: @subsection Stack pointer manipulation
4995: @cindex stack pointer manipulation words
4996:
1.44 crook 4997: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4998: doc-sp0
1.1 anton 4999: doc-sp@
5000: doc-sp!
1.21 crook 5001: doc-fp0
1.1 anton 5002: doc-fp@
5003: doc-fp!
1.21 crook 5004: doc-rp0
1.1 anton 5005: doc-rp@
5006: doc-rp!
1.21 crook 5007: doc-lp0
1.1 anton 5008: doc-lp@
5009: doc-lp!
5010:
1.44 crook 5011:
1.1 anton 5012: @node Memory, Control Structures, Stack Manipulation, Words
5013: @section Memory
1.26 crook 5014: @cindex memory words
1.1 anton 5015:
1.32 anton 5016: @menu
5017: * Memory model::
5018: * Dictionary allocation::
5019: * Heap Allocation::
5020: * Memory Access::
5021: * Address arithmetic::
5022: * Memory Blocks::
5023: @end menu
5024:
1.67 anton 5025: In addition to the standard Forth memory allocation words, there is also
5026: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5027: garbage collector}.
5028:
1.32 anton 5029: @node Memory model, Dictionary allocation, Memory, Memory
5030: @subsection ANS Forth and Gforth memory models
5031:
5032: @c The ANS Forth description is a mess (e.g., is the heap part of
5033: @c the dictionary?), so let's not stick to closely with it.
5034:
1.67 anton 5035: ANS Forth considers a Forth system as consisting of several address
5036: spaces, of which only @dfn{data space} is managed and accessible with
5037: the memory words. Memory not necessarily in data space includes the
5038: stacks, the code (called code space) and the headers (called name
5039: space). In Gforth everything is in data space, but the code for the
5040: primitives is usually read-only.
1.32 anton 5041:
5042: Data space is divided into a number of areas: The (data space portion of
5043: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5044: refer to the search data structure embodied in word lists and headers,
5045: because it is used for looking up names, just as you would in a
5046: conventional dictionary.}, the heap, and a number of system-allocated
5047: buffers.
5048:
1.68 anton 5049: @cindex address arithmetic restrictions, ANS vs. Gforth
5050: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5051: In ANS Forth data space is also divided into contiguous regions. You
5052: can only use address arithmetic within a contiguous region, not between
5053: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5054: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5055: allocation}).
5056:
5057: Gforth provides one big address space, and address arithmetic can be
5058: performed between any addresses. However, in the dictionary headers or
5059: code are interleaved with data, so almost the only contiguous data space
5060: regions there are those described by ANS Forth as contiguous; but you
5061: can be sure that the dictionary is allocated towards increasing
5062: addresses even between contiguous regions. The memory order of
5063: allocations in the heap is platform-dependent (and possibly different
5064: from one run to the next).
5065:
1.27 crook 5066:
1.32 anton 5067: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5068: @subsection Dictionary allocation
1.27 crook 5069: @cindex reserving data space
5070: @cindex data space - reserving some
5071:
1.32 anton 5072: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5073: you want to deallocate X, you also deallocate everything
5074: allocated after X.
5075:
1.68 anton 5076: @cindex contiguous regions in dictionary allocation
1.32 anton 5077: The allocations using the words below are contiguous and grow the region
5078: towards increasing addresses. Other words that allocate dictionary
5079: memory of any kind (i.e., defining words including @code{:noname}) end
5080: the contiguous region and start a new one.
5081:
5082: In ANS Forth only @code{create}d words are guaranteed to produce an
5083: address that is the start of the following contiguous region. In
5084: particular, the cell allocated by @code{variable} is not guaranteed to
5085: be contiguous with following @code{allot}ed memory.
5086:
5087: You can deallocate memory by using @code{allot} with a negative argument
5088: (with some restrictions, see @code{allot}). For larger deallocations use
5089: @code{marker}.
1.27 crook 5090:
1.29 crook 5091:
1.27 crook 5092: doc-here
5093: doc-unused
5094: doc-allot
5095: doc-c,
1.29 crook 5096: doc-f,
1.27 crook 5097: doc-,
5098: doc-2,
5099:
1.32 anton 5100: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5101: course you should allocate memory in an aligned way, too. I.e., before
5102: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5103: The words below align @code{here} if it is not already. Basically it is
5104: only already aligned for a type, if the last allocation was a multiple
5105: of the size of this type and if @code{here} was aligned for this type
5106: before.
5107:
5108: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5109: ANS Forth (@code{maxalign}ed in Gforth).
5110:
5111: doc-align
5112: doc-falign
5113: doc-sfalign
5114: doc-dfalign
5115: doc-maxalign
5116: doc-cfalign
5117:
5118:
5119: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5120: @subsection Heap allocation
5121: @cindex heap allocation
5122: @cindex dynamic allocation of memory
5123: @cindex memory-allocation word set
5124:
1.68 anton 5125: @cindex contiguous regions and heap allocation
1.32 anton 5126: Heap allocation supports deallocation of allocated memory in any
5127: order. Dictionary allocation is not affected by it (i.e., it does not
5128: end a contiguous region). In Gforth, these words are implemented using
5129: the standard C library calls malloc(), free() and resize().
5130:
1.68 anton 5131: The memory region produced by one invocation of @code{allocate} or
5132: @code{resize} is internally contiguous. There is no contiguity between
5133: such a region and any other region (including others allocated from the
5134: heap).
5135:
1.32 anton 5136: doc-allocate
5137: doc-free
5138: doc-resize
5139:
1.27 crook 5140:
1.32 anton 5141: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5142: @subsection Memory Access
5143: @cindex memory access words
5144:
5145: doc-@
5146: doc-!
5147: doc-+!
5148: doc-c@
5149: doc-c!
5150: doc-2@
5151: doc-2!
5152: doc-f@
5153: doc-f!
5154: doc-sf@
5155: doc-sf!
5156: doc-df@
5157: doc-df!
1.144 anton 5158: doc-sw@
5159: doc-uw@
5160: doc-w!
5161: doc-sl@
5162: doc-ul@
5163: doc-l!
1.68 anton 5164:
1.32 anton 5165: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5166: @subsection Address arithmetic
1.1 anton 5167: @cindex address arithmetic words
5168:
1.67 anton 5169: Address arithmetic is the foundation on which you can build data
5170: structures like arrays, records (@pxref{Structures}) and objects
5171: (@pxref{Object-oriented Forth}).
1.32 anton 5172:
1.68 anton 5173: @cindex address unit
5174: @cindex au (address unit)
1.1 anton 5175: ANS Forth does not specify the sizes of the data types. Instead, it
5176: offers a number of words for computing sizes and doing address
1.29 crook 5177: arithmetic. Address arithmetic is performed in terms of address units
5178: (aus); on most systems the address unit is one byte. Note that a
5179: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5180: platforms where it is a noop, it compiles to nothing).
1.1 anton 5181:
1.67 anton 5182: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5183: you have the address of a cell, perform @code{1 cells +}, and you will
5184: have the address of the next cell.
5185:
1.68 anton 5186: @cindex contiguous regions and address arithmetic
1.67 anton 5187: In ANS Forth you can perform address arithmetic only within a contiguous
5188: region, i.e., if you have an address into one region, you can only add
5189: and subtract such that the result is still within the region; you can
5190: only subtract or compare addresses from within the same contiguous
5191: region. Reasons: several contiguous regions can be arranged in memory
5192: in any way; on segmented systems addresses may have unusual
5193: representations, such that address arithmetic only works within a
5194: region. Gforth provides a few more guarantees (linear address space,
5195: dictionary grows upwards), but in general I have found it easy to stay
5196: within contiguous regions (exception: computing and comparing to the
5197: address just beyond the end of an array).
5198:
1.1 anton 5199: @cindex alignment of addresses for types
5200: ANS Forth also defines words for aligning addresses for specific
5201: types. Many computers require that accesses to specific data types
5202: must only occur at specific addresses; e.g., that cells may only be
5203: accessed at addresses divisible by 4. Even if a machine allows unaligned
5204: accesses, it can usually perform aligned accesses faster.
5205:
5206: For the performance-conscious: alignment operations are usually only
5207: necessary during the definition of a data structure, not during the
5208: (more frequent) accesses to it.
5209:
5210: ANS Forth defines no words for character-aligning addresses. This is not
5211: an oversight, but reflects the fact that addresses that are not
5212: char-aligned have no use in the standard and therefore will not be
5213: created.
5214:
5215: @cindex @code{CREATE} and alignment
1.29 crook 5216: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5217: are cell-aligned; in addition, Gforth guarantees that these addresses
5218: are aligned for all purposes.
5219:
1.26 crook 5220: Note that the ANS Forth word @code{char} has nothing to do with address
5221: arithmetic.
1.1 anton 5222:
1.44 crook 5223:
1.1 anton 5224: doc-chars
5225: doc-char+
5226: doc-cells
5227: doc-cell+
5228: doc-cell
5229: doc-aligned
5230: doc-floats
5231: doc-float+
5232: doc-float
5233: doc-faligned
5234: doc-sfloats
5235: doc-sfloat+
5236: doc-sfaligned
5237: doc-dfloats
5238: doc-dfloat+
5239: doc-dfaligned
5240: doc-maxaligned
5241: doc-cfaligned
5242: doc-address-unit-bits
1.145 anton 5243: doc-/w
5244: doc-/l
1.44 crook 5245:
1.32 anton 5246: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5247: @subsection Memory Blocks
5248: @cindex memory block words
1.27 crook 5249: @cindex character strings - moving and copying
5250:
1.49 anton 5251: Memory blocks often represent character strings; For ways of storing
5252: character strings in memory see @ref{String Formats}. For other
5253: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5254:
1.67 anton 5255: A few of these words work on address unit blocks. In that case, you
5256: usually have to insert @code{CHARS} before the word when working on
5257: character strings. Most words work on character blocks, and expect a
5258: char-aligned address.
5259:
5260: When copying characters between overlapping memory regions, use
5261: @code{chars move} or choose carefully between @code{cmove} and
5262: @code{cmove>}.
1.44 crook 5263:
1.1 anton 5264: doc-move
5265: doc-erase
5266: doc-cmove
5267: doc-cmove>
5268: doc-fill
5269: doc-blank
1.21 crook 5270: doc-compare
1.111 anton 5271: doc-str=
5272: doc-str<
5273: doc-string-prefix?
1.21 crook 5274: doc-search
1.27 crook 5275: doc--trailing
5276: doc-/string
1.82 anton 5277: doc-bounds
1.141 anton 5278: doc-pad
1.111 anton 5279:
1.27 crook 5280: @comment TODO examples
5281:
1.1 anton 5282:
1.26 crook 5283: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5284: @section Control Structures
5285: @cindex control structures
5286:
1.33 anton 5287: Control structures in Forth cannot be used interpretively, only in a
5288: colon definition@footnote{To be precise, they have no interpretation
5289: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5290: not like this limitation, but have not seen a satisfying way around it
5291: yet, although many schemes have been proposed.
1.1 anton 5292:
5293: @menu
1.33 anton 5294: * Selection:: IF ... ELSE ... ENDIF
5295: * Simple Loops:: BEGIN ...
1.29 crook 5296: * Counted Loops:: DO
1.67 anton 5297: * Arbitrary control structures::
5298: * Calls and returns::
1.1 anton 5299: * Exception Handling::
5300: @end menu
5301:
5302: @node Selection, Simple Loops, Control Structures, Control Structures
5303: @subsection Selection
5304: @cindex selection control structures
5305: @cindex control structures for selection
5306:
5307: @cindex @code{IF} control structure
5308: @example
1.29 crook 5309: @i{flag}
1.1 anton 5310: IF
1.29 crook 5311: @i{code}
1.1 anton 5312: ENDIF
5313: @end example
1.21 crook 5314: @noindent
1.33 anton 5315:
1.44 crook 5316: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5317: with any bit set represents truth) @i{code} is executed.
1.33 anton 5318:
1.1 anton 5319: @example
1.29 crook 5320: @i{flag}
1.1 anton 5321: IF
1.29 crook 5322: @i{code1}
1.1 anton 5323: ELSE
1.29 crook 5324: @i{code2}
1.1 anton 5325: ENDIF
5326: @end example
5327:
1.44 crook 5328: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5329: executed.
1.33 anton 5330:
1.1 anton 5331: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5332: standard, and @code{ENDIF} is not, although it is quite popular. We
5333: recommend using @code{ENDIF}, because it is less confusing for people
5334: who also know other languages (and is not prone to reinforcing negative
5335: prejudices against Forth in these people). Adding @code{ENDIF} to a
5336: system that only supplies @code{THEN} is simple:
5337: @example
1.82 anton 5338: : ENDIF POSTPONE then ; immediate
1.1 anton 5339: @end example
5340:
5341: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5342: (adv.)} has the following meanings:
5343: @quotation
5344: ... 2b: following next after in order ... 3d: as a necessary consequence
5345: (if you were there, then you saw them).
5346: @end quotation
5347: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5348: and many other programming languages has the meaning 3d.]
5349:
1.21 crook 5350: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5351: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5352: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5353: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5354: @file{compat/control.fs}.
5355:
5356: @cindex @code{CASE} control structure
5357: @example
1.213 anton 5358: @i{x}
1.1 anton 5359: CASE
1.213 anton 5360: @i{x1} OF @i{code1} ENDOF
5361: @i{x2} OF @i{code2} ENDOF
1.1 anton 5362: @dots{}
1.213 anton 5363: ( x ) @i{default-code} ( x )
1.131 anton 5364: ENDCASE ( )
1.1 anton 5365: @end example
5366:
1.213 anton 5367: Executes the first @i{codei}, where the @i{xi} is equal to @i{x}. If no
5368: @i{xi} matches, the optional @i{default-code} is executed. The optional
1.211 anton 5369: default case can be added by simply writing the code after the last
1.213 anton 5370: @code{ENDOF}. It may use @i{x}, which is on top of the stack, but must
5371: not consume it. The value @i{x} is consumed by this construction
1.211 anton 5372: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
5373: matches). Example:
5374:
5375: @example
1.213 anton 5376: : num-name ( n -- c-addr u )
1.211 anton 5377: case
1.213 anton 5378: 0 of s" zero " endof
5379: 1 of s" one " endof
5380: 2 of s" two " endof
5381: \ default case:
5382: s" other number"
5383: rot \ get n on top so ENDCASE can drop it
1.211 anton 5384: endcase ;
5385: @end example
1.1 anton 5386:
1.69 anton 5387: @progstyle
1.131 anton 5388: To keep the code understandable, you should ensure that you change the
5389: stack in the same way (wrt. number and types of stack items consumed
5390: and pushed) on all paths through a selection construct.
1.69 anton 5391:
1.1 anton 5392: @node Simple Loops, Counted Loops, Selection, Control Structures
5393: @subsection Simple Loops
5394: @cindex simple loops
5395: @cindex loops without count
5396:
5397: @cindex @code{WHILE} loop
5398: @example
5399: BEGIN
1.29 crook 5400: @i{code1}
5401: @i{flag}
1.1 anton 5402: WHILE
1.29 crook 5403: @i{code2}
1.1 anton 5404: REPEAT
5405: @end example
5406:
1.29 crook 5407: @i{code1} is executed and @i{flag} is computed. If it is true,
5408: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5409: false, execution continues after the @code{REPEAT}.
5410:
5411: @cindex @code{UNTIL} loop
5412: @example
5413: BEGIN
1.29 crook 5414: @i{code}
5415: @i{flag}
1.1 anton 5416: UNTIL
5417: @end example
5418:
1.29 crook 5419: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5420:
1.69 anton 5421: @progstyle
5422: To keep the code understandable, a complete iteration of the loop should
5423: not change the number and types of the items on the stacks.
5424:
1.1 anton 5425: @cindex endless loop
5426: @cindex loops, endless
5427: @example
5428: BEGIN
1.29 crook 5429: @i{code}
1.1 anton 5430: AGAIN
5431: @end example
5432:
5433: This is an endless loop.
5434:
5435: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5436: @subsection Counted Loops
5437: @cindex counted loops
5438: @cindex loops, counted
5439: @cindex @code{DO} loops
5440:
5441: The basic counted loop is:
5442: @example
1.29 crook 5443: @i{limit} @i{start}
1.1 anton 5444: ?DO
1.29 crook 5445: @i{body}
1.1 anton 5446: LOOP
5447: @end example
5448:
1.29 crook 5449: This performs one iteration for every integer, starting from @i{start}
5450: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5451: accessed with @code{i}. For example, the loop:
1.1 anton 5452: @example
5453: 10 0 ?DO
5454: i .
5455: LOOP
5456: @end example
1.21 crook 5457: @noindent
5458: prints @code{0 1 2 3 4 5 6 7 8 9}
5459:
1.1 anton 5460: The index of the innermost loop can be accessed with @code{i}, the index
5461: of the next loop with @code{j}, and the index of the third loop with
5462: @code{k}.
5463:
1.44 crook 5464:
1.1 anton 5465: doc-i
5466: doc-j
5467: doc-k
5468:
1.44 crook 5469:
1.1 anton 5470: The loop control data are kept on the return stack, so there are some
1.21 crook 5471: restrictions on mixing return stack accesses and counted loop words. In
5472: particuler, if you put values on the return stack outside the loop, you
5473: cannot read them inside the loop@footnote{well, not in a way that is
5474: portable.}. If you put values on the return stack within a loop, you
5475: have to remove them before the end of the loop and before accessing the
5476: index of the loop.
1.1 anton 5477:
5478: There are several variations on the counted loop:
5479:
1.21 crook 5480: @itemize @bullet
5481: @item
5482: @code{LEAVE} leaves the innermost counted loop immediately; execution
5483: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5484:
5485: @example
5486: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5487: @end example
5488: prints @code{0 1 2 3}
5489:
1.1 anton 5490:
1.21 crook 5491: @item
5492: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5493: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5494: return stack so @code{EXIT} can get to its return address. For example:
5495:
5496: @example
5497: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5498: @end example
5499: prints @code{0 1 2 3}
5500:
5501:
5502: @item
1.29 crook 5503: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5504: (and @code{LOOP} iterates until they become equal by wrap-around
5505: arithmetic). This behaviour is usually not what you want. Therefore,
5506: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5507: @code{?DO}), which do not enter the loop if @i{start} is greater than
5508: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5509: unsigned loop parameters.
5510:
1.21 crook 5511: @item
5512: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5513: the loop, independent of the loop parameters. Do not use @code{DO}, even
5514: if you know that the loop is entered in any case. Such knowledge tends
5515: to become invalid during maintenance of a program, and then the
5516: @code{DO} will make trouble.
5517:
5518: @item
1.29 crook 5519: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5520: index by @i{n} instead of by 1. The loop is terminated when the border
5521: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5522:
1.21 crook 5523: @example
5524: 4 0 +DO i . 2 +LOOP
5525: @end example
5526: @noindent
5527: prints @code{0 2}
5528:
5529: @example
5530: 4 1 +DO i . 2 +LOOP
5531: @end example
5532: @noindent
5533: prints @code{1 3}
1.1 anton 5534:
1.68 anton 5535: @item
1.1 anton 5536: @cindex negative increment for counted loops
5537: @cindex counted loops with negative increment
1.29 crook 5538: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5539:
1.21 crook 5540: @example
5541: -1 0 ?DO i . -1 +LOOP
5542: @end example
5543: @noindent
5544: prints @code{0 -1}
1.1 anton 5545:
1.21 crook 5546: @example
5547: 0 0 ?DO i . -1 +LOOP
5548: @end example
5549: prints nothing.
1.1 anton 5550:
1.29 crook 5551: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5552: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5553: index by @i{u} each iteration. The loop is terminated when the border
5554: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5555: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5556:
1.21 crook 5557: @example
5558: -2 0 -DO i . 1 -LOOP
5559: @end example
5560: @noindent
5561: prints @code{0 -1}
1.1 anton 5562:
1.21 crook 5563: @example
5564: -1 0 -DO i . 1 -LOOP
5565: @end example
5566: @noindent
5567: prints @code{0}
5568:
5569: @example
5570: 0 0 -DO i . 1 -LOOP
5571: @end example
5572: @noindent
5573: prints nothing.
1.1 anton 5574:
1.21 crook 5575: @end itemize
1.1 anton 5576:
5577: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5578: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5579: for these words that uses only standard words is provided in
5580: @file{compat/loops.fs}.
1.1 anton 5581:
5582:
5583: @cindex @code{FOR} loops
1.26 crook 5584: Another counted loop is:
1.1 anton 5585: @example
1.29 crook 5586: @i{n}
1.1 anton 5587: FOR
1.29 crook 5588: @i{body}
1.1 anton 5589: NEXT
5590: @end example
5591: This is the preferred loop of native code compiler writers who are too
1.26 crook 5592: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5593: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5594: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5595: Forth systems may behave differently, even if they support @code{FOR}
5596: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5597:
5598: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5599: @subsection Arbitrary control structures
5600: @cindex control structures, user-defined
5601:
5602: @cindex control-flow stack
5603: ANS Forth permits and supports using control structures in a non-nested
5604: way. Information about incomplete control structures is stored on the
5605: control-flow stack. This stack may be implemented on the Forth data
5606: stack, and this is what we have done in Gforth.
5607:
5608: @cindex @code{orig}, control-flow stack item
5609: @cindex @code{dest}, control-flow stack item
5610: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5611: entry represents a backward branch target. A few words are the basis for
5612: building any control structure possible (except control structures that
5613: need storage, like calls, coroutines, and backtracking).
5614:
1.44 crook 5615:
1.1 anton 5616: doc-if
5617: doc-ahead
5618: doc-then
5619: doc-begin
5620: doc-until
5621: doc-again
5622: doc-cs-pick
5623: doc-cs-roll
5624:
1.44 crook 5625:
1.21 crook 5626: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5627: manipulate the control-flow stack in a portable way. Without them, you
5628: would need to know how many stack items are occupied by a control-flow
5629: entry (many systems use one cell. In Gforth they currently take three,
5630: but this may change in the future).
5631:
1.1 anton 5632: Some standard control structure words are built from these words:
5633:
1.44 crook 5634:
1.1 anton 5635: doc-else
5636: doc-while
5637: doc-repeat
5638:
1.44 crook 5639:
5640: @noindent
1.1 anton 5641: Gforth adds some more control-structure words:
5642:
1.44 crook 5643:
1.1 anton 5644: doc-endif
5645: doc-?dup-if
5646: doc-?dup-0=-if
5647:
1.44 crook 5648:
5649: @noindent
1.1 anton 5650: Counted loop words constitute a separate group of words:
5651:
1.44 crook 5652:
1.1 anton 5653: doc-?do
5654: doc-+do
5655: doc-u+do
5656: doc--do
5657: doc-u-do
5658: doc-do
5659: doc-for
5660: doc-loop
5661: doc-+loop
5662: doc--loop
5663: doc-next
5664: doc-leave
5665: doc-?leave
5666: doc-unloop
5667: doc-done
5668:
1.44 crook 5669:
1.21 crook 5670: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5671: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5672: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5673: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5674: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5675: resolved (by using one of the loop-ending words or @code{DONE}).
5676:
1.44 crook 5677: @noindent
1.26 crook 5678: Another group of control structure words are:
1.1 anton 5679:
1.44 crook 5680:
1.1 anton 5681: doc-case
5682: doc-endcase
5683: doc-of
5684: doc-endof
5685:
1.44 crook 5686:
1.21 crook 5687: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5688: @code{CS-ROLL}.
1.1 anton 5689:
5690: @subsubsection Programming Style
1.47 crook 5691: @cindex control structures programming style
5692: @cindex programming style, arbitrary control structures
1.1 anton 5693:
5694: In order to ensure readability we recommend that you do not create
5695: arbitrary control structures directly, but define new control structure
5696: words for the control structure you want and use these words in your
1.26 crook 5697: program. For example, instead of writing:
1.1 anton 5698:
5699: @example
1.26 crook 5700: BEGIN
1.1 anton 5701: ...
1.26 crook 5702: IF [ 1 CS-ROLL ]
1.1 anton 5703: ...
1.26 crook 5704: AGAIN THEN
1.1 anton 5705: @end example
5706:
1.21 crook 5707: @noindent
1.1 anton 5708: we recommend defining control structure words, e.g.,
5709:
5710: @example
1.26 crook 5711: : WHILE ( DEST -- ORIG DEST )
5712: POSTPONE IF
5713: 1 CS-ROLL ; immediate
5714:
5715: : REPEAT ( orig dest -- )
5716: POSTPONE AGAIN
5717: POSTPONE THEN ; immediate
1.1 anton 5718: @end example
5719:
1.21 crook 5720: @noindent
1.1 anton 5721: and then using these to create the control structure:
5722:
5723: @example
1.26 crook 5724: BEGIN
1.1 anton 5725: ...
1.26 crook 5726: WHILE
1.1 anton 5727: ...
1.26 crook 5728: REPEAT
1.1 anton 5729: @end example
5730:
5731: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5732: @code{WHILE} are predefined, so in this example it would not be
5733: necessary to define them.
5734:
5735: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5736: @subsection Calls and returns
5737: @cindex calling a definition
5738: @cindex returning from a definition
5739:
1.3 anton 5740: @cindex recursive definitions
5741: A definition can be called simply be writing the name of the definition
1.26 crook 5742: to be called. Normally a definition is invisible during its own
1.3 anton 5743: definition. If you want to write a directly recursive definition, you
1.26 crook 5744: can use @code{recursive} to make the current definition visible, or
5745: @code{recurse} to call the current definition directly.
1.3 anton 5746:
1.44 crook 5747:
1.3 anton 5748: doc-recursive
5749: doc-recurse
5750:
1.44 crook 5751:
1.21 crook 5752: @comment TODO add example of the two recursion methods
1.12 anton 5753: @quotation
5754: @progstyle
5755: I prefer using @code{recursive} to @code{recurse}, because calling the
5756: definition by name is more descriptive (if the name is well-chosen) than
5757: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5758: implementation, it is much better to read (and think) ``now sort the
5759: partitions'' than to read ``now do a recursive call''.
5760: @end quotation
1.3 anton 5761:
1.29 crook 5762: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5763:
5764: @example
1.28 crook 5765: Defer foo
1.3 anton 5766:
5767: : bar ( ... -- ... )
5768: ... foo ... ;
5769:
5770: :noname ( ... -- ... )
5771: ... bar ... ;
5772: IS foo
5773: @end example
5774:
1.170 pazsan 5775: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5776:
1.26 crook 5777: The current definition returns control to the calling definition when
1.33 anton 5778: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5779:
5780: doc-exit
5781: doc-;s
5782:
1.44 crook 5783:
1.1 anton 5784: @node Exception Handling, , Calls and returns, Control Structures
5785: @subsection Exception Handling
1.26 crook 5786: @cindex exceptions
1.1 anton 5787:
1.68 anton 5788: @c quit is a very bad idea for error handling,
5789: @c because it does not translate into a THROW
5790: @c it also does not belong into this chapter
5791:
5792: If a word detects an error condition that it cannot handle, it can
5793: @code{throw} an exception. In the simplest case, this will terminate
5794: your program, and report an appropriate error.
1.21 crook 5795:
1.68 anton 5796: doc-throw
1.1 anton 5797:
1.69 anton 5798: @code{Throw} consumes a cell-sized error number on the stack. There are
5799: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5800: Gforth (and most other systems) you can use the iors produced by various
5801: words as error numbers (e.g., a typical use of @code{allocate} is
5802: @code{allocate throw}). Gforth also provides the word @code{exception}
5803: to define your own error numbers (with decent error reporting); an ANS
5804: Forth version of this word (but without the error messages) is available
5805: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5806: numbers (anything outside the range -4095..0), but won't get nice error
5807: messages, only numbers. For example, try:
5808:
5809: @example
1.69 anton 5810: -10 throw \ ANS defined
5811: -267 throw \ system defined
5812: s" my error" exception throw \ user defined
5813: 7 throw \ arbitrary number
1.68 anton 5814: @end example
5815:
5816: doc---exception-exception
1.1 anton 5817:
1.69 anton 5818: A common idiom to @code{THROW} a specific error if a flag is true is
5819: this:
5820:
5821: @example
5822: @code{( flag ) 0<> @i{errno} and throw}
5823: @end example
5824:
5825: Your program can provide exception handlers to catch exceptions. An
5826: exception handler can be used to correct the problem, or to clean up
5827: some data structures and just throw the exception to the next exception
5828: handler. Note that @code{throw} jumps to the dynamically innermost
5829: exception handler. The system's exception handler is outermost, and just
5830: prints an error and restarts command-line interpretation (or, in batch
5831: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5832:
1.68 anton 5833: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5834:
1.68 anton 5835: doc-catch
1.160 anton 5836: doc-nothrow
1.68 anton 5837:
5838: The most common use of exception handlers is to clean up the state when
5839: an error happens. E.g.,
1.1 anton 5840:
1.26 crook 5841: @example
1.68 anton 5842: base @ >r hex \ actually the hex should be inside foo, or we h
5843: ['] foo catch ( nerror|0 )
5844: r> base !
1.69 anton 5845: ( nerror|0 ) throw \ pass it on
1.26 crook 5846: @end example
1.1 anton 5847:
1.69 anton 5848: A use of @code{catch} for handling the error @code{myerror} might look
5849: like this:
1.44 crook 5850:
1.68 anton 5851: @example
1.69 anton 5852: ['] foo catch
5853: CASE
1.160 anton 5854: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5855: dup throw \ default: pass other errors on, do nothing on non-errors
5856: ENDCASE
1.68 anton 5857: @end example
1.44 crook 5858:
1.68 anton 5859: Having to wrap the code into a separate word is often cumbersome,
5860: therefore Gforth provides an alternative syntax:
1.1 anton 5861:
5862: @example
1.69 anton 5863: TRY
1.68 anton 5864: @i{code1}
1.172 anton 5865: IFERROR
5866: @i{code2}
5867: THEN
5868: @i{code3}
1.69 anton 5869: ENDTRY
1.1 anton 5870: @end example
5871:
1.172 anton 5872: This performs @i{code1}. If @i{code1} completes normally, execution
1.201 anton 5873: continues with @i{code3}. If there is an exception in @i{code1} or
5874: before @code{endtry}, the stacks are reset to the depth during
1.172 anton 5875: @code{try}, the throw value is pushed on the data stack, and execution
1.201 anton 5876: constinues at @i{code2}, and finally falls through to @i{code3}.
1.26 crook 5877:
1.68 anton 5878: doc-try
5879: doc-endtry
1.172 anton 5880: doc-iferror
5881:
5882: If you don't need @i{code2}, you can write @code{restore} instead of
5883: @code{iferror then}:
5884:
5885: @example
5886: TRY
5887: @i{code1}
5888: RESTORE
5889: @i{code3}
5890: ENDTRY
5891: @end example
1.26 crook 5892:
1.172 anton 5893: @cindex unwind-protect
1.69 anton 5894: The cleanup example from above in this syntax:
1.26 crook 5895:
1.68 anton 5896: @example
1.174 anton 5897: base @@ @{ oldbase @}
1.172 anton 5898: TRY
1.68 anton 5899: hex foo \ now the hex is placed correctly
1.69 anton 5900: 0 \ value for throw
1.172 anton 5901: RESTORE
5902: oldbase base !
5903: ENDTRY
5904: throw
1.1 anton 5905: @end example
5906:
1.172 anton 5907: An additional advantage of this variant is that an exception between
5908: @code{restore} and @code{endtry} (e.g., from the user pressing
5909: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5910: so the base will be restored under all circumstances.
5911:
5912: However, you have to ensure that this code does not cause an exception
5913: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5914: Moreover, you should also make sure that the stack contents needed by
5915: the @code{iferror}/@code{restore} code exist everywhere between
5916: @code{try} and @code{endtry}; in our example this is achived by
5917: putting the data in a local before the @code{try} (you cannot use the
5918: return stack because the exception frame (@i{sys1}) is in the way
5919: there).
5920:
5921: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5922:
5923: @cindex @code{recover} (old Gforth versions)
5924: If you do not want this exception-restarting behaviour, you achieve
5925: this as follows:
5926:
5927: @example
5928: TRY
5929: @i{code1}
5930: ENDTRY-IFERROR
5931: @i{code2}
5932: THEN
5933: @end example
5934:
5935: If there is an exception in @i{code1}, then @i{code2} is executed,
5936: otherwise execution continues behind the @code{then} (or in a possible
5937: @code{else} branch). This corresponds to the construct
5938:
5939: @example
5940: TRY
5941: @i{code1}
5942: RECOVER
5943: @i{code2}
5944: ENDTRY
5945: @end example
5946:
5947: in Gforth before version 0.7. So you can directly replace
5948: @code{recover}-using code; however, we recommend that you check if it
5949: would not be better to use one of the other @code{try} variants while
5950: you are at it.
5951:
1.173 anton 5952: To ease the transition, Gforth provides two compatibility files:
5953: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5954: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5955: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5956: ... endtry} syntax on new systems, so you can use that file as a
5957: stopgap to run old programs. Both files work on any system (they just
5958: do nothing if the system already has the syntax it implements), so you
5959: can unconditionally @code{require} one of these files, even if you use
5960: a mix old and new systems.
5961:
1.172 anton 5962: doc-restore
5963: doc-endtry-iferror
5964:
5965: Here's the error handling example:
1.1 anton 5966:
1.68 anton 5967: @example
1.69 anton 5968: TRY
1.68 anton 5969: foo
1.172 anton 5970: ENDTRY-IFERROR
1.69 anton 5971: CASE
1.160 anton 5972: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5973: throw \ pass other errors on
5974: ENDCASE
1.172 anton 5975: THEN
1.68 anton 5976: @end example
1.1 anton 5977:
1.69 anton 5978: @progstyle
5979: As usual, you should ensure that the stack depth is statically known at
5980: the end: either after the @code{throw} for passing on errors, or after
5981: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5982: selection construct for handling the error).
5983:
1.68 anton 5984: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5985: and you can provide an error message. @code{Abort} just produces an
5986: ``Aborted'' error.
1.1 anton 5987:
1.68 anton 5988: The problem with these words is that exception handlers cannot
5989: differentiate between different @code{abort"}s; they just look like
5990: @code{-2 throw} to them (the error message cannot be accessed by
5991: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5992: exception handlers.
1.44 crook 5993:
1.68 anton 5994: doc-abort"
1.26 crook 5995: doc-abort
1.29 crook 5996:
5997:
1.44 crook 5998:
1.29 crook 5999: @c -------------------------------------------------------------
1.47 crook 6000: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 6001: @section Defining Words
6002: @cindex defining words
6003:
1.47 crook 6004: Defining words are used to extend Forth by creating new entries in the dictionary.
6005:
1.29 crook 6006: @menu
1.67 anton 6007: * CREATE::
1.44 crook 6008: * Variables:: Variables and user variables
1.67 anton 6009: * Constants::
1.44 crook 6010: * Values:: Initialised variables
1.67 anton 6011: * Colon Definitions::
1.44 crook 6012: * Anonymous Definitions:: Definitions without names
1.69 anton 6013: * Supplying names:: Passing definition names as strings
1.67 anton 6014: * User-defined Defining Words::
1.170 pazsan 6015: * Deferred Words:: Allow forward references
1.67 anton 6016: * Aliases::
1.29 crook 6017: @end menu
6018:
1.44 crook 6019: @node CREATE, Variables, Defining Words, Defining Words
6020: @subsection @code{CREATE}
1.29 crook 6021: @cindex simple defining words
6022: @cindex defining words, simple
6023:
6024: Defining words are used to create new entries in the dictionary. The
6025: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6026: this:
6027:
6028: @example
6029: CREATE new-word1
6030: @end example
6031:
1.69 anton 6032: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6033: input stream (@code{new-word1} in our example). It generates a
6034: dictionary entry for @code{new-word1}. When @code{new-word1} is
6035: executed, all that it does is leave an address on the stack. The address
6036: represents the value of the data space pointer (@code{HERE}) at the time
6037: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6038: associating a name with the address of a region of memory.
1.29 crook 6039:
1.34 anton 6040: doc-create
6041:
1.69 anton 6042: Note that in ANS Forth guarantees only for @code{create} that its body
6043: is in dictionary data space (i.e., where @code{here}, @code{allot}
6044: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6045: @code{create}d words can be modified with @code{does>}
6046: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6047: can only be applied to @code{create}d words.
6048:
1.29 crook 6049: By extending this example to reserve some memory in data space, we end
1.69 anton 6050: up with something like a @i{variable}. Here are two different ways to do
6051: it:
1.29 crook 6052:
6053: @example
6054: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6055: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6056: @end example
6057:
6058: The variable can be examined and modified using @code{@@} (``fetch'') and
6059: @code{!} (``store'') like this:
6060:
6061: @example
6062: new-word2 @@ . \ get address, fetch from it and display
6063: 1234 new-word2 ! \ new value, get address, store to it
6064: @end example
6065:
1.44 crook 6066: @cindex arrays
6067: A similar mechanism can be used to create arrays. For example, an
6068: 80-character text input buffer:
1.29 crook 6069:
6070: @example
1.44 crook 6071: CREATE text-buf 80 chars allot
6072:
1.168 anton 6073: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6074: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6075: @end example
1.29 crook 6076:
1.44 crook 6077: You can build arbitrarily complex data structures by allocating
1.49 anton 6078: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6079: learn about some Gforth tools that make it easier,
1.49 anton 6080: @xref{Structures}.
1.44 crook 6081:
6082:
6083: @node Variables, Constants, CREATE, Defining Words
6084: @subsection Variables
6085: @cindex variables
6086:
6087: The previous section showed how a sequence of commands could be used to
6088: generate a variable. As a final refinement, the whole code sequence can
6089: be wrapped up in a defining word (pre-empting the subject of the next
6090: section), making it easier to create new variables:
6091:
6092: @example
6093: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6094: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6095:
6096: myvariableX foo \ variable foo starts off with an unknown value
6097: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6098:
6099: 45 3 * foo ! \ set foo to 135
6100: 1234 joe ! \ set joe to 1234
6101: 3 joe +! \ increment joe by 3.. to 1237
6102: @end example
6103:
6104: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6105: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6106: guarantee that a @code{Variable} is initialised when it is created
6107: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6108: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6109: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6110: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6111: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6112: store a boolean, you can use @code{on} and @code{off} to toggle its
6113: state.
1.29 crook 6114:
1.34 anton 6115: doc-variable
6116: doc-2variable
6117: doc-fvariable
6118:
1.29 crook 6119: @cindex user variables
6120: @cindex user space
6121: The defining word @code{User} behaves in the same way as @code{Variable}.
6122: The difference is that it reserves space in @i{user (data) space} rather
6123: than normal data space. In a Forth system that has a multi-tasker, each
6124: task has its own set of user variables.
6125:
1.34 anton 6126: doc-user
1.67 anton 6127: @c doc-udp
6128: @c doc-uallot
1.34 anton 6129:
1.29 crook 6130: @comment TODO is that stuff about user variables strictly correct? Is it
6131: @comment just terminal tasks that have user variables?
6132: @comment should document tasker.fs (with some examples) elsewhere
6133: @comment in this manual, then expand on user space and user variables.
6134:
1.44 crook 6135: @node Constants, Values, Variables, Defining Words
6136: @subsection Constants
6137: @cindex constants
6138:
6139: @code{Constant} allows you to declare a fixed value and refer to it by
6140: name. For example:
1.29 crook 6141:
6142: @example
6143: 12 Constant INCHES-PER-FOOT
6144: 3E+08 fconstant SPEED-O-LIGHT
6145: @end example
6146:
6147: A @code{Variable} can be both read and written, so its run-time
6148: behaviour is to supply an address through which its current value can be
6149: manipulated. In contrast, the value of a @code{Constant} cannot be
6150: changed once it has been declared@footnote{Well, often it can be -- but
6151: not in a Standard, portable way. It's safer to use a @code{Value} (read
6152: on).} so it's not necessary to supply the address -- it is more
6153: efficient to return the value of the constant directly. That's exactly
6154: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6155: the top of the stack (You can find one
6156: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6157:
1.69 anton 6158: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6159: double and floating-point constants, respectively.
6160:
1.34 anton 6161: doc-constant
6162: doc-2constant
6163: doc-fconstant
6164:
6165: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6166: @c nac-> How could that not be true in an ANS Forth? You can't define a
6167: @c constant, use it and then delete the definition of the constant..
1.69 anton 6168:
6169: @c anton->An ANS Forth system can compile a constant to a literal; On
6170: @c decompilation you would see only the number, just as if it had been used
6171: @c in the first place. The word will stay, of course, but it will only be
6172: @c used by the text interpreter (no run-time duties, except when it is
6173: @c POSTPONEd or somesuch).
6174:
6175: @c nac:
1.44 crook 6176: @c I agree that it's rather deep, but IMO it is an important difference
6177: @c relative to other programming languages.. often it's annoying: it
6178: @c certainly changes my programming style relative to C.
6179:
1.69 anton 6180: @c anton: In what way?
6181:
1.29 crook 6182: Constants in Forth behave differently from their equivalents in other
6183: programming languages. In other languages, a constant (such as an EQU in
6184: assembler or a #define in C) only exists at compile-time; in the
6185: executable program the constant has been translated into an absolute
6186: number and, unless you are using a symbolic debugger, it's impossible to
6187: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6188: an entry in the header space and remains there after the code that uses
6189: it has been defined. In fact, it must remain in the dictionary since it
6190: has run-time duties to perform. For example:
1.29 crook 6191:
6192: @example
6193: 12 Constant INCHES-PER-FOOT
6194: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6195: @end example
6196:
6197: @cindex in-lining of constants
6198: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6199: associated with the constant @code{INCHES-PER-FOOT}. If you use
6200: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6201: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6202: attempt to optimise constants by in-lining them where they are used. You
6203: can force Gforth to in-line a constant like this:
6204:
6205: @example
6206: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6207: @end example
6208:
6209: If you use @code{see} to decompile @i{this} version of
6210: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6211: longer present. To understand how this works, read
6212: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6213:
6214: In-lining constants in this way might improve execution time
6215: fractionally, and can ensure that a constant is now only referenced at
6216: compile-time. However, the definition of the constant still remains in
6217: the dictionary. Some Forth compilers provide a mechanism for controlling
6218: a second dictionary for holding transient words such that this second
6219: dictionary can be deleted later in order to recover memory
6220: space. However, there is no standard way of doing this.
6221:
6222:
1.44 crook 6223: @node Values, Colon Definitions, Constants, Defining Words
6224: @subsection Values
6225: @cindex values
1.34 anton 6226:
1.69 anton 6227: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6228: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6229: (not in ANS Forth) you can access (and change) a @code{value} also with
6230: @code{>body}.
6231:
6232: Here are some
6233: examples:
1.29 crook 6234:
6235: @example
1.69 anton 6236: 12 Value APPLES \ Define APPLES with an initial value of 12
6237: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6238: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6239: APPLES \ puts 35 on the top of the stack.
1.29 crook 6240: @end example
6241:
1.44 crook 6242: doc-value
6243: doc-to
1.29 crook 6244:
1.35 anton 6245:
1.69 anton 6246:
1.44 crook 6247: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6248: @subsection Colon Definitions
6249: @cindex colon definitions
1.35 anton 6250:
6251: @example
1.44 crook 6252: : name ( ... -- ... )
6253: word1 word2 word3 ;
1.29 crook 6254: @end example
6255:
1.44 crook 6256: @noindent
6257: Creates a word called @code{name} that, upon execution, executes
6258: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6259:
1.49 anton 6260: The explanation above is somewhat superficial. For simple examples of
6261: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6262: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6263: Compilation Semantics}.
1.29 crook 6264:
1.44 crook 6265: doc-:
6266: doc-;
1.1 anton 6267:
1.34 anton 6268:
1.69 anton 6269: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6270: @subsection Anonymous Definitions
6271: @cindex colon definitions
6272: @cindex defining words without name
1.34 anton 6273:
1.44 crook 6274: Sometimes you want to define an @dfn{anonymous word}; a word without a
6275: name. You can do this with:
1.1 anton 6276:
1.44 crook 6277: doc-:noname
1.1 anton 6278:
1.44 crook 6279: This leaves the execution token for the word on the stack after the
6280: closing @code{;}. Here's an example in which a deferred word is
6281: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6282:
1.29 crook 6283: @example
1.44 crook 6284: Defer deferred
6285: :noname ( ... -- ... )
6286: ... ;
6287: IS deferred
1.29 crook 6288: @end example
1.26 crook 6289:
1.44 crook 6290: @noindent
6291: Gforth provides an alternative way of doing this, using two separate
6292: words:
1.27 crook 6293:
1.44 crook 6294: doc-noname
6295: @cindex execution token of last defined word
1.116 anton 6296: doc-latestxt
1.1 anton 6297:
1.44 crook 6298: @noindent
6299: The previous example can be rewritten using @code{noname} and
1.116 anton 6300: @code{latestxt}:
1.1 anton 6301:
1.26 crook 6302: @example
1.44 crook 6303: Defer deferred
6304: noname : ( ... -- ... )
6305: ... ;
1.116 anton 6306: latestxt IS deferred
1.26 crook 6307: @end example
1.1 anton 6308:
1.29 crook 6309: @noindent
1.44 crook 6310: @code{noname} works with any defining word, not just @code{:}.
6311:
1.116 anton 6312: @code{latestxt} also works when the last word was not defined as
1.71 anton 6313: @code{noname}. It does not work for combined words, though. It also has
6314: the useful property that is is valid as soon as the header for a
6315: definition has been built. Thus:
1.44 crook 6316:
6317: @example
1.116 anton 6318: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6319: @end example
1.1 anton 6320:
1.44 crook 6321: @noindent
6322: prints 3 numbers; the last two are the same.
1.26 crook 6323:
1.69 anton 6324: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6325: @subsection Supplying the name of a defined word
6326: @cindex names for defined words
6327: @cindex defining words, name given in a string
6328:
6329: By default, a defining word takes the name for the defined word from the
6330: input stream. Sometimes you want to supply the name from a string. You
6331: can do this with:
6332:
6333: doc-nextname
6334:
6335: For example:
6336:
6337: @example
6338: s" foo" nextname create
6339: @end example
6340:
6341: @noindent
6342: is equivalent to:
6343:
6344: @example
6345: create foo
6346: @end example
6347:
6348: @noindent
6349: @code{nextname} works with any defining word.
6350:
1.1 anton 6351:
1.170 pazsan 6352: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6353: @subsection User-defined Defining Words
6354: @cindex user-defined defining words
6355: @cindex defining words, user-defined
1.1 anton 6356:
1.29 crook 6357: You can create a new defining word by wrapping defining-time code around
6358: an existing defining word and putting the sequence in a colon
1.69 anton 6359: definition.
6360:
6361: @c anton: This example is very complex and leads in a quite different
6362: @c direction from the CREATE-DOES> stuff that follows. It should probably
6363: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6364: @c subsection of Defining Words)
6365:
6366: For example, suppose that you have a word @code{stats} that
1.29 crook 6367: gathers statistics about colon definitions given the @i{xt} of the
6368: definition, and you want every colon definition in your application to
6369: make a call to @code{stats}. You can define and use a new version of
6370: @code{:} like this:
6371:
6372: @example
6373: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6374: ... ; \ other code
6375:
1.116 anton 6376: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6377:
6378: my: foo + - ;
6379: @end example
6380:
6381: When @code{foo} is defined using @code{my:} these steps occur:
6382:
6383: @itemize @bullet
6384: @item
6385: @code{my:} is executed.
6386: @item
6387: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6388: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6389: the input stream for a name, builds a dictionary header for the name
6390: @code{foo} and switches @code{state} from interpret to compile.
6391: @item
1.116 anton 6392: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6393: being defined -- @code{foo} -- onto the stack.
6394: @item
6395: The code that was produced by @code{postpone literal} is executed; this
6396: causes the value on the stack to be compiled as a literal in the code
6397: area of @code{foo}.
6398: @item
6399: The code @code{['] stats} compiles a literal into the definition of
6400: @code{my:}. When @code{compile,} is executed, that literal -- the
6401: execution token for @code{stats} -- is layed down in the code area of
6402: @code{foo} , following the literal@footnote{Strictly speaking, the
6403: mechanism that @code{compile,} uses to convert an @i{xt} into something
6404: in the code area is implementation-dependent. A threaded implementation
6405: might spit out the execution token directly whilst another
6406: implementation might spit out a native code sequence.}.
6407: @item
6408: At this point, the execution of @code{my:} is complete, and control
6409: returns to the text interpreter. The text interpreter is in compile
6410: state, so subsequent text @code{+ -} is compiled into the definition of
6411: @code{foo} and the @code{;} terminates the definition as always.
6412: @end itemize
6413:
6414: You can use @code{see} to decompile a word that was defined using
6415: @code{my:} and see how it is different from a normal @code{:}
6416: definition. For example:
6417:
6418: @example
6419: : bar + - ; \ like foo but using : rather than my:
6420: see bar
6421: : bar
6422: + - ;
6423: see foo
6424: : foo
6425: 107645672 stats + - ;
6426:
1.140 anton 6427: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6428: @end example
6429:
6430: You can use techniques like this to make new defining words in terms of
6431: @i{any} existing defining word.
1.1 anton 6432:
6433:
1.29 crook 6434: @cindex defining defining words
1.26 crook 6435: @cindex @code{CREATE} ... @code{DOES>}
6436: If you want the words defined with your defining words to behave
6437: differently from words defined with standard defining words, you can
6438: write your defining word like this:
1.1 anton 6439:
6440: @example
1.26 crook 6441: : def-word ( "name" -- )
1.29 crook 6442: CREATE @i{code1}
1.26 crook 6443: DOES> ( ... -- ... )
1.29 crook 6444: @i{code2} ;
1.26 crook 6445:
6446: def-word name
1.1 anton 6447: @end example
6448:
1.29 crook 6449: @cindex child words
6450: This fragment defines a @dfn{defining word} @code{def-word} and then
6451: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6452: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6453: is not executed at this time. The word @code{name} is sometimes called a
6454: @dfn{child} of @code{def-word}.
6455:
6456: When you execute @code{name}, the address of the body of @code{name} is
6457: put on the data stack and @i{code2} is executed (the address of the body
6458: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6459: @code{CREATE}, i.e., the address a @code{create}d word returns by
6460: default).
6461:
6462: @c anton:
6463: @c www.dictionary.com says:
6464: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6465: @c several generations of absence, usually caused by the chance
6466: @c recombination of genes. 2.An individual or a part that exhibits
6467: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6468: @c of previous behavior after a period of absence.
6469: @c
6470: @c Doesn't seem to fit.
1.29 crook 6471:
1.69 anton 6472: @c @cindex atavism in child words
1.33 anton 6473: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6474: similarly; they all have a common run-time behaviour determined by
6475: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6476: body of the child word. The structure of the data is common to all
6477: children of @code{def-word}, but the data values are specific -- and
6478: private -- to each child word. When a child word is executed, the
6479: address of its private data area is passed as a parameter on TOS to be
6480: used and manipulated@footnote{It is legitimate both to read and write to
6481: this data area.} by @i{code2}.
1.29 crook 6482:
6483: The two fragments of code that make up the defining words act (are
6484: executed) at two completely separate times:
1.1 anton 6485:
1.29 crook 6486: @itemize @bullet
6487: @item
6488: At @i{define time}, the defining word executes @i{code1} to generate a
6489: child word
6490: @item
6491: At @i{child execution time}, when a child word is invoked, @i{code2}
6492: is executed, using parameters (data) that are private and specific to
6493: the child word.
6494: @end itemize
6495:
1.44 crook 6496: Another way of understanding the behaviour of @code{def-word} and
6497: @code{name} is to say that, if you make the following definitions:
1.33 anton 6498: @example
6499: : def-word1 ( "name" -- )
6500: CREATE @i{code1} ;
6501:
6502: : action1 ( ... -- ... )
6503: @i{code2} ;
6504:
6505: def-word1 name1
6506: @end example
6507:
1.44 crook 6508: @noindent
6509: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6510:
1.29 crook 6511: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6512:
1.1 anton 6513: @example
1.29 crook 6514: : CONSTANT ( w "name" -- )
6515: CREATE ,
1.26 crook 6516: DOES> ( -- w )
6517: @@ ;
1.1 anton 6518: @end example
6519:
1.29 crook 6520: @comment There is a beautiful description of how this works and what
6521: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6522: @comment commentary on the Counting Fruits problem.
6523:
6524: When you create a constant with @code{5 CONSTANT five}, a set of
6525: define-time actions take place; first a new word @code{five} is created,
6526: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6527: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6528: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6529: no code of its own; it simply contains a data field and a pointer to the
6530: code that follows @code{DOES>} in its defining word. That makes words
6531: created in this way very compact.
6532:
6533: The final example in this section is intended to remind you that space
6534: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6535: both read and written by a Standard program@footnote{Exercise: use this
6536: example as a starting point for your own implementation of @code{Value}
6537: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6538: @code{[']}.}:
6539:
6540: @example
6541: : foo ( "name" -- )
6542: CREATE -1 ,
6543: DOES> ( -- )
1.33 anton 6544: @@ . ;
1.29 crook 6545:
6546: foo first-word
6547: foo second-word
6548:
6549: 123 ' first-word >BODY !
6550: @end example
6551:
6552: If @code{first-word} had been a @code{CREATE}d word, we could simply
6553: have executed it to get the address of its data field. However, since it
6554: was defined to have @code{DOES>} actions, its execution semantics are to
6555: perform those @code{DOES>} actions. To get the address of its data field
6556: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6557: translate the xt into the address of the data field. When you execute
6558: @code{first-word}, it will display @code{123}. When you execute
6559: @code{second-word} it will display @code{-1}.
1.26 crook 6560:
6561: @cindex stack effect of @code{DOES>}-parts
6562: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6563: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6564: the stack effect of the defined words, not the stack effect of the
6565: following code (the following code expects the address of the body on
6566: the top of stack, which is not reflected in the stack comment). This is
6567: the convention that I use and recommend (it clashes a bit with using
6568: locals declarations for stack effect specification, though).
1.1 anton 6569:
1.53 anton 6570: @menu
6571: * CREATE..DOES> applications::
6572: * CREATE..DOES> details::
1.63 anton 6573: * Advanced does> usage example::
1.155 anton 6574: * Const-does>::
1.53 anton 6575: @end menu
6576:
6577: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6578: @subsubsection Applications of @code{CREATE..DOES>}
6579: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6580:
1.26 crook 6581: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6582:
1.26 crook 6583: @cindex factoring similar colon definitions
6584: When you see a sequence of code occurring several times, and you can
6585: identify a meaning, you will factor it out as a colon definition. When
6586: you see similar colon definitions, you can factor them using
6587: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6588: that look very similar:
1.1 anton 6589: @example
1.26 crook 6590: : ori, ( reg-target reg-source n -- )
6591: 0 asm-reg-reg-imm ;
6592: : andi, ( reg-target reg-source n -- )
6593: 1 asm-reg-reg-imm ;
1.1 anton 6594: @end example
6595:
1.26 crook 6596: @noindent
6597: This could be factored with:
6598: @example
6599: : reg-reg-imm ( op-code -- )
6600: CREATE ,
6601: DOES> ( reg-target reg-source n -- )
6602: @@ asm-reg-reg-imm ;
6603:
6604: 0 reg-reg-imm ori,
6605: 1 reg-reg-imm andi,
6606: @end example
1.1 anton 6607:
1.26 crook 6608: @cindex currying
6609: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6610: supply a part of the parameters for a word (known as @dfn{currying} in
6611: the functional language community). E.g., @code{+} needs two
6612: parameters. Creating versions of @code{+} with one parameter fixed can
6613: be done like this:
1.82 anton 6614:
1.1 anton 6615: @example
1.82 anton 6616: : curry+ ( n1 "name" -- )
1.26 crook 6617: CREATE ,
6618: DOES> ( n2 -- n1+n2 )
6619: @@ + ;
6620:
6621: 3 curry+ 3+
6622: -2 curry+ 2-
1.1 anton 6623: @end example
6624:
1.91 anton 6625:
1.63 anton 6626: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6627: @subsubsection The gory details of @code{CREATE..DOES>}
6628: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6629:
1.26 crook 6630: doc-does>
1.1 anton 6631:
1.26 crook 6632: @cindex @code{DOES>} in a separate definition
6633: This means that you need not use @code{CREATE} and @code{DOES>} in the
6634: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6635: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6636: @example
6637: : does1
6638: DOES> ( ... -- ... )
1.44 crook 6639: ... ;
6640:
6641: : does2
6642: DOES> ( ... -- ... )
6643: ... ;
6644:
6645: : def-word ( ... -- ... )
6646: create ...
6647: IF
6648: does1
6649: ELSE
6650: does2
6651: ENDIF ;
6652: @end example
6653:
6654: In this example, the selection of whether to use @code{does1} or
1.69 anton 6655: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6656: @code{CREATE}d.
6657:
6658: @cindex @code{DOES>} in interpretation state
6659: In a standard program you can apply a @code{DOES>}-part only if the last
6660: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6661: will override the behaviour of the last word defined in any case. In a
6662: standard program, you can use @code{DOES>} only in a colon
6663: definition. In Gforth, you can also use it in interpretation state, in a
6664: kind of one-shot mode; for example:
6665: @example
6666: CREATE name ( ... -- ... )
6667: @i{initialization}
6668: DOES>
6669: @i{code} ;
6670: @end example
6671:
6672: @noindent
6673: is equivalent to the standard:
6674: @example
6675: :noname
6676: DOES>
6677: @i{code} ;
6678: CREATE name EXECUTE ( ... -- ... )
6679: @i{initialization}
6680: @end example
6681:
1.53 anton 6682: doc->body
6683:
1.152 pazsan 6684: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6685: @subsubsection Advanced does> usage example
6686:
6687: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6688: for disassembling instructions, that follow a very repetetive scheme:
6689:
6690: @example
6691: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6692: @var{entry-num} cells @var{table} + !
6693: @end example
6694:
6695: Of course, this inspires the idea to factor out the commonalities to
6696: allow a definition like
6697:
6698: @example
6699: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6700: @end example
6701:
6702: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6703: correlated. Moreover, before I wrote the disassembler, there already
6704: existed code that defines instructions like this:
1.63 anton 6705:
6706: @example
6707: @var{entry-num} @var{inst-format} @var{inst-name}
6708: @end example
6709:
6710: This code comes from the assembler and resides in
6711: @file{arch/mips/insts.fs}.
6712:
6713: So I had to define the @var{inst-format} words that performed the scheme
6714: above when executed. At first I chose to use run-time code-generation:
6715:
6716: @example
6717: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6718: :noname Postpone @var{disasm-operands}
6719: name Postpone sliteral Postpone type Postpone ;
6720: swap cells @var{table} + ! ;
6721: @end example
6722:
6723: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6724:
1.63 anton 6725: An alternative would have been to write this using
6726: @code{create}/@code{does>}:
6727:
6728: @example
6729: : @var{inst-format} ( entry-num "name" -- )
6730: here name string, ( entry-num c-addr ) \ parse and save "name"
6731: noname create , ( entry-num )
1.116 anton 6732: latestxt swap cells @var{table} + !
1.63 anton 6733: does> ( addr w -- )
6734: \ disassemble instruction w at addr
6735: @@ >r
6736: @var{disasm-operands}
6737: r> count type ;
6738: @end example
6739:
6740: Somehow the first solution is simpler, mainly because it's simpler to
6741: shift a string from definition-time to use-time with @code{sliteral}
6742: than with @code{string,} and friends.
6743:
6744: I wrote a lot of words following this scheme and soon thought about
6745: factoring out the commonalities among them. Note that this uses a
6746: two-level defining word, i.e., a word that defines ordinary defining
6747: words.
6748:
6749: This time a solution involving @code{postpone} and friends seemed more
6750: difficult (try it as an exercise), so I decided to use a
6751: @code{create}/@code{does>} word; since I was already at it, I also used
6752: @code{create}/@code{does>} for the lower level (try using
6753: @code{postpone} etc. as an exercise), resulting in the following
6754: definition:
6755:
6756: @example
6757: : define-format ( disasm-xt table-xt -- )
6758: \ define an instruction format that uses disasm-xt for
6759: \ disassembling and enters the defined instructions into table
6760: \ table-xt
6761: create 2,
6762: does> ( u "inst" -- )
6763: \ defines an anonymous word for disassembling instruction inst,
6764: \ and enters it as u-th entry into table-xt
6765: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6766: noname create 2, \ define anonymous word
1.116 anton 6767: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6768: does> ( addr w -- )
6769: \ disassemble instruction w at addr
6770: 2@@ >r ( addr w disasm-xt R: c-addr )
6771: execute ( R: c-addr ) \ disassemble operands
6772: r> count type ; \ print name
6773: @end example
6774:
6775: Note that the tables here (in contrast to above) do the @code{cells +}
6776: by themselves (that's why you have to pass an xt). This word is used in
6777: the following way:
6778:
6779: @example
6780: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6781: @end example
6782:
1.71 anton 6783: As shown above, the defined instruction format is then used like this:
6784:
6785: @example
6786: @var{entry-num} @var{inst-format} @var{inst-name}
6787: @end example
6788:
1.63 anton 6789: In terms of currying, this kind of two-level defining word provides the
6790: parameters in three stages: first @var{disasm-operands} and @var{table},
6791: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6792: the instruction to be disassembled.
6793:
6794: Of course this did not quite fit all the instruction format names used
6795: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6796: the parameters into the right form.
6797:
6798: If you have trouble following this section, don't worry. First, this is
6799: involved and takes time (and probably some playing around) to
6800: understand; second, this is the first two-level
6801: @code{create}/@code{does>} word I have written in seventeen years of
6802: Forth; and if I did not have @file{insts.fs} to start with, I may well
6803: have elected to use just a one-level defining word (with some repeating
6804: of parameters when using the defining word). So it is not necessary to
6805: understand this, but it may improve your understanding of Forth.
1.44 crook 6806:
6807:
1.152 pazsan 6808: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6809: @subsubsection @code{Const-does>}
6810:
6811: A frequent use of @code{create}...@code{does>} is for transferring some
6812: values from definition-time to run-time. Gforth supports this use with
6813:
6814: doc-const-does>
6815:
6816: A typical use of this word is:
6817:
6818: @example
6819: : curry+ ( n1 "name" -- )
6820: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6821: + ;
6822:
6823: 3 curry+ 3+
6824: @end example
6825:
6826: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6827: definition to run-time.
6828:
6829: The advantages of using @code{const-does>} are:
6830:
6831: @itemize
6832:
6833: @item
6834: You don't have to deal with storing and retrieving the values, i.e.,
6835: your program becomes more writable and readable.
6836:
6837: @item
6838: When using @code{does>}, you have to introduce a @code{@@} that cannot
6839: be optimized away (because you could change the data using
6840: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6841:
6842: @end itemize
6843:
6844: An ANS Forth implementation of @code{const-does>} is available in
6845: @file{compat/const-does.fs}.
6846:
6847:
1.170 pazsan 6848: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6849: @subsection Deferred Words
1.44 crook 6850: @cindex deferred words
6851:
6852: The defining word @code{Defer} allows you to define a word by name
6853: without defining its behaviour; the definition of its behaviour is
6854: deferred. Here are two situation where this can be useful:
6855:
6856: @itemize @bullet
6857: @item
6858: Where you want to allow the behaviour of a word to be altered later, and
6859: for all precompiled references to the word to change when its behaviour
6860: is changed.
6861: @item
6862: For mutual recursion; @xref{Calls and returns}.
6863: @end itemize
6864:
6865: In the following example, @code{foo} always invokes the version of
6866: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6867: always invokes the version that prints ``@code{Hello}''. There is no way
6868: of getting @code{foo} to use the later version without re-ordering the
6869: source code and recompiling it.
6870:
6871: @example
6872: : greet ." Good morning" ;
6873: : foo ... greet ... ;
6874: : greet ." Hello" ;
6875: : bar ... greet ... ;
6876: @end example
6877:
6878: This problem can be solved by defining @code{greet} as a @code{Defer}red
6879: word. The behaviour of a @code{Defer}red word can be defined and
6880: redefined at any time by using @code{IS} to associate the xt of a
6881: previously-defined word with it. The previous example becomes:
6882:
6883: @example
1.69 anton 6884: Defer greet ( -- )
1.44 crook 6885: : foo ... greet ... ;
6886: : bar ... greet ... ;
1.69 anton 6887: : greet1 ( -- ) ." Good morning" ;
6888: : greet2 ( -- ) ." Hello" ;
1.132 anton 6889: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6890: @end example
6891:
1.69 anton 6892: @progstyle
6893: You should write a stack comment for every deferred word, and put only
6894: XTs into deferred words that conform to this stack effect. Otherwise
6895: it's too difficult to use the deferred word.
6896:
1.44 crook 6897: A deferred word can be used to improve the statistics-gathering example
6898: from @ref{User-defined Defining Words}; rather than edit the
6899: application's source code to change every @code{:} to a @code{my:}, do
6900: this:
6901:
6902: @example
6903: : real: : ; \ retain access to the original
6904: defer : \ redefine as a deferred word
1.132 anton 6905: ' my: IS : \ use special version of :
1.44 crook 6906: \
6907: \ load application here
6908: \
1.132 anton 6909: ' real: IS : \ go back to the original
1.44 crook 6910: @end example
6911:
6912:
1.132 anton 6913: One thing to note is that @code{IS} has special compilation semantics,
6914: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6915:
6916: @example
6917: : set-greet ( xt -- )
1.132 anton 6918: IS greet ;
1.44 crook 6919:
6920: ' greet1 set-greet
6921: @end example
6922:
1.132 anton 6923: In situations where @code{IS} does not fit, use @code{defer!} instead.
6924:
1.69 anton 6925: A deferred word can only inherit execution semantics from the xt
6926: (because that is all that an xt can represent -- for more discussion of
6927: this @pxref{Tokens for Words}); by default it will have default
6928: interpretation and compilation semantics deriving from this execution
6929: semantics. However, you can change the interpretation and compilation
6930: semantics of the deferred word in the usual ways:
1.44 crook 6931:
6932: @example
1.132 anton 6933: : bar .... ; immediate
1.44 crook 6934: Defer fred immediate
6935: Defer jim
6936:
1.132 anton 6937: ' bar IS jim \ jim has default semantics
6938: ' bar IS fred \ fred is immediate
1.44 crook 6939: @end example
6940:
6941: doc-defer
1.132 anton 6942: doc-defer!
1.44 crook 6943: doc-is
1.132 anton 6944: doc-defer@
6945: doc-action-of
1.44 crook 6946: @comment TODO document these: what's defers [is]
6947: doc-defers
6948:
6949: @c Use @code{words-deferred} to see a list of deferred words.
6950:
1.132 anton 6951: Definitions of these words (except @code{defers}) in ANS Forth are
6952: provided in @file{compat/defer.fs}.
1.44 crook 6953:
6954:
1.170 pazsan 6955: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6956: @subsection Aliases
6957: @cindex aliases
1.1 anton 6958:
1.44 crook 6959: The defining word @code{Alias} allows you to define a word by name that
6960: has the same behaviour as some other word. Here are two situation where
6961: this can be useful:
1.1 anton 6962:
1.44 crook 6963: @itemize @bullet
6964: @item
6965: When you want access to a word's definition from a different word list
6966: (for an example of this, see the definition of the @code{Root} word list
6967: in the Gforth source).
6968: @item
6969: When you want to create a synonym; a definition that can be known by
6970: either of two names (for example, @code{THEN} and @code{ENDIF} are
6971: aliases).
6972: @end itemize
1.1 anton 6973:
1.69 anton 6974: Like deferred words, an alias has default compilation and interpretation
6975: semantics at the beginning (not the modifications of the other word),
6976: but you can change them in the usual ways (@code{immediate},
6977: @code{compile-only}). For example:
1.1 anton 6978:
6979: @example
1.44 crook 6980: : foo ... ; immediate
6981:
6982: ' foo Alias bar \ bar is not an immediate word
6983: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6984: @end example
6985:
1.44 crook 6986: Words that are aliases have the same xt, different headers in the
6987: dictionary, and consequently different name tokens (@pxref{Tokens for
6988: Words}) and possibly different immediate flags. An alias can only have
6989: default or immediate compilation semantics; you can define aliases for
6990: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6991:
1.44 crook 6992: doc-alias
1.1 anton 6993:
6994:
1.47 crook 6995: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6996: @section Interpretation and Compilation Semantics
1.26 crook 6997: @cindex semantics, interpretation and compilation
1.1 anton 6998:
1.71 anton 6999: @c !! state and ' are used without explanation
7000: @c example for immediate/compile-only? or is the tutorial enough
7001:
1.26 crook 7002: @cindex interpretation semantics
1.71 anton 7003: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 7004: interpreter does when it encounters the word in interpret state. It also
7005: appears in some other contexts, e.g., the execution token returned by
1.71 anton 7006: @code{' @i{word}} identifies the interpretation semantics of @i{word}
7007: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 7008: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 7009:
1.26 crook 7010: @cindex compilation semantics
1.71 anton 7011: The @dfn{compilation semantics} of a (named) word are what the text
7012: interpreter does when it encounters the word in compile state. It also
7013: appears in other contexts, e.g, @code{POSTPONE @i{word}}
7014: compiles@footnote{In standard terminology, ``appends to the current
7015: definition''.} the compilation semantics of @i{word}.
1.1 anton 7016:
1.26 crook 7017: @cindex execution semantics
7018: The standard also talks about @dfn{execution semantics}. They are used
7019: only for defining the interpretation and compilation semantics of many
7020: words. By default, the interpretation semantics of a word are to
7021: @code{execute} its execution semantics, and the compilation semantics of
7022: a word are to @code{compile,} its execution semantics.@footnote{In
7023: standard terminology: The default interpretation semantics are its
7024: execution semantics; the default compilation semantics are to append its
7025: execution semantics to the execution semantics of the current
7026: definition.}
7027:
1.71 anton 7028: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
7029: the text interpreter, ticked, or @code{postpone}d, so they have no
7030: interpretation or compilation semantics. Their behaviour is represented
7031: by their XT (@pxref{Tokens for Words}), and we call it execution
7032: semantics, too.
7033:
1.26 crook 7034: @comment TODO expand, make it co-operate with new sections on text interpreter.
7035:
7036: @cindex immediate words
7037: @cindex compile-only words
7038: You can change the semantics of the most-recently defined word:
7039:
1.44 crook 7040:
1.26 crook 7041: doc-immediate
7042: doc-compile-only
7043: doc-restrict
7044:
1.82 anton 7045: By convention, words with non-default compilation semantics (e.g.,
7046: immediate words) often have names surrounded with brackets (e.g.,
7047: @code{[']}, @pxref{Execution token}).
1.44 crook 7048:
1.26 crook 7049: Note that ticking (@code{'}) a compile-only word gives an error
7050: (``Interpreting a compile-only word'').
1.1 anton 7051:
1.47 crook 7052: @menu
1.67 anton 7053: * Combined words::
1.47 crook 7054: @end menu
1.44 crook 7055:
1.71 anton 7056:
1.48 anton 7057: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7058: @subsection Combined Words
7059: @cindex combined words
7060:
7061: Gforth allows you to define @dfn{combined words} -- words that have an
7062: arbitrary combination of interpretation and compilation semantics.
7063:
1.26 crook 7064: doc-interpret/compile:
1.1 anton 7065:
1.26 crook 7066: This feature was introduced for implementing @code{TO} and @code{S"}. I
7067: recommend that you do not define such words, as cute as they may be:
7068: they make it hard to get at both parts of the word in some contexts.
7069: E.g., assume you want to get an execution token for the compilation
7070: part. Instead, define two words, one that embodies the interpretation
7071: part, and one that embodies the compilation part. Once you have done
7072: that, you can define a combined word with @code{interpret/compile:} for
7073: the convenience of your users.
1.1 anton 7074:
1.26 crook 7075: You might try to use this feature to provide an optimizing
7076: implementation of the default compilation semantics of a word. For
7077: example, by defining:
1.1 anton 7078: @example
1.26 crook 7079: :noname
7080: foo bar ;
7081: :noname
7082: POSTPONE foo POSTPONE bar ;
1.29 crook 7083: interpret/compile: opti-foobar
1.1 anton 7084: @end example
1.26 crook 7085:
1.23 crook 7086: @noindent
1.26 crook 7087: as an optimizing version of:
7088:
1.1 anton 7089: @example
1.26 crook 7090: : foobar
7091: foo bar ;
1.1 anton 7092: @end example
7093:
1.26 crook 7094: Unfortunately, this does not work correctly with @code{[compile]},
7095: because @code{[compile]} assumes that the compilation semantics of all
7096: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7097: opti-foobar} would compile compilation semantics, whereas
7098: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7099:
1.26 crook 7100: @cindex state-smart words (are a bad idea)
1.82 anton 7101: @anchor{state-smartness}
1.29 crook 7102: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7103: by @code{interpret/compile:} (words are state-smart if they check
7104: @code{STATE} during execution). E.g., they would try to code
7105: @code{foobar} like this:
1.1 anton 7106:
1.26 crook 7107: @example
7108: : foobar
7109: STATE @@
7110: IF ( compilation state )
7111: POSTPONE foo POSTPONE bar
7112: ELSE
7113: foo bar
7114: ENDIF ; immediate
7115: @end example
1.1 anton 7116:
1.26 crook 7117: Although this works if @code{foobar} is only processed by the text
7118: interpreter, it does not work in other contexts (like @code{'} or
7119: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7120: for a state-smart word, not for the interpretation semantics of the
7121: original @code{foobar}; when you execute this execution token (directly
7122: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7123: state, the result will not be what you expected (i.e., it will not
7124: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7125: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7126: M. Anton Ertl,
7127: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7128: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7129:
1.26 crook 7130: @cindex defining words with arbitrary semantics combinations
7131: It is also possible to write defining words that define words with
7132: arbitrary combinations of interpretation and compilation semantics. In
7133: general, they look like this:
1.1 anton 7134:
1.26 crook 7135: @example
7136: : def-word
7137: create-interpret/compile
1.29 crook 7138: @i{code1}
1.26 crook 7139: interpretation>
1.29 crook 7140: @i{code2}
1.26 crook 7141: <interpretation
7142: compilation>
1.29 crook 7143: @i{code3}
1.26 crook 7144: <compilation ;
7145: @end example
1.1 anton 7146:
1.29 crook 7147: For a @i{word} defined with @code{def-word}, the interpretation
7148: semantics are to push the address of the body of @i{word} and perform
7149: @i{code2}, and the compilation semantics are to push the address of
7150: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7151: can also be defined like this (except that the defined constants don't
7152: behave correctly when @code{[compile]}d):
1.1 anton 7153:
1.26 crook 7154: @example
7155: : constant ( n "name" -- )
7156: create-interpret/compile
7157: ,
7158: interpretation> ( -- n )
7159: @@
7160: <interpretation
7161: compilation> ( compilation. -- ; run-time. -- n )
7162: @@ postpone literal
7163: <compilation ;
7164: @end example
1.1 anton 7165:
1.44 crook 7166:
1.26 crook 7167: doc-create-interpret/compile
7168: doc-interpretation>
7169: doc-<interpretation
7170: doc-compilation>
7171: doc-<compilation
1.1 anton 7172:
1.44 crook 7173:
1.29 crook 7174: Words defined with @code{interpret/compile:} and
1.26 crook 7175: @code{create-interpret/compile} have an extended header structure that
7176: differs from other words; however, unless you try to access them with
7177: plain address arithmetic, you should not notice this. Words for
7178: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7179: @code{'} @i{word} @code{>body} also gives you the body of a word created
7180: with @code{create-interpret/compile}.
1.1 anton 7181:
1.44 crook 7182:
1.47 crook 7183: @c -------------------------------------------------------------
1.81 anton 7184: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7185: @section Tokens for Words
7186: @cindex tokens for words
7187:
7188: This section describes the creation and use of tokens that represent
7189: words.
7190:
1.71 anton 7191: @menu
7192: * Execution token:: represents execution/interpretation semantics
7193: * Compilation token:: represents compilation semantics
7194: * Name token:: represents named words
7195: @end menu
1.47 crook 7196:
1.71 anton 7197: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7198: @subsection Execution token
1.47 crook 7199:
7200: @cindex xt
7201: @cindex execution token
1.71 anton 7202: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7203: You can use @code{execute} to invoke this behaviour.
1.47 crook 7204:
1.71 anton 7205: @cindex tick (')
7206: You can use @code{'} to get an execution token that represents the
7207: interpretation semantics of a named word:
1.47 crook 7208:
7209: @example
1.97 anton 7210: 5 ' . ( n xt )
7211: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7212: @end example
1.47 crook 7213:
1.71 anton 7214: doc-'
7215:
7216: @code{'} parses at run-time; there is also a word @code{[']} that parses
7217: when it is compiled, and compiles the resulting XT:
7218:
7219: @example
7220: : foo ['] . execute ;
7221: 5 foo
7222: : bar ' execute ; \ by contrast,
7223: 5 bar . \ ' parses "." when bar executes
7224: @end example
7225:
7226: doc-[']
7227:
7228: If you want the execution token of @i{word}, write @code{['] @i{word}}
7229: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7230: @code{'} and @code{[']} behave somewhat unusually by complaining about
7231: compile-only words (because these words have no interpretation
7232: semantics). You might get what you want by using @code{COMP' @i{word}
7233: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7234: token}).
7235:
1.116 anton 7236: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7237: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7238: for the only behaviour the word has (the execution semantics). For
1.116 anton 7239: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7240: would produce if the word was defined anonymously.
7241:
7242: @example
7243: :noname ." hello" ;
7244: execute
1.47 crook 7245: @end example
7246:
1.71 anton 7247: An XT occupies one cell and can be manipulated like any other cell.
7248:
1.47 crook 7249: @cindex code field address
7250: @cindex CFA
1.71 anton 7251: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7252: operations that produce or consume it). For old hands: In Gforth, the
7253: XT is implemented as a code field address (CFA).
7254:
7255: doc-execute
7256: doc-perform
7257:
7258: @node Compilation token, Name token, Execution token, Tokens for Words
7259: @subsection Compilation token
1.47 crook 7260:
7261: @cindex compilation token
1.71 anton 7262: @cindex CT (compilation token)
7263: Gforth represents the compilation semantics of a named word by a
1.47 crook 7264: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7265: @i{xt} is an execution token. The compilation semantics represented by
7266: the compilation token can be performed with @code{execute}, which
7267: consumes the whole compilation token, with an additional stack effect
7268: determined by the represented compilation semantics.
7269:
7270: At present, the @i{w} part of a compilation token is an execution token,
7271: and the @i{xt} part represents either @code{execute} or
7272: @code{compile,}@footnote{Depending upon the compilation semantics of the
7273: word. If the word has default compilation semantics, the @i{xt} will
7274: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7275: @i{xt} will represent @code{execute}.}. However, don't rely on that
7276: knowledge, unless necessary; future versions of Gforth may introduce
7277: unusual compilation tokens (e.g., a compilation token that represents
7278: the compilation semantics of a literal).
7279:
1.71 anton 7280: You can perform the compilation semantics represented by the compilation
7281: token with @code{execute}. You can compile the compilation semantics
7282: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7283: equivalent to @code{postpone @i{word}}.
7284:
7285: doc-[comp']
7286: doc-comp'
7287: doc-postpone,
7288:
7289: @node Name token, , Compilation token, Tokens for Words
7290: @subsection Name token
1.47 crook 7291:
7292: @cindex name token
1.116 anton 7293: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7294: token is an abstract data type that occurs as argument or result of the
7295: words below.
7296:
7297: @c !! put this elswhere?
1.47 crook 7298: @cindex name field address
7299: @cindex NFA
1.116 anton 7300: The closest thing to the nt in older Forth systems is the name field
7301: address (NFA), but there are significant differences: in older Forth
7302: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7303: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7304: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7305: is a link field in the structure identified by the name token, but
7306: searching usually uses a hash table external to these structures; the
7307: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7308: implemented as the address of that count field.
1.47 crook 7309:
7310: doc-find-name
1.116 anton 7311: doc-latest
7312: doc->name
1.47 crook 7313: doc-name>int
7314: doc-name?int
7315: doc-name>comp
7316: doc-name>string
1.109 anton 7317: doc-id.
7318: doc-.name
7319: doc-.id
1.47 crook 7320:
1.81 anton 7321: @c ----------------------------------------------------------
7322: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7323: @section Compiling words
7324: @cindex compiling words
7325: @cindex macros
7326:
7327: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7328: between compilation and run-time. E.g., you can run arbitrary code
7329: between defining words (or for computing data used by defining words
7330: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7331: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7332: running arbitrary code while compiling a colon definition (exception:
7333: you must not allot dictionary space).
7334:
7335: @menu
7336: * Literals:: Compiling data values
7337: * Macros:: Compiling words
7338: @end menu
7339:
7340: @node Literals, Macros, Compiling words, Compiling words
7341: @subsection Literals
7342: @cindex Literals
7343:
7344: The simplest and most frequent example is to compute a literal during
7345: compilation. E.g., the following definition prints an array of strings,
7346: one string per line:
7347:
7348: @example
7349: : .strings ( addr u -- ) \ gforth
7350: 2* cells bounds U+DO
7351: cr i 2@@ type
7352: 2 cells +LOOP ;
7353: @end example
1.81 anton 7354:
1.82 anton 7355: With a simple-minded compiler like Gforth's, this computes @code{2
7356: cells} on every loop iteration. You can compute this value once and for
7357: all at compile time and compile it into the definition like this:
7358:
7359: @example
7360: : .strings ( addr u -- ) \ gforth
7361: 2* cells bounds U+DO
7362: cr i 2@@ type
7363: [ 2 cells ] literal +LOOP ;
7364: @end example
7365:
7366: @code{[} switches the text interpreter to interpret state (you will get
7367: an @code{ok} prompt if you type this example interactively and insert a
7368: newline between @code{[} and @code{]}), so it performs the
7369: interpretation semantics of @code{2 cells}; this computes a number.
7370: @code{]} switches the text interpreter back into compile state. It then
7371: performs @code{Literal}'s compilation semantics, which are to compile
7372: this number into the current word. You can decompile the word with
7373: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7374:
1.82 anton 7375: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7376: *} in this way.
1.81 anton 7377:
1.82 anton 7378: doc-[
7379: doc-]
1.81 anton 7380: doc-literal
7381: doc-]L
1.82 anton 7382:
7383: There are also words for compiling other data types than single cells as
7384: literals:
7385:
1.81 anton 7386: doc-2literal
7387: doc-fliteral
1.82 anton 7388: doc-sliteral
7389:
7390: @cindex colon-sys, passing data across @code{:}
7391: @cindex @code{:}, passing data across
7392: You might be tempted to pass data from outside a colon definition to the
7393: inside on the data stack. This does not work, because @code{:} puhes a
7394: colon-sys, making stuff below unaccessible. E.g., this does not work:
7395:
7396: @example
7397: 5 : foo literal ; \ error: "unstructured"
7398: @end example
7399:
7400: Instead, you have to pass the value in some other way, e.g., through a
7401: variable:
7402:
7403: @example
7404: variable temp
7405: 5 temp !
7406: : foo [ temp @@ ] literal ;
7407: @end example
7408:
7409:
7410: @node Macros, , Literals, Compiling words
7411: @subsection Macros
7412: @cindex Macros
7413: @cindex compiling compilation semantics
7414:
7415: @code{Literal} and friends compile data values into the current
7416: definition. You can also write words that compile other words into the
7417: current definition. E.g.,
7418:
7419: @example
7420: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7421: POSTPONE + ;
7422:
7423: : foo ( n1 n2 -- n )
7424: [ compile-+ ] ;
7425: 1 2 foo .
7426: @end example
7427:
7428: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7429: What happens in this example? @code{Postpone} compiles the compilation
7430: semantics of @code{+} into @code{compile-+}; later the text interpreter
7431: executes @code{compile-+} and thus the compilation semantics of +, which
7432: compile (the execution semantics of) @code{+} into
7433: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7434: should only be executed in compile state, so this example is not
7435: guaranteed to work on all standard systems, but on any decent system it
7436: will work.}
7437:
7438: doc-postpone
7439:
7440: Compiling words like @code{compile-+} are usually immediate (or similar)
7441: so you do not have to switch to interpret state to execute them;
1.206 anton 7442: modifying the last example accordingly produces:
1.82 anton 7443:
7444: @example
7445: : [compile-+] ( compilation: --; interpretation: -- )
7446: \ compiled code: ( n1 n2 -- n )
7447: POSTPONE + ; immediate
7448:
7449: : foo ( n1 n2 -- n )
7450: [compile-+] ;
7451: 1 2 foo .
7452: @end example
7453:
1.206 anton 7454: You will occassionally find the need to POSTPONE several words;
7455: putting POSTPONE before each such word is cumbersome, so Gforth
7456: provides a more convenient syntax: @code{]] ... [[}. This
7457: allows us to write @code{[compile-+]} as:
7458:
7459: @example
7460: : [compile-+] ( compilation: --; interpretation: -- )
7461: ]] + [[ ; immediate
7462: @end example
7463:
7464: doc-]]
7465: doc-[[
7466:
7467: The unusual direction of the brackets indicates their function:
7468: @code{]]} switches from compilation to postponing (i.e., compilation
7469: of compilation), just like @code{]} switches from immediate execution
7470: (interpretation) to compilation. Conversely, @code{[[} switches from
7471: postponing to compilation, ananlogous to @code{[} which switches from
7472: compilation to immediate execution.
7473:
7474: The real advantage of @code{]] }...@code{ [[} becomes apparent when
7475: there are many words to POSTPONE. E.g., the word
7476: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
7477: written much shorter as follows:
7478:
7479: @example
7480: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
7481: \ at run-time, execute xt ( ... x -- ... ) for each element of the
7482: \ array beginning at addr and containing u elements
7483: @{ xt @}
7484: ]] cells over + swap ?do
7485: i @@ [[ xt compile,
7486: 1 cells ]]L +loop [[ ;
7487: @end example
7488:
7489: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
7490: There are also other shortcuts
7491:
7492: doc-]]L
7493: doc-]]2L
7494: doc-]]FL
7495: doc-]]SL
7496:
7497: Note that parsing words don't parse at postpone time; if you want to
7498: provide the parsed string right away, you have to switch back to
7499: compilation:
7500:
7501: @example
7502: ]] ... [[ s" some string" ]]2L ... [[
7503: ]] ... [[ ['] + ]]L ... [[
7504: @end example
7505:
7506: Definitions of @code{]]} and friends in ANS Forth are provided in
7507: @file{compat/macros.fs}.
7508:
1.82 anton 7509: Immediate compiling words are similar to macros in other languages (in
7510: particular, Lisp). The important differences to macros in, e.g., C are:
7511:
7512: @itemize @bullet
7513:
7514: @item
7515: You use the same language for defining and processing macros, not a
7516: separate preprocessing language and processor.
7517:
7518: @item
7519: Consequently, the full power of Forth is available in macro definitions.
7520: E.g., you can perform arbitrarily complex computations, or generate
7521: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7522: Tutorial}). This power is very useful when writing a parser generators
7523: or other code-generating software.
7524:
7525: @item
7526: Macros defined using @code{postpone} etc. deal with the language at a
7527: higher level than strings; name binding happens at macro definition
7528: time, so you can avoid the pitfalls of name collisions that can happen
7529: in C macros. Of course, Forth is a liberal language and also allows to
7530: shoot yourself in the foot with text-interpreted macros like
7531:
7532: @example
7533: : [compile-+] s" +" evaluate ; immediate
7534: @end example
7535:
7536: Apart from binding the name at macro use time, using @code{evaluate}
7537: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7538: @end itemize
7539:
7540: You may want the macro to compile a number into a word. The word to do
7541: it is @code{literal}, but you have to @code{postpone} it, so its
7542: compilation semantics take effect when the macro is executed, not when
7543: it is compiled:
7544:
7545: @example
7546: : [compile-5] ( -- ) \ compiled code: ( -- n )
7547: 5 POSTPONE literal ; immediate
7548:
7549: : foo [compile-5] ;
7550: foo .
7551: @end example
7552:
7553: You may want to pass parameters to a macro, that the macro should
7554: compile into the current definition. If the parameter is a number, then
7555: you can use @code{postpone literal} (similar for other values).
7556:
7557: If you want to pass a word that is to be compiled, the usual way is to
7558: pass an execution token and @code{compile,} it:
7559:
7560: @example
7561: : twice1 ( xt -- ) \ compiled code: ... -- ...
7562: dup compile, compile, ;
7563:
7564: : 2+ ( n1 -- n2 )
7565: [ ' 1+ twice1 ] ;
7566: @end example
7567:
7568: doc-compile,
7569:
7570: An alternative available in Gforth, that allows you to pass compile-only
7571: words as parameters is to use the compilation token (@pxref{Compilation
7572: token}). The same example in this technique:
7573:
7574: @example
7575: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7576: 2dup 2>r execute 2r> execute ;
7577:
7578: : 2+ ( n1 -- n2 )
7579: [ comp' 1+ twice ] ;
7580: @end example
7581:
7582: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7583: works even if the executed compilation semantics has an effect on the
7584: data stack.
7585:
7586: You can also define complete definitions with these words; this provides
7587: an alternative to using @code{does>} (@pxref{User-defined Defining
7588: Words}). E.g., instead of
7589:
7590: @example
7591: : curry+ ( n1 "name" -- )
7592: CREATE ,
7593: DOES> ( n2 -- n1+n2 )
7594: @@ + ;
7595: @end example
7596:
7597: you could define
7598:
7599: @example
7600: : curry+ ( n1 "name" -- )
7601: \ name execution: ( n2 -- n1+n2 )
7602: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7603:
1.82 anton 7604: -3 curry+ 3-
7605: see 3-
7606: @end example
1.81 anton 7607:
1.82 anton 7608: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7609: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7610:
1.82 anton 7611: This way of writing defining words is sometimes more, sometimes less
7612: convenient than using @code{does>} (@pxref{Advanced does> usage
7613: example}). One advantage of this method is that it can be optimized
7614: better, because the compiler knows that the value compiled with
7615: @code{literal} is fixed, whereas the data associated with a
7616: @code{create}d word can be changed.
1.47 crook 7617:
1.206 anton 7618: @c doc-[compile] !! not properly documented
7619:
1.26 crook 7620: @c ----------------------------------------------------------
1.111 anton 7621: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7622: @section The Text Interpreter
7623: @cindex interpreter - outer
7624: @cindex text interpreter
7625: @cindex outer interpreter
1.1 anton 7626:
1.34 anton 7627: @c Should we really describe all these ugly details? IMO the text
7628: @c interpreter should be much cleaner, but that may not be possible within
7629: @c ANS Forth. - anton
1.44 crook 7630: @c nac-> I wanted to explain how it works to show how you can exploit
7631: @c it in your own programs. When I was writing a cross-compiler, figuring out
7632: @c some of these gory details was very helpful to me. None of the textbooks
7633: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7634: @c seems to positively avoid going into too much detail for some of
7635: @c the internals.
1.34 anton 7636:
1.71 anton 7637: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7638: @c it is; for the ugly details, I would prefer another place. I wonder
7639: @c whether we should have a chapter before "Words" that describes some
7640: @c basic concepts referred to in words, and a chapter after "Words" that
7641: @c describes implementation details.
7642:
1.29 crook 7643: The text interpreter@footnote{This is an expanded version of the
7644: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7645: that processes input from the current input device. It is also called
7646: the outer interpreter, in contrast to the inner interpreter
7647: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7648: implementations.
1.27 crook 7649:
1.29 crook 7650: @cindex interpret state
7651: @cindex compile state
7652: The text interpreter operates in one of two states: @dfn{interpret
7653: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7654: aptly-named variable @code{state}.
1.29 crook 7655:
7656: This section starts by describing how the text interpreter behaves when
7657: it is in interpret state, processing input from the user input device --
7658: the keyboard. This is the mode that a Forth system is in after it starts
7659: up.
7660:
7661: @cindex input buffer
7662: @cindex terminal input buffer
7663: The text interpreter works from an area of memory called the @dfn{input
7664: buffer}@footnote{When the text interpreter is processing input from the
7665: keyboard, this area of memory is called the @dfn{terminal input buffer}
7666: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7667: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7668: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7669: leading spaces (called @dfn{delimiters}) then parses a string (a
7670: sequence of non-space characters) until it reaches either a space
7671: character or the end of the buffer. Having parsed a string, it makes two
7672: attempts to process it:
1.27 crook 7673:
1.29 crook 7674: @cindex dictionary
1.27 crook 7675: @itemize @bullet
7676: @item
1.29 crook 7677: It looks for the string in a @dfn{dictionary} of definitions. If the
7678: string is found, the string names a @dfn{definition} (also known as a
7679: @dfn{word}) and the dictionary search returns information that allows
7680: the text interpreter to perform the word's @dfn{interpretation
7681: semantics}. In most cases, this simply means that the word will be
7682: executed.
1.27 crook 7683: @item
7684: If the string is not found in the dictionary, the text interpreter
1.29 crook 7685: attempts to treat it as a number, using the rules described in
7686: @ref{Number Conversion}. If the string represents a legal number in the
7687: current radix, the number is pushed onto a parameter stack (the data
7688: stack for integers, the floating-point stack for floating-point
7689: numbers).
7690: @end itemize
7691:
7692: If both attempts fail, or if the word is found in the dictionary but has
7693: no interpretation semantics@footnote{This happens if the word was
7694: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7695: remainder of the input buffer, issues an error message and waits for
7696: more input. If one of the attempts succeeds, the text interpreter
7697: repeats the parsing process until the whole of the input buffer has been
7698: processed, at which point it prints the status message ``@code{ ok}''
7699: and waits for more input.
7700:
1.71 anton 7701: @c anton: this should be in the input stream subsection (or below it)
7702:
1.29 crook 7703: @cindex parse area
7704: The text interpreter keeps track of its position in the input buffer by
7705: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7706: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7707: of the input buffer. The region from offset @code{>IN @@} to the end of
7708: the input buffer is called the @dfn{parse area}@footnote{In other words,
7709: the text interpreter processes the contents of the input buffer by
7710: parsing strings from the parse area until the parse area is empty.}.
7711: This example shows how @code{>IN} changes as the text interpreter parses
7712: the input buffer:
7713:
7714: @example
7715: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7716: CR ." ->" TYPE ." <-" ; IMMEDIATE
7717:
7718: 1 2 3 remaining + remaining .
7719:
7720: : foo 1 2 3 remaining SWAP remaining ;
7721: @end example
7722:
7723: @noindent
7724: The result is:
7725:
7726: @example
7727: ->+ remaining .<-
7728: ->.<-5 ok
7729:
7730: ->SWAP remaining ;-<
7731: ->;<- ok
7732: @end example
7733:
7734: @cindex parsing words
7735: The value of @code{>IN} can also be modified by a word in the input
7736: buffer that is executed by the text interpreter. This means that a word
7737: can ``trick'' the text interpreter into either skipping a section of the
7738: input buffer@footnote{This is how parsing words work.} or into parsing a
7739: section twice. For example:
1.27 crook 7740:
1.29 crook 7741: @example
1.71 anton 7742: : lat ." <<foo>>" ;
7743: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7744: @end example
7745:
7746: @noindent
7747: When @code{flat} is executed, this output is produced@footnote{Exercise
7748: for the reader: what would happen if the @code{3} were replaced with
7749: @code{4}?}:
7750:
7751: @example
1.71 anton 7752: <<bar>><<foo>>
1.29 crook 7753: @end example
7754:
1.71 anton 7755: This technique can be used to work around some of the interoperability
7756: problems of parsing words. Of course, it's better to avoid parsing
7757: words where possible.
7758:
1.29 crook 7759: @noindent
7760: Two important notes about the behaviour of the text interpreter:
1.27 crook 7761:
7762: @itemize @bullet
7763: @item
7764: It processes each input string to completion before parsing additional
1.29 crook 7765: characters from the input buffer.
7766: @item
7767: It treats the input buffer as a read-only region (and so must your code).
7768: @end itemize
7769:
7770: @noindent
7771: When the text interpreter is in compile state, its behaviour changes in
7772: these ways:
7773:
7774: @itemize @bullet
7775: @item
7776: If a parsed string is found in the dictionary, the text interpreter will
7777: perform the word's @dfn{compilation semantics}. In most cases, this
7778: simply means that the execution semantics of the word will be appended
7779: to the current definition.
1.27 crook 7780: @item
1.29 crook 7781: When a number is encountered, it is compiled into the current definition
7782: (as a literal) rather than being pushed onto a parameter stack.
7783: @item
7784: If an error occurs, @code{state} is modified to put the text interpreter
7785: back into interpret state.
7786: @item
7787: Each time a line is entered from the keyboard, Gforth prints
7788: ``@code{ compiled}'' rather than `` @code{ok}''.
7789: @end itemize
7790:
7791: @cindex text interpreter - input sources
7792: When the text interpreter is using an input device other than the
7793: keyboard, its behaviour changes in these ways:
7794:
7795: @itemize @bullet
7796: @item
7797: When the parse area is empty, the text interpreter attempts to refill
7798: the input buffer from the input source. When the input source is
1.71 anton 7799: exhausted, the input source is set back to the previous input source.
1.29 crook 7800: @item
7801: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7802: time the parse area is emptied.
7803: @item
7804: If an error occurs, the input source is set back to the user input
7805: device.
1.27 crook 7806: @end itemize
1.21 crook 7807:
1.49 anton 7808: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7809:
1.26 crook 7810: doc->in
1.27 crook 7811: doc-source
7812:
1.26 crook 7813: doc-tib
7814: doc-#tib
1.1 anton 7815:
1.44 crook 7816:
1.26 crook 7817: @menu
1.67 anton 7818: * Input Sources::
7819: * Number Conversion::
7820: * Interpret/Compile states::
7821: * Interpreter Directives::
1.26 crook 7822: @end menu
1.1 anton 7823:
1.29 crook 7824: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7825: @subsection Input Sources
7826: @cindex input sources
7827: @cindex text interpreter - input sources
7828:
1.44 crook 7829: By default, the text interpreter processes input from the user input
1.29 crook 7830: device (the keyboard) when Forth starts up. The text interpreter can
7831: process input from any of these sources:
7832:
7833: @itemize @bullet
7834: @item
7835: The user input device -- the keyboard.
7836: @item
7837: A file, using the words described in @ref{Forth source files}.
7838: @item
7839: A block, using the words described in @ref{Blocks}.
7840: @item
7841: A text string, using @code{evaluate}.
7842: @end itemize
7843:
7844: A program can identify the current input device from the values of
7845: @code{source-id} and @code{blk}.
7846:
1.44 crook 7847:
1.29 crook 7848: doc-source-id
7849: doc-blk
7850:
7851: doc-save-input
7852: doc-restore-input
7853:
7854: doc-evaluate
1.111 anton 7855: doc-query
1.1 anton 7856:
1.29 crook 7857:
1.44 crook 7858:
1.29 crook 7859: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7860: @subsection Number Conversion
7861: @cindex number conversion
7862: @cindex double-cell numbers, input format
7863: @cindex input format for double-cell numbers
7864: @cindex single-cell numbers, input format
7865: @cindex input format for single-cell numbers
7866: @cindex floating-point numbers, input format
7867: @cindex input format for floating-point numbers
1.1 anton 7868:
1.29 crook 7869: This section describes the rules that the text interpreter uses when it
7870: tries to convert a string into a number.
1.1 anton 7871:
1.26 crook 7872: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7873: number base@footnote{For example, 0-9 when the number base is decimal or
7874: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7875:
1.26 crook 7876: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7877:
1.29 crook 7878: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7879: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7880:
1.26 crook 7881: Let * represent any number of instances of the previous character
7882: (including none).
1.1 anton 7883:
1.26 crook 7884: Let any other character represent itself.
1.1 anton 7885:
1.29 crook 7886: @noindent
1.26 crook 7887: Now, the conversion rules are:
1.21 crook 7888:
1.26 crook 7889: @itemize @bullet
7890: @item
7891: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7892: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7893: @item
7894: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7895: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7896: arithmetic. Examples are -45 -5681 -0
7897: @item
7898: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7899: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7900: (all three of these represent the same number).
1.26 crook 7901: @item
7902: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7903: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7904: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7905: -34.65 (all three of these represent the same number).
1.26 crook 7906: @item
1.29 crook 7907: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7908: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7909: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7910: number) +12.E-4
1.26 crook 7911: @end itemize
1.1 anton 7912:
1.174 anton 7913: By default, the number base used for integer number conversion is
7914: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7915: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7916: change @code{base} anywhere, make sure to save the old value and
7917: restore it afterwards; better yet, use @code{base-execute}, which does
7918: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7919: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7920:
1.29 crook 7921: doc-dpl
1.174 anton 7922: doc-base-execute
1.26 crook 7923: doc-base
7924: doc-hex
7925: doc-decimal
1.1 anton 7926:
1.26 crook 7927: @cindex '-prefix for character strings
7928: @cindex &-prefix for decimal numbers
1.133 anton 7929: @cindex #-prefix for decimal numbers
1.26 crook 7930: @cindex %-prefix for binary numbers
7931: @cindex $-prefix for hexadecimal numbers
1.133 anton 7932: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7933: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7934: prefix@footnote{Some Forth implementations provide a similar scheme by
7935: implementing @code{$} etc. as parsing words that process the subsequent
7936: number in the input stream and push it onto the stack. For example, see
7937: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7938: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7939: is required between the prefix and the number.} before the first digit
1.133 anton 7940: of an (integer) number. The following prefixes are supported:
1.1 anton 7941:
1.26 crook 7942: @itemize @bullet
7943: @item
1.35 anton 7944: @code{&} -- decimal
1.26 crook 7945: @item
1.133 anton 7946: @code{#} -- decimal
7947: @item
1.35 anton 7948: @code{%} -- binary
1.26 crook 7949: @item
1.35 anton 7950: @code{$} -- hexadecimal
1.26 crook 7951: @item
1.133 anton 7952: @code{0x} -- hexadecimal, if base<33.
7953: @item
7954: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7955: optional @code{'} may be present after the character.
1.26 crook 7956: @end itemize
1.1 anton 7957:
1.26 crook 7958: Here are some examples, with the equivalent decimal number shown after
7959: in braces:
1.1 anton 7960:
1.26 crook 7961: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7962: 'A (65),
7963: -'a' (-97),
1.26 crook 7964: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7965:
1.26 crook 7966: @cindex number conversion - traps for the unwary
1.29 crook 7967: @noindent
1.26 crook 7968: Number conversion has a number of traps for the unwary:
1.1 anton 7969:
1.26 crook 7970: @itemize @bullet
7971: @item
7972: You cannot determine the current number base using the code sequence
1.35 anton 7973: @code{base @@ .} -- the number base is always 10 in the current number
7974: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7975: @item
7976: If the number base is set to a value greater than 14 (for example,
7977: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7978: it to be intepreted as either a single-precision integer or a
7979: floating-point number (Gforth treats it as an integer). The ambiguity
7980: can be resolved by explicitly stating the sign of the mantissa and/or
7981: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7982: ambiguity arises; either representation will be treated as a
7983: floating-point number.
7984: @item
1.29 crook 7985: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7986: It is used to specify file types.
7987: @item
1.72 anton 7988: ANS Forth requires the @code{.} of a double-precision number to be the
7989: final character in the string. Gforth allows the @code{.} to be
7990: anywhere after the first digit.
1.26 crook 7991: @item
7992: The number conversion process does not check for overflow.
7993: @item
1.72 anton 7994: In an ANS Forth program @code{base} is required to be decimal when
7995: converting floating-point numbers. In Gforth, number conversion to
7996: floating-point numbers always uses base &10, irrespective of the value
7997: of @code{base}.
1.26 crook 7998: @end itemize
1.1 anton 7999:
1.49 anton 8000: You can read numbers into your programs with the words described in
1.181 anton 8001: @ref{Line input and conversion}.
1.1 anton 8002:
1.82 anton 8003: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 8004: @subsection Interpret/Compile states
8005: @cindex Interpret/Compile states
1.1 anton 8006:
1.29 crook 8007: A standard program is not permitted to change @code{state}
8008: explicitly. However, it can change @code{state} implicitly, using the
8009: words @code{[} and @code{]}. When @code{[} is executed it switches
8010: @code{state} to interpret state, and therefore the text interpreter
8011: starts interpreting. When @code{]} is executed it switches @code{state}
8012: to compile state and therefore the text interpreter starts
1.44 crook 8013: compiling. The most common usage for these words is for switching into
8014: interpret state and back from within a colon definition; this technique
1.49 anton 8015: can be used to compile a literal (for an example, @pxref{Literals}) or
8016: for conditional compilation (for an example, @pxref{Interpreter
8017: Directives}).
1.44 crook 8018:
1.35 anton 8019:
8020: @c This is a bad example: It's non-standard, and it's not necessary.
8021: @c However, I can't think of a good example for switching into compile
8022: @c state when there is no current word (@code{state}-smart words are not a
8023: @c good reason). So maybe we should use an example for switching into
8024: @c interpret @code{state} in a colon def. - anton
1.44 crook 8025: @c nac-> I agree. I started out by putting in the example, then realised
8026: @c that it was non-ANS, so wrote more words around it. I hope this
8027: @c re-written version is acceptable to you. I do want to keep the example
8028: @c as it is helpful for showing what is and what is not portable, particularly
8029: @c where it outlaws a style in common use.
8030:
1.72 anton 8031: @c anton: it's more important to show what's portable. After we have done
1.83 anton 8032: @c that, we can also show what's not. In any case, I have written a
8033: @c section Compiling Words which also deals with [ ].
1.35 anton 8034:
1.95 anton 8035: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 8036:
1.95 anton 8037: @c @code{[} and @code{]} also give you the ability to switch into compile
8038: @c state and back, but we cannot think of any useful Standard application
8039: @c for this ability. Pre-ANS Forth textbooks have examples like this:
8040:
8041: @c @example
8042: @c : AA ." this is A" ;
8043: @c : BB ." this is B" ;
8044: @c : CC ." this is C" ;
8045:
8046: @c create table ] aa bb cc [
8047:
8048: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
8049: @c cells table + @@ execute ;
8050: @c @end example
8051:
8052: @c This example builds a jump table; @code{0 go} will display ``@code{this
8053: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
8054: @c defining @code{table} like this:
8055:
8056: @c @example
8057: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
8058: @c @end example
8059:
8060: @c The problem with this code is that the definition of @code{table} is not
8061: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
8062: @c @i{may} work on systems where code space and data space co-incide, the
8063: @c Standard only allows data space to be assigned for a @code{CREATE}d
8064: @c word. In addition, the Standard only allows @code{@@} to access data
8065: @c space, whilst this example is using it to access code space. The only
8066: @c portable, Standard way to build this table is to build it in data space,
8067: @c like this:
8068:
8069: @c @example
8070: @c create table ' aa , ' bb , ' cc ,
8071: @c @end example
1.29 crook 8072:
1.95 anton 8073: @c doc-state
1.44 crook 8074:
1.29 crook 8075:
1.82 anton 8076: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 8077: @subsection Interpreter Directives
8078: @cindex interpreter directives
1.72 anton 8079: @cindex conditional compilation
1.1 anton 8080:
1.29 crook 8081: These words are usually used in interpret state; typically to control
8082: which parts of a source file are processed by the text
1.26 crook 8083: interpreter. There are only a few ANS Forth Standard words, but Gforth
8084: supplements these with a rich set of immediate control structure words
8085: to compensate for the fact that the non-immediate versions can only be
1.29 crook 8086: used in compile state (@pxref{Control Structures}). Typical usages:
8087:
8088: @example
1.72 anton 8089: FALSE Constant HAVE-ASSEMBLER
1.29 crook 8090: .
8091: .
1.72 anton 8092: HAVE-ASSEMBLER [IF]
1.29 crook 8093: : ASSEMBLER-FEATURE
8094: ...
8095: ;
8096: [ENDIF]
8097: .
8098: .
8099: : SEE
8100: ... \ general-purpose SEE code
1.72 anton 8101: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 8102: ... \ assembler-specific SEE code
8103: [ [ENDIF] ]
8104: ;
8105: @end example
1.1 anton 8106:
1.44 crook 8107:
1.26 crook 8108: doc-[IF]
8109: doc-[ELSE]
8110: doc-[THEN]
8111: doc-[ENDIF]
1.1 anton 8112:
1.26 crook 8113: doc-[IFDEF]
8114: doc-[IFUNDEF]
1.1 anton 8115:
1.26 crook 8116: doc-[?DO]
8117: doc-[DO]
8118: doc-[FOR]
8119: doc-[LOOP]
8120: doc-[+LOOP]
8121: doc-[NEXT]
1.1 anton 8122:
1.26 crook 8123: doc-[BEGIN]
8124: doc-[UNTIL]
8125: doc-[AGAIN]
8126: doc-[WHILE]
8127: doc-[REPEAT]
1.1 anton 8128:
1.27 crook 8129:
1.26 crook 8130: @c -------------------------------------------------------------
1.111 anton 8131: @node The Input Stream, Word Lists, The Text Interpreter, Words
8132: @section The Input Stream
8133: @cindex input stream
8134:
8135: @c !! integrate this better with the "Text Interpreter" section
8136: The text interpreter reads from the input stream, which can come from
8137: several sources (@pxref{Input Sources}). Some words, in particular
8138: defining words, but also words like @code{'}, read parameters from the
8139: input stream instead of from the stack.
8140:
8141: Such words are called parsing words, because they parse the input
8142: stream. Parsing words are hard to use in other words, because it is
8143: hard to pass program-generated parameters through the input stream.
8144: They also usually have an unintuitive combination of interpretation and
8145: compilation semantics when implemented naively, leading to various
8146: approaches that try to produce a more intuitive behaviour
8147: (@pxref{Combined words}).
8148:
8149: It should be obvious by now that parsing words are a bad idea. If you
8150: want to implement a parsing word for convenience, also provide a factor
8151: of the word that does not parse, but takes the parameters on the stack.
8152: To implement the parsing word on top if it, you can use the following
8153: words:
8154:
8155: @c anton: these belong in the input stream section
8156: doc-parse
1.138 anton 8157: doc-parse-name
1.111 anton 8158: doc-parse-word
8159: doc-name
8160: doc-word
8161: doc-refill
8162:
8163: Conversely, if you have the bad luck (or lack of foresight) to have to
8164: deal with parsing words without having such factors, how do you pass a
8165: string that is not in the input stream to it?
8166:
8167: doc-execute-parsing
8168:
1.146 anton 8169: A definition of this word in ANS Forth is provided in
8170: @file{compat/execute-parsing.fs}.
8171:
1.111 anton 8172: If you want to run a parsing word on a file, the following word should
8173: help:
8174:
8175: doc-execute-parsing-file
8176:
8177: @c -------------------------------------------------------------
8178: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8179: @section Word Lists
8180: @cindex word lists
1.32 anton 8181: @cindex header space
1.1 anton 8182:
1.36 anton 8183: A wordlist is a list of named words; you can add new words and look up
8184: words by name (and you can remove words in a restricted way with
8185: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8186:
8187: @cindex search order stack
8188: The text interpreter searches the wordlists present in the search order
8189: (a stack of wordlists), from the top to the bottom. Within each
8190: wordlist, the search starts conceptually at the newest word; i.e., if
8191: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8192:
1.26 crook 8193: @cindex compilation word list
1.36 anton 8194: New words are added to the @dfn{compilation wordlist} (aka current
8195: wordlist).
1.1 anton 8196:
1.36 anton 8197: @cindex wid
8198: A word list is identified by a cell-sized word list identifier (@i{wid})
8199: in much the same way as a file is identified by a file handle. The
8200: numerical value of the wid has no (portable) meaning, and might change
8201: from session to session.
1.1 anton 8202:
1.29 crook 8203: The ANS Forth ``Search order'' word set is intended to provide a set of
8204: low-level tools that allow various different schemes to be
1.74 anton 8205: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8206: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8207: Forth.
1.1 anton 8208:
1.27 crook 8209: @comment TODO: locals section refers to here, saying that every word list (aka
8210: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8211: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8212:
1.45 crook 8213: @comment TODO: document markers, reveal, tables, mappedwordlist
8214:
8215: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8216: @comment word from the source files, rather than some alias.
1.44 crook 8217:
1.26 crook 8218: doc-forth-wordlist
8219: doc-definitions
8220: doc-get-current
8221: doc-set-current
8222: doc-get-order
1.185 anton 8223: doc-set-order
1.26 crook 8224: doc-wordlist
1.30 anton 8225: doc-table
1.79 anton 8226: doc->order
1.36 anton 8227: doc-previous
1.26 crook 8228: doc-also
1.185 anton 8229: doc-forth
1.26 crook 8230: doc-only
1.185 anton 8231: doc-order
1.15 anton 8232:
1.26 crook 8233: doc-find
8234: doc-search-wordlist
1.15 anton 8235:
1.26 crook 8236: doc-words
8237: doc-vlist
1.44 crook 8238: @c doc-words-deferred
1.1 anton 8239:
1.74 anton 8240: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8241: doc-root
8242: doc-vocabulary
8243: doc-seal
8244: doc-vocs
8245: doc-current
8246: doc-context
1.1 anton 8247:
1.44 crook 8248:
1.26 crook 8249: @menu
1.75 anton 8250: * Vocabularies::
1.67 anton 8251: * Why use word lists?::
1.75 anton 8252: * Word list example::
1.26 crook 8253: @end menu
8254:
1.75 anton 8255: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8256: @subsection Vocabularies
8257: @cindex Vocabularies, detailed explanation
8258:
8259: Here is an example of creating and using a new wordlist using ANS
8260: Forth words:
8261:
8262: @example
8263: wordlist constant my-new-words-wordlist
8264: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8265:
8266: \ add it to the search order
8267: also my-new-words
8268:
8269: \ alternatively, add it to the search order and make it
8270: \ the compilation word list
8271: also my-new-words definitions
8272: \ type "order" to see the problem
8273: @end example
8274:
8275: The problem with this example is that @code{order} has no way to
8276: associate the name @code{my-new-words} with the wid of the word list (in
8277: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8278: that has no associated name). There is no Standard way of associating a
8279: name with a wid.
8280:
8281: In Gforth, this example can be re-coded using @code{vocabulary}, which
8282: associates a name with a wid:
8283:
8284: @example
8285: vocabulary my-new-words
8286:
8287: \ add it to the search order
8288: also my-new-words
8289:
8290: \ alternatively, add it to the search order and make it
8291: \ the compilation word list
8292: my-new-words definitions
8293: \ type "order" to see that the problem is solved
8294: @end example
8295:
8296:
8297: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8298: @subsection Why use word lists?
8299: @cindex word lists - why use them?
8300:
1.74 anton 8301: Here are some reasons why people use wordlists:
1.26 crook 8302:
8303: @itemize @bullet
1.74 anton 8304:
8305: @c anton: Gforth's hashing implementation makes the search speed
8306: @c independent from the number of words. But it is linear with the number
8307: @c of wordlists that have to be searched, so in effect using more wordlists
8308: @c actually slows down compilation.
8309:
8310: @c @item
8311: @c To improve compilation speed by reducing the number of header space
8312: @c entries that must be searched. This is achieved by creating a new
8313: @c word list that contains all of the definitions that are used in the
8314: @c definition of a Forth system but which would not usually be used by
8315: @c programs running on that system. That word list would be on the search
8316: @c list when the Forth system was compiled but would be removed from the
8317: @c search list for normal operation. This can be a useful technique for
8318: @c low-performance systems (for example, 8-bit processors in embedded
8319: @c systems) but is unlikely to be necessary in high-performance desktop
8320: @c systems.
8321:
1.26 crook 8322: @item
8323: To prevent a set of words from being used outside the context in which
8324: they are valid. Two classic examples of this are an integrated editor
8325: (all of the edit commands are defined in a separate word list; the
8326: search order is set to the editor word list when the editor is invoked;
8327: the old search order is restored when the editor is terminated) and an
8328: integrated assembler (the op-codes for the machine are defined in a
8329: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8330:
8331: @item
8332: To organize the words of an application or library into a user-visible
8333: set (in @code{forth-wordlist} or some other common wordlist) and a set
8334: of helper words used just for the implementation (hidden in a separate
1.75 anton 8335: wordlist). This keeps @code{words}' output smaller, separates
8336: implementation and interface, and reduces the chance of name conflicts
8337: within the common wordlist.
1.74 anton 8338:
1.26 crook 8339: @item
8340: To prevent a name-space clash between multiple definitions with the same
8341: name. For example, when building a cross-compiler you might have a word
8342: @code{IF} that generates conditional code for your target system. By
8343: placing this definition in a different word list you can control whether
8344: the host system's @code{IF} or the target system's @code{IF} get used in
8345: any particular context by controlling the order of the word lists on the
8346: search order stack.
1.74 anton 8347:
1.26 crook 8348: @end itemize
1.1 anton 8349:
1.74 anton 8350: The downsides of using wordlists are:
8351:
8352: @itemize
8353:
8354: @item
8355: Debugging becomes more cumbersome.
8356:
8357: @item
8358: Name conflicts worked around with wordlists are still there, and you
8359: have to arrange the search order carefully to get the desired results;
8360: if you forget to do that, you get hard-to-find errors (as in any case
8361: where you read the code differently from the compiler; @code{see} can
1.75 anton 8362: help seeing which of several possible words the name resolves to in such
8363: cases). @code{See} displays just the name of the words, not what
8364: wordlist they belong to, so it might be misleading. Using unique names
8365: is a better approach to avoid name conflicts.
1.74 anton 8366:
8367: @item
8368: You have to explicitly undo any changes to the search order. In many
8369: cases it would be more convenient if this happened implicitly. Gforth
8370: currently does not provide such a feature, but it may do so in the
8371: future.
8372: @end itemize
8373:
8374:
1.75 anton 8375: @node Word list example, , Why use word lists?, Word Lists
8376: @subsection Word list example
8377: @cindex word lists - example
1.1 anton 8378:
1.74 anton 8379: The following example is from the
8380: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8381: garbage collector} and uses wordlists to separate public words from
8382: helper words:
8383:
8384: @example
8385: get-current ( wid )
8386: vocabulary garbage-collector also garbage-collector definitions
8387: ... \ define helper words
8388: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8389: ... \ define the public (i.e., API) words
8390: \ they can refer to the helper words
8391: previous \ restore original search order (helper words become invisible)
8392: @end example
8393:
1.26 crook 8394: @c -------------------------------------------------------------
8395: @node Environmental Queries, Files, Word Lists, Words
8396: @section Environmental Queries
8397: @cindex environmental queries
1.21 crook 8398:
1.26 crook 8399: ANS Forth introduced the idea of ``environmental queries'' as a way
8400: for a program running on a system to determine certain characteristics of the system.
8401: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8402:
1.32 anton 8403: The Standard requires that the header space used for environmental queries
8404: be distinct from the header space used for definitions.
1.21 crook 8405:
1.26 crook 8406: Typically, environmental queries are supported by creating a set of
1.29 crook 8407: definitions in a word list that is @i{only} used during environmental
1.26 crook 8408: queries; that is what Gforth does. There is no Standard way of adding
8409: definitions to the set of recognised environmental queries, but any
8410: implementation that supports the loading of optional word sets must have
8411: some mechanism for doing this (after loading the word set, the
8412: associated environmental query string must return @code{true}). In
8413: Gforth, the word list used to honour environmental queries can be
8414: manipulated just like any other word list.
1.21 crook 8415:
1.44 crook 8416:
1.26 crook 8417: doc-environment?
8418: doc-environment-wordlist
1.21 crook 8419:
1.26 crook 8420: doc-gforth
8421: doc-os-class
1.21 crook 8422:
1.44 crook 8423:
1.26 crook 8424: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8425: returning two items on the stack, querying it using @code{environment?}
8426: will return an additional item; the @code{true} flag that shows that the
8427: string was recognised.
1.21 crook 8428:
1.26 crook 8429: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8430:
1.26 crook 8431: Here are some examples of using environmental queries:
1.21 crook 8432:
1.26 crook 8433: @example
8434: s" address-unit-bits" environment? 0=
8435: [IF]
8436: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8437: [ELSE]
8438: drop \ ensure balanced stack effect
1.26 crook 8439: [THEN]
1.21 crook 8440:
1.75 anton 8441: \ this might occur in the prelude of a standard program that uses THROW
8442: s" exception" environment? [IF]
8443: 0= [IF]
8444: : throw abort" exception thrown" ;
8445: [THEN]
8446: [ELSE] \ we don't know, so make sure
8447: : throw abort" exception thrown" ;
8448: [THEN]
1.21 crook 8449:
1.26 crook 8450: s" gforth" environment? [IF] .( Gforth version ) TYPE
8451: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8452:
8453: \ a program using v*
8454: s" gforth" environment? [IF]
8455: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8456: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8457: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8458: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8459: LOOP
8460: 2drop 2drop ;
8461: [THEN]
8462: [ELSE] \
8463: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8464: ...
8465: [THEN]
1.26 crook 8466: @end example
1.21 crook 8467:
1.26 crook 8468: Here is an example of adding a definition to the environment word list:
1.21 crook 8469:
1.26 crook 8470: @example
8471: get-current environment-wordlist set-current
8472: true constant block
8473: true constant block-ext
8474: set-current
8475: @end example
1.21 crook 8476:
1.26 crook 8477: You can see what definitions are in the environment word list like this:
1.21 crook 8478:
1.26 crook 8479: @example
1.79 anton 8480: environment-wordlist >order words previous
1.26 crook 8481: @end example
1.21 crook 8482:
8483:
1.26 crook 8484: @c -------------------------------------------------------------
8485: @node Files, Blocks, Environmental Queries, Words
8486: @section Files
1.28 crook 8487: @cindex files
8488: @cindex I/O - file-handling
1.21 crook 8489:
1.26 crook 8490: Gforth provides facilities for accessing files that are stored in the
8491: host operating system's file-system. Files that are processed by Gforth
8492: can be divided into two categories:
1.21 crook 8493:
1.23 crook 8494: @itemize @bullet
8495: @item
1.29 crook 8496: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8497: @item
1.29 crook 8498: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8499: @end itemize
8500:
8501: @menu
1.48 anton 8502: * Forth source files::
8503: * General files::
1.167 anton 8504: * Redirection::
1.48 anton 8505: * Search Paths::
1.26 crook 8506: @end menu
8507:
8508: @c -------------------------------------------------------------
8509: @node Forth source files, General files, Files, Files
8510: @subsection Forth source files
8511: @cindex including files
8512: @cindex Forth source files
1.21 crook 8513:
1.26 crook 8514: The simplest way to interpret the contents of a file is to use one of
8515: these two formats:
1.21 crook 8516:
1.26 crook 8517: @example
8518: include mysource.fs
8519: s" mysource.fs" included
8520: @end example
1.21 crook 8521:
1.75 anton 8522: You usually want to include a file only if it is not included already
1.26 crook 8523: (by, say, another source file). In that case, you can use one of these
1.45 crook 8524: three formats:
1.21 crook 8525:
1.26 crook 8526: @example
8527: require mysource.fs
8528: needs mysource.fs
8529: s" mysource.fs" required
8530: @end example
1.21 crook 8531:
1.26 crook 8532: @cindex stack effect of included files
8533: @cindex including files, stack effect
1.45 crook 8534: It is good practice to write your source files such that interpreting them
8535: does not change the stack. Source files designed in this way can be used with
1.26 crook 8536: @code{required} and friends without complications. For example:
1.21 crook 8537:
1.26 crook 8538: @example
1.75 anton 8539: 1024 require foo.fs drop
1.26 crook 8540: @end example
1.21 crook 8541:
1.75 anton 8542: Here you want to pass the argument 1024 (e.g., a buffer size) to
8543: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8544: ), which allows its use with @code{require}. Of course with such
8545: parameters to required files, you have to ensure that the first
8546: @code{require} fits for all uses (i.e., @code{require} it early in the
8547: master load file).
1.44 crook 8548:
1.26 crook 8549: doc-include-file
8550: doc-included
1.28 crook 8551: doc-included?
1.26 crook 8552: doc-include
8553: doc-required
8554: doc-require
8555: doc-needs
1.75 anton 8556: @c doc-init-included-files @c internal
8557: doc-sourcefilename
8558: doc-sourceline#
1.44 crook 8559:
1.26 crook 8560: A definition in ANS Forth for @code{required} is provided in
8561: @file{compat/required.fs}.
1.21 crook 8562:
1.26 crook 8563: @c -------------------------------------------------------------
1.167 anton 8564: @node General files, Redirection, Forth source files, Files
1.26 crook 8565: @subsection General files
8566: @cindex general files
8567: @cindex file-handling
1.21 crook 8568:
1.75 anton 8569: Files are opened/created by name and type. The following file access
8570: methods (FAMs) are recognised:
1.44 crook 8571:
1.75 anton 8572: @cindex fam (file access method)
1.26 crook 8573: doc-r/o
8574: doc-r/w
8575: doc-w/o
8576: doc-bin
1.1 anton 8577:
1.44 crook 8578:
1.26 crook 8579: When a file is opened/created, it returns a file identifier,
1.29 crook 8580: @i{wfileid} that is used for all other file commands. All file
8581: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8582: successful operation and an implementation-defined non-zero value in the
8583: case of an error.
1.21 crook 8584:
1.44 crook 8585:
1.26 crook 8586: doc-open-file
8587: doc-create-file
1.21 crook 8588:
1.26 crook 8589: doc-close-file
8590: doc-delete-file
8591: doc-rename-file
8592: doc-read-file
8593: doc-read-line
1.154 anton 8594: doc-key-file
8595: doc-key?-file
1.26 crook 8596: doc-write-file
8597: doc-write-line
8598: doc-emit-file
8599: doc-flush-file
1.21 crook 8600:
1.26 crook 8601: doc-file-status
8602: doc-file-position
8603: doc-reposition-file
8604: doc-file-size
8605: doc-resize-file
1.21 crook 8606:
1.93 anton 8607: doc-slurp-file
8608: doc-slurp-fid
1.112 anton 8609: doc-stdin
8610: doc-stdout
8611: doc-stderr
1.44 crook 8612:
1.26 crook 8613: @c ---------------------------------------------------------
1.167 anton 8614: @node Redirection, Search Paths, General files, Files
8615: @subsection Redirection
8616: @cindex Redirection
8617: @cindex Input Redirection
8618: @cindex Output Redirection
8619:
8620: You can redirect the output of @code{type} and @code{emit} and all the
8621: words that use them (all output words that don't have an explicit
1.174 anton 8622: target file) to an arbitrary file with the @code{outfile-execute},
8623: used like this:
1.167 anton 8624:
8625: @example
1.174 anton 8626: : some-warning ( n -- )
8627: cr ." warning# " . ;
8628:
1.167 anton 8629: : print-some-warning ( n -- )
1.174 anton 8630: ['] some-warning stderr outfile-execute ;
1.167 anton 8631: @end example
8632:
1.174 anton 8633: After @code{some-warning} is executed, the original output direction
8634: is restored; this construct is safe against exceptions. Similarly,
8635: there is @code{infile-execute} for redirecting the input of @code{key}
8636: and its users (any input word that does not take a file explicitly).
8637:
8638: doc-outfile-execute
8639: doc-infile-execute
1.167 anton 8640:
8641: If you do not want to redirect the input or output to a file, you can
8642: also make use of the fact that @code{key}, @code{emit} and @code{type}
8643: are deferred words (@pxref{Deferred Words}). However, in that case
8644: you have to worry about the restoration and the protection against
8645: exceptions yourself; also, note that for redirecting the output in
8646: this way, you have to redirect both @code{emit} and @code{type}.
8647:
8648: @c ---------------------------------------------------------
8649: @node Search Paths, , Redirection, Files
1.26 crook 8650: @subsection Search Paths
8651: @cindex path for @code{included}
8652: @cindex file search path
8653: @cindex @code{include} search path
8654: @cindex search path for files
1.21 crook 8655:
1.26 crook 8656: If you specify an absolute filename (i.e., a filename starting with
8657: @file{/} or @file{~}, or with @file{:} in the second position (as in
8658: @samp{C:...})) for @code{included} and friends, that file is included
8659: just as you would expect.
1.21 crook 8660:
1.75 anton 8661: If the filename starts with @file{./}, this refers to the directory that
8662: the present file was @code{included} from. This allows files to include
8663: other files relative to their own position (irrespective of the current
8664: working directory or the absolute position). This feature is essential
8665: for libraries consisting of several files, where a file may include
8666: other files from the library. It corresponds to @code{#include "..."}
8667: in C. If the current input source is not a file, @file{.} refers to the
8668: directory of the innermost file being included, or, if there is no file
8669: being included, to the current working directory.
8670:
8671: For relative filenames (not starting with @file{./}), Gforth uses a
8672: search path similar to Forth's search order (@pxref{Word Lists}). It
8673: tries to find the given filename in the directories present in the path,
8674: and includes the first one it finds. There are separate search paths for
8675: Forth source files and general files. If the search path contains the
8676: directory @file{.}, this refers to the directory of the current file, or
8677: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8678:
1.26 crook 8679: Use @file{~+} to refer to the current working directory (as in the
8680: @code{bash}).
1.1 anton 8681:
1.75 anton 8682: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8683:
1.48 anton 8684: @menu
1.75 anton 8685: * Source Search Paths::
1.48 anton 8686: * General Search Paths::
8687: @end menu
8688:
1.26 crook 8689: @c ---------------------------------------------------------
1.75 anton 8690: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8691: @subsubsection Source Search Paths
8692: @cindex search path control, source files
1.5 anton 8693:
1.26 crook 8694: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8695: Gforth}). You can display it and change it using @code{fpath} in
8696: combination with the general path handling words.
1.5 anton 8697:
1.75 anton 8698: doc-fpath
8699: @c the functionality of the following words is easily available through
8700: @c fpath and the general path words. The may go away.
8701: @c doc-.fpath
8702: @c doc-fpath+
8703: @c doc-fpath=
8704: @c doc-open-fpath-file
1.44 crook 8705:
8706: @noindent
1.26 crook 8707: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8708:
1.26 crook 8709: @example
1.75 anton 8710: fpath path= /usr/lib/forth/|./
1.26 crook 8711: require timer.fs
8712: @end example
1.5 anton 8713:
1.75 anton 8714:
1.26 crook 8715: @c ---------------------------------------------------------
1.75 anton 8716: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8717: @subsubsection General Search Paths
1.75 anton 8718: @cindex search path control, source files
1.5 anton 8719:
1.26 crook 8720: Your application may need to search files in several directories, like
8721: @code{included} does. To facilitate this, Gforth allows you to define
8722: and use your own search paths, by providing generic equivalents of the
8723: Forth search path words:
1.5 anton 8724:
1.75 anton 8725: doc-open-path-file
8726: doc-path-allot
8727: doc-clear-path
8728: doc-also-path
1.26 crook 8729: doc-.path
8730: doc-path+
8731: doc-path=
1.5 anton 8732:
1.75 anton 8733: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8734:
1.75 anton 8735: Here's an example of creating an empty search path:
8736: @c
1.26 crook 8737: @example
1.75 anton 8738: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8739: @end example
1.5 anton 8740:
1.26 crook 8741: @c -------------------------------------------------------------
8742: @node Blocks, Other I/O, Files, Words
8743: @section Blocks
1.28 crook 8744: @cindex I/O - blocks
8745: @cindex blocks
8746:
8747: When you run Gforth on a modern desk-top computer, it runs under the
8748: control of an operating system which provides certain services. One of
8749: these services is @var{file services}, which allows Forth source code
8750: and data to be stored in files and read into Gforth (@pxref{Files}).
8751:
8752: Traditionally, Forth has been an important programming language on
8753: systems where it has interfaced directly to the underlying hardware with
8754: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8755: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8756:
8757: A block is a 1024-byte data area, which can be used to hold data or
8758: Forth source code. No structure is imposed on the contents of the
8759: block. A block is identified by its number; blocks are numbered
8760: contiguously from 1 to an implementation-defined maximum.
8761:
8762: A typical system that used blocks but no operating system might use a
8763: single floppy-disk drive for mass storage, with the disks formatted to
8764: provide 256-byte sectors. Blocks would be implemented by assigning the
8765: first four sectors of the disk to block 1, the second four sectors to
8766: block 2 and so on, up to the limit of the capacity of the disk. The disk
8767: would not contain any file system information, just the set of blocks.
8768:
1.29 crook 8769: @cindex blocks file
1.28 crook 8770: On systems that do provide file services, blocks are typically
1.29 crook 8771: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8772: file}. The size of the blocks file will be an exact multiple of 1024
8773: bytes, corresponding to the number of blocks it contains. This is the
8774: mechanism that Gforth uses.
8775:
1.29 crook 8776: @cindex @file{blocks.fb}
1.75 anton 8777: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8778: having specified a blocks file, Gforth defaults to the blocks file
8779: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8780: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8781:
1.29 crook 8782: @cindex block buffers
1.28 crook 8783: When you read and write blocks under program control, Gforth uses a
1.29 crook 8784: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8785: not used when you use @code{load} to interpret the contents of a block.
8786:
1.75 anton 8787: The behaviour of the block buffers is analagous to that of a cache.
8788: Each block buffer has three states:
1.28 crook 8789:
8790: @itemize @bullet
8791: @item
8792: Unassigned
8793: @item
8794: Assigned-clean
8795: @item
8796: Assigned-dirty
8797: @end itemize
8798:
1.29 crook 8799: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8800: block, the block (specified by its block number) must be assigned to a
8801: block buffer.
8802:
8803: The assignment of a block to a block buffer is performed by @code{block}
8804: or @code{buffer}. Use @code{block} when you wish to modify the existing
8805: contents of a block. Use @code{buffer} when you don't care about the
8806: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8807: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8808: with the particular block is already stored in a block buffer due to an
8809: earlier @code{block} command, @code{buffer} will return that block
8810: buffer and the existing contents of the block will be
8811: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8812: block buffer for the block.}.
1.28 crook 8813:
1.47 crook 8814: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8815: @code{buffer}, that block buffer becomes the @i{current block
8816: buffer}. Data may only be manipulated (read or written) within the
8817: current block buffer.
1.47 crook 8818:
8819: When the contents of the current block buffer has been modified it is
1.48 anton 8820: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8821: either abandon the changes (by doing nothing) or mark the block as
8822: changed (assigned-dirty), using @code{update}. Using @code{update} does
8823: not change the blocks file; it simply changes a block buffer's state to
8824: @i{assigned-dirty}. The block will be written implicitly when it's
8825: buffer is needed for another block, or explicitly by @code{flush} or
8826: @code{save-buffers}.
8827:
8828: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8829: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8830: @code{flush}.
1.28 crook 8831:
1.29 crook 8832: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8833: algorithm to assign a block buffer to a block. That means that any
8834: particular block can only be assigned to one specific block buffer,
1.29 crook 8835: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8836: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8837: the new block immediately. If it is @i{assigned-dirty} its current
8838: contents are written back to the blocks file on disk before it is
1.28 crook 8839: allocated to the new block.
8840:
8841: Although no structure is imposed on the contents of a block, it is
8842: traditional to display the contents as 16 lines each of 64 characters. A
8843: block provides a single, continuous stream of input (for example, it
8844: acts as a single parse area) -- there are no end-of-line characters
8845: within a block, and no end-of-file character at the end of a
8846: block. There are two consequences of this:
1.26 crook 8847:
1.28 crook 8848: @itemize @bullet
8849: @item
8850: The last character of one line wraps straight into the first character
8851: of the following line
8852: @item
8853: The word @code{\} -- comment to end of line -- requires special
8854: treatment; in the context of a block it causes all characters until the
8855: end of the current 64-character ``line'' to be ignored.
8856: @end itemize
8857:
8858: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8859: the current blocks file will be extended to the appropriate size and the
1.28 crook 8860: block buffer will be initialised with spaces.
8861:
1.47 crook 8862: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8863: for details) but doesn't encourage the use of blocks; the mechanism is
8864: only provided for backward compatibility -- ANS Forth requires blocks to
8865: be available when files are.
1.28 crook 8866:
8867: Common techniques that are used when working with blocks include:
8868:
8869: @itemize @bullet
8870: @item
8871: A screen editor that allows you to edit blocks without leaving the Forth
8872: environment.
8873: @item
8874: Shadow screens; where every code block has an associated block
8875: containing comments (for example: code in odd block numbers, comments in
8876: even block numbers). Typically, the block editor provides a convenient
8877: mechanism to toggle between code and comments.
8878: @item
8879: Load blocks; a single block (typically block 1) contains a number of
8880: @code{thru} commands which @code{load} the whole of the application.
8881: @end itemize
1.26 crook 8882:
1.29 crook 8883: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8884: integrated into a Forth programming environment.
1.26 crook 8885:
8886: @comment TODO what about errors on open-blocks?
1.44 crook 8887:
1.26 crook 8888: doc-open-blocks
8889: doc-use
1.75 anton 8890: doc-block-offset
1.26 crook 8891: doc-get-block-fid
8892: doc-block-position
1.28 crook 8893:
1.75 anton 8894: doc-list
1.28 crook 8895: doc-scr
8896:
1.184 anton 8897: doc-block
1.28 crook 8898: doc-buffer
8899:
1.75 anton 8900: doc-empty-buffers
8901: doc-empty-buffer
1.26 crook 8902: doc-update
1.28 crook 8903: doc-updated?
1.26 crook 8904: doc-save-buffers
1.75 anton 8905: doc-save-buffer
1.26 crook 8906: doc-flush
1.28 crook 8907:
1.26 crook 8908: doc-load
8909: doc-thru
8910: doc-+load
8911: doc-+thru
1.45 crook 8912: doc---gforthman--->
1.26 crook 8913: doc-block-included
8914:
1.44 crook 8915:
1.26 crook 8916: @c -------------------------------------------------------------
1.126 pazsan 8917: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8918: @section Other I/O
1.28 crook 8919: @cindex I/O - keyboard and display
1.26 crook 8920:
8921: @menu
8922: * Simple numeric output:: Predefined formats
8923: * Formatted numeric output:: Formatted (pictured) output
8924: * String Formats:: How Forth stores strings in memory
1.67 anton 8925: * Displaying characters and strings:: Other stuff
1.175 anton 8926: * Terminal output:: Cursor positioning etc.
1.181 anton 8927: * Single-key input::
8928: * Line input and conversion::
1.112 anton 8929: * Pipes:: How to create your own pipes
1.149 pazsan 8930: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8931: @end menu
8932:
8933: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8934: @subsection Simple numeric output
1.28 crook 8935: @cindex numeric output - simple/free-format
1.5 anton 8936:
1.26 crook 8937: The simplest output functions are those that display numbers from the
8938: data or floating-point stacks. Floating-point output is always displayed
8939: using base 10. Numbers displayed from the data stack use the value stored
8940: in @code{base}.
1.5 anton 8941:
1.44 crook 8942:
1.26 crook 8943: doc-.
8944: doc-dec.
8945: doc-hex.
8946: doc-u.
8947: doc-.r
8948: doc-u.r
8949: doc-d.
8950: doc-ud.
8951: doc-d.r
8952: doc-ud.r
8953: doc-f.
8954: doc-fe.
8955: doc-fs.
1.111 anton 8956: doc-f.rdp
1.44 crook 8957:
1.26 crook 8958: Examples of printing the number 1234.5678E23 in the different floating-point output
8959: formats are shown below:
1.5 anton 8960:
8961: @example
1.26 crook 8962: f. 123456779999999000000000000.
8963: fe. 123.456779999999E24
8964: fs. 1.23456779999999E26
1.5 anton 8965: @end example
8966:
8967:
1.26 crook 8968: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8969: @subsection Formatted numeric output
1.28 crook 8970: @cindex formatted numeric output
1.26 crook 8971: @cindex pictured numeric output
1.28 crook 8972: @cindex numeric output - formatted
1.26 crook 8973:
1.29 crook 8974: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8975: output} for formatted printing of integers. In this technique, digits
8976: are extracted from the number (using the current output radix defined by
8977: @code{base}), converted to ASCII codes and appended to a string that is
8978: built in a scratch-pad area of memory (@pxref{core-idef,
8979: Implementation-defined options, Implementation-defined
8980: options}). Arbitrary characters can be appended to the string during the
8981: extraction process. The completed string is specified by an address
8982: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8983: under program control.
1.5 anton 8984:
1.75 anton 8985: All of the integer output words described in the previous section
8986: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8987: numeric output.
1.5 anton 8988:
1.47 crook 8989: Three important things to remember about pictured numeric output:
1.5 anton 8990:
1.26 crook 8991: @itemize @bullet
8992: @item
1.28 crook 8993: It always operates on double-precision numbers; to display a
1.49 anton 8994: single-precision number, convert it first (for ways of doing this
8995: @pxref{Double precision}).
1.26 crook 8996: @item
1.28 crook 8997: It always treats the double-precision number as though it were
8998: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8999: @item
9000: The string is built up from right to left; least significant digit first.
9001: @end itemize
1.5 anton 9002:
1.44 crook 9003:
1.26 crook 9004: doc-<#
1.47 crook 9005: doc-<<#
1.26 crook 9006: doc-#
9007: doc-#s
9008: doc-hold
9009: doc-sign
9010: doc-#>
1.47 crook 9011: doc-#>>
1.5 anton 9012:
1.26 crook 9013: doc-represent
1.111 anton 9014: doc-f>str-rdp
9015: doc-f>buf-rdp
1.5 anton 9016:
1.44 crook 9017:
9018: @noindent
1.26 crook 9019: Here are some examples of using pictured numeric output:
1.5 anton 9020:
9021: @example
1.26 crook 9022: : my-u. ( u -- )
9023: \ Simplest use of pns.. behaves like Standard u.
9024: 0 \ convert to unsigned double
1.75 anton 9025: <<# \ start conversion
1.26 crook 9026: #s \ convert all digits
9027: #> \ complete conversion
1.75 anton 9028: TYPE SPACE \ display, with trailing space
9029: #>> ; \ release hold area
1.5 anton 9030:
1.26 crook 9031: : cents-only ( u -- )
9032: 0 \ convert to unsigned double
1.75 anton 9033: <<# \ start conversion
1.26 crook 9034: # # \ convert two least-significant digits
9035: #> \ complete conversion, discard other digits
1.75 anton 9036: TYPE SPACE \ display, with trailing space
9037: #>> ; \ release hold area
1.5 anton 9038:
1.26 crook 9039: : dollars-and-cents ( u -- )
9040: 0 \ convert to unsigned double
1.75 anton 9041: <<# \ start conversion
1.26 crook 9042: # # \ convert two least-significant digits
9043: [char] . hold \ insert decimal point
9044: #s \ convert remaining digits
9045: [char] $ hold \ append currency symbol
9046: #> \ complete conversion
1.75 anton 9047: TYPE SPACE \ display, with trailing space
9048: #>> ; \ release hold area
1.5 anton 9049:
1.26 crook 9050: : my-. ( n -- )
9051: \ handling negatives.. behaves like Standard .
9052: s>d \ convert to signed double
9053: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9054: <<# \ start conversion
1.26 crook 9055: #s \ convert all digits
9056: rot sign \ get at sign byte, append "-" if needed
9057: #> \ complete conversion
1.75 anton 9058: TYPE SPACE \ display, with trailing space
9059: #>> ; \ release hold area
1.5 anton 9060:
1.26 crook 9061: : account. ( n -- )
1.75 anton 9062: \ accountants don't like minus signs, they use parentheses
1.26 crook 9063: \ for negative numbers
9064: s>d \ convert to signed double
9065: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9066: <<# \ start conversion
1.26 crook 9067: 2 pick \ get copy of sign byte
9068: 0< IF [char] ) hold THEN \ right-most character of output
9069: #s \ convert all digits
9070: rot \ get at sign byte
9071: 0< IF [char] ( hold THEN
9072: #> \ complete conversion
1.75 anton 9073: TYPE SPACE \ display, with trailing space
9074: #>> ; \ release hold area
9075:
1.5 anton 9076: @end example
9077:
1.26 crook 9078: Here are some examples of using these words:
1.5 anton 9079:
9080: @example
1.26 crook 9081: 1 my-u. 1
9082: hex -1 my-u. decimal FFFFFFFF
9083: 1 cents-only 01
9084: 1234 cents-only 34
9085: 2 dollars-and-cents $0.02
9086: 1234 dollars-and-cents $12.34
9087: 123 my-. 123
9088: -123 my. -123
9089: 123 account. 123
9090: -456 account. (456)
1.5 anton 9091: @end example
9092:
9093:
1.26 crook 9094: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
9095: @subsection String Formats
1.27 crook 9096: @cindex strings - see character strings
9097: @cindex character strings - formats
1.28 crook 9098: @cindex I/O - see character strings
1.75 anton 9099: @cindex counted strings
9100:
9101: @c anton: this does not really belong here; maybe the memory section,
9102: @c or the principles chapter
1.26 crook 9103:
1.27 crook 9104: Forth commonly uses two different methods for representing character
9105: strings:
1.26 crook 9106:
9107: @itemize @bullet
9108: @item
9109: @cindex address of counted string
1.45 crook 9110: @cindex counted string
1.29 crook 9111: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9112: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9113: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9114: memory.
9115: @item
1.29 crook 9116: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9117: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9118: first byte of the string.
9119: @end itemize
9120:
9121: ANS Forth encourages the use of the second format when representing
1.75 anton 9122: strings.
1.26 crook 9123:
1.44 crook 9124:
1.26 crook 9125: doc-count
9126:
1.44 crook 9127:
1.49 anton 9128: For words that move, copy and search for strings see @ref{Memory
9129: Blocks}. For words that display characters and strings see
9130: @ref{Displaying characters and strings}.
1.26 crook 9131:
1.175 anton 9132: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9133: @subsection Displaying characters and strings
1.27 crook 9134: @cindex characters - compiling and displaying
9135: @cindex character strings - compiling and displaying
1.26 crook 9136:
9137: This section starts with a glossary of Forth words and ends with a set
9138: of examples.
9139:
9140: doc-bl
9141: doc-space
9142: doc-spaces
9143: doc-emit
9144: doc-toupper
9145: doc-."
9146: doc-.(
1.98 anton 9147: doc-.\"
1.26 crook 9148: doc-type
1.44 crook 9149: doc-typewhite
1.26 crook 9150: doc-cr
1.27 crook 9151: @cindex cursor control
1.26 crook 9152: doc-s"
1.98 anton 9153: doc-s\"
1.26 crook 9154: doc-c"
9155: doc-char
9156: doc-[char]
9157:
1.44 crook 9158:
9159: @noindent
1.26 crook 9160: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9161:
9162: @example
1.26 crook 9163: .( text-1)
9164: : my-word
9165: ." text-2" cr
9166: .( text-3)
9167: ;
9168:
9169: ." text-4"
9170:
9171: : my-char
9172: [char] ALPHABET emit
9173: char emit
9174: ;
1.5 anton 9175: @end example
9176:
1.26 crook 9177: When you load this code into Gforth, the following output is generated:
1.5 anton 9178:
1.26 crook 9179: @example
1.30 anton 9180: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9181: @end example
1.5 anton 9182:
1.26 crook 9183: @itemize @bullet
9184: @item
9185: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9186: is an immediate word; it behaves in the same way whether it is used inside
9187: or outside a colon definition.
9188: @item
9189: Message @code{text-4} is displayed because of Gforth's added interpretation
9190: semantics for @code{."}.
9191: @item
1.29 crook 9192: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9193: performs the compilation semantics for @code{."} within the definition of
9194: @code{my-word}.
9195: @end itemize
1.5 anton 9196:
1.26 crook 9197: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9198:
1.26 crook 9199: @example
1.30 anton 9200: @kbd{my-word @key{RET}} text-2
1.26 crook 9201: ok
1.30 anton 9202: @kbd{my-char fred @key{RET}} Af ok
9203: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9204: @end example
1.5 anton 9205:
9206: @itemize @bullet
9207: @item
1.26 crook 9208: Message @code{text-2} is displayed because of the run-time behaviour of
9209: @code{."}.
9210: @item
9211: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9212: on the stack at run-time. @code{emit} always displays the character
9213: when @code{my-char} is executed.
9214: @item
9215: @code{char} parses a string at run-time and the second @code{emit} displays
9216: the first character of the string.
1.5 anton 9217: @item
1.26 crook 9218: If you type @code{see my-char} you can see that @code{[char]} discarded
9219: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9220: definition of @code{my-char}.
1.5 anton 9221: @end itemize
9222:
9223:
1.181 anton 9224: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9225: @subsection Terminal output
9226: @cindex output to terminal
9227: @cindex terminal output
9228:
9229: If you are outputting to a terminal, you may want to control the
9230: positioning of the cursor:
9231: @cindex cursor positioning
9232:
9233: doc-at-xy
9234:
9235: In order to know where to position the cursor, it is often helpful to
9236: know the size of the screen:
9237: @cindex terminal size
9238:
9239: doc-form
9240:
9241: And sometimes you want to use:
9242: @cindex clear screen
9243:
9244: doc-page
9245:
9246: Note that on non-terminals you should use @code{12 emit}, not
9247: @code{page}, to get a form feed.
9248:
1.5 anton 9249:
1.181 anton 9250: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9251: @subsection Single-key input
9252: @cindex single-key input
9253: @cindex input, single-key
9254:
9255: If you want to get a single printable character, you can use
9256: @code{key}; to check whether a character is available for @code{key},
9257: you can use @code{key?}.
1.5 anton 9258:
1.181 anton 9259: doc-key
9260: doc-key?
1.27 crook 9261:
1.181 anton 9262: If you want to process a mix of printable and non-printable
9263: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9264: produces a keyboard event that you have to convert into a character
9265: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9266:
9267: Typical code for using EKEY looks like this:
9268:
9269: @example
9270: ekey ekey>char if ( c )
9271: ... \ do something with the character
9272: else ekey>fkey if ( key-id )
9273: case
9274: k-up of ... endof
9275: k-f1 of ... endof
9276: k-left k-shift-mask or k-ctrl-mask or of ... endof
9277: ...
9278: endcase
9279: else ( keyboard-event )
9280: drop \ just ignore an unknown keyboard event type
9281: then then
9282: @end example
1.44 crook 9283:
1.45 crook 9284: doc-ekey
1.141 anton 9285: doc-ekey>char
1.181 anton 9286: doc-ekey>fkey
1.45 crook 9287: doc-ekey?
1.141 anton 9288:
1.181 anton 9289: The key identifiers for cursor keys are:
1.141 anton 9290:
9291: doc-k-left
9292: doc-k-right
1.185 anton 9293: doc-k-up
9294: doc-k-down
9295: doc-k-home
9296: doc-k-end
1.141 anton 9297: doc-k-prior
9298: doc-k-next
9299: doc-k-insert
9300: doc-k-delete
9301:
1.181 anton 9302: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9303:
1.181 anton 9304: doc-k-f1
9305: doc-k-f2
9306: doc-k-f3
9307: doc-k-f4
9308: doc-k-f5
9309: doc-k-f6
9310: doc-k-f7
9311: doc-k-f8
9312: doc-k-f9
9313: doc-k-f10
9314: doc-k-f11
9315: doc-k-f12
9316:
9317: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9318:
9319: You can combine these key identifiers with masks for various shift keys:
9320:
9321: doc-k-shift-mask
9322: doc-k-ctrl-mask
9323: doc-k-alt-mask
9324:
9325: Note that, even if a Forth system has @code{ekey>fkey} and the key
9326: identifier words, the keys are not necessarily available or it may not
9327: necessarily be able to report all the keys and all the possible
9328: combinations with shift masks. Therefore, write your programs in such
9329: a way that they are still useful even if the keys and key combinations
9330: cannot be pressed or are not recognized.
9331:
9332: Examples: Older keyboards often do not have an F11 and F12 key. If
9333: you run Gforth in an xterm, the xterm catches a number of combinations
9334: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9335: Gforth currently does not recognize and report combinations with
9336: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9337: above would never be entered).
9338:
9339: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9340: you need the ANSI.SYS driver to get that behaviour); it works by
9341: recognizing the escape sequences that ANSI terminals send when such a
9342: key is pressed. If you have a terminal that sends other escape
9343: sequences, you will not get useful results on Gforth. Other Forth
9344: systems may work in a different way.
9345:
1.200 anton 9346: Gforth also provides a few words for outputting names of function
9347: keys:
9348:
9349: doc-fkey.
9350: doc-simple-fkey-string
9351:
1.181 anton 9352:
9353: @node Line input and conversion, Pipes, Single-key input, Other I/O
9354: @subsection Line input and conversion
9355: @cindex line input from terminal
9356: @cindex input, linewise from terminal
9357: @cindex convertin strings to numbers
9358: @cindex I/O - see input
9359:
9360: For ways of storing character strings in memory see @ref{String Formats}.
9361:
9362: @comment TODO examples for >number >float accept key key? pad parse word refill
9363: @comment then index them
1.141 anton 9364:
9365: Words for inputting one line from the keyboard:
9366:
9367: doc-accept
9368: doc-edit-line
9369:
9370: Conversion words:
9371:
1.143 anton 9372: doc-s>number?
9373: doc-s>unumber?
1.26 crook 9374: doc->number
9375: doc->float
1.143 anton 9376:
1.141 anton 9377:
1.27 crook 9378: @comment obsolescent words..
1.141 anton 9379: Obsolescent input and conversion words:
9380:
1.27 crook 9381: doc-convert
1.26 crook 9382: doc-expect
1.27 crook 9383: doc-span
1.5 anton 9384:
9385:
1.181 anton 9386: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9387: @subsection Pipes
9388: @cindex pipes, creating your own
9389:
9390: In addition to using Gforth in pipes created by other processes
9391: (@pxref{Gforth in pipes}), you can create your own pipe with
9392: @code{open-pipe}, and read from or write to it.
9393:
9394: doc-open-pipe
9395: doc-close-pipe
9396:
9397: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9398: you don't catch this exception, Gforth will catch it and exit, usually
9399: silently (@pxref{Gforth in pipes}). Since you probably do not want
9400: this, you should wrap a @code{catch} or @code{try} block around the code
9401: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9402: problem yourself, and then return to regular processing.
9403:
9404: doc-broken-pipe-error
9405:
1.155 anton 9406: @node Xchars and Unicode, , Pipes, Other I/O
9407: @subsection Xchars and Unicode
1.149 pazsan 9408:
1.188 pazsan 9409: ASCII is only appropriate for the English language. Most western
9410: languages however fit somewhat into the Forth frame, since a byte is
9411: sufficient to encode the few special characters in each (though not
9412: always the same encoding can be used; latin-1 is most widely used,
9413: though). For other languages, different char-sets have to be used,
9414: several of them variable-width. Most prominent representant is
9415: UTF-8. Let's call these extended characters xchars. The primitive
9416: fixed-size characters stored as bytes are called pchars in this
9417: section.
9418:
9419: The xchar words add a few data types:
9420:
9421: @itemize
9422:
9423: @item
9424: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9425: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9426: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9427: character set can be used.
9428:
9429: @item
9430: @var{xc-addr} is the address of an xchar in memory. Alignment
9431: requirements are the same as @var{c-addr}. The memory representation of an
9432: xchar differs from the stack representation, and depends on the
9433: encoding used. An xchar may use a variable number of pchars in memory.
9434:
9435: @item
9436: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9437: @var{xc-addr}, @var{u} pchars long.
9438:
9439: @end itemize
9440:
9441: doc-xc-size
9442: doc-x-size
9443: doc-xc@+
9444: doc-xc!+?
9445: doc-xchar+
9446: doc-xchar-
9447: doc-+x/string
9448: doc-x\string-
9449: doc--trailing-garbage
9450: doc-x-width
9451: doc-xkey
9452: doc-xemit
9453:
9454: There's a new environment query
9455:
9456: doc-xchar-encoding
1.112 anton 9457:
1.121 anton 9458: @node OS command line arguments, Locals, Other I/O, Words
9459: @section OS command line arguments
9460: @cindex OS command line arguments
9461: @cindex command line arguments, OS
9462: @cindex arguments, OS command line
9463:
9464: The usual way to pass arguments to Gforth programs on the command line
9465: is via the @option{-e} option, e.g.
9466:
9467: @example
9468: gforth -e "123 456" foo.fs -e bye
9469: @end example
9470:
9471: However, you may want to interpret the command-line arguments directly.
9472: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9473: through @code{next-arg}:
1.121 anton 9474:
1.123 anton 9475: doc-next-arg
1.121 anton 9476:
1.123 anton 9477: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9478:
9479: @example
9480: : echo ( -- )
1.122 anton 9481: begin
1.123 anton 9482: next-arg 2dup 0 0 d<> while
9483: type space
9484: repeat
9485: 2drop ;
1.121 anton 9486:
9487: echo cr bye
9488: @end example
9489:
9490: This can be invoked with
9491:
9492: @example
9493: gforth echo.fs hello world
9494: @end example
1.123 anton 9495:
9496: and it will print
9497:
9498: @example
9499: hello world
9500: @end example
9501:
9502: The next lower level of dealing with the OS command line are the
9503: following words:
9504:
9505: doc-arg
9506: doc-shift-args
9507:
9508: Finally, at the lowest level Gforth provides the following words:
9509:
9510: doc-argc
9511: doc-argv
1.121 anton 9512:
1.78 anton 9513: @c -------------------------------------------------------------
1.126 pazsan 9514: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9515: @section Locals
9516: @cindex locals
9517:
9518: Local variables can make Forth programming more enjoyable and Forth
9519: programs easier to read. Unfortunately, the locals of ANS Forth are
9520: laden with restrictions. Therefore, we provide not only the ANS Forth
9521: locals wordset, but also our own, more powerful locals wordset (we
9522: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9523:
1.78 anton 9524: The ideas in this section have also been published in M. Anton Ertl,
9525: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9526: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9527:
9528: @menu
1.78 anton 9529: * Gforth locals::
9530: * ANS Forth locals::
1.5 anton 9531: @end menu
9532:
1.78 anton 9533: @node Gforth locals, ANS Forth locals, Locals, Locals
9534: @subsection Gforth locals
9535: @cindex Gforth locals
9536: @cindex locals, Gforth style
1.5 anton 9537:
1.78 anton 9538: Locals can be defined with
1.44 crook 9539:
1.78 anton 9540: @example
9541: @{ local1 local2 ... -- comment @}
9542: @end example
9543: or
9544: @example
9545: @{ local1 local2 ... @}
9546: @end example
1.5 anton 9547:
1.78 anton 9548: E.g.,
9549: @example
9550: : max @{ n1 n2 -- n3 @}
9551: n1 n2 > if
9552: n1
9553: else
9554: n2
9555: endif ;
9556: @end example
1.44 crook 9557:
1.78 anton 9558: The similarity of locals definitions with stack comments is intended. A
9559: locals definition often replaces the stack comment of a word. The order
9560: of the locals corresponds to the order in a stack comment and everything
9561: after the @code{--} is really a comment.
1.77 anton 9562:
1.78 anton 9563: This similarity has one disadvantage: It is too easy to confuse locals
9564: declarations with stack comments, causing bugs and making them hard to
9565: find. However, this problem can be avoided by appropriate coding
9566: conventions: Do not use both notations in the same program. If you do,
9567: they should be distinguished using additional means, e.g. by position.
1.77 anton 9568:
1.78 anton 9569: @cindex types of locals
9570: @cindex locals types
9571: The name of the local may be preceded by a type specifier, e.g.,
9572: @code{F:} for a floating point value:
1.5 anton 9573:
1.78 anton 9574: @example
9575: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9576: \ complex multiplication
9577: Ar Br f* Ai Bi f* f-
9578: Ar Bi f* Ai Br f* f+ ;
9579: @end example
1.44 crook 9580:
1.78 anton 9581: @cindex flavours of locals
9582: @cindex locals flavours
9583: @cindex value-flavoured locals
9584: @cindex variable-flavoured locals
9585: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9586: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9587: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9588: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9589: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9590: produces its address (which becomes invalid when the variable's scope is
9591: left). E.g., the standard word @code{emit} can be defined in terms of
9592: @code{type} like this:
1.5 anton 9593:
1.78 anton 9594: @example
9595: : emit @{ C^ char* -- @}
9596: char* 1 type ;
9597: @end example
1.5 anton 9598:
1.78 anton 9599: @cindex default type of locals
9600: @cindex locals, default type
9601: A local without type specifier is a @code{W:} local. Both flavours of
9602: locals are initialized with values from the data or FP stack.
1.44 crook 9603:
1.78 anton 9604: Currently there is no way to define locals with user-defined data
9605: structures, but we are working on it.
1.5 anton 9606:
1.78 anton 9607: Gforth allows defining locals everywhere in a colon definition. This
9608: poses the following questions:
1.5 anton 9609:
1.78 anton 9610: @menu
9611: * Where are locals visible by name?::
9612: * How long do locals live?::
9613: * Locals programming style::
9614: * Locals implementation::
9615: @end menu
1.44 crook 9616:
1.78 anton 9617: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9618: @subsubsection Where are locals visible by name?
9619: @cindex locals visibility
9620: @cindex visibility of locals
9621: @cindex scope of locals
1.5 anton 9622:
1.78 anton 9623: Basically, the answer is that locals are visible where you would expect
9624: it in block-structured languages, and sometimes a little longer. If you
9625: want to restrict the scope of a local, enclose its definition in
9626: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9627:
9628:
1.78 anton 9629: doc-scope
9630: doc-endscope
1.5 anton 9631:
9632:
1.78 anton 9633: These words behave like control structure words, so you can use them
9634: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9635: arbitrary ways.
1.77 anton 9636:
1.78 anton 9637: If you want a more exact answer to the visibility question, here's the
9638: basic principle: A local is visible in all places that can only be
9639: reached through the definition of the local@footnote{In compiler
9640: construction terminology, all places dominated by the definition of the
9641: local.}. In other words, it is not visible in places that can be reached
9642: without going through the definition of the local. E.g., locals defined
9643: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9644: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9645: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9646:
1.78 anton 9647: The reasoning behind this solution is: We want to have the locals
9648: visible as long as it is meaningful. The user can always make the
9649: visibility shorter by using explicit scoping. In a place that can
9650: only be reached through the definition of a local, the meaning of a
9651: local name is clear. In other places it is not: How is the local
9652: initialized at the control flow path that does not contain the
9653: definition? Which local is meant, if the same name is defined twice in
9654: two independent control flow paths?
1.77 anton 9655:
1.78 anton 9656: This should be enough detail for nearly all users, so you can skip the
9657: rest of this section. If you really must know all the gory details and
9658: options, read on.
1.77 anton 9659:
1.78 anton 9660: In order to implement this rule, the compiler has to know which places
9661: are unreachable. It knows this automatically after @code{AHEAD},
9662: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9663: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9664: compiler that the control flow never reaches that place. If
9665: @code{UNREACHABLE} is not used where it could, the only consequence is
9666: that the visibility of some locals is more limited than the rule above
9667: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9668: lie to the compiler), buggy code will be produced.
1.77 anton 9669:
1.5 anton 9670:
1.78 anton 9671: doc-unreachable
1.5 anton 9672:
1.23 crook 9673:
1.78 anton 9674: Another problem with this rule is that at @code{BEGIN}, the compiler
9675: does not know which locals will be visible on the incoming
9676: back-edge. All problems discussed in the following are due to this
9677: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9678: loops as examples; the discussion also applies to @code{?DO} and other
9679: loops). Perhaps the most insidious example is:
1.26 crook 9680: @example
1.78 anton 9681: AHEAD
9682: BEGIN
9683: x
9684: [ 1 CS-ROLL ] THEN
9685: @{ x @}
9686: ...
9687: UNTIL
1.26 crook 9688: @end example
1.23 crook 9689:
1.78 anton 9690: This should be legal according to the visibility rule. The use of
9691: @code{x} can only be reached through the definition; but that appears
9692: textually below the use.
9693:
9694: From this example it is clear that the visibility rules cannot be fully
9695: implemented without major headaches. Our implementation treats common
9696: cases as advertised and the exceptions are treated in a safe way: The
9697: compiler makes a reasonable guess about the locals visible after a
9698: @code{BEGIN}; if it is too pessimistic, the
9699: user will get a spurious error about the local not being defined; if the
9700: compiler is too optimistic, it will notice this later and issue a
9701: warning. In the case above the compiler would complain about @code{x}
9702: being undefined at its use. You can see from the obscure examples in
9703: this section that it takes quite unusual control structures to get the
9704: compiler into trouble, and even then it will often do fine.
1.23 crook 9705:
1.78 anton 9706: If the @code{BEGIN} is reachable from above, the most optimistic guess
9707: is that all locals visible before the @code{BEGIN} will also be
9708: visible after the @code{BEGIN}. This guess is valid for all loops that
9709: are entered only through the @code{BEGIN}, in particular, for normal
9710: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9711: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9712: compiler. When the branch to the @code{BEGIN} is finally generated by
9713: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9714: warns the user if it was too optimistic:
1.26 crook 9715: @example
1.78 anton 9716: IF
9717: @{ x @}
9718: BEGIN
9719: \ x ?
9720: [ 1 cs-roll ] THEN
9721: ...
9722: UNTIL
1.26 crook 9723: @end example
1.23 crook 9724:
1.78 anton 9725: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9726: optimistically assumes that it lives until the @code{THEN}. It notices
9727: this difference when it compiles the @code{UNTIL} and issues a
9728: warning. The user can avoid the warning, and make sure that @code{x}
9729: is not used in the wrong area by using explicit scoping:
9730: @example
9731: IF
9732: SCOPE
9733: @{ x @}
9734: ENDSCOPE
9735: BEGIN
9736: [ 1 cs-roll ] THEN
9737: ...
9738: UNTIL
9739: @end example
1.23 crook 9740:
1.78 anton 9741: Since the guess is optimistic, there will be no spurious error messages
9742: about undefined locals.
1.44 crook 9743:
1.78 anton 9744: If the @code{BEGIN} is not reachable from above (e.g., after
9745: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9746: optimistic guess, as the locals visible after the @code{BEGIN} may be
9747: defined later. Therefore, the compiler assumes that no locals are
9748: visible after the @code{BEGIN}. However, the user can use
9749: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9750: visible at the BEGIN as at the point where the top control-flow stack
9751: item was created.
1.23 crook 9752:
1.44 crook 9753:
1.78 anton 9754: doc-assume-live
1.26 crook 9755:
1.23 crook 9756:
1.78 anton 9757: @noindent
9758: E.g.,
9759: @example
9760: @{ x @}
9761: AHEAD
9762: ASSUME-LIVE
9763: BEGIN
9764: x
9765: [ 1 CS-ROLL ] THEN
9766: ...
9767: UNTIL
9768: @end example
1.44 crook 9769:
1.78 anton 9770: Other cases where the locals are defined before the @code{BEGIN} can be
9771: handled by inserting an appropriate @code{CS-ROLL} before the
9772: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9773: behind the @code{ASSUME-LIVE}).
1.23 crook 9774:
1.78 anton 9775: Cases where locals are defined after the @code{BEGIN} (but should be
9776: visible immediately after the @code{BEGIN}) can only be handled by
9777: rearranging the loop. E.g., the ``most insidious'' example above can be
9778: arranged into:
9779: @example
9780: BEGIN
9781: @{ x @}
9782: ... 0=
9783: WHILE
9784: x
9785: REPEAT
9786: @end example
1.44 crook 9787:
1.78 anton 9788: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9789: @subsubsection How long do locals live?
9790: @cindex locals lifetime
9791: @cindex lifetime of locals
1.23 crook 9792:
1.78 anton 9793: The right answer for the lifetime question would be: A local lives at
9794: least as long as it can be accessed. For a value-flavoured local this
9795: means: until the end of its visibility. However, a variable-flavoured
9796: local could be accessed through its address far beyond its visibility
9797: scope. Ultimately, this would mean that such locals would have to be
9798: garbage collected. Since this entails un-Forth-like implementation
9799: complexities, I adopted the same cowardly solution as some other
9800: languages (e.g., C): The local lives only as long as it is visible;
9801: afterwards its address is invalid (and programs that access it
9802: afterwards are erroneous).
1.23 crook 9803:
1.78 anton 9804: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9805: @subsubsection Locals programming style
9806: @cindex locals programming style
9807: @cindex programming style, locals
1.23 crook 9808:
1.78 anton 9809: The freedom to define locals anywhere has the potential to change
9810: programming styles dramatically. In particular, the need to use the
9811: return stack for intermediate storage vanishes. Moreover, all stack
9812: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9813: determined arguments) can be eliminated: If the stack items are in the
9814: wrong order, just write a locals definition for all of them; then
9815: write the items in the order you want.
1.23 crook 9816:
1.78 anton 9817: This seems a little far-fetched and eliminating stack manipulations is
9818: unlikely to become a conscious programming objective. Still, the number
9819: of stack manipulations will be reduced dramatically if local variables
9820: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9821: a traditional implementation of @code{max}).
1.23 crook 9822:
1.78 anton 9823: This shows one potential benefit of locals: making Forth programs more
9824: readable. Of course, this benefit will only be realized if the
9825: programmers continue to honour the principle of factoring instead of
9826: using the added latitude to make the words longer.
1.23 crook 9827:
1.78 anton 9828: @cindex single-assignment style for locals
9829: Using @code{TO} can and should be avoided. Without @code{TO},
9830: every value-flavoured local has only a single assignment and many
9831: advantages of functional languages apply to Forth. I.e., programs are
9832: easier to analyse, to optimize and to read: It is clear from the
9833: definition what the local stands for, it does not turn into something
9834: different later.
1.23 crook 9835:
1.78 anton 9836: E.g., a definition using @code{TO} might look like this:
9837: @example
9838: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9839: u1 u2 min 0
9840: ?do
9841: addr1 c@@ addr2 c@@ -
9842: ?dup-if
9843: unloop exit
9844: then
9845: addr1 char+ TO addr1
9846: addr2 char+ TO addr2
9847: loop
9848: u1 u2 - ;
1.26 crook 9849: @end example
1.78 anton 9850: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9851: every loop iteration. @code{strcmp} is a typical example of the
9852: readability problems of using @code{TO}. When you start reading
9853: @code{strcmp}, you think that @code{addr1} refers to the start of the
9854: string. Only near the end of the loop you realize that it is something
9855: else.
1.23 crook 9856:
1.78 anton 9857: This can be avoided by defining two locals at the start of the loop that
9858: are initialized with the right value for the current iteration.
9859: @example
9860: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9861: addr1 addr2
9862: u1 u2 min 0
9863: ?do @{ s1 s2 @}
9864: s1 c@@ s2 c@@ -
9865: ?dup-if
9866: unloop exit
9867: then
9868: s1 char+ s2 char+
9869: loop
9870: 2drop
9871: u1 u2 - ;
9872: @end example
9873: Here it is clear from the start that @code{s1} has a different value
9874: in every loop iteration.
1.23 crook 9875:
1.78 anton 9876: @node Locals implementation, , Locals programming style, Gforth locals
9877: @subsubsection Locals implementation
9878: @cindex locals implementation
9879: @cindex implementation of locals
1.23 crook 9880:
1.78 anton 9881: @cindex locals stack
9882: Gforth uses an extra locals stack. The most compelling reason for
9883: this is that the return stack is not float-aligned; using an extra stack
9884: also eliminates the problems and restrictions of using the return stack
9885: as locals stack. Like the other stacks, the locals stack grows toward
9886: lower addresses. A few primitives allow an efficient implementation:
9887:
9888:
9889: doc-@local#
9890: doc-f@local#
9891: doc-laddr#
9892: doc-lp+!#
9893: doc-lp!
9894: doc->l
9895: doc-f>l
9896:
9897:
9898: In addition to these primitives, some specializations of these
9899: primitives for commonly occurring inline arguments are provided for
9900: efficiency reasons, e.g., @code{@@local0} as specialization of
9901: @code{@@local#} for the inline argument 0. The following compiling words
9902: compile the right specialized version, or the general version, as
9903: appropriate:
1.23 crook 9904:
1.5 anton 9905:
1.107 dvdkhlng 9906: @c doc-compile-@local
9907: @c doc-compile-f@local
1.78 anton 9908: doc-compile-lp+!
1.5 anton 9909:
9910:
1.78 anton 9911: Combinations of conditional branches and @code{lp+!#} like
9912: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9913: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9914:
1.78 anton 9915: A special area in the dictionary space is reserved for keeping the
9916: local variable names. @code{@{} switches the dictionary pointer to this
9917: area and @code{@}} switches it back and generates the locals
9918: initializing code. @code{W:} etc.@ are normal defining words. This
9919: special area is cleared at the start of every colon definition.
1.5 anton 9920:
1.78 anton 9921: @cindex word list for defining locals
9922: A special feature of Gforth's dictionary is used to implement the
9923: definition of locals without type specifiers: every word list (aka
9924: vocabulary) has its own methods for searching
9925: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9926: with a special search method: When it is searched for a word, it
9927: actually creates that word using @code{W:}. @code{@{} changes the search
9928: order to first search the word list containing @code{@}}, @code{W:} etc.,
9929: and then the word list for defining locals without type specifiers.
1.5 anton 9930:
1.78 anton 9931: The lifetime rules support a stack discipline within a colon
9932: definition: The lifetime of a local is either nested with other locals
9933: lifetimes or it does not overlap them.
1.23 crook 9934:
1.78 anton 9935: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9936: pointer manipulation is generated. Between control structure words
9937: locals definitions can push locals onto the locals stack. @code{AGAIN}
9938: is the simplest of the other three control flow words. It has to
9939: restore the locals stack depth of the corresponding @code{BEGIN}
9940: before branching. The code looks like this:
9941: @format
9942: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9943: @code{branch} <begin>
9944: @end format
1.26 crook 9945:
1.78 anton 9946: @code{UNTIL} is a little more complicated: If it branches back, it
9947: must adjust the stack just like @code{AGAIN}. But if it falls through,
9948: the locals stack must not be changed. The compiler generates the
9949: following code:
9950: @format
9951: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9952: @end format
9953: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9954:
1.78 anton 9955: @code{THEN} can produce somewhat inefficient code:
9956: @format
9957: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9958: <orig target>:
9959: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9960: @end format
9961: The second @code{lp+!#} adjusts the locals stack pointer from the
9962: level at the @i{orig} point to the level after the @code{THEN}. The
9963: first @code{lp+!#} adjusts the locals stack pointer from the current
9964: level to the level at the orig point, so the complete effect is an
9965: adjustment from the current level to the right level after the
9966: @code{THEN}.
1.26 crook 9967:
1.78 anton 9968: @cindex locals information on the control-flow stack
9969: @cindex control-flow stack items, locals information
9970: In a conventional Forth implementation a dest control-flow stack entry
9971: is just the target address and an orig entry is just the address to be
9972: patched. Our locals implementation adds a word list to every orig or dest
9973: item. It is the list of locals visible (or assumed visible) at the point
9974: described by the entry. Our implementation also adds a tag to identify
9975: the kind of entry, in particular to differentiate between live and dead
9976: (reachable and unreachable) orig entries.
1.26 crook 9977:
1.78 anton 9978: A few unusual operations have to be performed on locals word lists:
1.44 crook 9979:
1.5 anton 9980:
1.78 anton 9981: doc-common-list
9982: doc-sub-list?
9983: doc-list-size
1.52 anton 9984:
9985:
1.78 anton 9986: Several features of our locals word list implementation make these
9987: operations easy to implement: The locals word lists are organised as
9988: linked lists; the tails of these lists are shared, if the lists
9989: contain some of the same locals; and the address of a name is greater
9990: than the address of the names behind it in the list.
1.5 anton 9991:
1.78 anton 9992: Another important implementation detail is the variable
9993: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9994: determine if they can be reached directly or only through the branch
9995: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9996: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9997: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9998:
1.78 anton 9999: Counted loops are similar to other loops in most respects, but
10000: @code{LEAVE} requires special attention: It performs basically the same
10001: service as @code{AHEAD}, but it does not create a control-flow stack
10002: entry. Therefore the information has to be stored elsewhere;
10003: traditionally, the information was stored in the target fields of the
10004: branches created by the @code{LEAVE}s, by organizing these fields into a
10005: linked list. Unfortunately, this clever trick does not provide enough
10006: space for storing our extended control flow information. Therefore, we
10007: introduce another stack, the leave stack. It contains the control-flow
10008: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 10009:
1.78 anton 10010: Local names are kept until the end of the colon definition, even if
10011: they are no longer visible in any control-flow path. In a few cases
10012: this may lead to increased space needs for the locals name area, but
10013: usually less than reclaiming this space would cost in code size.
1.5 anton 10014:
1.44 crook 10015:
1.78 anton 10016: @node ANS Forth locals, , Gforth locals, Locals
10017: @subsection ANS Forth locals
10018: @cindex locals, ANS Forth style
1.5 anton 10019:
1.78 anton 10020: The ANS Forth locals wordset does not define a syntax for locals, but
10021: words that make it possible to define various syntaxes. One of the
10022: possible syntaxes is a subset of the syntax we used in the Gforth locals
10023: wordset, i.e.:
1.29 crook 10024:
10025: @example
1.78 anton 10026: @{ local1 local2 ... -- comment @}
10027: @end example
10028: @noindent
10029: or
10030: @example
10031: @{ local1 local2 ... @}
1.29 crook 10032: @end example
10033:
1.78 anton 10034: The order of the locals corresponds to the order in a stack comment. The
10035: restrictions are:
1.5 anton 10036:
1.78 anton 10037: @itemize @bullet
10038: @item
10039: Locals can only be cell-sized values (no type specifiers are allowed).
10040: @item
10041: Locals can be defined only outside control structures.
10042: @item
10043: Locals can interfere with explicit usage of the return stack. For the
10044: exact (and long) rules, see the standard. If you don't use return stack
10045: accessing words in a definition using locals, you will be all right. The
10046: purpose of this rule is to make locals implementation on the return
10047: stack easier.
10048: @item
10049: The whole definition must be in one line.
10050: @end itemize
1.5 anton 10051:
1.78 anton 10052: Locals defined in ANS Forth behave like @code{VALUE}s
10053: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10054: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 10055:
1.78 anton 10056: Since the syntax above is supported by Gforth directly, you need not do
10057: anything to use it. If you want to port a program using this syntax to
10058: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10059: syntax on the other system.
1.5 anton 10060:
1.78 anton 10061: Note that a syntax shown in the standard, section A.13 looks
10062: similar, but is quite different in having the order of locals
10063: reversed. Beware!
1.5 anton 10064:
1.78 anton 10065: The ANS Forth locals wordset itself consists of one word:
1.5 anton 10066:
1.78 anton 10067: doc-(local)
1.5 anton 10068:
1.78 anton 10069: The ANS Forth locals extension wordset defines a syntax using
10070: @code{locals|}, but it is so awful that we strongly recommend not to use
10071: it. We have implemented this syntax to make porting to Gforth easy, but
10072: do not document it here. The problem with this syntax is that the locals
10073: are defined in an order reversed with respect to the standard stack
10074: comment notation, making programs harder to read, and easier to misread
10075: and miswrite. The only merit of this syntax is that it is easy to
10076: implement using the ANS Forth locals wordset.
1.53 anton 10077:
10078:
1.78 anton 10079: @c ----------------------------------------------------------
10080: @node Structures, Object-oriented Forth, Locals, Words
10081: @section Structures
10082: @cindex structures
10083: @cindex records
1.53 anton 10084:
1.78 anton 10085: This section presents the structure package that comes with Gforth. A
10086: version of the package implemented in ANS Forth is available in
10087: @file{compat/struct.fs}. This package was inspired by a posting on
10088: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10089: possibly John Hayes). A version of this section has been published in
10090: M. Anton Ertl,
10091: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10092: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10093: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 10094:
1.78 anton 10095: @menu
10096: * Why explicit structure support?::
10097: * Structure Usage::
10098: * Structure Naming Convention::
10099: * Structure Implementation::
10100: * Structure Glossary::
1.183 anton 10101: * Forth200x Structures::
1.78 anton 10102: @end menu
1.55 anton 10103:
1.78 anton 10104: @node Why explicit structure support?, Structure Usage, Structures, Structures
10105: @subsection Why explicit structure support?
1.53 anton 10106:
1.78 anton 10107: @cindex address arithmetic for structures
10108: @cindex structures using address arithmetic
10109: If we want to use a structure containing several fields, we could simply
10110: reserve memory for it, and access the fields using address arithmetic
10111: (@pxref{Address arithmetic}). As an example, consider a structure with
10112: the following fields
1.57 anton 10113:
1.78 anton 10114: @table @code
10115: @item a
10116: is a float
10117: @item b
10118: is a cell
10119: @item c
10120: is a float
10121: @end table
1.57 anton 10122:
1.78 anton 10123: Given the (float-aligned) base address of the structure we get the
10124: address of the field
1.52 anton 10125:
1.78 anton 10126: @table @code
10127: @item a
10128: without doing anything further.
10129: @item b
10130: with @code{float+}
10131: @item c
10132: with @code{float+ cell+ faligned}
10133: @end table
1.52 anton 10134:
1.78 anton 10135: It is easy to see that this can become quite tiring.
1.52 anton 10136:
1.78 anton 10137: Moreover, it is not very readable, because seeing a
10138: @code{cell+} tells us neither which kind of structure is
10139: accessed nor what field is accessed; we have to somehow infer the kind
10140: of structure, and then look up in the documentation, which field of
10141: that structure corresponds to that offset.
1.53 anton 10142:
1.78 anton 10143: Finally, this kind of address arithmetic also causes maintenance
10144: troubles: If you add or delete a field somewhere in the middle of the
10145: structure, you have to find and change all computations for the fields
10146: afterwards.
1.52 anton 10147:
1.78 anton 10148: So, instead of using @code{cell+} and friends directly, how
10149: about storing the offsets in constants:
1.52 anton 10150:
1.78 anton 10151: @example
10152: 0 constant a-offset
10153: 0 float+ constant b-offset
10154: 0 float+ cell+ faligned c-offset
10155: @end example
1.64 pazsan 10156:
1.78 anton 10157: Now we can get the address of field @code{x} with @code{x-offset
10158: +}. This is much better in all respects. Of course, you still
10159: have to change all later offset definitions if you add a field. You can
10160: fix this by declaring the offsets in the following way:
1.57 anton 10161:
1.78 anton 10162: @example
10163: 0 constant a-offset
10164: a-offset float+ constant b-offset
10165: b-offset cell+ faligned constant c-offset
10166: @end example
1.57 anton 10167:
1.78 anton 10168: Since we always use the offsets with @code{+}, we could use a defining
10169: word @code{cfield} that includes the @code{+} in the action of the
10170: defined word:
1.64 pazsan 10171:
1.78 anton 10172: @example
10173: : cfield ( n "name" -- )
10174: create ,
10175: does> ( name execution: addr1 -- addr2 )
10176: @@ + ;
1.64 pazsan 10177:
1.78 anton 10178: 0 cfield a
10179: 0 a float+ cfield b
10180: 0 b cell+ faligned cfield c
10181: @end example
1.64 pazsan 10182:
1.78 anton 10183: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10184:
1.78 anton 10185: The structure field words now can be used quite nicely. However,
10186: their definition is still a bit cumbersome: We have to repeat the
10187: name, the information about size and alignment is distributed before
10188: and after the field definitions etc. The structure package presented
10189: here addresses these problems.
1.64 pazsan 10190:
1.78 anton 10191: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10192: @subsection Structure Usage
10193: @cindex structure usage
1.57 anton 10194:
1.78 anton 10195: @cindex @code{field} usage
10196: @cindex @code{struct} usage
10197: @cindex @code{end-struct} usage
10198: You can define a structure for a (data-less) linked list with:
1.57 anton 10199: @example
1.78 anton 10200: struct
10201: cell% field list-next
10202: end-struct list%
1.57 anton 10203: @end example
10204:
1.78 anton 10205: With the address of the list node on the stack, you can compute the
10206: address of the field that contains the address of the next node with
10207: @code{list-next}. E.g., you can determine the length of a list
10208: with:
1.57 anton 10209:
10210: @example
1.78 anton 10211: : list-length ( list -- n )
10212: \ "list" is a pointer to the first element of a linked list
10213: \ "n" is the length of the list
10214: 0 BEGIN ( list1 n1 )
10215: over
10216: WHILE ( list1 n1 )
10217: 1+ swap list-next @@ swap
10218: REPEAT
10219: nip ;
1.57 anton 10220: @end example
10221:
1.78 anton 10222: You can reserve memory for a list node in the dictionary with
10223: @code{list% %allot}, which leaves the address of the list node on the
10224: stack. For the equivalent allocation on the heap you can use @code{list%
10225: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10226: use @code{list% %allocate}). You can get the the size of a list
10227: node with @code{list% %size} and its alignment with @code{list%
10228: %alignment}.
10229:
10230: Note that in ANS Forth the body of a @code{create}d word is
10231: @code{aligned} but not necessarily @code{faligned};
10232: therefore, if you do a:
1.57 anton 10233:
10234: @example
1.78 anton 10235: create @emph{name} foo% %allot drop
1.57 anton 10236: @end example
10237:
1.78 anton 10238: @noindent
10239: then the memory alloted for @code{foo%} is guaranteed to start at the
10240: body of @code{@emph{name}} only if @code{foo%} contains only character,
10241: cell and double fields. Therefore, if your structure contains floats,
10242: better use
1.57 anton 10243:
10244: @example
1.78 anton 10245: foo% %allot constant @emph{name}
1.57 anton 10246: @end example
10247:
1.78 anton 10248: @cindex structures containing structures
10249: You can include a structure @code{foo%} as a field of
10250: another structure, like this:
1.65 anton 10251: @example
1.78 anton 10252: struct
10253: ...
10254: foo% field ...
10255: ...
10256: end-struct ...
1.65 anton 10257: @end example
1.52 anton 10258:
1.78 anton 10259: @cindex structure extension
10260: @cindex extended records
10261: Instead of starting with an empty structure, you can extend an
10262: existing structure. E.g., a plain linked list without data, as defined
10263: above, is hardly useful; You can extend it to a linked list of integers,
10264: like this:@footnote{This feature is also known as @emph{extended
10265: records}. It is the main innovation in the Oberon language; in other
10266: words, adding this feature to Modula-2 led Wirth to create a new
10267: language, write a new compiler etc. Adding this feature to Forth just
10268: required a few lines of code.}
1.52 anton 10269:
1.78 anton 10270: @example
10271: list%
10272: cell% field intlist-int
10273: end-struct intlist%
10274: @end example
1.55 anton 10275:
1.78 anton 10276: @code{intlist%} is a structure with two fields:
10277: @code{list-next} and @code{intlist-int}.
1.55 anton 10278:
1.78 anton 10279: @cindex structures containing arrays
10280: You can specify an array type containing @emph{n} elements of
10281: type @code{foo%} like this:
1.55 anton 10282:
10283: @example
1.78 anton 10284: foo% @emph{n} *
1.56 anton 10285: @end example
1.55 anton 10286:
1.78 anton 10287: You can use this array type in any place where you can use a normal
10288: type, e.g., when defining a @code{field}, or with
10289: @code{%allot}.
10290:
10291: @cindex first field optimization
10292: The first field is at the base address of a structure and the word for
10293: this field (e.g., @code{list-next}) actually does not change the address
10294: on the stack. You may be tempted to leave it away in the interest of
10295: run-time and space efficiency. This is not necessary, because the
10296: structure package optimizes this case: If you compile a first-field
10297: words, no code is generated. So, in the interest of readability and
10298: maintainability you should include the word for the field when accessing
10299: the field.
1.52 anton 10300:
10301:
1.78 anton 10302: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10303: @subsection Structure Naming Convention
10304: @cindex structure naming convention
1.52 anton 10305:
1.78 anton 10306: The field names that come to (my) mind are often quite generic, and,
10307: if used, would cause frequent name clashes. E.g., many structures
10308: probably contain a @code{counter} field. The structure names
10309: that come to (my) mind are often also the logical choice for the names
10310: of words that create such a structure.
1.52 anton 10311:
1.78 anton 10312: Therefore, I have adopted the following naming conventions:
1.52 anton 10313:
1.78 anton 10314: @itemize @bullet
10315: @cindex field naming convention
10316: @item
10317: The names of fields are of the form
10318: @code{@emph{struct}-@emph{field}}, where
10319: @code{@emph{struct}} is the basic name of the structure, and
10320: @code{@emph{field}} is the basic name of the field. You can
10321: think of field words as converting the (address of the)
10322: structure into the (address of the) field.
1.52 anton 10323:
1.78 anton 10324: @cindex structure naming convention
10325: @item
10326: The names of structures are of the form
10327: @code{@emph{struct}%}, where
10328: @code{@emph{struct}} is the basic name of the structure.
10329: @end itemize
1.52 anton 10330:
1.78 anton 10331: This naming convention does not work that well for fields of extended
10332: structures; e.g., the integer list structure has a field
10333: @code{intlist-int}, but has @code{list-next}, not
10334: @code{intlist-next}.
1.53 anton 10335:
1.78 anton 10336: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10337: @subsection Structure Implementation
10338: @cindex structure implementation
10339: @cindex implementation of structures
1.52 anton 10340:
1.78 anton 10341: The central idea in the implementation is to pass the data about the
10342: structure being built on the stack, not in some global
10343: variable. Everything else falls into place naturally once this design
10344: decision is made.
1.53 anton 10345:
1.78 anton 10346: The type description on the stack is of the form @emph{align
10347: size}. Keeping the size on the top-of-stack makes dealing with arrays
10348: very simple.
1.53 anton 10349:
1.78 anton 10350: @code{field} is a defining word that uses @code{Create}
10351: and @code{DOES>}. The body of the field contains the offset
10352: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10353:
10354: @example
1.78 anton 10355: @@ +
1.53 anton 10356: @end example
10357:
1.78 anton 10358: @noindent
10359: i.e., add the offset to the address, giving the stack effect
10360: @i{addr1 -- addr2} for a field.
10361:
10362: @cindex first field optimization, implementation
10363: This simple structure is slightly complicated by the optimization
10364: for fields with offset 0, which requires a different
10365: @code{DOES>}-part (because we cannot rely on there being
10366: something on the stack if such a field is invoked during
10367: compilation). Therefore, we put the different @code{DOES>}-parts
10368: in separate words, and decide which one to invoke based on the
10369: offset. For a zero offset, the field is basically a noop; it is
10370: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10371:
1.183 anton 10372: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10373: @subsection Structure Glossary
10374: @cindex structure glossary
1.53 anton 10375:
1.5 anton 10376:
1.78 anton 10377: doc-%align
10378: doc-%alignment
10379: doc-%alloc
10380: doc-%allocate
10381: doc-%allot
10382: doc-cell%
10383: doc-char%
10384: doc-dfloat%
10385: doc-double%
10386: doc-end-struct
10387: doc-field
10388: doc-float%
10389: doc-naligned
10390: doc-sfloat%
10391: doc-%size
10392: doc-struct
1.54 anton 10393:
10394:
1.183 anton 10395: @node Forth200x Structures, , Structure Glossary, Structures
10396: @subsection Forth200x Structures
10397: @cindex Structures in Forth200x
10398:
10399: The Forth 200x standard defines a slightly less convenient form of
10400: structures. In general (when using @code{field+}, you have to perform
10401: the alignment yourself, but there are a number of convenience words
10402: (e.g., @code{field:} that perform the alignment for you.
10403:
10404: A typical usage example is:
10405:
10406: @example
10407: 0
10408: field: s-a
10409: faligned 2 floats +field s-b
10410: constant s-struct
10411: @end example
10412:
10413: An alternative way of writing this structure is:
10414:
10415: @example
10416: begin-structure s-struct
10417: field: s-a
10418: faligned 2 floats +field s-b
10419: end-structure
10420: @end example
10421:
10422: doc-begin-structure
10423: doc-end-structure
10424: doc-+field
10425: doc-cfield:
10426: doc-field:
10427: doc-2field:
10428: doc-ffield:
10429: doc-sffield:
10430: doc-dffield:
10431:
1.26 crook 10432: @c -------------------------------------------------------------
1.78 anton 10433: @node Object-oriented Forth, Programming Tools, Structures, Words
10434: @section Object-oriented Forth
10435:
10436: Gforth comes with three packages for object-oriented programming:
10437: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10438: is preloaded, so you have to @code{include} them before use. The most
10439: important differences between these packages (and others) are discussed
10440: in @ref{Comparison with other object models}. All packages are written
10441: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10442:
1.78 anton 10443: @menu
10444: * Why object-oriented programming?::
10445: * Object-Oriented Terminology::
10446: * Objects::
10447: * OOF::
10448: * Mini-OOF::
10449: * Comparison with other object models::
10450: @end menu
1.5 anton 10451:
1.78 anton 10452: @c ----------------------------------------------------------------
10453: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10454: @subsection Why object-oriented programming?
10455: @cindex object-oriented programming motivation
10456: @cindex motivation for object-oriented programming
1.44 crook 10457:
1.78 anton 10458: Often we have to deal with several data structures (@emph{objects}),
10459: that have to be treated similarly in some respects, but differently in
10460: others. Graphical objects are the textbook example: circles, triangles,
10461: dinosaurs, icons, and others, and we may want to add more during program
10462: development. We want to apply some operations to any graphical object,
10463: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10464: has to do something different for every kind of object.
10465: @comment TODO add some other operations eg perimeter, area
10466: @comment and tie in to concrete examples later..
1.5 anton 10467:
1.78 anton 10468: We could implement @code{draw} as a big @code{CASE}
10469: control structure that executes the appropriate code depending on the
10470: kind of object to be drawn. This would be not be very elegant, and,
10471: moreover, we would have to change @code{draw} every time we add
10472: a new kind of graphical object (say, a spaceship).
1.44 crook 10473:
1.78 anton 10474: What we would rather do is: When defining spaceships, we would tell
10475: the system: ``Here's how you @code{draw} a spaceship; you figure
10476: out the rest''.
1.5 anton 10477:
1.78 anton 10478: This is the problem that all systems solve that (rightfully) call
10479: themselves object-oriented; the object-oriented packages presented here
10480: solve this problem (and not much else).
10481: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10482:
1.78 anton 10483: @c ------------------------------------------------------------------------
10484: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10485: @subsection Object-Oriented Terminology
10486: @cindex object-oriented terminology
10487: @cindex terminology for object-oriented programming
1.5 anton 10488:
1.78 anton 10489: This section is mainly for reference, so you don't have to understand
10490: all of it right away. The terminology is mainly Smalltalk-inspired. In
10491: short:
1.44 crook 10492:
1.78 anton 10493: @table @emph
10494: @cindex class
10495: @item class
10496: a data structure definition with some extras.
1.5 anton 10497:
1.78 anton 10498: @cindex object
10499: @item object
10500: an instance of the data structure described by the class definition.
1.5 anton 10501:
1.78 anton 10502: @cindex instance variables
10503: @item instance variables
10504: fields of the data structure.
1.5 anton 10505:
1.78 anton 10506: @cindex selector
10507: @cindex method selector
10508: @cindex virtual function
10509: @item selector
10510: (or @emph{method selector}) a word (e.g.,
10511: @code{draw}) that performs an operation on a variety of data
10512: structures (classes). A selector describes @emph{what} operation to
10513: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10514:
1.78 anton 10515: @cindex method
10516: @item method
10517: the concrete definition that performs the operation
10518: described by the selector for a specific class. A method specifies
10519: @emph{how} the operation is performed for a specific class.
1.5 anton 10520:
1.78 anton 10521: @cindex selector invocation
10522: @cindex message send
10523: @cindex invoking a selector
10524: @item selector invocation
10525: a call of a selector. One argument of the call (the TOS (top-of-stack))
10526: is used for determining which method is used. In Smalltalk terminology:
10527: a message (consisting of the selector and the other arguments) is sent
10528: to the object.
1.5 anton 10529:
1.78 anton 10530: @cindex receiving object
10531: @item receiving object
10532: the object used for determining the method executed by a selector
10533: invocation. In the @file{objects.fs} model, it is the object that is on
10534: the TOS when the selector is invoked. (@emph{Receiving} comes from
10535: the Smalltalk @emph{message} terminology.)
1.5 anton 10536:
1.78 anton 10537: @cindex child class
10538: @cindex parent class
10539: @cindex inheritance
10540: @item child class
10541: a class that has (@emph{inherits}) all properties (instance variables,
10542: selectors, methods) from a @emph{parent class}. In Smalltalk
10543: terminology: The subclass inherits from the superclass. In C++
10544: terminology: The derived class inherits from the base class.
1.5 anton 10545:
1.78 anton 10546: @end table
1.5 anton 10547:
1.78 anton 10548: @c If you wonder about the message sending terminology, it comes from
10549: @c a time when each object had it's own task and objects communicated via
10550: @c message passing; eventually the Smalltalk developers realized that
10551: @c they can do most things through simple (indirect) calls. They kept the
10552: @c terminology.
1.5 anton 10553:
1.78 anton 10554: @c --------------------------------------------------------------
10555: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10556: @subsection The @file{objects.fs} model
10557: @cindex objects
10558: @cindex object-oriented programming
1.26 crook 10559:
1.78 anton 10560: @cindex @file{objects.fs}
10561: @cindex @file{oof.fs}
1.26 crook 10562:
1.78 anton 10563: This section describes the @file{objects.fs} package. This material also
10564: has been published in M. Anton Ertl,
10565: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10566: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10567: 37--43.
10568: @c McKewan's and Zsoter's packages
1.26 crook 10569:
1.78 anton 10570: This section assumes that you have read @ref{Structures}.
1.5 anton 10571:
1.78 anton 10572: The techniques on which this model is based have been used to implement
10573: the parser generator, Gray, and have also been used in Gforth for
10574: implementing the various flavours of word lists (hashed or not,
10575: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10576:
10577:
1.26 crook 10578: @menu
1.78 anton 10579: * Properties of the Objects model::
10580: * Basic Objects Usage::
10581: * The Objects base class::
10582: * Creating objects::
10583: * Object-Oriented Programming Style::
10584: * Class Binding::
10585: * Method conveniences::
10586: * Classes and Scoping::
10587: * Dividing classes::
10588: * Object Interfaces::
10589: * Objects Implementation::
10590: * Objects Glossary::
1.26 crook 10591: @end menu
1.5 anton 10592:
1.78 anton 10593: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10594:
1.78 anton 10595: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10596: @subsubsection Properties of the @file{objects.fs} model
10597: @cindex @file{objects.fs} properties
1.5 anton 10598:
1.78 anton 10599: @itemize @bullet
10600: @item
10601: It is straightforward to pass objects on the stack. Passing
10602: selectors on the stack is a little less convenient, but possible.
1.44 crook 10603:
1.78 anton 10604: @item
10605: Objects are just data structures in memory, and are referenced by their
10606: address. You can create words for objects with normal defining words
10607: like @code{constant}. Likewise, there is no difference between instance
10608: variables that contain objects and those that contain other data.
1.5 anton 10609:
1.78 anton 10610: @item
10611: Late binding is efficient and easy to use.
1.44 crook 10612:
1.78 anton 10613: @item
10614: It avoids parsing, and thus avoids problems with state-smartness
10615: and reduced extensibility; for convenience there are a few parsing
10616: words, but they have non-parsing counterparts. There are also a few
10617: defining words that parse. This is hard to avoid, because all standard
10618: defining words parse (except @code{:noname}); however, such
10619: words are not as bad as many other parsing words, because they are not
10620: state-smart.
1.5 anton 10621:
1.78 anton 10622: @item
10623: It does not try to incorporate everything. It does a few things and does
10624: them well (IMO). In particular, this model was not designed to support
10625: information hiding (although it has features that may help); you can use
10626: a separate package for achieving this.
1.5 anton 10627:
1.78 anton 10628: @item
10629: It is layered; you don't have to learn and use all features to use this
10630: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10631: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10632: are optional and independent of each other.
1.5 anton 10633:
1.78 anton 10634: @item
10635: An implementation in ANS Forth is available.
1.5 anton 10636:
1.78 anton 10637: @end itemize
1.5 anton 10638:
1.44 crook 10639:
1.78 anton 10640: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10641: @subsubsection Basic @file{objects.fs} Usage
10642: @cindex basic objects usage
10643: @cindex objects, basic usage
1.5 anton 10644:
1.78 anton 10645: You can define a class for graphical objects like this:
1.44 crook 10646:
1.78 anton 10647: @cindex @code{class} usage
10648: @cindex @code{end-class} usage
10649: @cindex @code{selector} usage
1.5 anton 10650: @example
1.78 anton 10651: object class \ "object" is the parent class
10652: selector draw ( x y graphical -- )
10653: end-class graphical
10654: @end example
10655:
10656: This code defines a class @code{graphical} with an
10657: operation @code{draw}. We can perform the operation
10658: @code{draw} on any @code{graphical} object, e.g.:
10659:
10660: @example
10661: 100 100 t-rex draw
1.26 crook 10662: @end example
1.5 anton 10663:
1.78 anton 10664: @noindent
10665: where @code{t-rex} is a word (say, a constant) that produces a
10666: graphical object.
10667:
10668: @comment TODO add a 2nd operation eg perimeter.. and use for
10669: @comment a concrete example
1.5 anton 10670:
1.78 anton 10671: @cindex abstract class
10672: How do we create a graphical object? With the present definitions,
10673: we cannot create a useful graphical object. The class
10674: @code{graphical} describes graphical objects in general, but not
10675: any concrete graphical object type (C++ users would call it an
10676: @emph{abstract class}); e.g., there is no method for the selector
10677: @code{draw} in the class @code{graphical}.
1.5 anton 10678:
1.78 anton 10679: For concrete graphical objects, we define child classes of the
10680: class @code{graphical}, e.g.:
1.5 anton 10681:
1.78 anton 10682: @cindex @code{overrides} usage
10683: @cindex @code{field} usage in class definition
1.26 crook 10684: @example
1.78 anton 10685: graphical class \ "graphical" is the parent class
10686: cell% field circle-radius
1.5 anton 10687:
1.78 anton 10688: :noname ( x y circle -- )
10689: circle-radius @@ draw-circle ;
10690: overrides draw
1.5 anton 10691:
1.78 anton 10692: :noname ( n-radius circle -- )
10693: circle-radius ! ;
10694: overrides construct
1.5 anton 10695:
1.78 anton 10696: end-class circle
10697: @end example
1.44 crook 10698:
1.78 anton 10699: Here we define a class @code{circle} as a child of @code{graphical},
10700: with field @code{circle-radius} (which behaves just like a field
10701: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10702: for the selectors @code{draw} and @code{construct} (@code{construct} is
10703: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10704:
1.78 anton 10705: Now we can create a circle on the heap (i.e.,
10706: @code{allocate}d memory) with:
1.44 crook 10707:
1.78 anton 10708: @cindex @code{heap-new} usage
1.5 anton 10709: @example
1.78 anton 10710: 50 circle heap-new constant my-circle
1.5 anton 10711: @end example
10712:
1.78 anton 10713: @noindent
10714: @code{heap-new} invokes @code{construct}, thus
10715: initializing the field @code{circle-radius} with 50. We can draw
10716: this new circle at (100,100) with:
1.5 anton 10717:
10718: @example
1.78 anton 10719: 100 100 my-circle draw
1.5 anton 10720: @end example
10721:
1.78 anton 10722: @cindex selector invocation, restrictions
10723: @cindex class definition, restrictions
10724: Note: You can only invoke a selector if the object on the TOS
10725: (the receiving object) belongs to the class where the selector was
10726: defined or one of its descendents; e.g., you can invoke
10727: @code{draw} only for objects belonging to @code{graphical}
10728: or its descendents (e.g., @code{circle}). Immediately before
10729: @code{end-class}, the search order has to be the same as
10730: immediately after @code{class}.
10731:
10732: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10733: @subsubsection The @file{object.fs} base class
10734: @cindex @code{object} class
10735:
10736: When you define a class, you have to specify a parent class. So how do
10737: you start defining classes? There is one class available from the start:
10738: @code{object}. It is ancestor for all classes and so is the
10739: only class that has no parent. It has two selectors: @code{construct}
10740: and @code{print}.
10741:
10742: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10743: @subsubsection Creating objects
10744: @cindex creating objects
10745: @cindex object creation
10746: @cindex object allocation options
10747:
10748: @cindex @code{heap-new} discussion
10749: @cindex @code{dict-new} discussion
10750: @cindex @code{construct} discussion
10751: You can create and initialize an object of a class on the heap with
10752: @code{heap-new} ( ... class -- object ) and in the dictionary
10753: (allocation with @code{allot}) with @code{dict-new} (
10754: ... class -- object ). Both words invoke @code{construct}, which
10755: consumes the stack items indicated by "..." above.
10756:
10757: @cindex @code{init-object} discussion
10758: @cindex @code{class-inst-size} discussion
10759: If you want to allocate memory for an object yourself, you can get its
10760: alignment and size with @code{class-inst-size 2@@} ( class --
10761: align size ). Once you have memory for an object, you can initialize
10762: it with @code{init-object} ( ... class object -- );
10763: @code{construct} does only a part of the necessary work.
10764:
10765: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10766: @subsubsection Object-Oriented Programming Style
10767: @cindex object-oriented programming style
10768: @cindex programming style, object-oriented
1.5 anton 10769:
1.78 anton 10770: This section is not exhaustive.
1.5 anton 10771:
1.78 anton 10772: @cindex stack effects of selectors
10773: @cindex selectors and stack effects
10774: In general, it is a good idea to ensure that all methods for the
10775: same selector have the same stack effect: when you invoke a selector,
10776: you often have no idea which method will be invoked, so, unless all
10777: methods have the same stack effect, you will not know the stack effect
10778: of the selector invocation.
1.5 anton 10779:
1.78 anton 10780: One exception to this rule is methods for the selector
10781: @code{construct}. We know which method is invoked, because we
10782: specify the class to be constructed at the same place. Actually, I
10783: defined @code{construct} as a selector only to give the users a
10784: convenient way to specify initialization. The way it is used, a
10785: mechanism different from selector invocation would be more natural
10786: (but probably would take more code and more space to explain).
1.5 anton 10787:
1.78 anton 10788: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10789: @subsubsection Class Binding
10790: @cindex class binding
10791: @cindex early binding
1.5 anton 10792:
1.78 anton 10793: @cindex late binding
10794: Normal selector invocations determine the method at run-time depending
10795: on the class of the receiving object. This run-time selection is called
10796: @i{late binding}.
1.5 anton 10797:
1.78 anton 10798: Sometimes it's preferable to invoke a different method. For example,
10799: you might want to use the simple method for @code{print}ing
10800: @code{object}s instead of the possibly long-winded @code{print} method
10801: of the receiver class. You can achieve this by replacing the invocation
10802: of @code{print} with:
1.5 anton 10803:
1.78 anton 10804: @cindex @code{[bind]} usage
1.5 anton 10805: @example
1.78 anton 10806: [bind] object print
1.5 anton 10807: @end example
10808:
1.78 anton 10809: @noindent
10810: in compiled code or:
10811:
10812: @cindex @code{bind} usage
1.5 anton 10813: @example
1.78 anton 10814: bind object print
1.5 anton 10815: @end example
10816:
1.78 anton 10817: @cindex class binding, alternative to
10818: @noindent
10819: in interpreted code. Alternatively, you can define the method with a
10820: name (e.g., @code{print-object}), and then invoke it through the
10821: name. Class binding is just a (often more convenient) way to achieve
10822: the same effect; it avoids name clutter and allows you to invoke
10823: methods directly without naming them first.
1.5 anton 10824:
1.78 anton 10825: @cindex superclass binding
10826: @cindex parent class binding
10827: A frequent use of class binding is this: When we define a method
10828: for a selector, we often want the method to do what the selector does
10829: in the parent class, and a little more. There is a special word for
10830: this purpose: @code{[parent]}; @code{[parent]
10831: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10832: selector}}, where @code{@emph{parent}} is the parent
10833: class of the current class. E.g., a method definition might look like:
1.44 crook 10834:
1.78 anton 10835: @cindex @code{[parent]} usage
10836: @example
10837: :noname
10838: dup [parent] foo \ do parent's foo on the receiving object
10839: ... \ do some more
10840: ; overrides foo
10841: @end example
1.6 pazsan 10842:
1.78 anton 10843: @cindex class binding as optimization
10844: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10845: March 1997), Andrew McKewan presents class binding as an optimization
10846: technique. I recommend not using it for this purpose unless you are in
10847: an emergency. Late binding is pretty fast with this model anyway, so the
10848: benefit of using class binding is small; the cost of using class binding
10849: where it is not appropriate is reduced maintainability.
1.44 crook 10850:
1.78 anton 10851: While we are at programming style questions: You should bind
10852: selectors only to ancestor classes of the receiving object. E.g., say,
10853: you know that the receiving object is of class @code{foo} or its
10854: descendents; then you should bind only to @code{foo} and its
10855: ancestors.
1.12 anton 10856:
1.78 anton 10857: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10858: @subsubsection Method conveniences
10859: @cindex method conveniences
1.44 crook 10860:
1.78 anton 10861: In a method you usually access the receiving object pretty often. If
10862: you define the method as a plain colon definition (e.g., with
10863: @code{:noname}), you may have to do a lot of stack
10864: gymnastics. To avoid this, you can define the method with @code{m:
10865: ... ;m}. E.g., you could define the method for
10866: @code{draw}ing a @code{circle} with
1.6 pazsan 10867:
1.78 anton 10868: @cindex @code{this} usage
10869: @cindex @code{m:} usage
10870: @cindex @code{;m} usage
10871: @example
10872: m: ( x y circle -- )
10873: ( x y ) this circle-radius @@ draw-circle ;m
10874: @end example
1.6 pazsan 10875:
1.78 anton 10876: @cindex @code{exit} in @code{m: ... ;m}
10877: @cindex @code{exitm} discussion
10878: @cindex @code{catch} in @code{m: ... ;m}
10879: When this method is executed, the receiver object is removed from the
10880: stack; you can access it with @code{this} (admittedly, in this
10881: example the use of @code{m: ... ;m} offers no advantage). Note
10882: that I specify the stack effect for the whole method (i.e. including
10883: the receiver object), not just for the code between @code{m:}
10884: and @code{;m}. You cannot use @code{exit} in
10885: @code{m:...;m}; instead, use
10886: @code{exitm}.@footnote{Moreover, for any word that calls
10887: @code{catch} and was defined before loading
10888: @code{objects.fs}, you have to redefine it like I redefined
10889: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10890:
1.78 anton 10891: @cindex @code{inst-var} usage
10892: You will frequently use sequences of the form @code{this
10893: @emph{field}} (in the example above: @code{this
10894: circle-radius}). If you use the field only in this way, you can
10895: define it with @code{inst-var} and eliminate the
10896: @code{this} before the field name. E.g., the @code{circle}
10897: class above could also be defined with:
1.6 pazsan 10898:
1.78 anton 10899: @example
10900: graphical class
10901: cell% inst-var radius
1.6 pazsan 10902:
1.78 anton 10903: m: ( x y circle -- )
10904: radius @@ draw-circle ;m
10905: overrides draw
1.6 pazsan 10906:
1.78 anton 10907: m: ( n-radius circle -- )
10908: radius ! ;m
10909: overrides construct
1.6 pazsan 10910:
1.78 anton 10911: end-class circle
10912: @end example
1.6 pazsan 10913:
1.78 anton 10914: @code{radius} can only be used in @code{circle} and its
10915: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10916:
1.78 anton 10917: @cindex @code{inst-value} usage
10918: You can also define fields with @code{inst-value}, which is
10919: to @code{inst-var} what @code{value} is to
10920: @code{variable}. You can change the value of such a field with
10921: @code{[to-inst]}. E.g., we could also define the class
10922: @code{circle} like this:
1.44 crook 10923:
1.78 anton 10924: @example
10925: graphical class
10926: inst-value radius
1.6 pazsan 10927:
1.78 anton 10928: m: ( x y circle -- )
10929: radius draw-circle ;m
10930: overrides draw
1.44 crook 10931:
1.78 anton 10932: m: ( n-radius circle -- )
10933: [to-inst] radius ;m
10934: overrides construct
1.6 pazsan 10935:
1.78 anton 10936: end-class circle
10937: @end example
1.6 pazsan 10938:
1.78 anton 10939: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10940:
1.78 anton 10941: @c Finally, you can define named methods with @code{:m}. One use of this
10942: @c feature is the definition of words that occur only in one class and are
10943: @c not intended to be overridden, but which still need method context
10944: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10945: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10946:
10947:
1.78 anton 10948: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10949: @subsubsection Classes and Scoping
10950: @cindex classes and scoping
10951: @cindex scoping and classes
1.6 pazsan 10952:
1.78 anton 10953: Inheritance is frequent, unlike structure extension. This exacerbates
10954: the problem with the field name convention (@pxref{Structure Naming
10955: Convention}): One always has to remember in which class the field was
10956: originally defined; changing a part of the class structure would require
10957: changes for renaming in otherwise unaffected code.
1.6 pazsan 10958:
1.78 anton 10959: @cindex @code{inst-var} visibility
10960: @cindex @code{inst-value} visibility
10961: To solve this problem, I added a scoping mechanism (which was not in my
10962: original charter): A field defined with @code{inst-var} (or
10963: @code{inst-value}) is visible only in the class where it is defined and in
10964: the descendent classes of this class. Using such fields only makes
10965: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10966:
1.78 anton 10967: This scoping mechanism allows us to use the unadorned field name,
10968: because name clashes with unrelated words become much less likely.
1.6 pazsan 10969:
1.78 anton 10970: @cindex @code{protected} discussion
10971: @cindex @code{private} discussion
10972: Once we have this mechanism, we can also use it for controlling the
10973: visibility of other words: All words defined after
10974: @code{protected} are visible only in the current class and its
10975: descendents. @code{public} restores the compilation
10976: (i.e. @code{current}) word list that was in effect before. If you
10977: have several @code{protected}s without an intervening
10978: @code{public} or @code{set-current}, @code{public}
10979: will restore the compilation word list in effect before the first of
10980: these @code{protected}s.
1.6 pazsan 10981:
1.78 anton 10982: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10983: @subsubsection Dividing classes
10984: @cindex Dividing classes
10985: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10986:
1.78 anton 10987: You may want to do the definition of methods separate from the
10988: definition of the class, its selectors, fields, and instance variables,
10989: i.e., separate the implementation from the definition. You can do this
10990: in the following way:
1.6 pazsan 10991:
1.78 anton 10992: @example
10993: graphical class
10994: inst-value radius
10995: end-class circle
1.6 pazsan 10996:
1.78 anton 10997: ... \ do some other stuff
1.6 pazsan 10998:
1.78 anton 10999: circle methods \ now we are ready
1.44 crook 11000:
1.78 anton 11001: m: ( x y circle -- )
11002: radius draw-circle ;m
11003: overrides draw
1.6 pazsan 11004:
1.78 anton 11005: m: ( n-radius circle -- )
11006: [to-inst] radius ;m
11007: overrides construct
1.44 crook 11008:
1.78 anton 11009: end-methods
11010: @end example
1.7 pazsan 11011:
1.78 anton 11012: You can use several @code{methods}...@code{end-methods} sections. The
11013: only things you can do to the class in these sections are: defining
11014: methods, and overriding the class's selectors. You must not define new
11015: selectors or fields.
1.7 pazsan 11016:
1.78 anton 11017: Note that you often have to override a selector before using it. In
11018: particular, you usually have to override @code{construct} with a new
11019: method before you can invoke @code{heap-new} and friends. E.g., you
11020: must not create a circle before the @code{overrides construct} sequence
11021: in the example above.
1.7 pazsan 11022:
1.78 anton 11023: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
11024: @subsubsection Object Interfaces
11025: @cindex object interfaces
11026: @cindex interfaces for objects
1.7 pazsan 11027:
1.78 anton 11028: In this model you can only call selectors defined in the class of the
11029: receiving objects or in one of its ancestors. If you call a selector
11030: with a receiving object that is not in one of these classes, the
11031: result is undefined; if you are lucky, the program crashes
11032: immediately.
1.7 pazsan 11033:
1.78 anton 11034: @cindex selectors common to hardly-related classes
11035: Now consider the case when you want to have a selector (or several)
11036: available in two classes: You would have to add the selector to a
11037: common ancestor class, in the worst case to @code{object}. You
11038: may not want to do this, e.g., because someone else is responsible for
11039: this ancestor class.
1.7 pazsan 11040:
1.78 anton 11041: The solution for this problem is interfaces. An interface is a
11042: collection of selectors. If a class implements an interface, the
11043: selectors become available to the class and its descendents. A class
11044: can implement an unlimited number of interfaces. For the problem
11045: discussed above, we would define an interface for the selector(s), and
11046: both classes would implement the interface.
1.7 pazsan 11047:
1.78 anton 11048: As an example, consider an interface @code{storage} for
11049: writing objects to disk and getting them back, and a class
11050: @code{foo} that implements it. The code would look like this:
1.7 pazsan 11051:
1.78 anton 11052: @cindex @code{interface} usage
11053: @cindex @code{end-interface} usage
11054: @cindex @code{implementation} usage
11055: @example
11056: interface
11057: selector write ( file object -- )
11058: selector read1 ( file object -- )
11059: end-interface storage
1.13 pazsan 11060:
1.78 anton 11061: bar class
11062: storage implementation
1.13 pazsan 11063:
1.78 anton 11064: ... overrides write
11065: ... overrides read1
11066: ...
11067: end-class foo
11068: @end example
1.13 pazsan 11069:
1.78 anton 11070: @noindent
11071: (I would add a word @code{read} @i{( file -- object )} that uses
11072: @code{read1} internally, but that's beyond the point illustrated
11073: here.)
1.13 pazsan 11074:
1.78 anton 11075: Note that you cannot use @code{protected} in an interface; and
11076: of course you cannot define fields.
1.13 pazsan 11077:
1.78 anton 11078: In the Neon model, all selectors are available for all classes;
11079: therefore it does not need interfaces. The price you pay in this model
11080: is slower late binding, and therefore, added complexity to avoid late
11081: binding.
1.13 pazsan 11082:
1.78 anton 11083: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11084: @subsubsection @file{objects.fs} Implementation
11085: @cindex @file{objects.fs} implementation
1.13 pazsan 11086:
1.78 anton 11087: @cindex @code{object-map} discussion
11088: An object is a piece of memory, like one of the data structures
11089: described with @code{struct...end-struct}. It has a field
11090: @code{object-map} that points to the method map for the object's
11091: class.
1.13 pazsan 11092:
1.78 anton 11093: @cindex method map
11094: @cindex virtual function table
11095: The @emph{method map}@footnote{This is Self terminology; in C++
11096: terminology: virtual function table.} is an array that contains the
11097: execution tokens (@i{xt}s) of the methods for the object's class. Each
11098: selector contains an offset into a method map.
1.13 pazsan 11099:
1.78 anton 11100: @cindex @code{selector} implementation, class
11101: @code{selector} is a defining word that uses
11102: @code{CREATE} and @code{DOES>}. The body of the
11103: selector contains the offset; the @code{DOES>} action for a
11104: class selector is, basically:
1.8 pazsan 11105:
11106: @example
1.78 anton 11107: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 11108: @end example
11109:
1.78 anton 11110: Since @code{object-map} is the first field of the object, it
11111: does not generate any code. As you can see, calling a selector has a
11112: small, constant cost.
1.26 crook 11113:
1.78 anton 11114: @cindex @code{current-interface} discussion
11115: @cindex class implementation and representation
11116: A class is basically a @code{struct} combined with a method
11117: map. During the class definition the alignment and size of the class
11118: are passed on the stack, just as with @code{struct}s, so
11119: @code{field} can also be used for defining class
11120: fields. However, passing more items on the stack would be
11121: inconvenient, so @code{class} builds a data structure in memory,
11122: which is accessed through the variable
11123: @code{current-interface}. After its definition is complete, the
11124: class is represented on the stack by a pointer (e.g., as parameter for
11125: a child class definition).
1.26 crook 11126:
1.78 anton 11127: A new class starts off with the alignment and size of its parent,
11128: and a copy of the parent's method map. Defining new fields extends the
11129: size and alignment; likewise, defining new selectors extends the
11130: method map. @code{overrides} just stores a new @i{xt} in the method
11131: map at the offset given by the selector.
1.13 pazsan 11132:
1.78 anton 11133: @cindex class binding, implementation
11134: Class binding just gets the @i{xt} at the offset given by the selector
11135: from the class's method map and @code{compile,}s (in the case of
11136: @code{[bind]}) it.
1.13 pazsan 11137:
1.78 anton 11138: @cindex @code{this} implementation
11139: @cindex @code{catch} and @code{this}
11140: @cindex @code{this} and @code{catch}
11141: I implemented @code{this} as a @code{value}. At the
11142: start of an @code{m:...;m} method the old @code{this} is
11143: stored to the return stack and restored at the end; and the object on
11144: the TOS is stored @code{TO this}. This technique has one
11145: disadvantage: If the user does not leave the method via
11146: @code{;m}, but via @code{throw} or @code{exit},
11147: @code{this} is not restored (and @code{exit} may
11148: crash). To deal with the @code{throw} problem, I have redefined
11149: @code{catch} to save and restore @code{this}; the same
11150: should be done with any word that can catch an exception. As for
11151: @code{exit}, I simply forbid it (as a replacement, there is
11152: @code{exitm}).
1.13 pazsan 11153:
1.78 anton 11154: @cindex @code{inst-var} implementation
11155: @code{inst-var} is just the same as @code{field}, with
11156: a different @code{DOES>} action:
1.13 pazsan 11157: @example
1.78 anton 11158: @@ this +
1.8 pazsan 11159: @end example
1.78 anton 11160: Similar for @code{inst-value}.
1.8 pazsan 11161:
1.78 anton 11162: @cindex class scoping implementation
11163: Each class also has a word list that contains the words defined with
11164: @code{inst-var} and @code{inst-value}, and its protected
11165: words. It also has a pointer to its parent. @code{class} pushes
11166: the word lists of the class and all its ancestors onto the search order stack,
11167: and @code{end-class} drops them.
1.20 pazsan 11168:
1.78 anton 11169: @cindex interface implementation
11170: An interface is like a class without fields, parent and protected
11171: words; i.e., it just has a method map. If a class implements an
11172: interface, its method map contains a pointer to the method map of the
11173: interface. The positive offsets in the map are reserved for class
11174: methods, therefore interface map pointers have negative
11175: offsets. Interfaces have offsets that are unique throughout the
11176: system, unlike class selectors, whose offsets are only unique for the
11177: classes where the selector is available (invokable).
1.20 pazsan 11178:
1.78 anton 11179: This structure means that interface selectors have to perform one
11180: indirection more than class selectors to find their method. Their body
11181: contains the interface map pointer offset in the class method map, and
11182: the method offset in the interface method map. The
11183: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11184:
11185: @example
1.78 anton 11186: ( object selector-body )
11187: 2dup selector-interface @@ ( object selector-body object interface-offset )
11188: swap object-map @@ + @@ ( object selector-body map )
11189: swap selector-offset @@ + @@ execute
1.20 pazsan 11190: @end example
11191:
1.78 anton 11192: where @code{object-map} and @code{selector-offset} are
11193: first fields and generate no code.
1.20 pazsan 11194:
1.78 anton 11195: As a concrete example, consider the following code:
1.20 pazsan 11196:
11197: @example
1.78 anton 11198: interface
11199: selector if1sel1
11200: selector if1sel2
11201: end-interface if1
1.20 pazsan 11202:
1.78 anton 11203: object class
11204: if1 implementation
11205: selector cl1sel1
11206: cell% inst-var cl1iv1
1.20 pazsan 11207:
1.78 anton 11208: ' m1 overrides construct
11209: ' m2 overrides if1sel1
11210: ' m3 overrides if1sel2
11211: ' m4 overrides cl1sel2
11212: end-class cl1
1.20 pazsan 11213:
1.78 anton 11214: create obj1 object dict-new drop
11215: create obj2 cl1 dict-new drop
11216: @end example
1.20 pazsan 11217:
1.78 anton 11218: The data structure created by this code (including the data structure
11219: for @code{object}) is shown in the
11220: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11221: @comment TODO add this diagram..
1.20 pazsan 11222:
1.78 anton 11223: @node Objects Glossary, , Objects Implementation, Objects
11224: @subsubsection @file{objects.fs} Glossary
11225: @cindex @file{objects.fs} Glossary
1.20 pazsan 11226:
11227:
1.78 anton 11228: doc---objects-bind
11229: doc---objects-<bind>
11230: doc---objects-bind'
11231: doc---objects-[bind]
11232: doc---objects-class
11233: doc---objects-class->map
11234: doc---objects-class-inst-size
11235: doc---objects-class-override!
1.79 anton 11236: doc---objects-class-previous
11237: doc---objects-class>order
1.78 anton 11238: doc---objects-construct
11239: doc---objects-current'
11240: doc---objects-[current]
11241: doc---objects-current-interface
11242: doc---objects-dict-new
11243: doc---objects-end-class
11244: doc---objects-end-class-noname
11245: doc---objects-end-interface
11246: doc---objects-end-interface-noname
11247: doc---objects-end-methods
11248: doc---objects-exitm
11249: doc---objects-heap-new
11250: doc---objects-implementation
11251: doc---objects-init-object
11252: doc---objects-inst-value
11253: doc---objects-inst-var
11254: doc---objects-interface
11255: doc---objects-m:
11256: doc---objects-:m
11257: doc---objects-;m
11258: doc---objects-method
11259: doc---objects-methods
11260: doc---objects-object
11261: doc---objects-overrides
11262: doc---objects-[parent]
11263: doc---objects-print
11264: doc---objects-protected
11265: doc---objects-public
11266: doc---objects-selector
11267: doc---objects-this
11268: doc---objects-<to-inst>
11269: doc---objects-[to-inst]
11270: doc---objects-to-this
11271: doc---objects-xt-new
1.20 pazsan 11272:
11273:
1.78 anton 11274: @c -------------------------------------------------------------
11275: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11276: @subsection The @file{oof.fs} model
11277: @cindex oof
11278: @cindex object-oriented programming
1.20 pazsan 11279:
1.78 anton 11280: @cindex @file{objects.fs}
11281: @cindex @file{oof.fs}
1.20 pazsan 11282:
1.78 anton 11283: This section describes the @file{oof.fs} package.
1.20 pazsan 11284:
1.78 anton 11285: The package described in this section has been used in bigFORTH since 1991, and
11286: used for two large applications: a chromatographic system used to
11287: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11288:
1.78 anton 11289: You can find a description (in German) of @file{oof.fs} in @cite{Object
11290: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11291: 10(2), 1994.
1.20 pazsan 11292:
1.78 anton 11293: @menu
11294: * Properties of the OOF model::
11295: * Basic OOF Usage::
11296: * The OOF base class::
11297: * Class Declaration::
11298: * Class Implementation::
11299: @end menu
1.20 pazsan 11300:
1.78 anton 11301: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11302: @subsubsection Properties of the @file{oof.fs} model
11303: @cindex @file{oof.fs} properties
1.20 pazsan 11304:
1.78 anton 11305: @itemize @bullet
11306: @item
11307: This model combines object oriented programming with information
11308: hiding. It helps you writing large application, where scoping is
11309: necessary, because it provides class-oriented scoping.
1.20 pazsan 11310:
1.78 anton 11311: @item
11312: Named objects, object pointers, and object arrays can be created,
11313: selector invocation uses the ``object selector'' syntax. Selector invocation
11314: to objects and/or selectors on the stack is a bit less convenient, but
11315: possible.
1.44 crook 11316:
1.78 anton 11317: @item
11318: Selector invocation and instance variable usage of the active object is
11319: straightforward, since both make use of the active object.
1.44 crook 11320:
1.78 anton 11321: @item
11322: Late binding is efficient and easy to use.
1.20 pazsan 11323:
1.78 anton 11324: @item
11325: State-smart objects parse selectors. However, extensibility is provided
11326: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11327:
1.78 anton 11328: @item
11329: An implementation in ANS Forth is available.
1.20 pazsan 11330:
1.78 anton 11331: @end itemize
1.23 crook 11332:
11333:
1.78 anton 11334: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11335: @subsubsection Basic @file{oof.fs} Usage
11336: @cindex @file{oof.fs} usage
1.23 crook 11337:
1.78 anton 11338: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11339:
1.78 anton 11340: You can define a class for graphical objects like this:
1.23 crook 11341:
1.78 anton 11342: @cindex @code{class} usage
11343: @cindex @code{class;} usage
11344: @cindex @code{method} usage
11345: @example
11346: object class graphical \ "object" is the parent class
1.139 pazsan 11347: method draw ( x y -- )
1.78 anton 11348: class;
11349: @end example
1.23 crook 11350:
1.78 anton 11351: This code defines a class @code{graphical} with an
11352: operation @code{draw}. We can perform the operation
11353: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11354:
1.78 anton 11355: @example
11356: 100 100 t-rex draw
11357: @end example
1.23 crook 11358:
1.78 anton 11359: @noindent
11360: where @code{t-rex} is an object or object pointer, created with e.g.
11361: @code{graphical : t-rex}.
1.23 crook 11362:
1.78 anton 11363: @cindex abstract class
11364: How do we create a graphical object? With the present definitions,
11365: we cannot create a useful graphical object. The class
11366: @code{graphical} describes graphical objects in general, but not
11367: any concrete graphical object type (C++ users would call it an
11368: @emph{abstract class}); e.g., there is no method for the selector
11369: @code{draw} in the class @code{graphical}.
1.23 crook 11370:
1.78 anton 11371: For concrete graphical objects, we define child classes of the
11372: class @code{graphical}, e.g.:
1.23 crook 11373:
1.78 anton 11374: @example
11375: graphical class circle \ "graphical" is the parent class
11376: cell var circle-radius
11377: how:
11378: : draw ( x y -- )
11379: circle-radius @@ draw-circle ;
1.23 crook 11380:
1.139 pazsan 11381: : init ( n-radius -- )
1.78 anton 11382: circle-radius ! ;
11383: class;
11384: @end example
1.1 anton 11385:
1.78 anton 11386: Here we define a class @code{circle} as a child of @code{graphical},
11387: with a field @code{circle-radius}; it defines new methods for the
11388: selectors @code{draw} and @code{init} (@code{init} is defined in
11389: @code{object}, the parent class of @code{graphical}).
1.1 anton 11390:
1.78 anton 11391: Now we can create a circle in the dictionary with:
1.1 anton 11392:
1.78 anton 11393: @example
11394: 50 circle : my-circle
11395: @end example
1.21 crook 11396:
1.78 anton 11397: @noindent
11398: @code{:} invokes @code{init}, thus initializing the field
11399: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11400: with:
1.1 anton 11401:
1.78 anton 11402: @example
11403: 100 100 my-circle draw
11404: @end example
1.1 anton 11405:
1.78 anton 11406: @cindex selector invocation, restrictions
11407: @cindex class definition, restrictions
11408: Note: You can only invoke a selector if the receiving object belongs to
11409: the class where the selector was defined or one of its descendents;
11410: e.g., you can invoke @code{draw} only for objects belonging to
11411: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11412: mechanism will check if you try to invoke a selector that is not
11413: defined in this class hierarchy, so you'll get an error at compilation
11414: time.
1.1 anton 11415:
11416:
1.78 anton 11417: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11418: @subsubsection The @file{oof.fs} base class
11419: @cindex @file{oof.fs} base class
1.1 anton 11420:
1.78 anton 11421: When you define a class, you have to specify a parent class. So how do
11422: you start defining classes? There is one class available from the start:
11423: @code{object}. You have to use it as ancestor for all classes. It is the
11424: only class that has no parent. Classes are also objects, except that
11425: they don't have instance variables; class manipulation such as
11426: inheritance or changing definitions of a class is handled through
11427: selectors of the class @code{object}.
1.1 anton 11428:
1.78 anton 11429: @code{object} provides a number of selectors:
1.1 anton 11430:
1.78 anton 11431: @itemize @bullet
11432: @item
11433: @code{class} for subclassing, @code{definitions} to add definitions
11434: later on, and @code{class?} to get type informations (is the class a
11435: subclass of the class passed on the stack?).
1.1 anton 11436:
1.78 anton 11437: doc---object-class
11438: doc---object-definitions
11439: doc---object-class?
1.1 anton 11440:
11441:
1.26 crook 11442: @item
1.78 anton 11443: @code{init} and @code{dispose} as constructor and destructor of the
11444: object. @code{init} is invocated after the object's memory is allocated,
11445: while @code{dispose} also handles deallocation. Thus if you redefine
11446: @code{dispose}, you have to call the parent's dispose with @code{super
11447: dispose}, too.
11448:
11449: doc---object-init
11450: doc---object-dispose
11451:
1.1 anton 11452:
1.26 crook 11453: @item
1.78 anton 11454: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11455: @code{[]} to create named and unnamed objects and object arrays or
11456: object pointers.
11457:
11458: doc---object-new
11459: doc---object-new[]
11460: doc---object-:
11461: doc---object-ptr
11462: doc---object-asptr
11463: doc---object-[]
11464:
1.1 anton 11465:
1.26 crook 11466: @item
1.78 anton 11467: @code{::} and @code{super} for explicit scoping. You should use explicit
11468: scoping only for super classes or classes with the same set of instance
11469: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11470:
1.78 anton 11471: doc---object-::
11472: doc---object-super
1.21 crook 11473:
11474:
1.26 crook 11475: @item
1.78 anton 11476: @code{self} to get the address of the object
1.21 crook 11477:
1.78 anton 11478: doc---object-self
1.21 crook 11479:
11480:
1.78 anton 11481: @item
11482: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11483: pointers and instance defers.
1.21 crook 11484:
1.78 anton 11485: doc---object-bind
11486: doc---object-bound
11487: doc---object-link
11488: doc---object-is
1.21 crook 11489:
11490:
1.78 anton 11491: @item
11492: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11493: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11494:
1.78 anton 11495: doc---object-'
11496: doc---object-postpone
1.21 crook 11497:
11498:
1.78 anton 11499: @item
11500: @code{with} and @code{endwith} to select the active object from the
11501: stack, and enable its scope. Using @code{with} and @code{endwith}
11502: also allows you to create code using selector @code{postpone} without being
11503: trapped by the state-smart objects.
1.21 crook 11504:
1.78 anton 11505: doc---object-with
11506: doc---object-endwith
1.21 crook 11507:
11508:
1.78 anton 11509: @end itemize
1.21 crook 11510:
1.78 anton 11511: @node Class Declaration, Class Implementation, The OOF base class, OOF
11512: @subsubsection Class Declaration
11513: @cindex class declaration
1.21 crook 11514:
1.78 anton 11515: @itemize @bullet
11516: @item
11517: Instance variables
1.21 crook 11518:
1.78 anton 11519: doc---oof-var
1.21 crook 11520:
11521:
1.78 anton 11522: @item
11523: Object pointers
1.21 crook 11524:
1.78 anton 11525: doc---oof-ptr
11526: doc---oof-asptr
1.21 crook 11527:
11528:
1.78 anton 11529: @item
11530: Instance defers
1.21 crook 11531:
1.78 anton 11532: doc---oof-defer
1.21 crook 11533:
11534:
1.78 anton 11535: @item
11536: Method selectors
1.21 crook 11537:
1.78 anton 11538: doc---oof-early
11539: doc---oof-method
1.21 crook 11540:
11541:
1.78 anton 11542: @item
11543: Class-wide variables
1.21 crook 11544:
1.78 anton 11545: doc---oof-static
1.21 crook 11546:
11547:
1.78 anton 11548: @item
11549: End declaration
1.1 anton 11550:
1.78 anton 11551: doc---oof-how:
11552: doc---oof-class;
1.21 crook 11553:
11554:
1.78 anton 11555: @end itemize
1.21 crook 11556:
1.78 anton 11557: @c -------------------------------------------------------------
11558: @node Class Implementation, , Class Declaration, OOF
11559: @subsubsection Class Implementation
11560: @cindex class implementation
1.21 crook 11561:
1.78 anton 11562: @c -------------------------------------------------------------
11563: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11564: @subsection The @file{mini-oof.fs} model
11565: @cindex mini-oof
1.21 crook 11566:
1.78 anton 11567: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11568: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11569: and reduces to the bare minimum of features. This is based on a posting
11570: of Bernd Paysan in comp.lang.forth.
1.21 crook 11571:
1.78 anton 11572: @menu
11573: * Basic Mini-OOF Usage::
11574: * Mini-OOF Example::
11575: * Mini-OOF Implementation::
11576: @end menu
1.21 crook 11577:
1.78 anton 11578: @c -------------------------------------------------------------
11579: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11580: @subsubsection Basic @file{mini-oof.fs} Usage
11581: @cindex mini-oof usage
1.21 crook 11582:
1.78 anton 11583: There is a base class (@code{class}, which allocates one cell for the
11584: object pointer) plus seven other words: to define a method, a variable,
11585: a class; to end a class, to resolve binding, to allocate an object and
11586: to compile a class method.
11587: @comment TODO better description of the last one
1.26 crook 11588:
1.21 crook 11589:
1.78 anton 11590: doc-object
11591: doc-method
11592: doc-var
11593: doc-class
11594: doc-end-class
11595: doc-defines
11596: doc-new
11597: doc-::
1.21 crook 11598:
11599:
11600:
1.78 anton 11601: @c -------------------------------------------------------------
11602: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11603: @subsubsection Mini-OOF Example
11604: @cindex mini-oof example
1.1 anton 11605:
1.78 anton 11606: A short example shows how to use this package. This example, in slightly
11607: extended form, is supplied as @file{moof-exm.fs}
11608: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11609:
1.26 crook 11610: @example
1.78 anton 11611: object class
11612: method init
11613: method draw
11614: end-class graphical
1.26 crook 11615: @end example
1.20 pazsan 11616:
1.78 anton 11617: This code defines a class @code{graphical} with an
11618: operation @code{draw}. We can perform the operation
11619: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11620:
1.26 crook 11621: @example
1.78 anton 11622: 100 100 t-rex draw
1.26 crook 11623: @end example
1.12 anton 11624:
1.78 anton 11625: where @code{t-rex} is an object or object pointer, created with e.g.
11626: @code{graphical new Constant t-rex}.
1.12 anton 11627:
1.78 anton 11628: For concrete graphical objects, we define child classes of the
11629: class @code{graphical}, e.g.:
1.12 anton 11630:
1.26 crook 11631: @example
11632: graphical class
1.78 anton 11633: cell var circle-radius
11634: end-class circle \ "graphical" is the parent class
1.12 anton 11635:
1.78 anton 11636: :noname ( x y -- )
11637: circle-radius @@ draw-circle ; circle defines draw
11638: :noname ( r -- )
11639: circle-radius ! ; circle defines init
11640: @end example
1.12 anton 11641:
1.78 anton 11642: There is no implicit init method, so we have to define one. The creation
11643: code of the object now has to call init explicitely.
1.21 crook 11644:
1.78 anton 11645: @example
11646: circle new Constant my-circle
11647: 50 my-circle init
1.12 anton 11648: @end example
11649:
1.78 anton 11650: It is also possible to add a function to create named objects with
11651: automatic call of @code{init}, given that all objects have @code{init}
11652: on the same place:
1.38 anton 11653:
1.78 anton 11654: @example
11655: : new: ( .. o "name" -- )
11656: new dup Constant init ;
11657: 80 circle new: large-circle
11658: @end example
1.12 anton 11659:
1.78 anton 11660: We can draw this new circle at (100,100) with:
1.12 anton 11661:
1.78 anton 11662: @example
11663: 100 100 my-circle draw
11664: @end example
1.12 anton 11665:
1.78 anton 11666: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11667: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11668:
1.78 anton 11669: Object-oriented systems with late binding typically use a
11670: ``vtable''-approach: the first variable in each object is a pointer to a
11671: table, which contains the methods as function pointers. The vtable
11672: may also contain other information.
1.12 anton 11673:
1.79 anton 11674: So first, let's declare selectors:
1.37 anton 11675:
11676: @example
1.79 anton 11677: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11678: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11679: @end example
1.37 anton 11680:
1.79 anton 11681: During selector declaration, the number of selectors and instance
11682: variables is on the stack (in address units). @code{method} creates one
11683: selector and increments the selector number. To execute a selector, it
1.78 anton 11684: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11685: executes the method @i{xt} stored there. Each selector takes the object
11686: it is invoked with as top of stack parameter; it passes the parameters
11687: (including the object) unchanged to the appropriate method which should
1.78 anton 11688: consume that object.
1.37 anton 11689:
1.78 anton 11690: Now, we also have to declare instance variables
1.37 anton 11691:
1.78 anton 11692: @example
1.79 anton 11693: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11694: DOES> ( o -- addr ) @@ + ;
1.37 anton 11695: @end example
11696:
1.78 anton 11697: As before, a word is created with the current offset. Instance
11698: variables can have different sizes (cells, floats, doubles, chars), so
11699: all we do is take the size and add it to the offset. If your machine
11700: has alignment restrictions, put the proper @code{aligned} or
11701: @code{faligned} before the variable, to adjust the variable
11702: offset. That's why it is on the top of stack.
1.37 anton 11703:
1.78 anton 11704: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11705:
1.78 anton 11706: @example
11707: Create object 1 cells , 2 cells ,
1.79 anton 11708: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11709: @end example
1.12 anton 11710:
1.78 anton 11711: For inheritance, the vtable of the parent object has to be
11712: copied when a new, derived class is declared. This gives all the
11713: methods of the parent class, which can be overridden, though.
1.12 anton 11714:
1.78 anton 11715: @example
1.79 anton 11716: : end-class ( class selectors vars "name" -- )
1.78 anton 11717: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11718: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11719: @end example
1.12 anton 11720:
1.78 anton 11721: The first line creates the vtable, initialized with
11722: @code{noop}s. The second line is the inheritance mechanism, it
11723: copies the xts from the parent vtable.
1.12 anton 11724:
1.78 anton 11725: We still have no way to define new methods, let's do that now:
1.12 anton 11726:
1.26 crook 11727: @example
1.79 anton 11728: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11729: @end example
1.12 anton 11730:
1.78 anton 11731: To allocate a new object, we need a word, too:
1.12 anton 11732:
1.78 anton 11733: @example
11734: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11735: @end example
11736:
1.78 anton 11737: Sometimes derived classes want to access the method of the
11738: parent object. There are two ways to achieve this with Mini-OOF:
11739: first, you could use named words, and second, you could look up the
11740: vtable of the parent object.
1.12 anton 11741:
1.78 anton 11742: @example
11743: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11744: @end example
1.12 anton 11745:
11746:
1.78 anton 11747: Nothing can be more confusing than a good example, so here is
11748: one. First let's declare a text object (called
11749: @code{button}), that stores text and position:
1.12 anton 11750:
1.78 anton 11751: @example
11752: object class
11753: cell var text
11754: cell var len
11755: cell var x
11756: cell var y
11757: method init
11758: method draw
11759: end-class button
11760: @end example
1.12 anton 11761:
1.78 anton 11762: @noindent
11763: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11764:
1.26 crook 11765: @example
1.78 anton 11766: :noname ( o -- )
11767: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11768: button defines draw
11769: :noname ( addr u o -- )
11770: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11771: button defines init
1.26 crook 11772: @end example
1.12 anton 11773:
1.78 anton 11774: @noindent
11775: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11776: new data and no new selectors:
1.78 anton 11777:
11778: @example
11779: button class
11780: end-class bold-button
1.12 anton 11781:
1.78 anton 11782: : bold 27 emit ." [1m" ;
11783: : normal 27 emit ." [0m" ;
11784: @end example
1.1 anton 11785:
1.78 anton 11786: @noindent
11787: The class @code{bold-button} has a different draw method to
11788: @code{button}, but the new method is defined in terms of the draw method
11789: for @code{button}:
1.20 pazsan 11790:
1.78 anton 11791: @example
11792: :noname bold [ button :: draw ] normal ; bold-button defines draw
11793: @end example
1.21 crook 11794:
1.78 anton 11795: @noindent
1.79 anton 11796: Finally, create two objects and apply selectors:
1.21 crook 11797:
1.26 crook 11798: @example
1.78 anton 11799: button new Constant foo
11800: s" thin foo" foo init
11801: page
11802: foo draw
11803: bold-button new Constant bar
11804: s" fat bar" bar init
11805: 1 bar y !
11806: bar draw
1.26 crook 11807: @end example
1.21 crook 11808:
11809:
1.78 anton 11810: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11811: @subsection Comparison with other object models
11812: @cindex comparison of object models
11813: @cindex object models, comparison
11814:
11815: Many object-oriented Forth extensions have been proposed (@cite{A survey
11816: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11817: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11818: relation of the object models described here to two well-known and two
11819: closely-related (by the use of method maps) models. Andras Zsoter
11820: helped us with this section.
11821:
11822: @cindex Neon model
11823: The most popular model currently seems to be the Neon model (see
11824: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11825: 1997) by Andrew McKewan) but this model has a number of limitations
11826: @footnote{A longer version of this critique can be
11827: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11828: Dimensions, May 1997) by Anton Ertl.}:
11829:
11830: @itemize @bullet
11831: @item
11832: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11833: to pass objects on the stack.
1.21 crook 11834:
1.78 anton 11835: @item
11836: It requires that the selector parses the input stream (at
1.79 anton 11837: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11838: hard to find.
1.21 crook 11839:
1.78 anton 11840: @item
1.79 anton 11841: It allows using every selector on every object; this eliminates the
11842: need for interfaces, but makes it harder to create efficient
11843: implementations.
1.78 anton 11844: @end itemize
1.21 crook 11845:
1.78 anton 11846: @cindex Pountain's object-oriented model
11847: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11848: Press, London, 1987) by Dick Pountain. However, it is not really about
11849: object-oriented programming, because it hardly deals with late
11850: binding. Instead, it focuses on features like information hiding and
11851: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11852:
1.78 anton 11853: @cindex Zsoter's object-oriented model
1.79 anton 11854: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11855: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11856: describes a model that makes heavy use of an active object (like
11857: @code{this} in @file{objects.fs}): The active object is not only used
11858: for accessing all fields, but also specifies the receiving object of
11859: every selector invocation; you have to change the active object
11860: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11861: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11862: the method entry point is unnecessary with Zsoter's model, because the
11863: receiving object is the active object already. On the other hand, the
11864: explicit change is absolutely necessary in that model, because otherwise
11865: no one could ever change the active object. An ANS Forth implementation
11866: of this model is available through
11867: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11868:
1.78 anton 11869: @cindex @file{oof.fs}, differences to other models
11870: The @file{oof.fs} model combines information hiding and overloading
11871: resolution (by keeping names in various word lists) with object-oriented
11872: programming. It sets the active object implicitly on method entry, but
11873: also allows explicit changing (with @code{>o...o>} or with
11874: @code{with...endwith}). It uses parsing and state-smart objects and
11875: classes for resolving overloading and for early binding: the object or
11876: class parses the selector and determines the method from this. If the
11877: selector is not parsed by an object or class, it performs a call to the
11878: selector for the active object (late binding), like Zsoter's model.
11879: Fields are always accessed through the active object. The big
11880: disadvantage of this model is the parsing and the state-smartness, which
11881: reduces extensibility and increases the opportunities for subtle bugs;
11882: essentially, you are only safe if you never tick or @code{postpone} an
11883: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11884:
1.78 anton 11885: @cindex @file{mini-oof.fs}, differences to other models
11886: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11887: version of the @file{objects.fs} model, but syntactically it is a
11888: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11889:
11890:
1.78 anton 11891: @c -------------------------------------------------------------
1.150 anton 11892: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11893: @section Programming Tools
11894: @cindex programming tools
1.21 crook 11895:
1.78 anton 11896: @c !! move this and assembler down below OO stuff.
1.21 crook 11897:
1.78 anton 11898: @menu
1.150 anton 11899: * Examining:: Data and Code.
11900: * Forgetting words:: Usually before reloading.
1.78 anton 11901: * Debugging:: Simple and quick.
11902: * Assertions:: Making your programs self-checking.
11903: * Singlestep Debugger:: Executing your program word by word.
11904: @end menu
1.21 crook 11905:
1.78 anton 11906: @node Examining, Forgetting words, Programming Tools, Programming Tools
11907: @subsection Examining data and code
11908: @cindex examining data and code
11909: @cindex data examination
11910: @cindex code examination
1.44 crook 11911:
1.78 anton 11912: The following words inspect the stack non-destructively:
1.21 crook 11913:
1.78 anton 11914: doc-.s
11915: doc-f.s
1.158 anton 11916: doc-maxdepth-.s
1.44 crook 11917:
1.78 anton 11918: There is a word @code{.r} but it does @i{not} display the return stack!
11919: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11920:
1.78 anton 11921: doc-depth
11922: doc-fdepth
11923: doc-clearstack
1.124 anton 11924: doc-clearstacks
1.21 crook 11925:
1.78 anton 11926: The following words inspect memory.
1.21 crook 11927:
1.78 anton 11928: doc-?
11929: doc-dump
1.21 crook 11930:
1.78 anton 11931: And finally, @code{see} allows to inspect code:
1.21 crook 11932:
1.78 anton 11933: doc-see
11934: doc-xt-see
1.111 anton 11935: doc-simple-see
11936: doc-simple-see-range
1.182 anton 11937: doc-see-code
11938: doc-see-code-range
1.21 crook 11939:
1.78 anton 11940: @node Forgetting words, Debugging, Examining, Programming Tools
11941: @subsection Forgetting words
11942: @cindex words, forgetting
11943: @cindex forgeting words
1.21 crook 11944:
1.78 anton 11945: @c anton: other, maybe better places for this subsection: Defining Words;
11946: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11947:
1.78 anton 11948: Forth allows you to forget words (and everything that was alloted in the
11949: dictonary after them) in a LIFO manner.
1.21 crook 11950:
1.78 anton 11951: doc-marker
1.21 crook 11952:
1.78 anton 11953: The most common use of this feature is during progam development: when
11954: you change a source file, forget all the words it defined and load it
11955: again (since you also forget everything defined after the source file
11956: was loaded, you have to reload that, too). Note that effects like
11957: storing to variables and destroyed system words are not undone when you
11958: forget words. With a system like Gforth, that is fast enough at
11959: starting up and compiling, I find it more convenient to exit and restart
11960: Gforth, as this gives me a clean slate.
1.21 crook 11961:
1.78 anton 11962: Here's an example of using @code{marker} at the start of a source file
11963: that you are debugging; it ensures that you only ever have one copy of
11964: the file's definitions compiled at any time:
1.21 crook 11965:
1.78 anton 11966: @example
11967: [IFDEF] my-code
11968: my-code
11969: [ENDIF]
1.26 crook 11970:
1.78 anton 11971: marker my-code
11972: init-included-files
1.21 crook 11973:
1.78 anton 11974: \ .. definitions start here
11975: \ .
11976: \ .
11977: \ end
11978: @end example
1.21 crook 11979:
1.26 crook 11980:
1.78 anton 11981: @node Debugging, Assertions, Forgetting words, Programming Tools
11982: @subsection Debugging
11983: @cindex debugging
1.21 crook 11984:
1.78 anton 11985: Languages with a slow edit/compile/link/test development loop tend to
11986: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11987:
1.78 anton 11988: A much better (faster) way in fast-compiling languages is to add
11989: printing code at well-selected places, let the program run, look at
11990: the output, see where things went wrong, add more printing code, etc.,
11991: until the bug is found.
1.21 crook 11992:
1.78 anton 11993: The simple debugging aids provided in @file{debugs.fs}
11994: are meant to support this style of debugging.
1.21 crook 11995:
1.78 anton 11996: The word @code{~~} prints debugging information (by default the source
11997: location and the stack contents). It is easy to insert. If you use Emacs
11998: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11999: query-replace them with nothing). The deferred words
1.101 anton 12000: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 12001: @code{~~}. The default source location output format works well with
12002: Emacs' compilation mode, so you can step through the program at the
12003: source level using @kbd{C-x `} (the advantage over a stepping debugger
12004: is that you can step in any direction and you know where the crash has
12005: happened or where the strange data has occurred).
1.21 crook 12006:
1.78 anton 12007: doc-~~
12008: doc-printdebugdata
1.101 anton 12009: doc-.debugline
1.203 anton 12010: doc-debug-fid
1.21 crook 12011:
1.106 anton 12012: @cindex filenames in @code{~~} output
12013: @code{~~} (and assertions) will usually print the wrong file name if a
12014: marker is executed in the same file after their occurance. They will
12015: print @samp{*somewhere*} as file name if a marker is executed in the
12016: same file before their occurance.
12017:
12018:
1.78 anton 12019: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
12020: @subsection Assertions
12021: @cindex assertions
1.21 crook 12022:
1.78 anton 12023: It is a good idea to make your programs self-checking, especially if you
12024: make an assumption that may become invalid during maintenance (for
12025: example, that a certain field of a data structure is never zero). Gforth
12026: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 12027:
12028: @example
1.78 anton 12029: assert( @i{flag} )
1.26 crook 12030: @end example
12031:
1.78 anton 12032: The code between @code{assert(} and @code{)} should compute a flag, that
12033: should be true if everything is alright and false otherwise. It should
12034: not change anything else on the stack. The overall stack effect of the
12035: assertion is @code{( -- )}. E.g.
1.21 crook 12036:
1.26 crook 12037: @example
1.78 anton 12038: assert( 1 1 + 2 = ) \ what we learn in school
12039: assert( dup 0<> ) \ assert that the top of stack is not zero
12040: assert( false ) \ this code should not be reached
1.21 crook 12041: @end example
12042:
1.78 anton 12043: The need for assertions is different at different times. During
12044: debugging, we want more checking, in production we sometimes care more
12045: for speed. Therefore, assertions can be turned off, i.e., the assertion
12046: becomes a comment. Depending on the importance of an assertion and the
12047: time it takes to check it, you may want to turn off some assertions and
12048: keep others turned on. Gforth provides several levels of assertions for
12049: this purpose:
12050:
12051:
12052: doc-assert0(
12053: doc-assert1(
12054: doc-assert2(
12055: doc-assert3(
12056: doc-assert(
12057: doc-)
1.21 crook 12058:
12059:
1.78 anton 12060: The variable @code{assert-level} specifies the highest assertions that
12061: are turned on. I.e., at the default @code{assert-level} of one,
12062: @code{assert0(} and @code{assert1(} assertions perform checking, while
12063: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 12064:
1.78 anton 12065: The value of @code{assert-level} is evaluated at compile-time, not at
12066: run-time. Therefore you cannot turn assertions on or off at run-time;
12067: you have to set the @code{assert-level} appropriately before compiling a
12068: piece of code. You can compile different pieces of code at different
12069: @code{assert-level}s (e.g., a trusted library at level 1 and
12070: newly-written code at level 3).
1.26 crook 12071:
12072:
1.78 anton 12073: doc-assert-level
1.26 crook 12074:
12075:
1.78 anton 12076: If an assertion fails, a message compatible with Emacs' compilation mode
12077: is produced and the execution is aborted (currently with @code{ABORT"}.
12078: If there is interest, we will introduce a special throw code. But if you
12079: intend to @code{catch} a specific condition, using @code{throw} is
12080: probably more appropriate than an assertion).
1.106 anton 12081:
12082: @cindex filenames in assertion output
12083: Assertions (and @code{~~}) will usually print the wrong file name if a
12084: marker is executed in the same file after their occurance. They will
12085: print @samp{*somewhere*} as file name if a marker is executed in the
12086: same file before their occurance.
1.44 crook 12087:
1.78 anton 12088: Definitions in ANS Forth for these assertion words are provided
12089: in @file{compat/assert.fs}.
1.26 crook 12090:
1.44 crook 12091:
1.78 anton 12092: @node Singlestep Debugger, , Assertions, Programming Tools
12093: @subsection Singlestep Debugger
12094: @cindex singlestep Debugger
12095: @cindex debugging Singlestep
1.44 crook 12096:
1.189 anton 12097: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 12098:
1.78 anton 12099: When you create a new word there's often the need to check whether it
12100: behaves correctly or not. You can do this by typing @code{dbg
12101: badword}. A debug session might look like this:
1.26 crook 12102:
1.78 anton 12103: @example
12104: : badword 0 DO i . LOOP ; ok
12105: 2 dbg badword
12106: : badword
12107: Scanning code...
1.44 crook 12108:
1.78 anton 12109: Nesting debugger ready!
1.44 crook 12110:
1.78 anton 12111: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
12112: 400D4740 8049F68 DO -> [ 0 ]
12113: 400D4744 804A0C8 i -> [ 1 ] 00000
12114: 400D4748 400C5E60 . -> 0 [ 0 ]
12115: 400D474C 8049D0C LOOP -> [ 0 ]
12116: 400D4744 804A0C8 i -> [ 1 ] 00001
12117: 400D4748 400C5E60 . -> 1 [ 0 ]
12118: 400D474C 8049D0C LOOP -> [ 0 ]
12119: 400D4758 804B384 ; -> ok
12120: @end example
1.21 crook 12121:
1.78 anton 12122: Each line displayed is one step. You always have to hit return to
12123: execute the next word that is displayed. If you don't want to execute
12124: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12125: an overview what keys are available:
1.44 crook 12126:
1.78 anton 12127: @table @i
1.44 crook 12128:
1.78 anton 12129: @item @key{RET}
12130: Next; Execute the next word.
1.21 crook 12131:
1.78 anton 12132: @item n
12133: Nest; Single step through next word.
1.44 crook 12134:
1.78 anton 12135: @item u
12136: Unnest; Stop debugging and execute rest of word. If we got to this word
12137: with nest, continue debugging with the calling word.
1.44 crook 12138:
1.78 anton 12139: @item d
12140: Done; Stop debugging and execute rest.
1.21 crook 12141:
1.78 anton 12142: @item s
12143: Stop; Abort immediately.
1.44 crook 12144:
1.78 anton 12145: @end table
1.44 crook 12146:
1.78 anton 12147: Debugging large application with this mechanism is very difficult, because
12148: you have to nest very deeply into the program before the interesting part
12149: begins. This takes a lot of time.
1.26 crook 12150:
1.78 anton 12151: To do it more directly put a @code{BREAK:} command into your source code.
12152: When program execution reaches @code{BREAK:} the single step debugger is
12153: invoked and you have all the features described above.
1.44 crook 12154:
1.78 anton 12155: If you have more than one part to debug it is useful to know where the
12156: program has stopped at the moment. You can do this by the
12157: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12158: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12159:
1.26 crook 12160:
1.78 anton 12161: doc-dbg
12162: doc-break:
12163: doc-break"
1.44 crook 12164:
1.150 anton 12165: @c ------------------------------------------------------------
12166: @node C Interface, Assembler and Code Words, Programming Tools, Words
12167: @section C Interface
12168: @cindex C interface
12169: @cindex foreign language interface
12170: @cindex interface to C functions
12171:
1.178 anton 12172: Note that the C interface is not yet complete; callbacks are missing,
12173: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12174:
12175: @menu
12176: * Calling C Functions::
12177: * Declaring C Functions::
1.180 anton 12178: * Calling C function pointers::
1.196 anton 12179: * Defining library interfaces::
12180: * Declaring OS-level libraries::
1.150 anton 12181: * Callbacks::
1.178 anton 12182: * C interface internals::
1.155 anton 12183: * Low-Level C Interface Words::
1.150 anton 12184: @end menu
12185:
1.151 pazsan 12186: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12187: @subsection Calling C functions
1.155 anton 12188: @cindex C functions, calls to
12189: @cindex calling C functions
1.150 anton 12190:
1.151 pazsan 12191: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12192: can call it as follows: You push the arguments on the stack(s), and
12193: then call the word for the C function. The arguments have to be
12194: pushed in the same order as the arguments appear in the C
12195: documentation (i.e., the first argument is deepest on the stack).
12196: Integer and pointer arguments have to be pushed on the data stack,
12197: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12198: by the called C function.
1.150 anton 12199:
1.155 anton 12200: On returning from the C function, the return value, if any, resides on
12201: the appropriate stack: an integer return value is pushed on the data
12202: stack, an FP return value on the FP stack, and a void return value
12203: results in not pushing anything. Note that most C functions have a
12204: return value, even if that is often not used in C; in Forth, you have
12205: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12206:
1.177 anton 12207: The C interface automatically converts between the C type and the
12208: Forth type as necessary, on a best-effort basis (in some cases, there
12209: may be some loss).
1.150 anton 12210:
12211: As an example, consider the POSIX function @code{lseek()}:
12212:
12213: @example
12214: off_t lseek(int fd, off_t offset, int whence);
12215: @end example
12216:
12217: This function takes three integer arguments, and returns an integer
12218: argument, so a Forth call for setting the current file offset to the
12219: start of the file could look like this:
12220:
12221: @example
12222: fd @@ 0 SEEK_SET lseek -1 = if
12223: ... \ error handling
12224: then
12225: @end example
12226:
12227: You might be worried that an @code{off_t} does not fit into a cell, so
12228: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12229: of the return values. In that case, in your declaration of the
12230: function (@pxref{Declaring C Functions}) you should declare it to use
12231: double-cells for the off_t argument and return value, and maybe give
12232: the resulting Forth word a different name, like @code{dlseek}; the
12233: result could be called like this:
1.150 anton 12234:
12235: @example
12236: fd @@ 0. SEEK_SET dlseek -1. d= if
12237: ... \ error handling
12238: then
12239: @end example
12240:
12241: Passing and returning structs or unions is currently not supported by
12242: our interface@footnote{If you know the calling convention of your C
12243: compiler, you usually can call such functions in some way, but that
12244: way is usually not portable between platforms, and sometimes not even
12245: between C compilers.}.
12246:
1.177 anton 12247: Calling functions with a variable number of arguments (@emph{variadic}
12248: functions, e.g., @code{printf()}) is only supported by having you
12249: declare one function-calling word for each argument pattern, and
12250: calling the appropriate word for the desired pattern.
12251:
1.150 anton 12252:
1.155 anton 12253:
1.180 anton 12254: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12255: @subsection Declaring C Functions
1.155 anton 12256: @cindex C functions, declarations
12257: @cindex declaring C functions
1.150 anton 12258:
12259: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12260: it. The declaration consists of two parts:
12261:
12262: @table @b
12263:
12264: @item The C part
1.179 anton 12265: is the C declaration of the function, or more typically and portably,
12266: a C-style @code{#include} of a file that contains the declaration of
12267: the C function.
1.177 anton 12268:
12269: @item The Forth part
12270: declares the Forth types of the parameters and the Forth word name
12271: corresponding to the C function.
12272:
12273: @end table
12274:
12275: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12276: declarations are:
12277:
12278: @example
12279: \c #define _FILE_OFFSET_BITS 64
12280: \c #include <sys/types.h>
12281: \c #include <unistd.h>
12282: c-function lseek lseek n n n -- n
12283: c-function dlseek lseek n d n -- d
12284: @end example
12285:
1.178 anton 12286: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12287: of the line is ordinary C code. You can use as many lines of C
12288: declarations as you like, and they are visible for all further
12289: function declarations.
12290:
12291: The Forth part declares each interface word with @code{c-function},
12292: followed by the Forth name of the word, the C name of the called
12293: function, and the stack effect of the word. The stack effect contains
1.178 anton 12294: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12295: exactly one type for the return value. The possible types are:
12296:
12297: @table @code
12298:
12299: @item n
12300: single-cell integer
12301:
12302: @item a
12303: address (single-cell)
12304:
12305: @item d
12306: double-cell integer
12307:
12308: @item r
12309: floating-point value
12310:
12311: @item func
12312: C function pointer
12313:
12314: @item void
12315: no value (used as return type for void functions)
12316:
12317: @end table
12318:
12319: @cindex variadic C functions
12320:
12321: To deal with variadic C functions, you can declare one Forth word for
12322: every pattern you want to use, e.g.:
12323:
12324: @example
12325: \c #include <stdio.h>
12326: c-function printf-nr printf a n r -- n
12327: c-function printf-rn printf a r n -- n
12328: @end example
12329:
12330: Note that with C functions declared as variadic (or if you don't
12331: provide a prototype), the C interface has no C type to convert to, so
12332: no automatic conversion happens, which may lead to portability
12333: problems in some cases. In such cases you can perform the conversion
12334: explicitly on the C level, e.g., as follows:
12335:
12336: @example
1.178 anton 12337: \c #define printfll(s,ll) printf(s,(long long)ll)
12338: c-function printfll printfll a n -- n
1.177 anton 12339: @end example
12340:
12341: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12342: that casts (converts) the Forth single-cell integer into a
12343: C @code{long long} before calling @code{printf()}.
1.177 anton 12344:
12345: doc-\c
12346: doc-c-function
1.207 pazsan 12347: doc-c-value
12348: doc-c-variable
1.177 anton 12349:
12350: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12351: dynamic linking. If these features are not available, there are
12352: other, less convenient and less portable C interfaces in @file{lib.fs}
12353: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12354: mostly incompatible with each other and with the documented C
12355: interface; you can find some examples for the @file{lib.fs} interface
12356: in @file{lib.fs}.
1.177 anton 12357:
12358:
1.196 anton 12359: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180 anton 12360: @subsection Calling C function pointers from Forth
12361: @cindex C function pointers, calling from Forth
1.177 anton 12362:
1.180 anton 12363: If you come across a C function pointer (e.g., in some C-constructed
12364: structure) and want to call it from your Forth program, you can also
12365: use the features explained until now to achieve that, as follows:
1.150 anton 12366:
1.180 anton 12367: Let us assume that there is a C function pointer type @code{func1}
12368: defined in some header file @file{func1.h}, and you know that these
12369: functions take one integer argument and return an integer result; and
12370: you want to call functions through such pointers. Just define
1.155 anton 12371:
1.180 anton 12372: @example
12373: \c #include <func1.h>
12374: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12375: c-function call-func1 call_func1 n func -- n
12376: @end example
12377:
12378: and then you can call a function pointed to by, say @code{func1a} as
12379: follows:
12380:
12381: @example
12382: -5 func1a call-func1 .
12383: @end example
12384:
12385: In the C part, @code{call_func} is defined as a macro to avoid having
12386: to declare the exact parameter and return types, so the C compiler
12387: knows them from the declaration of @code{func1}.
12388:
12389: The Forth word @code{call-func1} is similar to @code{execute}, except
12390: that it takes a C @code{func1} pointer instead of a Forth execution
12391: token, and it is specific to @code{func1} pointers. For each type of
12392: function pointer you want to call from Forth, you have to define
12393: a separate calling word.
12394:
12395:
1.196 anton 12396: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12397: @subsection Defining library interfaces
12398: @cindex giving a name to a library interface
12399: @cindex library interface names
12400:
12401: You can give a name to a bunch of C function declarations (a library
12402: interface), as follows:
12403:
12404: @example
12405: c-library lseek-lib
12406: \c #define _FILE_OFFSET_BITS 64
12407: ...
12408: end-c-library
12409: @end example
12410:
1.202 anton 12411: The effect of giving such a name to the interface is that the names of
12412: the generated files will contain that name, and when you use the
12413: interface a second time, it will use the existing files instead of
12414: generating and compiling them again, saving you time. Note that even
12415: if you change the declarations, the old (stale) files will be used,
12416: probably leading to errors. So, during development of the
12417: declarations we recommend not using @code{c-library}. Normally these
12418: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12419: that directory you can get rid of stale files.
12420:
12421: Note that you should use @code{c-library} before everything else
12422: having anything to do with that library, as it resets some setup
12423: stuff. The idea is that the typical use is to put each
12424: @code{c-library}...@code{end-library} unit in its own file, and to be
12425: able to include these files in any order.
1.196 anton 12426:
12427: Note that the library name is not allocated in the dictionary and
12428: therefore does not shadow dictionary names. It is used in the file
12429: system, so you have to use naming conventions appropriate for file
12430: systems. Also, you must not call a function you declare after
12431: @code{c-library} before you perform @code{end-c-library}.
12432:
12433: A major benefit of these named library interfaces is that, once they
12434: are generated, the tools used to generated them (in particular, the C
12435: compiler and libtool) are no longer needed, so the interface can be
12436: used even on machines that do not have the tools installed.
12437:
12438: doc-c-library-name
12439: doc-c-library
12440: doc-end-c-library
12441:
12442:
12443: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12444: @subsection Declaring OS-level libraries
1.195 anton 12445: @cindex Shared libraries in C interface
12446: @cindex Dynamically linked libraries in C interface
12447: @cindex Libraries in C interface
12448:
1.196 anton 12449: For calling some C functions, you need to link with a specific
12450: OS-level library that contains that function. E.g., the @code{sin}
12451: function requires linking a special library by using the command line
12452: switch @code{-lm}. In our C iterface you do the equivalent thing by
12453: calling @code{add-lib} as follows:
1.195 anton 12454:
12455: @example
12456: clear-libs
12457: s" m" add-lib
12458: \c #include <math.h>
12459: c-function sin sin r -- r
12460: @end example
12461:
12462: First, you clear any libraries that may have been declared earlier
12463: (you don't need them for @code{sin}); then you add the @code{m}
12464: library (actually @code{libm.so} or somesuch) to the currently
12465: declared libraries; you can add as many as you need. Finally you
12466: declare the function as shown above. Typically you will use the same
12467: set of library declarations for many function declarations; you need
12468: to write only one set for that, right at the beginning.
12469:
1.196 anton 12470: Note that you must not call @code{clear-libs} inside
12471: @code{c-library...end-c-library}; however, @code{c-library} performs
12472: the function of @code{clear-libs}, so @code{clear-libs} is not
12473: necessary, and you usually want to put @code{add-lib} calls inside
12474: @code{c-library...end-c-library}.
12475:
1.195 anton 12476: doc-clear-libs
12477: doc-add-lib
12478:
12479:
1.196 anton 12480: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150 anton 12481: @subsection Callbacks
1.155 anton 12482: @cindex Callback functions written in Forth
12483: @cindex C function pointers to Forth words
12484:
1.177 anton 12485: Callbacks are not yet supported by the documented C interface. You
12486: can use the undocumented @file{lib.fs} interface for callbacks.
12487:
1.155 anton 12488: In some cases you have to pass a function pointer to a C function,
12489: i.e., the library wants to call back to your application (and the
12490: pointed-to function is called a callback function). You can pass the
12491: address of an existing C function (that you get with @code{lib-sym},
12492: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12493: function, you probably want to define the function as a Forth word.
12494:
12495: @c I don't understand the existing callback interface from the example - anton
12496:
1.165 anton 12497:
12498: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12499: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12500: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12501: @c > > C-Funktionsadresse auf dem TOS).
12502: @c >
12503: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12504: @c > gesehen habe, wozu das gut ist.
12505: @c
12506: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12507: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12508: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12509: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12510: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12511: @c demselben Prototyp.
12512:
12513:
1.178 anton 12514: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12515: @subsection How the C interface works
12516:
12517: The documented C interface works by generating a C code out of the
12518: declarations.
12519:
12520: In particular, for every Forth word declared with @code{c-function},
12521: it generates a wrapper function in C that takes the Forth data from
12522: the Forth stacks, and calls the target C function with these data as
12523: arguments. The C compiler then performs an implicit conversion
12524: between the Forth type from the stack, and the C type for the
12525: parameter, which is given by the C function prototype. After the C
12526: function returns, the return value is likewise implicitly converted to
12527: a Forth type and written back on the stack.
12528:
12529: The @code{\c} lines are literally included in the C code (but without
12530: the @code{\c}), and provide the necessary declarations so that the C
12531: compiler knows the C types and has enough information to perform the
12532: conversion.
12533:
12534: These wrapper functions are eventually compiled and dynamically linked
12535: into Gforth, and then they can be called.
12536:
1.195 anton 12537: The libraries added with @code{add-lib} are used in the compile
12538: command line to specify dependent libraries with @code{-l@var{lib}},
12539: causing these libraries to be dynamically linked when the wrapper
12540: function is linked.
12541:
1.177 anton 12542:
1.178 anton 12543: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12544: @subsection Low-Level C Interface Words
1.44 crook 12545:
1.155 anton 12546: doc-open-lib
12547: doc-lib-sym
1.196 anton 12548: doc-lib-error
1.177 anton 12549: doc-call-c
1.26 crook 12550:
1.78 anton 12551: @c -------------------------------------------------------------
1.150 anton 12552: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12553: @section Assembler and Code Words
12554: @cindex assembler
12555: @cindex code words
1.44 crook 12556:
1.78 anton 12557: @menu
1.221 anton 12558: * Assembler Definitions:: Definitions in assembly language
1.78 anton 12559: * Common Assembler:: Assembler Syntax
12560: * Common Disassembler::
12561: * 386 Assembler:: Deviations and special cases
1.221 anton 12562: * AMD64 Assembler::
1.78 anton 12563: * Alpha Assembler:: Deviations and special cases
12564: * MIPS assembler:: Deviations and special cases
1.161 anton 12565: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 12566: * ARM Assembler:: Deviations and special cases
1.78 anton 12567: * Other assemblers:: How to write them
12568: @end menu
1.21 crook 12569:
1.221 anton 12570: @node Assembler Definitions, Common Assembler, Assembler and Code Words, Assembler and Code Words
1.219 anton 12571: @subsection Definitions in assembly language
1.21 crook 12572:
1.219 anton 12573: Gforth provides ways to implement words in assembly language (using
12574: @code{abi-code}...@code{end-code}), and also ways to define defining
12575: words with arbitrary run-time behaviour (like @code{does>}), where
12576: (unlike @code{does>}) the behaviour is not defined in Forth, but in
12577: assembly language (with @code{;code}).
12578:
12579: However, the machine-independent nature of Gforth poses a few
12580: problems: First of all, Gforth runs on several architectures, so it
12581: can provide no standard assembler. It does provide assemblers for
12582: several of the architectures it runs on, though. Moreover, you can
12583: use a system-independent assembler in Gforth, or compile machine code
12584: directly with @code{,} and @code{c,}.
12585:
12586: Another problem is that the virtual machine registers of Gforth (the
12587: stack pointers and the virtual machine instruction pointer) depend on
12588: the installation and engine. Also, which registers are free to use
12589: also depend on the installation and engine. So any code written to
12590: run in the context of the Gforth virtual machine is essentially
12591: limited to the installation and engine it was developed for (it may
12592: run elsewhere, but you cannot rely on that).
12593:
12594: Fortunately, you can define @code{abi-code} words in Gforth that are
1.221 anton 12595: portable to any Gforth running on a platform with the same calling
12596: convention (ABI); typically this means portability to the same
1.219 anton 12597: architecture/OS combination, sometimes crossing OS boundaries).
1.44 crook 12598:
1.78 anton 12599: doc-assembler
12600: doc-init-asm
1.215 dvdkhlng 12601: doc-abi-code
1.78 anton 12602: doc-end-code
1.219 anton 12603: doc-code
1.78 anton 12604: doc-;code
12605: doc-flush-icache
1.44 crook 12606:
1.21 crook 12607:
1.219 anton 12608: If @code{flush-icache} does not work correctly, @code{abi-code} words
1.78 anton 12609: etc. will not work (reliably), either.
1.44 crook 12610:
1.219 anton 12611: The typical usage of these words can be shown most easily by analogy
12612: to the equivalent high-level defining words:
1.44 crook 12613:
1.78 anton 12614: @example
1.219 anton 12615: : foo abi-code foo
1.78 anton 12616: <high-level Forth words> <assembler>
12617: ; end-code
12618:
12619: : bar : bar
12620: <high-level Forth words> <high-level Forth words>
12621: CREATE CREATE
12622: <high-level Forth words> <high-level Forth words>
12623: DOES> ;code
12624: <high-level Forth words> <assembler>
12625: ; end-code
12626: @end example
1.21 crook 12627:
1.219 anton 12628: For using @code{abi-code}, take a look at the ABI documentation of
12629: your platform to see how the parameters are passed (so you know where
12630: you get the stack pointers) and how the return value is passed (so you
12631: know where the data stack pointer is returned). The ABI documentation
12632: also tells you which registers are saved by the caller (caller-saved),
12633: so you are free to destroy them in your code, and which registers have
12634: to be preserved by the called word (callee-saved), so you have to save
1.221 anton 12635: them before using them, and restore them afterwards. For some
12636: architectures and OSs we give short summaries of the parts of the
12637: calling convention in the appropriate sections. More
1.219 anton 12638: reverse-engineering oriented people can also find out about the
12639: passing and returning of the stack pointers through @code{see
12640: abi-call}.
12641:
12642: Most ABIs pass the parameters through registers, but some (in
1.221 anton 12643: particular the most common 386 (aka IA-32) calling conventions) pass
12644: them on the architectural stack. The common ABIs all pass the return
12645: value in a register.
12646:
12647: Other things you need to know for using @code{abi-code} is that both
12648: the data and the FP stack grow downwards (towards lower addresses) in
12649: Gforth, with @code{1 cells} size per cell, and @code{1 floats} size
12650: per FP value.
1.219 anton 12651:
12652: Here's an example of using @code{abi-code} on the 386 architecture:
12653:
12654: @example
12655: abi-code my+ ( n1 n2 -- n )
12656: 4 sp d) ax mov \ sp into return reg
12657: ax ) cx mov \ tos
12658: 4 # ax add \ update sp (pop)
1.221 anton 12659: cx ax ) add \ sec = sec+tos
1.219 anton 12660: ret \ return from my+
12661: end-code
12662: @end example
1.44 crook 12663:
1.221 anton 12664: An AMD64 variant of this example can be found in @ref{AMD64 Assembler}.
1.44 crook 12665:
1.221 anton 12666: Here's a 386 example that deals with FP values:
12667:
12668: @example
12669: abi-code my-f+ ( r1 r2 -- r )
12670: 8 sp d) cx mov \ load address of fp
12671: cx ) dx mov \ load fp
12672: .fl dx ) fld \ r2
12673: 8 # dx add \ update fp
12674: .fl dx ) fadd \ r1+r2
12675: .fl dx ) fstp \ store r
12676: dx cx ) mov \ store new fp
12677: 4 sp d) ax mov \ sp into return reg
12678: ret \ return from my-f+
12679: end-code
12680: @end example
12681:
12682:
12683: @node Common Assembler, Common Disassembler, Assembler Definitions, Assembler and Code Words
1.78 anton 12684: @subsection Common Assembler
1.44 crook 12685:
1.78 anton 12686: The assemblers in Gforth generally use a postfix syntax, i.e., the
12687: instruction name follows the operands.
1.21 crook 12688:
1.78 anton 12689: The operands are passed in the usual order (the same that is used in the
12690: manual of the architecture). Since they all are Forth words, they have
12691: to be separated by spaces; you can also use Forth words to compute the
12692: operands.
1.44 crook 12693:
1.78 anton 12694: The instruction names usually end with a @code{,}. This makes it easier
12695: to visually separate instructions if you put several of them on one
12696: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12697:
1.78 anton 12698: Registers are usually specified by number; e.g., (decimal) @code{11}
12699: specifies registers R11 and F11 on the Alpha architecture (which one,
12700: depends on the instruction). The usual names are also available, e.g.,
12701: @code{s2} for R11 on Alpha.
1.21 crook 12702:
1.78 anton 12703: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12704: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12705: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12706: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12707: conditions are specified in a way specific to each assembler.
1.1 anton 12708:
1.219 anton 12709: The rest of this section is of interest mainly for those who want to
12710: define @code{code} words (instead of the more portable @code{abi-code}
12711: words).
12712:
1.78 anton 12713: Note that the register assignments of the Gforth engine can change
12714: between Gforth versions, or even between different compilations of the
1.215 dvdkhlng 12715: same Gforth version (e.g., if you use a different GCC version). If
12716: you are using @code{CODE} instead of @code{ABI-CODE}, and you want to
12717: refer to Gforth's registers (e.g., the stack pointer or TOS), I
12718: recommend defining your own words for refering to these registers, and
1.219 anton 12719: using them later on; then you can adapt to a changed register
1.221 anton 12720: assignment.
1.1 anton 12721:
1.219 anton 12722: The most common use of these registers is to end a @code{code}
12723: definition with a dispatch to the next word (the @code{next} routine).
12724: A portable way to do this is to jump to @code{' noop >code-address}
12725: (of course, this is less efficient than integrating the @code{next}
12726: code and scheduling it well). When using @code{ABI-CODE}, you can
12727: just assemble a normal subroutine return (but make sure you return the
12728: data stack pointer).
1.1 anton 12729:
1.219 anton 12730: Another difference between Gforth versions is that the top of stack is
1.215 dvdkhlng 12731: kept in memory in @code{gforth} and, on most platforms, in a register
12732: in @code{gforth-fast}. For @code{ABI-CODE} definitions, any stack
12733: caching registers are guaranteed to be flushed to the stack, allowing
1.219 anton 12734: you to reliably access the top of stack in memory.
1.96 anton 12735:
1.78 anton 12736: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12737: @subsection Common Disassembler
1.127 anton 12738: @cindex disassembler, general
12739: @cindex gdb disassembler
1.1 anton 12740:
1.78 anton 12741: You can disassemble a @code{code} word with @code{see}
12742: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12743:
1.127 anton 12744: doc-discode
1.44 crook 12745:
1.127 anton 12746: There are two kinds of disassembler for Gforth: The Forth disassembler
12747: (available on some CPUs) and the gdb disassembler (available on
12748: platforms with @command{gdb} and @command{mktemp}). If both are
12749: available, the Forth disassembler is used by default. If you prefer
12750: the gdb disassembler, say
12751:
12752: @example
12753: ' disasm-gdb is discode
12754: @end example
12755:
12756: If neither is available, @code{discode} performs @code{dump}.
12757:
12758: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12759: assembler (i.e., same syntax, etc.). It also includes additional
12760: information in comments. In particular, the address of the instruction
12761: is given in a comment before the instruction.
1.1 anton 12762:
1.127 anton 12763: The gdb disassembler produces output in the same format as the gdb
12764: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12765: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12766: the 386 and AMD64 architectures).
12767:
1.78 anton 12768: @code{See} may display more or less than the actual code of the word,
12769: because the recognition of the end of the code is unreliable. You can
1.127 anton 12770: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12771: the code word is not immediately followed by a named word. If you have
1.116 anton 12772: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12773: to ensure that the end is recognized.
1.21 crook 12774:
1.221 anton 12775: @node 386 Assembler, AMD64 Assembler, Common Disassembler, Assembler and Code Words
1.78 anton 12776: @subsection 386 Assembler
1.44 crook 12777:
1.78 anton 12778: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12779: available under GPL, and originally part of bigFORTH.
1.21 crook 12780:
1.78 anton 12781: The 386 disassembler included in Gforth was written by Andrew McKewan
12782: and is in the public domain.
1.21 crook 12783:
1.91 anton 12784: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12785:
1.221 anton 12786: The assembler uses a postfix syntax with AT&T-style parameter order
12787: (i.e., destination last).
1.1 anton 12788:
1.78 anton 12789: The assembler includes all instruction of the Athlon, i.e. 486 core
12790: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12791: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12792: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12793:
1.78 anton 12794: There are several prefixes to switch between different operation sizes,
12795: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12796: double-word accesses. Addressing modes can be switched with @code{.wa}
12797: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12798: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12799:
1.78 anton 12800: For floating point operations, the prefixes are @code{.fs} (IEEE
12801: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
1.221 anton 12802: (word), @code{.fd} (double-word), and @code{.fq} (quad-word). The
12803: default is @code{.fx}, so you need to specify @code{.fl} explicitly
12804: when dealing with Gforth FP values.
1.21 crook 12805:
1.78 anton 12806: The MMX opcodes don't have size prefixes, they are spelled out like in
12807: the Intel assembler. Instead of move from and to memory, there are
12808: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12809:
1.78 anton 12810: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12811: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12812: e.g., @code{3 #}. Here are some examples of addressing modes in various
12813: syntaxes:
1.21 crook 12814:
1.26 crook 12815: @example
1.91 anton 12816: Gforth Intel (NASM) AT&T (gas) Name
12817: .w ax ax %ax register (16 bit)
12818: ax eax %eax register (32 bit)
12819: 3 # offset 3 $3 immediate
12820: 1000 #) byte ptr 1000 1000 displacement
12821: bx ) [ebx] (%ebx) base
12822: 100 di d) 100[edi] 100(%edi) base+displacement
12823: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12824: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12825: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12826: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12827: @end example
12828:
12829: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12830: @code{DI)} to enforce 32-bit displacement fields (useful for
12831: later patching).
1.21 crook 12832:
1.78 anton 12833: Some example of instructions are:
1.1 anton 12834:
12835: @example
1.78 anton 12836: ax bx mov \ move ebx,eax
12837: 3 # ax mov \ mov eax,3
1.137 pazsan 12838: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12839: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12840: .w ax bx mov \ mov bx,ax
1.1 anton 12841: @end example
12842:
1.78 anton 12843: The following forms are supported for binary instructions:
1.1 anton 12844:
12845: @example
1.78 anton 12846: <reg> <reg> <inst>
12847: <n> # <reg> <inst>
12848: <mem> <reg> <inst>
12849: <reg> <mem> <inst>
1.136 pazsan 12850: <n> # <mem> <inst>
1.1 anton 12851: @end example
12852:
1.136 pazsan 12853: The shift/rotate syntax is:
1.1 anton 12854:
1.26 crook 12855: @example
1.78 anton 12856: <reg/mem> 1 # shl \ shortens to shift without immediate
12857: <reg/mem> 4 # shl
12858: <reg/mem> cl shl
1.26 crook 12859: @end example
1.1 anton 12860:
1.78 anton 12861: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12862: the byte version.
1.1 anton 12863:
1.78 anton 12864: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12865: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12866: pc < >= <= >}. (Note that most of these words shadow some Forth words
12867: when @code{assembler} is in front of @code{forth} in the search path,
12868: e.g., in @code{code} words). Currently the control structure words use
12869: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12870: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12871:
1.221 anton 12872: Based on the Intel ABI (used in Linux), @code{abi-code} words can find
12873: the data stack pointer at @code{4 sp d)}, and the address of the FP
12874: stack pointer at @code{8 sp d)}; the data stack pointer is returned in
12875: @code{ax}; @code{Ax}, @code{cx}, and @code{dx} are caller-saved, so
12876: you do not need to preserve their values inside the word. You can
12877: return from the word with @code{ret}, the parameters are cleaned up by
12878: the caller.
12879:
12880: For examples of 386 @code{abi-code} words, see @ref{Assembler Definitions}.
1.21 crook 12881:
12882:
1.221 anton 12883: @node AMD64 Assembler, Alpha Assembler, 386 Assembler, Assembler and Code Words
1.220 dvdkhlng 12884: @subsection AMD64 (x86_64) Assembler
1.161 anton 12885:
1.220 dvdkhlng 12886: The AMD64 assembler is a slightly modified version of the 386
12887: assembler, and as such shares most of the syntax. Two new prefixes,
12888: @code{.q} and @code{.qa}, are provided to select 64-bit operand and
1.221 anton 12889: address sizes respectively. 64-bit sizes are the default, so normally
12890: you only have to use the other prefixes. Also there are additional
12891: register operands @code{R8}-@code{R15}.
1.220 dvdkhlng 12892:
12893: The registers lack the 'e' or 'r' prefix; even in 64 bit mode,
12894: @code{rax} is called @code{ax}. Additional register operands are
12895: available to refer to the lowest-significant byte of all registers:
12896: @code{R8L}-@code{R15L}, @code{SPL}, @code{BPL}, @code{SIL},
12897: @code{DIL}.
12898:
1.221 anton 12899: The Linux-AMD64 calling convention is to pass the first 6 integer
12900: parameters in rdi, rsi, rdx, rcx, r8 and r9 and to return the result
12901: in rax and rdx; to pass the first 8 FP parameters in xmm0--xmm7 and to
12902: return FP results in xmm0--xmm1. So @code{abi-code} words get the
12903: data stack pointer in @code{di} and the address of the FP stack
12904: pointer in @code{si}, and return the data stack pointer in @code{ax}.
12905: The other caller-saved registers are: r10, r11, xmm8-xmm15. This
1.222 anton 12906: calling convention reportedly is also used in other non-Microsoft OSs.
12907: @c source: http://en.wikipedia.org/wiki/X86_calling_conventions#AMD64_ABI_convention
12908:
12909: @c source: http://msdn.microsoft.com/en-us/library/9b372w95(v=VS.90).aspx
12910: Windows x64 passes the first four integer parameters in rcx, rdx, r8
12911: and r9 and return the integer result in rax. The other caller-saved
12912: registers are r10 and r11.
1.221 anton 12913:
1.220 dvdkhlng 12914: Here is an example of an AMD64 @code{abi-code} word:
12915:
12916: @example
12917: abi-code my+ ( n1 n2 -- n3 )
1.221 anton 12918: \ SP passed in di, returned in ax, address of FP passed in si
12919: 8 di d) ax lea \ compute new sp in result reg
12920: di ) dx mov \ get old tos
12921: dx ax ) add \ add to new tos
12922: ret
1.220 dvdkhlng 12923: end-code
12924: @end example
12925:
1.226 dvdkhlng 12926: Here's a AMD64 example that deals with FP values:
12927:
12928: @example
12929: abi-code my-f+ ( r1 r2 -- r )
12930: \ SP passed in di, returned in ax, address of FP passed in si
1.227 dvdkhlng 12931: si ) dx mov \ load fp
12932: 8 dx d) xmm0 movsd \ r2
12933: dx ) xmm0 addsd \ r1+r2
12934: xmm0 8 dx d) movsd \ store r
12935: 8 # si ) add \ update fp
12936: di ax mov \ sp into return reg
1.226 dvdkhlng 12937: ret
12938: end-code
12939: @end example
12940:
1.221 anton 12941: @node Alpha Assembler, MIPS assembler, AMD64 Assembler, Assembler and Code Words
1.78 anton 12942: @subsection Alpha Assembler
1.21 crook 12943:
1.78 anton 12944: The Alpha assembler and disassembler were originally written by Bernd
12945: Thallner.
1.26 crook 12946:
1.78 anton 12947: The register names @code{a0}--@code{a5} are not available to avoid
12948: shadowing hex numbers.
1.2 jwilke 12949:
1.78 anton 12950: Immediate forms of arithmetic instructions are distinguished by a
12951: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12952: does not count as arithmetic instruction).
1.2 jwilke 12953:
1.78 anton 12954: You have to specify all operands to an instruction, even those that
12955: other assemblers consider optional, e.g., the destination register for
12956: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12957:
1.78 anton 12958: You can specify conditions for @code{if,} by removing the first @code{b}
12959: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12960:
1.26 crook 12961: @example
1.78 anton 12962: 11 fgt if, \ if F11>0e
12963: ...
12964: endif,
1.26 crook 12965: @end example
1.2 jwilke 12966:
1.78 anton 12967: @code{fbgt,} gives @code{fgt}.
12968:
1.161 anton 12969: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12970: @subsection MIPS assembler
1.2 jwilke 12971:
1.78 anton 12972: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12973:
1.224 dvdkhlng 12974: Currently the assembler and disassembler covers most of the MIPS32
12975: architecture and doesn't support FP instructions.
1.2 jwilke 12976:
1.78 anton 12977: The register names @code{$a0}--@code{$a3} are not available to avoid
1.224 dvdkhlng 12978: shadowing hex numbers. Use register numbers @code{$4}--@code{$7}
12979: instead.
1.2 jwilke 12980:
1.224 dvdkhlng 12981: Nothing distinguishes registers from immediate values. Use explicit
12982: opcode names with the @code{i} suffix for instructions with immediate
12983: argument. E.g. @code{addiu,} in place of @code{addu,}.
12984:
12985: Where the architecture manual specifies several formats for the
12986: instruction (e.g., for @code{jalr,}),use the one with more arguments
12987: (i.e. two for @code{jalr,}). When in doubt, see
1.78 anton 12988: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12989:
1.224 dvdkhlng 12990: Branches and jumps in the MIPS architecture have a delay slot. You
12991: have to fill it manually (the simplest way is to use @code{nop,}), the
1.78 anton 12992: assembler does not do it for you (unlike @command{as}). Even
1.224 dvdkhlng 12993: @code{if,}, @code{ahead,}, @code{until,}, @code{again,},
12994: @code{while,}, @code{else,} and @code{repeat,} need a delay slot.
12995: Since @code{begin,} and @code{then,} just specify branch targets, they
12996: are not affected. For branches the argument specifying the target is
12997: a relative address. Add the address of the delay slot to get the
12998: absolute address.
12999:
13000: Note that you must not put branches nor jumps (nor control-flow
13001: instructions) into the delay slot. Also it is a bad idea to put
13002: pseudo-ops such as @code{li,} into a delay slot, as these may expand
13003: to several instructions. The MIPS I architecture also had load delay
13004: slots, and newer MIPSes still have restrictions on using @code{mfhi,}
13005: and @code{mflo,}. Be careful to satisfy these restrictions, the
13006: assembler does not do it for you.
13007:
13008: Some example of instructions are:
13009:
13010: @example
13011: $ra 12 $sp sw, \ sw ra,12(sp)
13012: $4 8 $s0 lw, \ lw a0,8(s0)
13013: $v0 $0 lui, \ lui v0,0x0
13014: $s0 $s4 $12 addiu, \ addiu s0,s4,0x12
13015: $s0 $s4 $4 addu, \ addu s0,s4,$a0
13016: $ra $t9 jalr, \ jalr t9
13017: @end example
1.1 anton 13018:
1.78 anton 13019: You can specify the conditions for @code{if,} etc. by taking a
13020: conditional branch and leaving away the @code{b} at the start and the
13021: @code{,} at the end. E.g.,
1.1 anton 13022:
1.26 crook 13023: @example
1.78 anton 13024: 4 5 eq if,
13025: ... \ do something if $4 equals $5
13026: then,
1.26 crook 13027: @end example
1.1 anton 13028:
1.223 dvdkhlng 13029: The calling conventions for 32-bit MIPS machines is to pass the first
13030: 4 arguments in registers @code{$4}..@code{$7}, and to use
13031: @code{$v0}-@code{$v1} for return values. In addition to these
13032: registers, it is ok to clobber registers @code{$t0}-@code{$t8} without
13033: saving and restoring them.
13034:
13035: If you use @code{jalr,} to call into dynamic library routines, you
13036: must first load the called function's address into @code{$t9}, which
13037: is used by position-indirect code to do relative memory accesses.
13038:
13039: Here is an example of a MIPS32 @code{abi-code} word:
13040:
13041: @example
13042: abi-code my+ ( n1 n2 -- n3 )
13043: \ SP passed in $4, returned in $v0
1.225 dvdkhlng 13044: $t0 4 $4 lw, \ load n1, n2 from stack
13045: $t1 0 $4 lw,
1.223 dvdkhlng 13046: $t0 $t0 $t1 addu, \ add n1+n2, result in $t0
13047: $t0 4 $4 sw, \ store result (overwriting n1)
13048: $ra jr, \ return to caller
13049: $v0 $4 4 addiu, \ (delay slot) return uptated SP in $v0
13050: end-code
13051: @end example
1.161 anton 13052:
1.193 dvdkhlng 13053: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161 anton 13054: @subsection PowerPC assembler
13055:
1.162 anton 13056: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 13057: Revucky.
13058:
1.162 anton 13059: This assembler does not follow the convention of ending mnemonic names
13060: with a ``,'', so some mnemonic names shadow regular Forth words (in
13061: particular: @code{and or xor fabs}); so if you want to use the Forth
13062: words, you have to make them visible first, e.g., with @code{also
13063: forth}.
13064:
1.161 anton 13065: Registers are referred to by their number, e.g., @code{9} means the
13066: integer register 9 or the FP register 9 (depending on the
13067: instruction).
13068:
13069: Because there is no way to distinguish registers from immediate values,
13070: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 13071: @code{addi,}, not just @code{add,}.
1.161 anton 13072:
1.162 anton 13073: The assembler and disassembler usually support the most general form
1.161 anton 13074: of an instruction, but usually not the shorter forms (especially for
13075: branches).
13076:
13077:
1.193 dvdkhlng 13078: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
13079: @subsection ARM Assembler
1.161 anton 13080:
1.215 dvdkhlng 13081: The ARM assembler includes all instruction of ARM architecture version
13082: 4, and the BLX instruction from architecture 5. It does not (yet)
13083: have support for Thumb instructions. It also lacks support for any
13084: co-processors.
13085:
13086: The assembler uses a postfix syntax with the same operand order as
13087: used in the ARM Architecture Reference Manual. Mnemonics are suffixed
13088: by a comma.
1.193 dvdkhlng 13089:
13090: Registers are specified by their names @code{r0} through @code{r15},
13091: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
1.215 dvdkhlng 13092: @code{fp} provided for convenience. Note that @code{ip} refers to
13093: the``intra procedure call scratch register'' (@code{r12}) and does not
13094: refer to an instruction pointer. @code{sp} refers to the ARM ABI
13095: stack pointer (@code{r13}) and not the Forth stack pointer.
1.193 dvdkhlng 13096:
13097: Condition codes can be specified anywhere in the instruction, but will
13098: be most readable if specified just in front of the mnemonic. The 'S'
13099: flag is not a separate word, but encoded into instruction mnemonics,
13100: ie. just use @code{adds,} instead of @code{add,} if you want the
13101: status register to be updated.
13102:
13103: The following table lists the syntax of operands for general
13104: instructions:
13105:
13106: @example
13107: Gforth normal assembler description
13108: 123 # #123 immediate
13109: r12 r12 register
13110: r12 4 #LSL r12, LSL #4 shift left by immediate
13111: r12 r1 #LSL r12, LSL r1 shift left by register
13112: r12 4 #LSR r12, LSR #4 shift right by immediate
13113: r12 r1 #LSR r12, LSR r1 shift right by register
13114: r12 4 #ASR r12, ASR #4 arithmetic shift right
13115: r12 r1 #ASR r12, ASR r1 ... by register
13116: r12 4 #ROR r12, ROR #4 rotate right by immediate
13117: r12 r1 #ROR r12, ROR r1 ... by register
13118: r12 RRX r12, RRX rotate right with extend by 1
13119: @end example
13120:
13121: Memory operand syntax is listed in this table:
13122:
13123: @example
13124: Gforth normal assembler description
13125: r4 ] [r4] register
13126: r4 4 #] [r4, #+4] register with immediate offset
13127: r4 -4 #] [r4, #-4] with negative offset
13128: r4 r1 +] [r4, +r1] register with register offset
13129: r4 r1 -] [r4, -r1] with negated register offset
13130: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
13131: r4 4 #]! [r4, #+4]! immediate preincrement
13132: r4 r1 +]! [r4, +r1]! register preincrement
13133: r4 r1 -]! [r4, +r1]! register predecrement
13134: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
13135: r4 -4 ]# [r4], #-4 immediate postdecrement
13136: r4 r1 ]+ [r4], r1 register postincrement
13137: r4 r1 ]- [r4], -r1 register postdecrement
13138: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
13139: ' xyz >body [#] xyz PC-relative addressing
13140: @end example
13141:
13142: Register lists for load/store multiple instructions are started and
1.220 dvdkhlng 13143: terminated by using the words @code{@{} and @code{@}} respectively.
1.215 dvdkhlng 13144: Between braces, register names can be listed one by one or register
13145: ranges can be formed by using the postfix operator @code{r-r}. The
13146: @code{^} flag is not encoded in the register list operand, but instead
13147: directly encoded into the instruction mnemonic, ie. use @code{^ldm,}
13148: and @code{^stm,}.
1.193 dvdkhlng 13149:
13150: Addressing modes for load/store multiple are not encoded as
1.216 dvdkhlng 13151: instruction suffixes, but instead specified like an addressing mode,
13152: Use one of @code{DA}, @code{IA}, @code{DB}, @code{IB}, @code{DA!},
13153: @code{IA!}, @code{DB!} or @code{IB!}.
1.193 dvdkhlng 13154:
13155: The following table gives some examples:
13156:
13157: @example
13158: Gforth normal assembler
1.216 dvdkhlng 13159: r4 ia @{ r0 r7 r8 @} stm, stmia r4, @{r0,r7,r8@}
13160: r4 db! @{ r0 r7 r8 @} ldm, ldmdb r4!, @{r0,r7,r8@}
13161: sp ia! @{ r0 r15 r-r @} ^ldm, ldmfd sp!, @{r0-r15@}^
1.193 dvdkhlng 13162: @end example
13163:
1.215 dvdkhlng 13164: Control structure words typical for Forth assemblers are available:
13165: @code{if,} @code{ahead,} @code{then,} @code{else,} @code{begin,}
13166: @code{until,} @code{again,} @code{while,} @code{repeat,}
13167: @code{repeat-until,}. Conditions are specified in front of these words:
1.193 dvdkhlng 13168:
13169: @example
13170: r1 r2 cmp, \ compare r1 and r2
13171: eq if, \ equal?
13172: ... \ code executed if r1 == r2
13173: then,
13174: @end example
13175:
1.215 dvdkhlng 13176: Example of a definition using the ARM assembler:
1.193 dvdkhlng 13177:
13178: @example
1.215 dvdkhlng 13179: abi-code my+ ( n1 n2 -- n3 )
1.220 dvdkhlng 13180: \ arm abi: r0=SP, r1=&FP, r2,r3,r12 saved by caller
13181: r0 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
13182: r3 r2 r3 add, \ r3 = n1+n1
13183: r3 r0 -4 #]! str, \ push r3
13184: pc lr mov, \ return to caller, new SP in r0
1.193 dvdkhlng 13185: end-code
13186: @end example
13187:
13188: @node Other assemblers, , ARM Assembler, Assembler and Code Words
1.78 anton 13189: @subsection Other assemblers
13190:
13191: If you want to contribute another assembler/disassembler, please contact
1.103 anton 13192: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13193: an assembler already. If you are writing them from scratch, please use
13194: a similar syntax style as the one we use (i.e., postfix, commas at the
13195: end of the instruction names, @pxref{Common Assembler}); make the output
13196: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 13197: similar to the style we used.
13198:
13199: Hints on implementation: The most important part is to have a good test
13200: suite that contains all instructions. Once you have that, the rest is
13201: easy. For actual coding you can take a look at
13202: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13203: the assembler and disassembler, avoiding redundancy and some potential
13204: bugs. You can also look at that file (and @pxref{Advanced does> usage
13205: example}) to get ideas how to factor a disassembler.
13206:
13207: Start with the disassembler, because it's easier to reuse data from the
13208: disassembler for the assembler than the other way round.
1.1 anton 13209:
1.78 anton 13210: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13211: how simple it can be.
1.1 anton 13212:
1.161 anton 13213:
13214:
13215:
1.78 anton 13216: @c -------------------------------------------------------------
13217: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13218: @section Threading Words
13219: @cindex threading words
1.1 anton 13220:
1.78 anton 13221: @cindex code address
13222: These words provide access to code addresses and other threading stuff
13223: in Gforth (and, possibly, other interpretive Forths). It more or less
13224: abstracts away the differences between direct and indirect threading
13225: (and, for direct threading, the machine dependences). However, at
13226: present this wordset is still incomplete. It is also pretty low-level;
13227: some day it will hopefully be made unnecessary by an internals wordset
13228: that abstracts implementation details away completely.
1.1 anton 13229:
1.78 anton 13230: The terminology used here stems from indirect threaded Forth systems; in
13231: such a system, the XT of a word is represented by the CFA (code field
13232: address) of a word; the CFA points to a cell that contains the code
13233: address. The code address is the address of some machine code that
13234: performs the run-time action of invoking the word (e.g., the
13235: @code{dovar:} routine pushes the address of the body of the word (a
13236: variable) on the stack
13237: ).
1.1 anton 13238:
1.78 anton 13239: @cindex code address
13240: @cindex code field address
13241: In an indirect threaded Forth, you can get the code address of @i{name}
13242: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13243: >code-address}, independent of the threading method.
1.1 anton 13244:
1.78 anton 13245: doc-threading-method
13246: doc->code-address
13247: doc-code-address!
1.1 anton 13248:
1.78 anton 13249: @cindex @code{does>}-handler
13250: @cindex @code{does>}-code
13251: For a word defined with @code{DOES>}, the code address usually points to
13252: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13253: routine (in Gforth on some platforms, it can also point to the dodoes
13254: routine itself). What you are typically interested in, though, is
13255: whether a word is a @code{DOES>}-defined word, and what Forth code it
13256: executes; @code{>does-code} tells you that.
1.1 anton 13257:
1.78 anton 13258: doc->does-code
1.1 anton 13259:
1.78 anton 13260: To create a @code{DOES>}-defined word with the following basic words,
13261: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13262: @code{/does-handler} aus behind you have to place your executable Forth
13263: code. Finally you have to create a word and modify its behaviour with
13264: @code{does-handler!}.
1.1 anton 13265:
1.78 anton 13266: doc-does-code!
13267: doc-does-handler!
13268: doc-/does-handler
1.1 anton 13269:
1.78 anton 13270: The code addresses produced by various defining words are produced by
13271: the following words:
1.1 anton 13272:
1.78 anton 13273: doc-docol:
13274: doc-docon:
13275: doc-dovar:
13276: doc-douser:
13277: doc-dodefer:
13278: doc-dofield:
1.1 anton 13279:
1.99 anton 13280: @cindex definer
13281: The following two words generalize @code{>code-address},
13282: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13283:
13284: doc->definer
13285: doc-definer!
13286:
1.26 crook 13287: @c -------------------------------------------------------------
1.78 anton 13288: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 13289: @section Passing Commands to the Operating System
13290: @cindex operating system - passing commands
13291: @cindex shell commands
13292:
13293: Gforth allows you to pass an arbitrary string to the host operating
13294: system shell (if such a thing exists) for execution.
13295:
13296: doc-sh
13297: doc-system
13298: doc-$?
1.23 crook 13299: doc-getenv
1.44 crook 13300:
1.26 crook 13301: @c -------------------------------------------------------------
1.47 crook 13302: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13303: @section Keeping track of Time
13304: @cindex time-related words
13305:
13306: doc-ms
13307: doc-time&date
1.79 anton 13308: doc-utime
13309: doc-cputime
1.47 crook 13310:
13311:
13312: @c -------------------------------------------------------------
13313: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 13314: @section Miscellaneous Words
13315: @cindex miscellaneous words
13316:
1.29 crook 13317: @comment TODO find homes for these
13318:
1.26 crook 13319: These section lists the ANS Forth words that are not documented
1.21 crook 13320: elsewhere in this manual. Ultimately, they all need proper homes.
13321:
1.68 anton 13322: doc-quit
1.44 crook 13323:
1.26 crook 13324: The following ANS Forth words are not currently supported by Gforth
1.27 crook 13325: (@pxref{ANS conformance}):
1.21 crook 13326:
13327: @code{EDITOR}
13328: @code{EMIT?}
13329: @code{FORGET}
13330:
1.24 anton 13331: @c ******************************************************************
13332: @node Error messages, Tools, Words, Top
13333: @chapter Error messages
13334: @cindex error messages
13335: @cindex backtrace
13336:
13337: A typical Gforth error message looks like this:
13338:
13339: @example
1.86 anton 13340: in file included from \evaluated string/:-1
1.24 anton 13341: in file included from ./yyy.fs:1
13342: ./xxx.fs:4: Invalid memory address
1.134 anton 13343: >>>bar<<<
1.79 anton 13344: Backtrace:
1.25 anton 13345: $400E664C @@
13346: $400E6664 foo
1.24 anton 13347: @end example
13348:
13349: The message identifying the error is @code{Invalid memory address}. The
13350: error happened when text-interpreting line 4 of the file
13351: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13352: word on the line where the error happened, is pointed out (with
1.134 anton 13353: @code{>>>} and @code{<<<}).
1.24 anton 13354:
13355: The file containing the error was included in line 1 of @file{./yyy.fs},
13356: and @file{yyy.fs} was included from a non-file (in this case, by giving
13357: @file{yyy.fs} as command-line parameter to Gforth).
13358:
13359: At the end of the error message you find a return stack dump that can be
13360: interpreted as a backtrace (possibly empty). On top you find the top of
13361: the return stack when the @code{throw} happened, and at the bottom you
13362: find the return stack entry just above the return stack of the topmost
13363: text interpreter.
13364:
13365: To the right of most return stack entries you see a guess for the word
13366: that pushed that return stack entry as its return address. This gives a
13367: backtrace. In our case we see that @code{bar} called @code{foo}, and
13368: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13369: address} exception).
13370:
13371: Note that the backtrace is not perfect: We don't know which return stack
13372: entries are return addresses (so we may get false positives); and in
13373: some cases (e.g., for @code{abort"}) we cannot determine from the return
13374: address the word that pushed the return address, so for some return
13375: addresses you see no names in the return stack dump.
1.25 anton 13376:
13377: @cindex @code{catch} and backtraces
13378: The return stack dump represents the return stack at the time when a
13379: specific @code{throw} was executed. In programs that make use of
13380: @code{catch}, it is not necessarily clear which @code{throw} should be
13381: used for the return stack dump (e.g., consider one @code{throw} that
13382: indicates an error, which is caught, and during recovery another error
1.160 anton 13383: happens; which @code{throw} should be used for the stack dump?).
13384: Gforth presents the return stack dump for the first @code{throw} after
13385: the last executed (not returned-to) @code{catch} or @code{nothrow};
13386: this works well in the usual case. To get the right backtrace, you
13387: usually want to insert @code{nothrow} or @code{['] false catch drop}
13388: after a @code{catch} if the error is not rethrown.
1.25 anton 13389:
13390: @cindex @code{gforth-fast} and backtraces
13391: @cindex @code{gforth-fast}, difference from @code{gforth}
13392: @cindex backtraces with @code{gforth-fast}
13393: @cindex return stack dump with @code{gforth-fast}
1.79 anton 13394: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 13395: from primitives (e.g., invalid memory address, stack empty etc.);
13396: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 13397: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 13398: exception caused by a primitive in @code{gforth-fast}, you will
13399: typically see no return stack dump at all; however, if the exception is
13400: caught by @code{catch} (e.g., for restoring some state), and then
13401: @code{throw}n again, the return stack dump will be for the first such
13402: @code{throw}.
1.2 jwilke 13403:
1.5 anton 13404: @c ******************************************************************
1.24 anton 13405: @node Tools, ANS conformance, Error messages, Top
1.1 anton 13406: @chapter Tools
13407:
13408: @menu
13409: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 13410: * Stack depth changes:: Where does this stack item come from?
1.1 anton 13411: @end menu
13412:
13413: See also @ref{Emacs and Gforth}.
13414:
1.126 pazsan 13415: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 13416: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13417: @cindex @file{ans-report.fs}
13418: @cindex report the words used in your program
13419: @cindex words used in your program
13420:
13421: If you want to label a Forth program as ANS Forth Program, you must
13422: document which wordsets the program uses; for extension wordsets, it is
13423: helpful to list the words the program requires from these wordsets
13424: (because Forth systems are allowed to provide only some words of them).
13425:
13426: The @file{ans-report.fs} tool makes it easy for you to determine which
13427: words from which wordset and which non-ANS words your application
13428: uses. You simply have to include @file{ans-report.fs} before loading the
13429: program you want to check. After loading your program, you can get the
13430: report with @code{print-ans-report}. A typical use is to run this as
13431: batch job like this:
13432: @example
13433: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13434: @end example
13435:
13436: The output looks like this (for @file{compat/control.fs}):
13437: @example
13438: The program uses the following words
13439: from CORE :
13440: : POSTPONE THEN ; immediate ?dup IF 0=
13441: from BLOCK-EXT :
13442: \
13443: from FILE :
13444: (
13445: @end example
13446:
13447: @subsection Caveats
13448:
13449: Note that @file{ans-report.fs} just checks which words are used, not whether
13450: they are used in an ANS Forth conforming way!
13451:
13452: Some words are defined in several wordsets in the
13453: standard. @file{ans-report.fs} reports them for only one of the
13454: wordsets, and not necessarily the one you expect. It depends on usage
13455: which wordset is the right one to specify. E.g., if you only use the
13456: compilation semantics of @code{S"}, it is a Core word; if you also use
13457: its interpretation semantics, it is a File word.
1.124 anton 13458:
13459:
1.127 anton 13460: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13461: @section Stack depth changes during interpretation
13462: @cindex @file{depth-changes.fs}
13463: @cindex depth changes during interpretation
13464: @cindex stack depth changes during interpretation
13465: @cindex items on the stack after interpretation
13466:
13467: Sometimes you notice that, after loading a file, there are items left
13468: on the stack. The tool @file{depth-changes.fs} helps you find out
13469: quickly where in the file these stack items are coming from.
13470:
13471: The simplest way of using @file{depth-changes.fs} is to include it
13472: before the file(s) you want to check, e.g.:
13473:
13474: @example
13475: gforth depth-changes.fs my-file.fs
13476: @end example
13477:
13478: This will compare the stack depths of the data and FP stack at every
13479: empty line (in interpretation state) against these depths at the last
13480: empty line (in interpretation state). If the depths are not equal,
13481: the position in the file and the stack contents are printed with
13482: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13483: change has occured in the paragraph of non-empty lines before the
13484: indicated line. It is a good idea to leave an empty line at the end
13485: of the file, so the last paragraph is checked, too.
13486:
13487: Checking only at empty lines usually works well, but sometimes you
13488: have big blocks of non-empty lines (e.g., when building a big table),
13489: and you want to know where in this block the stack depth changed. You
13490: can check all interpreted lines with
13491:
13492: @example
13493: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13494: @end example
13495:
13496: This checks the stack depth at every end-of-line. So the depth change
13497: occured in the line reported by the @code{~~} (not in the line
13498: before).
13499:
13500: Note that, while this offers better accuracy in indicating where the
13501: stack depth changes, it will often report many intentional stack depth
13502: changes (e.g., when an interpreted computation stretches across
13503: several lines). You can suppress the checking of some lines by
13504: putting backslashes at the end of these lines (not followed by white
13505: space), and using
13506:
13507: @example
13508: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13509: @end example
1.1 anton 13510:
13511: @c ******************************************************************
1.65 anton 13512: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13513: @chapter ANS conformance
13514: @cindex ANS conformance of Gforth
13515:
13516: To the best of our knowledge, Gforth is an
13517:
13518: ANS Forth System
13519: @itemize @bullet
13520: @item providing the Core Extensions word set
13521: @item providing the Block word set
13522: @item providing the Block Extensions word set
13523: @item providing the Double-Number word set
13524: @item providing the Double-Number Extensions word set
13525: @item providing the Exception word set
13526: @item providing the Exception Extensions word set
13527: @item providing the Facility word set
1.40 anton 13528: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13529: @item providing the File Access word set
13530: @item providing the File Access Extensions word set
13531: @item providing the Floating-Point word set
13532: @item providing the Floating-Point Extensions word set
13533: @item providing the Locals word set
13534: @item providing the Locals Extensions word set
13535: @item providing the Memory-Allocation word set
13536: @item providing the Memory-Allocation Extensions word set (that one's easy)
13537: @item providing the Programming-Tools word set
13538: @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
13539: @item providing the Search-Order word set
13540: @item providing the Search-Order Extensions word set
13541: @item providing the String word set
13542: @item providing the String Extensions word set (another easy one)
13543: @end itemize
13544:
1.118 anton 13545: Gforth has the following environmental restrictions:
13546:
13547: @cindex environmental restrictions
13548: @itemize @bullet
13549: @item
13550: While processing the OS command line, if an exception is not caught,
13551: Gforth exits with a non-zero exit code instyead of performing QUIT.
13552:
13553: @item
13554: When an @code{throw} is performed after a @code{query}, Gforth does not
13555: allways restore the input source specification in effect at the
13556: corresponding catch.
13557:
13558: @end itemize
13559:
13560:
1.1 anton 13561: @cindex system documentation
13562: In addition, ANS Forth systems are required to document certain
13563: implementation choices. This chapter tries to meet these
13564: requirements. In many cases it gives a way to ask the system for the
13565: information instead of providing the information directly, in
13566: particular, if the information depends on the processor, the operating
13567: system or the installation options chosen, or if they are likely to
13568: change during the maintenance of Gforth.
13569:
13570: @comment The framework for the rest has been taken from pfe.
13571:
13572: @menu
13573: * The Core Words::
13574: * The optional Block word set::
13575: * The optional Double Number word set::
13576: * The optional Exception word set::
13577: * The optional Facility word set::
13578: * The optional File-Access word set::
13579: * The optional Floating-Point word set::
13580: * The optional Locals word set::
13581: * The optional Memory-Allocation word set::
13582: * The optional Programming-Tools word set::
13583: * The optional Search-Order word set::
13584: @end menu
13585:
13586:
13587: @c =====================================================================
13588: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13589: @comment node-name, next, previous, up
13590: @section The Core Words
13591: @c =====================================================================
13592: @cindex core words, system documentation
13593: @cindex system documentation, core words
13594:
13595: @menu
13596: * core-idef:: Implementation Defined Options
13597: * core-ambcond:: Ambiguous Conditions
13598: * core-other:: Other System Documentation
13599: @end menu
13600:
13601: @c ---------------------------------------------------------------------
13602: @node core-idef, core-ambcond, The Core Words, The Core Words
13603: @subsection Implementation Defined Options
13604: @c ---------------------------------------------------------------------
13605: @cindex core words, implementation-defined options
13606: @cindex implementation-defined options, core words
13607:
13608:
13609: @table @i
13610: @item (Cell) aligned addresses:
13611: @cindex cell-aligned addresses
13612: @cindex aligned addresses
13613: processor-dependent. Gforth's alignment words perform natural alignment
13614: (e.g., an address aligned for a datum of size 8 is divisible by
13615: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13616:
13617: @item @code{EMIT} and non-graphic characters:
13618: @cindex @code{EMIT} and non-graphic characters
13619: @cindex non-graphic characters and @code{EMIT}
13620: The character is output using the C library function (actually, macro)
13621: @code{putc}.
13622:
13623: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13624: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13625: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13626: @cindex @code{ACCEPT}, editing
13627: @cindex @code{EXPECT}, editing
13628: This is modeled on the GNU readline library (@pxref{Readline
13629: Interaction, , Command Line Editing, readline, The GNU Readline
13630: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13631: producing a full word completion every time you type it (instead of
1.28 crook 13632: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13633:
13634: @item character set:
13635: @cindex character set
13636: The character set of your computer and display device. Gforth is
13637: 8-bit-clean (but some other component in your system may make trouble).
13638:
13639: @item Character-aligned address requirements:
13640: @cindex character-aligned address requirements
13641: installation-dependent. Currently a character is represented by a C
13642: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13643: (Comments on that requested).
13644:
13645: @item character-set extensions and matching of names:
13646: @cindex character-set extensions and matching of names
1.26 crook 13647: @cindex case-sensitivity for name lookup
13648: @cindex name lookup, case-sensitivity
13649: @cindex locale and case-sensitivity
1.21 crook 13650: Any character except the ASCII NUL character can be used in a
1.1 anton 13651: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13652: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13653: function is probably influenced by the locale. E.g., the @code{C} locale
13654: does not know about accents and umlauts, so they are matched
13655: case-sensitively in that locale. For portability reasons it is best to
13656: write programs such that they work in the @code{C} locale. Then one can
13657: use libraries written by a Polish programmer (who might use words
13658: containing ISO Latin-2 encoded characters) and by a French programmer
13659: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13660: funny results for some of the words (which ones, depends on the font you
13661: are using)). Also, the locale you prefer may not be available in other
13662: operating systems. Hopefully, Unicode will solve these problems one day.
13663:
13664: @item conditions under which control characters match a space delimiter:
13665: @cindex space delimiters
13666: @cindex control characters as delimiters
1.117 anton 13667: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13668: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13669: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13670: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13671: interpreter (aka text interpreter) by default, treats all white-space
13672: characters as delimiters.
13673:
1.26 crook 13674: @item format of the control-flow stack:
13675: @cindex control-flow stack, format
13676: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13677: stack item in cells is given by the constant @code{cs-item-size}. At the
13678: time of this writing, an item consists of a (pointer to a) locals list
13679: (third), an address in the code (second), and a tag for identifying the
13680: item (TOS). The following tags are used: @code{defstart},
13681: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13682: @code{scopestart}.
13683:
13684: @item conversion of digits > 35
13685: @cindex digits > 35
13686: The characters @code{[\]^_'} are the digits with the decimal value
13687: 36@minus{}41. There is no way to input many of the larger digits.
13688:
13689: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13690: @cindex @code{EXPECT}, display after end of input
13691: @cindex @code{ACCEPT}, display after end of input
13692: The cursor is moved to the end of the entered string. If the input is
13693: terminated using the @kbd{Return} key, a space is typed.
13694:
13695: @item exception abort sequence of @code{ABORT"}:
13696: @cindex exception abort sequence of @code{ABORT"}
13697: @cindex @code{ABORT"}, exception abort sequence
13698: The error string is stored into the variable @code{"error} and a
13699: @code{-2 throw} is performed.
13700:
13701: @item input line terminator:
13702: @cindex input line terminator
13703: @cindex line terminator on input
1.26 crook 13704: @cindex newline character on input
1.1 anton 13705: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13706: lines. One of these characters is typically produced when you type the
13707: @kbd{Enter} or @kbd{Return} key.
13708:
13709: @item maximum size of a counted string:
13710: @cindex maximum size of a counted string
13711: @cindex counted string, maximum size
13712: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13713: on all platforms, but this may change.
1.1 anton 13714:
13715: @item maximum size of a parsed string:
13716: @cindex maximum size of a parsed string
13717: @cindex parsed string, maximum size
13718: Given by the constant @code{/line}. Currently 255 characters.
13719:
13720: @item maximum size of a definition name, in characters:
13721: @cindex maximum size of a definition name, in characters
13722: @cindex name, maximum length
1.113 anton 13723: MAXU/8
1.1 anton 13724:
13725: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13726: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13727: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13728: MAXU/8
1.1 anton 13729:
13730: @item method of selecting the user input device:
13731: @cindex user input device, method of selecting
13732: The user input device is the standard input. There is currently no way to
13733: change it from within Gforth. However, the input can typically be
13734: redirected in the command line that starts Gforth.
13735:
13736: @item method of selecting the user output device:
13737: @cindex user output device, method of selecting
13738: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13739: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13740: output when the user output device is a terminal, otherwise the output
13741: is buffered.
1.1 anton 13742:
13743: @item methods of dictionary compilation:
13744: What are we expected to document here?
13745:
13746: @item number of bits in one address unit:
13747: @cindex number of bits in one address unit
13748: @cindex address unit, size in bits
13749: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13750: platforms.
1.1 anton 13751:
13752: @item number representation and arithmetic:
13753: @cindex number representation and arithmetic
1.79 anton 13754: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13755:
13756: @item ranges for integer types:
13757: @cindex ranges for integer types
13758: @cindex integer types, ranges
13759: Installation-dependent. Make environmental queries for @code{MAX-N},
13760: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13761: unsigned (and positive) types is 0. The lower bound for signed types on
13762: two's complement and one's complement machines machines can be computed
13763: by adding 1 to the upper bound.
13764:
13765: @item read-only data space regions:
13766: @cindex read-only data space regions
13767: @cindex data-space, read-only regions
13768: The whole Forth data space is writable.
13769:
13770: @item size of buffer at @code{WORD}:
13771: @cindex size of buffer at @code{WORD}
13772: @cindex @code{WORD} buffer size
13773: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13774: shared with the pictured numeric output string. If overwriting
13775: @code{PAD} is acceptable, it is as large as the remaining dictionary
13776: space, although only as much can be sensibly used as fits in a counted
13777: string.
13778:
13779: @item size of one cell in address units:
13780: @cindex cell size
13781: @code{1 cells .}.
13782:
13783: @item size of one character in address units:
13784: @cindex char size
1.79 anton 13785: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13786:
13787: @item size of the keyboard terminal buffer:
13788: @cindex size of the keyboard terminal buffer
13789: @cindex terminal buffer, size
13790: Varies. You can determine the size at a specific time using @code{lp@@
13791: tib - .}. It is shared with the locals stack and TIBs of files that
13792: include the current file. You can change the amount of space for TIBs
13793: and locals stack at Gforth startup with the command line option
13794: @code{-l}.
13795:
13796: @item size of the pictured numeric output buffer:
13797: @cindex size of the pictured numeric output buffer
13798: @cindex pictured numeric output buffer, size
13799: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13800: shared with @code{WORD}.
13801:
13802: @item size of the scratch area returned by @code{PAD}:
13803: @cindex size of the scratch area returned by @code{PAD}
13804: @cindex @code{PAD} size
13805: The remainder of dictionary space. @code{unused pad here - - .}.
13806:
13807: @item system case-sensitivity characteristics:
13808: @cindex case-sensitivity characteristics
1.26 crook 13809: Dictionary searches are case-insensitive (except in
1.1 anton 13810: @code{TABLE}s). However, as explained above under @i{character-set
13811: extensions}, the matching for non-ASCII characters is determined by the
13812: locale you are using. In the default @code{C} locale all non-ASCII
13813: characters are matched case-sensitively.
13814:
13815: @item system prompt:
13816: @cindex system prompt
13817: @cindex prompt
13818: @code{ ok} in interpret state, @code{ compiled} in compile state.
13819:
13820: @item division rounding:
13821: @cindex division rounding
1.166 anton 13822: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13823: division (with the default installation of Gforth). You can check
13824: this with @code{s" floored" environment? drop .}. If you write
13825: programs that need a specific division rounding, best use
13826: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13827:
13828: @item values of @code{STATE} when true:
13829: @cindex @code{STATE} values
13830: -1.
13831:
13832: @item values returned after arithmetic overflow:
13833: On two's complement machines, arithmetic is performed modulo
13834: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13835: arithmetic (with appropriate mapping for signed types). Division by
13836: zero typically results in a @code{-55 throw} (Floating-point
13837: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13838: division overflow can result in these throws, or in @code{-11 throw};
13839: in @code{gforth-fast} division overflow and divide by zero may also
13840: result in returning bogus results without producing an exception.
1.1 anton 13841:
13842: @item whether the current definition can be found after @t{DOES>}:
13843: @cindex @t{DOES>}, visibility of current definition
13844: No.
13845:
13846: @end table
13847:
13848: @c ---------------------------------------------------------------------
13849: @node core-ambcond, core-other, core-idef, The Core Words
13850: @subsection Ambiguous conditions
13851: @c ---------------------------------------------------------------------
13852: @cindex core words, ambiguous conditions
13853: @cindex ambiguous conditions, core words
13854:
13855: @table @i
13856:
13857: @item a name is neither a word nor a number:
13858: @cindex name not found
1.26 crook 13859: @cindex undefined word
1.80 anton 13860: @code{-13 throw} (Undefined word).
1.1 anton 13861:
13862: @item a definition name exceeds the maximum length allowed:
1.26 crook 13863: @cindex word name too long
1.1 anton 13864: @code{-19 throw} (Word name too long)
13865:
13866: @item addressing a region not inside the various data spaces of the forth system:
13867: @cindex Invalid memory address
1.32 anton 13868: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13869: typically readable. Accessing other addresses gives results dependent on
13870: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13871: address).
13872:
13873: @item argument type incompatible with parameter:
1.26 crook 13874: @cindex argument type mismatch
1.1 anton 13875: This is usually not caught. Some words perform checks, e.g., the control
13876: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13877: mismatch).
13878:
13879: @item attempting to obtain the execution token of a word with undefined execution semantics:
13880: @cindex Interpreting a compile-only word, for @code{'} etc.
13881: @cindex execution token of words with undefined execution semantics
13882: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13883: get an execution token for @code{compile-only-error} (which performs a
13884: @code{-14 throw} when executed).
13885:
13886: @item dividing by zero:
13887: @cindex dividing by zero
13888: @cindex floating point unidentified fault, integer division
1.80 anton 13889: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13890: zero); on other systems, this typically results in a @code{-55 throw}
13891: (Floating-point unidentified fault).
1.1 anton 13892:
13893: @item insufficient data stack or return stack space:
13894: @cindex insufficient data stack or return stack space
13895: @cindex stack overflow
1.26 crook 13896: @cindex address alignment exception, stack overflow
1.1 anton 13897: @cindex Invalid memory address, stack overflow
13898: Depending on the operating system, the installation, and the invocation
13899: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13900: it is not checked. If it is checked, you typically get a @code{-3 throw}
13901: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13902: throw} (Invalid memory address) (depending on the platform and how you
13903: achieved the overflow) as soon as the overflow happens. If it is not
13904: checked, overflows typically result in mysterious illegal memory
13905: accesses, producing @code{-9 throw} (Invalid memory address) or
13906: @code{-23 throw} (Address alignment exception); they might also destroy
13907: the internal data structure of @code{ALLOCATE} and friends, resulting in
13908: various errors in these words.
1.1 anton 13909:
13910: @item insufficient space for loop control parameters:
13911: @cindex insufficient space for loop control parameters
1.80 anton 13912: Like other return stack overflows.
1.1 anton 13913:
13914: @item insufficient space in the dictionary:
13915: @cindex insufficient space in the dictionary
13916: @cindex dictionary overflow
1.12 anton 13917: If you try to allot (either directly with @code{allot}, or indirectly
13918: with @code{,}, @code{create} etc.) more memory than available in the
13919: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13920: to access memory beyond the end of the dictionary, the results are
13921: similar to stack overflows.
1.1 anton 13922:
13923: @item interpreting a word with undefined interpretation semantics:
13924: @cindex interpreting a word with undefined interpretation semantics
13925: @cindex Interpreting a compile-only word
13926: For some words, we have defined interpretation semantics. For the
13927: others: @code{-14 throw} (Interpreting a compile-only word).
13928:
13929: @item modifying the contents of the input buffer or a string literal:
13930: @cindex modifying the contents of the input buffer or a string literal
13931: These are located in writable memory and can be modified.
13932:
13933: @item overflow of the pictured numeric output string:
13934: @cindex overflow of the pictured numeric output string
13935: @cindex pictured numeric output string, overflow
1.24 anton 13936: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13937:
13938: @item parsed string overflow:
13939: @cindex parsed string overflow
13940: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13941:
13942: @item producing a result out of range:
13943: @cindex result out of range
13944: On two's complement machines, arithmetic is performed modulo
13945: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13946: arithmetic (with appropriate mapping for signed types). Division by
13947: zero typically results in a @code{-10 throw} (divide by zero) or
13948: @code{-55 throw} (floating point unidentified fault). Overflow on
13949: division may result in these errors or in @code{-11 throw} (result out
13950: of range). @code{Gforth-fast} may silently produce bogus results on
13951: division overflow or division by zero. @code{Convert} and
1.24 anton 13952: @code{>number} currently overflow silently.
1.1 anton 13953:
13954: @item reading from an empty data or return stack:
13955: @cindex stack empty
13956: @cindex stack underflow
1.24 anton 13957: @cindex return stack underflow
1.1 anton 13958: The data stack is checked by the outer (aka text) interpreter after
13959: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13960: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13961: depending on operating system, installation, and invocation. If they are
13962: caught by a check, they typically result in @code{-4 throw} (Stack
13963: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13964: (Invalid memory address), depending on the platform and which stack
13965: underflows and by how much. Note that even if the system uses checking
13966: (through the MMU), your program may have to underflow by a significant
13967: number of stack items to trigger the reaction (the reason for this is
13968: that the MMU, and therefore the checking, works with a page-size
13969: granularity). If there is no checking, the symptoms resulting from an
13970: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13971: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13972: (Invalid memory address) and Illegal Instruction (typically @code{-260
13973: throw}).
1.1 anton 13974:
13975: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13976: @cindex unexpected end of the input buffer
13977: @cindex zero-length string as a name
13978: @cindex Attempt to use zero-length string as a name
13979: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13980: use zero-length string as a name). Words like @code{'} probably will not
13981: find what they search. Note that it is possible to create zero-length
13982: names with @code{nextname} (should it not?).
13983:
13984: @item @code{>IN} greater than input buffer:
13985: @cindex @code{>IN} greater than input buffer
13986: The next invocation of a parsing word returns a string with length 0.
13987:
13988: @item @code{RECURSE} appears after @code{DOES>}:
13989: @cindex @code{RECURSE} appears after @code{DOES>}
13990: Compiles a recursive call to the defining word, not to the defined word.
13991:
13992: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13993: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13994: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13995: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13996: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13997: the end of the file was reached), its source-id may be
13998: reused. Therefore, restoring an input source specification referencing a
13999: closed file may lead to unpredictable results instead of a @code{-12
14000: THROW}.
14001:
14002: In the future, Gforth may be able to restore input source specifications
14003: from other than the current input source.
14004:
14005: @item data space containing definitions gets de-allocated:
14006: @cindex data space containing definitions gets de-allocated
14007: Deallocation with @code{allot} is not checked. This typically results in
14008: memory access faults or execution of illegal instructions.
14009:
14010: @item data space read/write with incorrect alignment:
14011: @cindex data space read/write with incorrect alignment
14012: @cindex alignment faults
1.26 crook 14013: @cindex address alignment exception
1.1 anton 14014: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 14015: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 14016: alignment turned on, incorrect alignment results in a @code{-9 throw}
14017: (Invalid memory address). There are reportedly some processors with
1.12 anton 14018: alignment restrictions that do not report violations.
1.1 anton 14019:
14020: @item data space pointer not properly aligned, @code{,}, @code{C,}:
14021: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
14022: Like other alignment errors.
14023:
14024: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
14025: Like other stack underflows.
14026:
14027: @item loop control parameters not available:
14028: @cindex loop control parameters not available
14029: Not checked. The counted loop words simply assume that the top of return
14030: stack items are loop control parameters and behave accordingly.
14031:
14032: @item most recent definition does not have a name (@code{IMMEDIATE}):
14033: @cindex most recent definition does not have a name (@code{IMMEDIATE})
14034: @cindex last word was headerless
14035: @code{abort" last word was headerless"}.
14036:
14037: @item name not defined by @code{VALUE} used by @code{TO}:
14038: @cindex name not defined by @code{VALUE} used by @code{TO}
14039: @cindex @code{TO} on non-@code{VALUE}s
14040: @cindex Invalid name argument, @code{TO}
14041: @code{-32 throw} (Invalid name argument) (unless name is a local or was
14042: defined by @code{CONSTANT}; in the latter case it just changes the constant).
14043:
14044: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
14045: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 14046: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 14047: @code{-13 throw} (Undefined word)
14048:
14049: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
14050: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
14051: Gforth behaves as if they were of the same type. I.e., you can predict
14052: the behaviour by interpreting all parameters as, e.g., signed.
14053:
14054: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
14055: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
14056: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
14057: compilation semantics of @code{TO}.
14058:
14059: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 14060: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 14061: @cindex @code{WORD}, string overflow
14062: Not checked. The string will be ok, but the count will, of course,
14063: contain only the least significant bits of the length.
14064:
14065: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
14066: @cindex @code{LSHIFT}, large shift counts
14067: @cindex @code{RSHIFT}, large shift counts
14068: Processor-dependent. Typical behaviours are returning 0 and using only
14069: the low bits of the shift count.
14070:
14071: @item word not defined via @code{CREATE}:
14072: @cindex @code{>BODY} of non-@code{CREATE}d words
14073: @code{>BODY} produces the PFA of the word no matter how it was defined.
14074:
14075: @cindex @code{DOES>} of non-@code{CREATE}d words
14076: @code{DOES>} changes the execution semantics of the last defined word no
14077: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
14078: @code{CREATE , DOES>}.
14079:
14080: @item words improperly used outside @code{<#} and @code{#>}:
14081: Not checked. As usual, you can expect memory faults.
14082:
14083: @end table
14084:
14085:
14086: @c ---------------------------------------------------------------------
14087: @node core-other, , core-ambcond, The Core Words
14088: @subsection Other system documentation
14089: @c ---------------------------------------------------------------------
14090: @cindex other system documentation, core words
14091: @cindex core words, other system documentation
14092:
14093: @table @i
14094: @item nonstandard words using @code{PAD}:
14095: @cindex @code{PAD} use by nonstandard words
14096: None.
14097:
14098: @item operator's terminal facilities available:
14099: @cindex operator's terminal facilities available
1.80 anton 14100: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 14101: and you can give commands to Gforth interactively. The actual facilities
14102: available depend on how you invoke Gforth.
14103:
14104: @item program data space available:
14105: @cindex program data space available
14106: @cindex data space available
14107: @code{UNUSED .} gives the remaining dictionary space. The total
14108: dictionary space can be specified with the @code{-m} switch
14109: (@pxref{Invoking Gforth}) when Gforth starts up.
14110:
14111: @item return stack space available:
14112: @cindex return stack space available
14113: You can compute the total return stack space in cells with
14114: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
14115: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
14116:
14117: @item stack space available:
14118: @cindex stack space available
14119: You can compute the total data stack space in cells with
14120: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
14121: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
14122:
14123: @item system dictionary space required, in address units:
14124: @cindex system dictionary space required, in address units
14125: Type @code{here forthstart - .} after startup. At the time of this
14126: writing, this gives 80080 (bytes) on a 32-bit system.
14127: @end table
14128:
14129:
14130: @c =====================================================================
14131: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
14132: @section The optional Block word set
14133: @c =====================================================================
14134: @cindex system documentation, block words
14135: @cindex block words, system documentation
14136:
14137: @menu
14138: * block-idef:: Implementation Defined Options
14139: * block-ambcond:: Ambiguous Conditions
14140: * block-other:: Other System Documentation
14141: @end menu
14142:
14143:
14144: @c ---------------------------------------------------------------------
14145: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14146: @subsection Implementation Defined Options
14147: @c ---------------------------------------------------------------------
14148: @cindex implementation-defined options, block words
14149: @cindex block words, implementation-defined options
14150:
14151: @table @i
14152: @item the format for display by @code{LIST}:
14153: @cindex @code{LIST} display format
14154: First the screen number is displayed, then 16 lines of 64 characters,
14155: each line preceded by the line number.
14156:
14157: @item the length of a line affected by @code{\}:
14158: @cindex length of a line affected by @code{\}
14159: @cindex @code{\}, line length in blocks
14160: 64 characters.
14161: @end table
14162:
14163:
14164: @c ---------------------------------------------------------------------
14165: @node block-ambcond, block-other, block-idef, The optional Block word set
14166: @subsection Ambiguous conditions
14167: @c ---------------------------------------------------------------------
14168: @cindex block words, ambiguous conditions
14169: @cindex ambiguous conditions, block words
14170:
14171: @table @i
14172: @item correct block read was not possible:
14173: @cindex block read not possible
14174: Typically results in a @code{throw} of some OS-derived value (between
14175: -512 and -2048). If the blocks file was just not long enough, blanks are
14176: supplied for the missing portion.
14177:
14178: @item I/O exception in block transfer:
14179: @cindex I/O exception in block transfer
14180: @cindex block transfer, I/O exception
14181: Typically results in a @code{throw} of some OS-derived value (between
14182: -512 and -2048).
14183:
14184: @item invalid block number:
14185: @cindex invalid block number
14186: @cindex block number invalid
14187: @code{-35 throw} (Invalid block number)
14188:
14189: @item a program directly alters the contents of @code{BLK}:
14190: @cindex @code{BLK}, altering @code{BLK}
14191: The input stream is switched to that other block, at the same
14192: position. If the storing to @code{BLK} happens when interpreting
14193: non-block input, the system will get quite confused when the block ends.
14194:
14195: @item no current block buffer for @code{UPDATE}:
14196: @cindex @code{UPDATE}, no current block buffer
14197: @code{UPDATE} has no effect.
14198:
14199: @end table
14200:
14201: @c ---------------------------------------------------------------------
14202: @node block-other, , block-ambcond, The optional Block word set
14203: @subsection Other system documentation
14204: @c ---------------------------------------------------------------------
14205: @cindex other system documentation, block words
14206: @cindex block words, other system documentation
14207:
14208: @table @i
14209: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14210: No restrictions (yet).
14211:
14212: @item the number of blocks available for source and data:
14213: depends on your disk space.
14214:
14215: @end table
14216:
14217:
14218: @c =====================================================================
14219: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14220: @section The optional Double Number word set
14221: @c =====================================================================
14222: @cindex system documentation, double words
14223: @cindex double words, system documentation
14224:
14225: @menu
14226: * double-ambcond:: Ambiguous Conditions
14227: @end menu
14228:
14229:
14230: @c ---------------------------------------------------------------------
14231: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
14232: @subsection Ambiguous conditions
14233: @c ---------------------------------------------------------------------
14234: @cindex double words, ambiguous conditions
14235: @cindex ambiguous conditions, double words
14236:
14237: @table @i
1.29 crook 14238: @item @i{d} outside of range of @i{n} in @code{D>S}:
14239: @cindex @code{D>S}, @i{d} out of range of @i{n}
14240: The least significant cell of @i{d} is produced.
1.1 anton 14241:
14242: @end table
14243:
14244:
14245: @c =====================================================================
14246: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14247: @section The optional Exception word set
14248: @c =====================================================================
14249: @cindex system documentation, exception words
14250: @cindex exception words, system documentation
14251:
14252: @menu
14253: * exception-idef:: Implementation Defined Options
14254: @end menu
14255:
14256:
14257: @c ---------------------------------------------------------------------
14258: @node exception-idef, , The optional Exception word set, The optional Exception word set
14259: @subsection Implementation Defined Options
14260: @c ---------------------------------------------------------------------
14261: @cindex implementation-defined options, exception words
14262: @cindex exception words, implementation-defined options
14263:
14264: @table @i
14265: @item @code{THROW}-codes used in the system:
14266: @cindex @code{THROW}-codes used in the system
14267: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 14268: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 14269: codes -512@minus{}-2047 are used for OS errors (for file and memory
14270: allocation operations). The mapping from OS error numbers to throw codes
14271: is -512@minus{}@code{errno}. One side effect of this mapping is that
14272: undefined OS errors produce a message with a strange number; e.g.,
14273: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14274: @end table
14275:
14276: @c =====================================================================
14277: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14278: @section The optional Facility word set
14279: @c =====================================================================
14280: @cindex system documentation, facility words
14281: @cindex facility words, system documentation
14282:
14283: @menu
14284: * facility-idef:: Implementation Defined Options
14285: * facility-ambcond:: Ambiguous Conditions
14286: @end menu
14287:
14288:
14289: @c ---------------------------------------------------------------------
14290: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14291: @subsection Implementation Defined Options
14292: @c ---------------------------------------------------------------------
14293: @cindex implementation-defined options, facility words
14294: @cindex facility words, implementation-defined options
14295:
14296: @table @i
14297: @item encoding of keyboard events (@code{EKEY}):
14298: @cindex keyboard events, encoding in @code{EKEY}
14299: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 14300: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 14301: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14302: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14303: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14304: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 14305:
1.1 anton 14306:
14307: @item duration of a system clock tick:
14308: @cindex duration of a system clock tick
14309: @cindex clock tick duration
14310: System dependent. With respect to @code{MS}, the time is specified in
14311: microseconds. How well the OS and the hardware implement this, is
14312: another question.
14313:
14314: @item repeatability to be expected from the execution of @code{MS}:
14315: @cindex repeatability to be expected from the execution of @code{MS}
14316: @cindex @code{MS}, repeatability to be expected
14317: System dependent. On Unix, a lot depends on load. If the system is
14318: lightly loaded, and the delay is short enough that Gforth does not get
14319: swapped out, the performance should be acceptable. Under MS-DOS and
14320: other single-tasking systems, it should be good.
14321:
14322: @end table
14323:
14324:
14325: @c ---------------------------------------------------------------------
14326: @node facility-ambcond, , facility-idef, The optional Facility word set
14327: @subsection Ambiguous conditions
14328: @c ---------------------------------------------------------------------
14329: @cindex facility words, ambiguous conditions
14330: @cindex ambiguous conditions, facility words
14331:
14332: @table @i
14333: @item @code{AT-XY} can't be performed on user output device:
14334: @cindex @code{AT-XY} can't be performed on user output device
14335: Largely terminal dependent. No range checks are done on the arguments.
14336: No errors are reported. You may see some garbage appearing, you may see
14337: simply nothing happen.
14338:
14339: @end table
14340:
14341:
14342: @c =====================================================================
14343: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14344: @section The optional File-Access word set
14345: @c =====================================================================
14346: @cindex system documentation, file words
14347: @cindex file words, system documentation
14348:
14349: @menu
14350: * file-idef:: Implementation Defined Options
14351: * file-ambcond:: Ambiguous Conditions
14352: @end menu
14353:
14354: @c ---------------------------------------------------------------------
14355: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14356: @subsection Implementation Defined Options
14357: @c ---------------------------------------------------------------------
14358: @cindex implementation-defined options, file words
14359: @cindex file words, implementation-defined options
14360:
14361: @table @i
14362: @item file access methods used:
14363: @cindex file access methods used
14364: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14365: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14366: @code{wb}): The file is cleared, if it exists, and created, if it does
14367: not (with both @code{open-file} and @code{create-file}). Under Unix
14368: @code{create-file} creates a file with 666 permissions modified by your
14369: umask.
14370:
14371: @item file exceptions:
14372: @cindex file exceptions
14373: The file words do not raise exceptions (except, perhaps, memory access
14374: faults when you pass illegal addresses or file-ids).
14375:
14376: @item file line terminator:
14377: @cindex file line terminator
14378: System-dependent. Gforth uses C's newline character as line
14379: terminator. What the actual character code(s) of this are is
14380: system-dependent.
14381:
14382: @item file name format:
14383: @cindex file name format
14384: System dependent. Gforth just uses the file name format of your OS.
14385:
14386: @item information returned by @code{FILE-STATUS}:
14387: @cindex @code{FILE-STATUS}, returned information
14388: @code{FILE-STATUS} returns the most powerful file access mode allowed
14389: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14390: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14391: along with the returned mode.
14392:
14393: @item input file state after an exception when including source:
14394: @cindex exception when including source
14395: All files that are left via the exception are closed.
14396:
1.29 crook 14397: @item @i{ior} values and meaning:
14398: @cindex @i{ior} values and meaning
1.68 anton 14399: @cindex @i{wior} values and meaning
1.29 crook 14400: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14401: intended as throw codes. They typically are in the range
14402: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14403: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14404:
14405: @item maximum depth of file input nesting:
14406: @cindex maximum depth of file input nesting
14407: @cindex file input nesting, maximum depth
14408: limited by the amount of return stack, locals/TIB stack, and the number
14409: of open files available. This should not give you troubles.
14410:
14411: @item maximum size of input line:
14412: @cindex maximum size of input line
14413: @cindex input line size, maximum
14414: @code{/line}. Currently 255.
14415:
14416: @item methods of mapping block ranges to files:
14417: @cindex mapping block ranges to files
14418: @cindex files containing blocks
14419: @cindex blocks in files
14420: By default, blocks are accessed in the file @file{blocks.fb} in the
14421: current working directory. The file can be switched with @code{USE}.
14422:
14423: @item number of string buffers provided by @code{S"}:
14424: @cindex @code{S"}, number of string buffers
14425: 1
14426:
14427: @item size of string buffer used by @code{S"}:
14428: @cindex @code{S"}, size of string buffer
14429: @code{/line}. currently 255.
14430:
14431: @end table
14432:
14433: @c ---------------------------------------------------------------------
14434: @node file-ambcond, , file-idef, The optional File-Access word set
14435: @subsection Ambiguous conditions
14436: @c ---------------------------------------------------------------------
14437: @cindex file words, ambiguous conditions
14438: @cindex ambiguous conditions, file words
14439:
14440: @table @i
14441: @item attempting to position a file outside its boundaries:
14442: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14443: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14444: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14445:
14446: @item attempting to read from file positions not yet written:
14447: @cindex reading from file positions not yet written
14448: End-of-file, i.e., zero characters are read and no error is reported.
14449:
1.29 crook 14450: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14451: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14452: An appropriate exception may be thrown, but a memory fault or other
14453: problem is more probable.
14454:
1.29 crook 14455: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14456: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14457: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14458: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14459: thrown.
14460:
14461: @item named file cannot be opened (@code{INCLUDED}):
14462: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14463: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14464:
14465: @item requesting an unmapped block number:
14466: @cindex unmapped block numbers
14467: There are no unmapped legal block numbers. On some operating systems,
14468: writing a block with a large number may overflow the file system and
14469: have an error message as consequence.
14470:
14471: @item using @code{source-id} when @code{blk} is non-zero:
14472: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14473: @code{source-id} performs its function. Typically it will give the id of
14474: the source which loaded the block. (Better ideas?)
14475:
14476: @end table
14477:
14478:
14479: @c =====================================================================
14480: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14481: @section The optional Floating-Point word set
14482: @c =====================================================================
14483: @cindex system documentation, floating-point words
14484: @cindex floating-point words, system documentation
14485:
14486: @menu
14487: * floating-idef:: Implementation Defined Options
14488: * floating-ambcond:: Ambiguous Conditions
14489: @end menu
14490:
14491:
14492: @c ---------------------------------------------------------------------
14493: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14494: @subsection Implementation Defined Options
14495: @c ---------------------------------------------------------------------
14496: @cindex implementation-defined options, floating-point words
14497: @cindex floating-point words, implementation-defined options
14498:
14499: @table @i
14500: @item format and range of floating point numbers:
14501: @cindex format and range of floating point numbers
14502: @cindex floating point numbers, format and range
14503: System-dependent; the @code{double} type of C.
14504:
1.29 crook 14505: @item results of @code{REPRESENT} when @i{float} is out of range:
14506: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14507: System dependent; @code{REPRESENT} is implemented using the C library
14508: function @code{ecvt()} and inherits its behaviour in this respect.
14509:
14510: @item rounding or truncation of floating-point numbers:
14511: @cindex rounding of floating-point numbers
14512: @cindex truncation of floating-point numbers
14513: @cindex floating-point numbers, rounding or truncation
14514: System dependent; the rounding behaviour is inherited from the hosting C
14515: compiler. IEEE-FP-based (i.e., most) systems by default round to
14516: nearest, and break ties by rounding to even (i.e., such that the last
14517: bit of the mantissa is 0).
14518:
14519: @item size of floating-point stack:
14520: @cindex floating-point stack size
14521: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14522: the floating-point stack (in floats). You can specify this on startup
14523: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14524:
14525: @item width of floating-point stack:
14526: @cindex floating-point stack width
14527: @code{1 floats}.
14528:
14529: @end table
14530:
14531:
14532: @c ---------------------------------------------------------------------
14533: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14534: @subsection Ambiguous conditions
14535: @c ---------------------------------------------------------------------
14536: @cindex floating-point words, ambiguous conditions
14537: @cindex ambiguous conditions, floating-point words
14538:
14539: @table @i
14540: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14541: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14542: System-dependent. Typically results in a @code{-23 THROW} like other
14543: alignment violations.
14544:
14545: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14546: @cindex @code{f@@} used with an address that is not float aligned
14547: @cindex @code{f!} used with an address that is not float aligned
14548: System-dependent. Typically results in a @code{-23 THROW} like other
14549: alignment violations.
14550:
14551: @item floating-point result out of range:
14552: @cindex floating-point result out of range
1.80 anton 14553: System-dependent. Can result in a @code{-43 throw} (floating point
14554: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14555: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14556: unidentified fault), or can produce a special value representing, e.g.,
14557: Infinity.
14558:
14559: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14560: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14561: System-dependent. Typically results in an alignment fault like other
14562: alignment violations.
14563:
1.35 anton 14564: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14565: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14566: The floating-point number is converted into decimal nonetheless.
14567:
14568: @item Both arguments are equal to zero (@code{FATAN2}):
14569: @cindex @code{FATAN2}, both arguments are equal to zero
14570: System-dependent. @code{FATAN2} is implemented using the C library
14571: function @code{atan2()}.
14572:
1.29 crook 14573: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14574: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14575: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14576: because of small errors and the tan will be a very large (or very small)
14577: but finite number.
14578:
1.29 crook 14579: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14580: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14581: The result is rounded to the nearest float.
14582:
14583: @item dividing by zero:
14584: @cindex dividing by zero, floating-point
14585: @cindex floating-point dividing by zero
14586: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14587: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14588: (floating point divide by zero) or @code{-55 throw} (Floating-point
14589: unidentified fault).
1.1 anton 14590:
14591: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14592: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14593: System dependent. On IEEE-FP based systems the number is converted into
14594: an infinity.
14595:
1.29 crook 14596: @item @i{float}<1 (@code{FACOSH}):
14597: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14598: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14599: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14600:
1.29 crook 14601: @item @i{float}=<-1 (@code{FLNP1}):
14602: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14603: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14604: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14605: negative infinity for @i{float}=-1).
1.1 anton 14606:
1.29 crook 14607: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14608: @cindex @code{FLN}, @i{float}=<0
14609: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14610: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14611: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14612: negative infinity for @i{float}=0).
1.1 anton 14613:
1.29 crook 14614: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14615: @cindex @code{FASINH}, @i{float}<0
14616: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14617: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14618: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14619: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14620: C library?).
1.1 anton 14621:
1.29 crook 14622: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14623: @cindex @code{FACOS}, |@i{float}|>1
14624: @cindex @code{FASIN}, |@i{float}|>1
14625: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14626: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14627: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14628:
1.29 crook 14629: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14630: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14631: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14632: Platform-dependent; typically, some double number is produced and no
14633: error is reported.
1.1 anton 14634:
14635: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14636: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14637: @code{Precision} characters of the numeric output area are used. If
14638: @code{precision} is too high, these words will smash the data or code
14639: close to @code{here}.
1.1 anton 14640: @end table
14641:
14642: @c =====================================================================
14643: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14644: @section The optional Locals word set
14645: @c =====================================================================
14646: @cindex system documentation, locals words
14647: @cindex locals words, system documentation
14648:
14649: @menu
14650: * locals-idef:: Implementation Defined Options
14651: * locals-ambcond:: Ambiguous Conditions
14652: @end menu
14653:
14654:
14655: @c ---------------------------------------------------------------------
14656: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14657: @subsection Implementation Defined Options
14658: @c ---------------------------------------------------------------------
14659: @cindex implementation-defined options, locals words
14660: @cindex locals words, implementation-defined options
14661:
14662: @table @i
14663: @item maximum number of locals in a definition:
14664: @cindex maximum number of locals in a definition
14665: @cindex locals, maximum number in a definition
14666: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14667: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14668: characters. The number of locals in a definition is bounded by the size
14669: of locals-buffer, which contains the names of the locals.
14670:
14671: @end table
14672:
14673:
14674: @c ---------------------------------------------------------------------
14675: @node locals-ambcond, , locals-idef, The optional Locals word set
14676: @subsection Ambiguous conditions
14677: @c ---------------------------------------------------------------------
14678: @cindex locals words, ambiguous conditions
14679: @cindex ambiguous conditions, locals words
14680:
14681: @table @i
14682: @item executing a named local in interpretation state:
14683: @cindex local in interpretation state
14684: @cindex Interpreting a compile-only word, for a local
14685: Locals have no interpretation semantics. If you try to perform the
14686: interpretation semantics, you will get a @code{-14 throw} somewhere
14687: (Interpreting a compile-only word). If you perform the compilation
14688: semantics, the locals access will be compiled (irrespective of state).
14689:
1.29 crook 14690: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14691: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14692: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14693: @cindex Invalid name argument, @code{TO}
14694: @code{-32 throw} (Invalid name argument)
14695:
14696: @end table
14697:
14698:
14699: @c =====================================================================
14700: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14701: @section The optional Memory-Allocation word set
14702: @c =====================================================================
14703: @cindex system documentation, memory-allocation words
14704: @cindex memory-allocation words, system documentation
14705:
14706: @menu
14707: * memory-idef:: Implementation Defined Options
14708: @end menu
14709:
14710:
14711: @c ---------------------------------------------------------------------
14712: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14713: @subsection Implementation Defined Options
14714: @c ---------------------------------------------------------------------
14715: @cindex implementation-defined options, memory-allocation words
14716: @cindex memory-allocation words, implementation-defined options
14717:
14718: @table @i
1.29 crook 14719: @item values and meaning of @i{ior}:
14720: @cindex @i{ior} values and meaning
14721: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14722: intended as throw codes. They typically are in the range
14723: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14724: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14725:
14726: @end table
14727:
14728: @c =====================================================================
14729: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14730: @section The optional Programming-Tools word set
14731: @c =====================================================================
14732: @cindex system documentation, programming-tools words
14733: @cindex programming-tools words, system documentation
14734:
14735: @menu
14736: * programming-idef:: Implementation Defined Options
14737: * programming-ambcond:: Ambiguous Conditions
14738: @end menu
14739:
14740:
14741: @c ---------------------------------------------------------------------
14742: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14743: @subsection Implementation Defined Options
14744: @c ---------------------------------------------------------------------
14745: @cindex implementation-defined options, programming-tools words
14746: @cindex programming-tools words, implementation-defined options
14747:
14748: @table @i
14749: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14750: @cindex @code{;CODE} ending sequence
14751: @cindex @code{CODE} ending sequence
14752: @code{END-CODE}
14753:
14754: @item manner of processing input following @code{;CODE} and @code{CODE}:
14755: @cindex @code{;CODE}, processing input
14756: @cindex @code{CODE}, processing input
14757: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14758: the input is processed by the text interpreter, (starting) in interpret
14759: state.
14760:
14761: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14762: @cindex @code{ASSEMBLER}, search order capability
14763: The ANS Forth search order word set.
14764:
14765: @item source and format of display by @code{SEE}:
14766: @cindex @code{SEE}, source and format of output
1.80 anton 14767: The source for @code{see} is the executable code used by the inner
1.1 anton 14768: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14769: (and on some platforms, assembly code for primitives) as well as
14770: possible.
1.1 anton 14771:
14772: @end table
14773:
14774: @c ---------------------------------------------------------------------
14775: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14776: @subsection Ambiguous conditions
14777: @c ---------------------------------------------------------------------
14778: @cindex programming-tools words, ambiguous conditions
14779: @cindex ambiguous conditions, programming-tools words
14780:
14781: @table @i
14782:
1.21 crook 14783: @item deleting the compilation word list (@code{FORGET}):
14784: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14785: Not implemented (yet).
14786:
1.29 crook 14787: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14788: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14789: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14790: @cindex control-flow stack underflow
14791: This typically results in an @code{abort"} with a descriptive error
14792: message (may change into a @code{-22 throw} (Control structure mismatch)
14793: in the future). You may also get a memory access error. If you are
14794: unlucky, this ambiguous condition is not caught.
14795:
1.29 crook 14796: @item @i{name} can't be found (@code{FORGET}):
14797: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14798: Not implemented (yet).
14799:
1.29 crook 14800: @item @i{name} not defined via @code{CREATE}:
14801: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14802: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14803: the execution semantics of the last defined word no matter how it was
14804: defined.
14805:
14806: @item @code{POSTPONE} applied to @code{[IF]}:
14807: @cindex @code{POSTPONE} applied to @code{[IF]}
14808: @cindex @code{[IF]} and @code{POSTPONE}
14809: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14810: equivalent to @code{[IF]}.
14811:
14812: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14813: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14814: Continue in the same state of conditional compilation in the next outer
14815: input source. Currently there is no warning to the user about this.
14816:
14817: @item removing a needed definition (@code{FORGET}):
14818: @cindex @code{FORGET}, removing a needed definition
14819: Not implemented (yet).
14820:
14821: @end table
14822:
14823:
14824: @c =====================================================================
14825: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14826: @section The optional Search-Order word set
14827: @c =====================================================================
14828: @cindex system documentation, search-order words
14829: @cindex search-order words, system documentation
14830:
14831: @menu
14832: * search-idef:: Implementation Defined Options
14833: * search-ambcond:: Ambiguous Conditions
14834: @end menu
14835:
14836:
14837: @c ---------------------------------------------------------------------
14838: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14839: @subsection Implementation Defined Options
14840: @c ---------------------------------------------------------------------
14841: @cindex implementation-defined options, search-order words
14842: @cindex search-order words, implementation-defined options
14843:
14844: @table @i
14845: @item maximum number of word lists in search order:
14846: @cindex maximum number of word lists in search order
14847: @cindex search order, maximum depth
14848: @code{s" wordlists" environment? drop .}. Currently 16.
14849:
14850: @item minimum search order:
14851: @cindex minimum search order
14852: @cindex search order, minimum
14853: @code{root root}.
14854:
14855: @end table
14856:
14857: @c ---------------------------------------------------------------------
14858: @node search-ambcond, , search-idef, The optional Search-Order word set
14859: @subsection Ambiguous conditions
14860: @c ---------------------------------------------------------------------
14861: @cindex search-order words, ambiguous conditions
14862: @cindex ambiguous conditions, search-order words
14863:
14864: @table @i
1.21 crook 14865: @item changing the compilation word list (during compilation):
14866: @cindex changing the compilation word list (during compilation)
14867: @cindex compilation word list, change before definition ends
14868: The word is entered into the word list that was the compilation word list
1.1 anton 14869: at the start of the definition. Any changes to the name field (e.g.,
14870: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14871: are applied to the latest defined word (as reported by @code{latest} or
14872: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14873:
14874: @item search order empty (@code{previous}):
14875: @cindex @code{previous}, search order empty
1.26 crook 14876: @cindex vocstack empty, @code{previous}
1.1 anton 14877: @code{abort" Vocstack empty"}.
14878:
14879: @item too many word lists in search order (@code{also}):
14880: @cindex @code{also}, too many word lists in search order
1.26 crook 14881: @cindex vocstack full, @code{also}
1.1 anton 14882: @code{abort" Vocstack full"}.
14883:
14884: @end table
14885:
14886: @c ***************************************************************
1.65 anton 14887: @node Standard vs Extensions, Model, ANS conformance, Top
14888: @chapter Should I use Gforth extensions?
14889: @cindex Gforth extensions
14890:
14891: As you read through the rest of this manual, you will see documentation
14892: for @i{Standard} words, and documentation for some appealing Gforth
14893: @i{extensions}. You might ask yourself the question: @i{``Should I
14894: restrict myself to the standard, or should I use the extensions?''}
14895:
14896: The answer depends on the goals you have for the program you are working
14897: on:
14898:
14899: @itemize @bullet
14900:
14901: @item Is it just for yourself or do you want to share it with others?
14902:
14903: @item
14904: If you want to share it, do the others all use Gforth?
14905:
14906: @item
14907: If it is just for yourself, do you want to restrict yourself to Gforth?
14908:
14909: @end itemize
14910:
14911: If restricting the program to Gforth is ok, then there is no reason not
14912: to use extensions. It is still a good idea to keep to the standard
14913: where it is easy, in case you want to reuse these parts in another
14914: program that you want to be portable.
14915:
14916: If you want to be able to port the program to other Forth systems, there
14917: are the following points to consider:
14918:
14919: @itemize @bullet
14920:
14921: @item
14922: Most Forth systems that are being maintained support the ANS Forth
14923: standard. So if your program complies with the standard, it will be
14924: portable among many systems.
14925:
14926: @item
14927: A number of the Gforth extensions can be implemented in ANS Forth using
14928: public-domain files provided in the @file{compat/} directory. These are
14929: mentioned in the text in passing. There is no reason not to use these
14930: extensions, your program will still be ANS Forth compliant; just include
14931: the appropriate compat files with your program.
14932:
14933: @item
14934: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14935: analyse your program and determine what non-Standard words it relies
14936: upon. However, it does not check whether you use standard words in a
14937: non-standard way.
14938:
14939: @item
14940: Some techniques are not standardized by ANS Forth, and are hard or
14941: impossible to implement in a standard way, but can be implemented in
14942: most Forth systems easily, and usually in similar ways (e.g., accessing
14943: word headers). Forth has a rich historical precedent for programmers
14944: taking advantage of implementation-dependent features of their tools
14945: (for example, relying on a knowledge of the dictionary
14946: structure). Sometimes these techniques are necessary to extract every
14947: last bit of performance from the hardware, sometimes they are just a
14948: programming shorthand.
14949:
14950: @item
14951: Does using a Gforth extension save more work than the porting this part
14952: to other Forth systems (if any) will cost?
14953:
14954: @item
14955: Is the additional functionality worth the reduction in portability and
14956: the additional porting problems?
14957:
14958: @end itemize
14959:
14960: In order to perform these consideratios, you need to know what's
14961: standard and what's not. This manual generally states if something is
1.81 anton 14962: non-standard, but the authoritative source is the
14963: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14964: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14965: into the thought processes of the technical committee.
14966:
14967: Note also that portability between Forth systems is not the only
14968: portability issue; there is also the issue of portability between
14969: different platforms (processor/OS combinations).
14970:
14971: @c ***************************************************************
14972: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14973: @chapter Model
14974:
14975: This chapter has yet to be written. It will contain information, on
14976: which internal structures you can rely.
14977:
14978: @c ***************************************************************
14979: @node Integrating Gforth, Emacs and Gforth, Model, Top
14980: @chapter Integrating Gforth into C programs
14981:
14982: This is not yet implemented.
14983:
14984: Several people like to use Forth as scripting language for applications
14985: that are otherwise written in C, C++, or some other language.
14986:
14987: The Forth system ATLAST provides facilities for embedding it into
14988: applications; unfortunately it has several disadvantages: most
14989: importantly, it is not based on ANS Forth, and it is apparently dead
14990: (i.e., not developed further and not supported). The facilities
1.21 crook 14991: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14992: making the switch should not be hard.
14993:
14994: We also tried to design the interface such that it can easily be
14995: implemented by other Forth systems, so that we may one day arrive at a
14996: standardized interface. Such a standard interface would allow you to
14997: replace the Forth system without having to rewrite C code.
14998:
14999: You embed the Gforth interpreter by linking with the library
15000: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
15001: global symbols in this library that belong to the interface, have the
15002: prefix @code{forth_}. (Global symbols that are used internally have the
15003: prefix @code{gforth_}).
15004:
15005: You can include the declarations of Forth types and the functions and
15006: variables of the interface with @code{#include <forth.h>}.
15007:
15008: Types.
15009:
15010: Variables.
15011:
15012: Data and FP Stack pointer. Area sizes.
15013:
15014: functions.
15015:
15016: forth_init(imagefile)
15017: forth_evaluate(string) exceptions?
15018: forth_goto(address) (or forth_execute(xt)?)
15019: forth_continue() (a corountining mechanism)
15020:
15021: Adding primitives.
15022:
15023: No checking.
15024:
15025: Signals?
15026:
15027: Accessing the Stacks
15028:
1.26 crook 15029: @c ******************************************************************
1.1 anton 15030: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
15031: @chapter Emacs and Gforth
15032: @cindex Emacs and Gforth
15033:
15034: @cindex @file{gforth.el}
15035: @cindex @file{forth.el}
15036: @cindex Rydqvist, Goran
1.107 dvdkhlng 15037: @cindex Kuehling, David
1.1 anton 15038: @cindex comment editing commands
15039: @cindex @code{\}, editing with Emacs
15040: @cindex debug tracer editing commands
15041: @cindex @code{~~}, removal with Emacs
15042: @cindex Forth mode in Emacs
1.107 dvdkhlng 15043:
1.1 anton 15044: Gforth comes with @file{gforth.el}, an improved version of
15045: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 15046: improvements are:
15047:
15048: @itemize @bullet
15049: @item
1.107 dvdkhlng 15050: A better handling of indentation.
15051: @item
15052: A custom hilighting engine for Forth-code.
1.26 crook 15053: @item
15054: Comment paragraph filling (@kbd{M-q})
15055: @item
15056: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
15057: @item
15058: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 15059: @item
15060: Support of the @code{info-lookup} feature for looking up the
15061: documentation of a word.
1.107 dvdkhlng 15062: @item
15063: Support for reading and writing blocks files.
1.26 crook 15064: @end itemize
15065:
1.107 dvdkhlng 15066: To get a basic description of these features, enter Forth mode and
15067: type @kbd{C-h m}.
1.1 anton 15068:
15069: @cindex source location of error or debugging output in Emacs
15070: @cindex error output, finding the source location in Emacs
15071: @cindex debugging output, finding the source location in Emacs
15072: In addition, Gforth supports Emacs quite well: The source code locations
15073: given in error messages, debugging output (from @code{~~}) and failed
15074: assertion messages are in the right format for Emacs' compilation mode
15075: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
15076: Manual}) so the source location corresponding to an error or other
15077: message is only a few keystrokes away (@kbd{C-x `} for the next error,
15078: @kbd{C-c C-c} for the error under the cursor).
15079:
1.107 dvdkhlng 15080: @cindex viewing the documentation of a word in Emacs
15081: @cindex context-sensitive help
15082: Moreover, for words documented in this manual, you can look up the
15083: glossary entry quickly by using @kbd{C-h TAB}
15084: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
15085: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
15086: later and does not work for words containing @code{:}.
15087:
15088: @menu
15089: * Installing gforth.el:: Making Emacs aware of Forth.
15090: * Emacs Tags:: Viewing the source of a word in Emacs.
15091: * Hilighting:: Making Forth code look prettier.
15092: * Auto-Indentation:: Customizing auto-indentation.
15093: * Blocks Files:: Reading and writing blocks files.
15094: @end menu
15095:
15096: @c ----------------------------------
1.109 anton 15097: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 15098: @section Installing gforth.el
15099: @cindex @file{.emacs}
15100: @cindex @file{gforth.el}, installation
15101: To make the features from @file{gforth.el} available in Emacs, add
15102: the following lines to your @file{.emacs} file:
15103:
15104: @example
15105: (autoload 'forth-mode "gforth.el")
15106: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
15107: auto-mode-alist))
15108: (autoload 'forth-block-mode "gforth.el")
15109: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
15110: auto-mode-alist))
15111: (add-hook 'forth-mode-hook (function (lambda ()
15112: ;; customize variables here:
15113: (setq forth-indent-level 4)
15114: (setq forth-minor-indent-level 2)
15115: (setq forth-hilight-level 3)
15116: ;;; ...
15117: )))
15118: @end example
15119:
15120: @c ----------------------------------
15121: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
15122: @section Emacs Tags
1.1 anton 15123: @cindex @file{TAGS} file
15124: @cindex @file{etags.fs}
15125: @cindex viewing the source of a word in Emacs
1.43 anton 15126: @cindex @code{require}, placement in files
15127: @cindex @code{include}, placement in files
1.107 dvdkhlng 15128: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
15129: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 15130: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 15131: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 15132: several tags files at the same time (e.g., one for the Gforth sources
15133: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
15134: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
15135: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 15136: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
15137: with @file{etags.fs}, you should avoid putting definitions both before
15138: and after @code{require} etc., otherwise you will see the same file
15139: visited several times by commands like @code{tags-search}.
1.1 anton 15140:
1.107 dvdkhlng 15141: @c ----------------------------------
15142: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
15143: @section Hilighting
15144: @cindex hilighting Forth code in Emacs
15145: @cindex highlighting Forth code in Emacs
15146: @file{gforth.el} comes with a custom source hilighting engine. When
15147: you open a file in @code{forth-mode}, it will be completely parsed,
15148: assigning faces to keywords, comments, strings etc. While you edit
15149: the file, modified regions get parsed and updated on-the-fly.
15150:
15151: Use the variable `forth-hilight-level' to change the level of
15152: decoration from 0 (no hilighting at all) to 3 (the default). Even if
15153: you set the hilighting level to 0, the parser will still work in the
15154: background, collecting information about whether regions of text are
15155: ``compiled'' or ``interpreted''. Those information are required for
15156: auto-indentation to work properly. Set `forth-disable-parser' to
15157: non-nil if your computer is too slow to handle parsing. This will
15158: have an impact on the smartness of the auto-indentation engine,
15159: though.
15160:
15161: Sometimes Forth sources define new features that should be hilighted,
15162: new control structures, defining-words etc. You can use the variable
15163: `forth-custom-words' to make @code{forth-mode} hilight additional
15164: words and constructs. See the docstring of `forth-words' for details
15165: (in Emacs, type @kbd{C-h v forth-words}).
15166:
15167: `forth-custom-words' is meant to be customized in your
15168: @file{.emacs} file. To customize hilighing in a file-specific manner,
15169: set `forth-local-words' in a local-variables section at the end of
15170: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
15171:
15172: Example:
15173: @example
15174: 0 [IF]
15175: Local Variables:
15176: forth-local-words:
15177: ((("t:") definition-starter (font-lock-keyword-face . 1)
15178: "[ \t\n]" t name (font-lock-function-name-face . 3))
15179: ((";t") definition-ender (font-lock-keyword-face . 1)))
15180: End:
15181: [THEN]
15182: @end example
15183:
15184: @c ----------------------------------
15185: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
15186: @section Auto-Indentation
15187: @cindex auto-indentation of Forth code in Emacs
15188: @cindex indentation of Forth code in Emacs
15189: @code{forth-mode} automatically tries to indent lines in a smart way,
15190: whenever you type @key{TAB} or break a line with @kbd{C-m}.
15191:
15192: Simple customization can be achieved by setting
15193: `forth-indent-level' and `forth-minor-indent-level' in your
15194: @file{.emacs} file. For historical reasons @file{gforth.el} indents
15195: per default by multiples of 4 columns. To use the more traditional
15196: 3-column indentation, add the following lines to your @file{.emacs}:
15197:
15198: @example
15199: (add-hook 'forth-mode-hook (function (lambda ()
15200: ;; customize variables here:
15201: (setq forth-indent-level 3)
15202: (setq forth-minor-indent-level 1)
15203: )))
15204: @end example
15205:
15206: If you want indentation to recognize non-default words, customize it
15207: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
15208: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15209: v forth-indent-words}).
15210:
15211: To customize indentation in a file-specific manner, set
15212: `forth-local-indent-words' in a local-variables section at the end of
15213: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15214: Emacs Manual}).
15215:
15216: Example:
15217: @example
15218: 0 [IF]
15219: Local Variables:
15220: forth-local-indent-words:
15221: ((("t:") (0 . 2) (0 . 2))
15222: ((";t") (-2 . 0) (0 . -2)))
15223: End:
15224: [THEN]
15225: @end example
15226:
15227: @c ----------------------------------
1.109 anton 15228: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 15229: @section Blocks Files
15230: @cindex blocks files, use with Emacs
15231: @code{forth-mode} Autodetects blocks files by checking whether the
15232: length of the first line exceeds 1023 characters. It then tries to
15233: convert the file into normal text format. When you save the file, it
15234: will be written to disk as normal stream-source file.
15235:
15236: If you want to write blocks files, use @code{forth-blocks-mode}. It
15237: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 15238:
1.107 dvdkhlng 15239: @itemize @bullet
15240: @item
15241: Files are written to disk in blocks file format.
15242: @item
15243: Screen numbers are displayed in the mode line (enumerated beginning
15244: with the value of `forth-block-base')
15245: @item
15246: Warnings are displayed when lines exceed 64 characters.
15247: @item
15248: The beginning of the currently edited block is marked with an
15249: overlay-arrow.
15250: @end itemize
1.41 anton 15251:
1.107 dvdkhlng 15252: There are some restrictions you should be aware of. When you open a
15253: blocks file that contains tabulator or newline characters, these
15254: characters will be translated into spaces when the file is written
15255: back to disk. If tabs or newlines are encountered during blocks file
15256: reading, an error is output to the echo area. So have a look at the
15257: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 15258:
1.107 dvdkhlng 15259: Please consult the docstring of @code{forth-blocks-mode} for more
15260: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 15261:
1.26 crook 15262: @c ******************************************************************
1.1 anton 15263: @node Image Files, Engine, Emacs and Gforth, Top
15264: @chapter Image Files
1.26 crook 15265: @cindex image file
15266: @cindex @file{.fi} files
1.1 anton 15267: @cindex precompiled Forth code
15268: @cindex dictionary in persistent form
15269: @cindex persistent form of dictionary
15270:
15271: An image file is a file containing an image of the Forth dictionary,
15272: i.e., compiled Forth code and data residing in the dictionary. By
15273: convention, we use the extension @code{.fi} for image files.
15274:
15275: @menu
1.18 anton 15276: * Image Licensing Issues:: Distribution terms for images.
15277: * Image File Background:: Why have image files?
1.67 anton 15278: * Non-Relocatable Image Files:: don't always work.
1.18 anton 15279: * Data-Relocatable Image Files:: are better.
1.67 anton 15280: * Fully Relocatable Image Files:: better yet.
1.18 anton 15281: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 15282: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 15283: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 15284: @end menu
15285:
1.18 anton 15286: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15287: @section Image Licensing Issues
15288: @cindex license for images
15289: @cindex image license
15290:
15291: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15292: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15293: original image; i.e., according to copyright law it is a derived work of
15294: the original image.
15295:
15296: Since Gforth is distributed under the GNU GPL, the newly created image
15297: falls under the GNU GPL, too. In particular, this means that if you
15298: distribute the image, you have to make all of the sources for the image
1.113 anton 15299: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 15300: GNU General Public License (Section 3)}.
15301:
15302: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15303: contains only code compiled from the sources you gave it; if none of
15304: these sources is under the GPL, the terms discussed above do not apply
15305: to the image. However, if your image needs an engine (a gforth binary)
15306: that is under the GPL, you should make sure that you distribute both in
15307: a way that is at most a @emph{mere aggregation}, if you don't want the
15308: terms of the GPL to apply to the image.
15309:
15310: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 15311: @section Image File Background
15312: @cindex image file background
15313:
1.80 anton 15314: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 15315: definitions written in Forth. Since the Forth compiler itself belongs to
15316: those definitions, it is not possible to start the system with the
1.80 anton 15317: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 15318: code as an image file in nearly executable form. When Gforth starts up,
15319: a C routine loads the image file into memory, optionally relocates the
15320: addresses, then sets up the memory (stacks etc.) according to
15321: information in the image file, and (finally) starts executing Forth
15322: code.
1.1 anton 15323:
1.204 anton 15324: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15325: You can use a different image by using the @code{-i},
15326: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15327: Gforth}), e.g.:
15328:
15329: @example
15330: gforth-fast -i myimage.fi
15331: @end example
15332:
15333: There are different variants of image files, and they represent
15334: different compromises between the goals of making it easy to generate
15335: image files and making them portable.
1.1 anton 15336:
15337: @cindex relocation at run-time
1.26 crook 15338: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 15339: run-time. This avoids many of the complications discussed below (image
15340: files are data relocatable without further ado), but costs performance
1.204 anton 15341: (one addition per memory access) and makes it difficult to pass
15342: addresses between Forth and library calls or other programs.
1.1 anton 15343:
15344: @cindex relocation at load-time
1.26 crook 15345: By contrast, the Gforth loader performs relocation at image load time. The
15346: loader also has to replace tokens that represent primitive calls with the
1.1 anton 15347: appropriate code-field addresses (or code addresses in the case of
15348: direct threading).
15349:
15350: There are three kinds of image files, with different degrees of
15351: relocatability: non-relocatable, data-relocatable, and fully relocatable
15352: image files.
15353:
15354: @cindex image file loader
15355: @cindex relocating loader
15356: @cindex loader for image files
15357: These image file variants have several restrictions in common; they are
15358: caused by the design of the image file loader:
15359:
15360: @itemize @bullet
15361: @item
15362: There is only one segment; in particular, this means, that an image file
15363: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 15364: them). The contents of the stacks are not represented, either.
1.1 anton 15365:
15366: @item
15367: The only kinds of relocation supported are: adding the same offset to
15368: all cells that represent data addresses; and replacing special tokens
15369: with code addresses or with pieces of machine code.
15370:
15371: If any complex computations involving addresses are performed, the
15372: results cannot be represented in the image file. Several applications that
15373: use such computations come to mind:
1.204 anton 15374:
1.1 anton 15375: @itemize @minus
15376: @item
15377: Hashing addresses (or data structures which contain addresses) for table
15378: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15379: purpose, you will have no problem, because the hash tables are
15380: recomputed automatically when the system is started. If you use your own
15381: hash tables, you will have to do something similar.
15382:
15383: @item
15384: There's a cute implementation of doubly-linked lists that uses
15385: @code{XOR}ed addresses. You could represent such lists as singly-linked
15386: in the image file, and restore the doubly-linked representation on
15387: startup.@footnote{In my opinion, though, you should think thrice before
15388: using a doubly-linked list (whatever implementation).}
15389:
15390: @item
15391: The code addresses of run-time routines like @code{docol:} cannot be
15392: represented in the image file (because their tokens would be replaced by
15393: machine code in direct threaded implementations). As a workaround,
15394: compute these addresses at run-time with @code{>code-address} from the
15395: executions tokens of appropriate words (see the definitions of
1.80 anton 15396: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 15397:
15398: @item
15399: On many architectures addresses are represented in machine code in some
15400: shifted or mangled form. You cannot put @code{CODE} words that contain
15401: absolute addresses in this form in a relocatable image file. Workarounds
15402: are representing the address in some relative form (e.g., relative to
15403: the CFA, which is present in some register), or loading the address from
15404: a place where it is stored in a non-mangled form.
15405: @end itemize
15406: @end itemize
15407:
15408: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15409: @section Non-Relocatable Image Files
15410: @cindex non-relocatable image files
1.26 crook 15411: @cindex image file, non-relocatable
1.1 anton 15412:
1.204 anton 15413: These files are simple memory dumps of the dictionary. They are
15414: specific to the executable (i.e., @file{gforth} file) they were
15415: created with. What's worse, they are specific to the place on which
15416: the dictionary resided when the image was created. Now, there is no
1.1 anton 15417: guarantee that the dictionary will reside at the same place the next
15418: time you start Gforth, so there's no guarantee that a non-relocatable
1.204 anton 15419: image will work the next time (Gforth will complain instead of
15420: crashing, though). Indeed, on OSs with (enabled) address-space
15421: randomization non-relocatable images are unlikely to work.
1.1 anton 15422:
1.204 anton 15423: You can create a non-relocatable image file with @code{savesystem}, e.g.:
1.1 anton 15424:
1.204 anton 15425: @example
15426: gforth app.fs -e "savesystem app.fi bye"
15427: @end example
1.44 crook 15428:
1.1 anton 15429: doc-savesystem
15430:
1.44 crook 15431:
1.1 anton 15432: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15433: @section Data-Relocatable Image Files
15434: @cindex data-relocatable image files
1.26 crook 15435: @cindex image file, data-relocatable
1.1 anton 15436:
1.204 anton 15437: These files contain relocatable data addresses, but fixed code
15438: addresses (instead of tokens). They are specific to the executable
15439: (i.e., @file{gforth} file) they were created with. Also, they disable
15440: dynamic native code generation (typically a factor of 2 in speed).
15441: You get a data-relocatable image, if you pass the engine you want to
15442: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15443: (@pxref{gforthmi}), e.g.
15444:
15445: @example
15446: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15447: @end example
15448:
15449: Note that the @code{--no-dynamic} is required here for the image to
15450: work (otherwise it will contain references to dynamically generated
15451: code that is not saved in the image).
15452:
1.1 anton 15453:
15454: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15455: @section Fully Relocatable Image Files
15456: @cindex fully relocatable image files
1.26 crook 15457: @cindex image file, fully relocatable
1.1 anton 15458:
15459: @cindex @file{kern*.fi}, relocatability
15460: @cindex @file{gforth.fi}, relocatability
15461: These image files have relocatable data addresses, and tokens for code
15462: addresses. They can be used with different binaries (e.g., with and
15463: without debugging) on the same machine, and even across machines with
1.204 anton 15464: the same data formats (byte order, cell size, floating point format),
15465: and they work with dynamic native code generation. However, they are
15466: usually specific to the version of Gforth they were created with. The
15467: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
1.1 anton 15468:
15469: There are two ways to create a fully relocatable image file:
15470:
15471: @menu
1.29 crook 15472: * gforthmi:: The normal way
1.1 anton 15473: * cross.fs:: The hard way
15474: @end menu
15475:
15476: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15477: @subsection @file{gforthmi}
15478: @cindex @file{comp-i.fs}
15479: @cindex @file{gforthmi}
15480:
15481: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15482: image @i{file} that contains everything you would load by invoking
15483: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15484: @example
1.29 crook 15485: gforthmi @i{file} @i{options}
1.1 anton 15486: @end example
15487:
15488: E.g., if you want to create an image @file{asm.fi} that has the file
15489: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15490: like this:
15491:
15492: @example
15493: gforthmi asm.fi asm.fs
15494: @end example
15495:
1.27 crook 15496: @file{gforthmi} is implemented as a sh script and works like this: It
15497: produces two non-relocatable images for different addresses and then
15498: compares them. Its output reflects this: first you see the output (if
1.62 crook 15499: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15500: files, then you see the output of the comparing program: It displays the
15501: offset used for data addresses and the offset used for code addresses;
1.1 anton 15502: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15503: image files, it displays a line like this:
1.1 anton 15504:
15505: @example
15506: 78DC BFFFFA50 BFFFFA40
15507: @end example
15508:
15509: This means that at offset $78dc from @code{forthstart}, one input image
15510: contains $bffffa50, and the other contains $bffffa40. Since these cells
15511: cannot be represented correctly in the output image, you should examine
15512: these places in the dictionary and verify that these cells are dead
15513: (i.e., not read before they are written).
1.39 anton 15514:
15515: @cindex --application, @code{gforthmi} option
15516: If you insert the option @code{--application} in front of the image file
15517: name, you will get an image that uses the @code{--appl-image} option
15518: instead of the @code{--image-file} option (@pxref{Invoking
15519: Gforth}). When you execute such an image on Unix (by typing the image
15520: name as command), the Gforth engine will pass all options to the image
15521: instead of trying to interpret them as engine options.
1.1 anton 15522:
1.27 crook 15523: If you type @file{gforthmi} with no arguments, it prints some usage
15524: instructions.
15525:
1.1 anton 15526: @cindex @code{savesystem} during @file{gforthmi}
15527: @cindex @code{bye} during @file{gforthmi}
15528: @cindex doubly indirect threaded code
1.44 crook 15529: @cindex environment variables
15530: @cindex @code{GFORTHD} -- environment variable
15531: @cindex @code{GFORTH} -- environment variable
1.1 anton 15532: @cindex @code{gforth-ditc}
1.29 crook 15533: There are a few wrinkles: After processing the passed @i{options}, the
1.204 anton 15534: words @code{savesystem} and @code{bye} must be visible. A special
15535: doubly indirect threaded version of the @file{gforth} executable is
15536: used for creating the non-relocatable images; you can pass the exact
15537: filename of this executable through the environment variable
15538: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15539: that is not doubly indirect threaded, you will not get a fully
15540: relocatable image, but a data-relocatable image
15541: (@pxref{Data-Relocatable Image Files}), because there is no code
15542: address offset). The normal @file{gforth} executable is used for
15543: creating the relocatable image; you can pass the exact filename of
15544: this executable through the environment variable @code{GFORTH}.
1.1 anton 15545:
15546: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15547: @subsection @file{cross.fs}
15548: @cindex @file{cross.fs}
15549: @cindex cross-compiler
15550: @cindex metacompiler
1.47 crook 15551: @cindex target compiler
1.1 anton 15552:
15553: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15554: programming language (@pxref{Cross Compiler}).
1.1 anton 15555:
1.47 crook 15556: @code{cross} allows you to create image files for machines with
1.1 anton 15557: different data sizes and data formats than the one used for generating
15558: the image file. You can also use it to create an application image that
15559: does not contain a Forth compiler. These features are bought with
15560: restrictions and inconveniences in programming. E.g., addresses have to
15561: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15562: order to make the code relocatable.
15563:
15564:
15565: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15566: @section Stack and Dictionary Sizes
15567: @cindex image file, stack and dictionary sizes
15568: @cindex dictionary size default
15569: @cindex stack size default
15570:
15571: If you invoke Gforth with a command line flag for the size
15572: (@pxref{Invoking Gforth}), the size you specify is stored in the
15573: dictionary. If you save the dictionary with @code{savesystem} or create
15574: an image with @file{gforthmi}, this size will become the default
15575: for the resulting image file. E.g., the following will create a
1.21 crook 15576: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15577:
15578: @example
15579: gforthmi gforth.fi -m 1M
15580: @end example
15581:
15582: In other words, if you want to set the default size for the dictionary
15583: and the stacks of an image, just invoke @file{gforthmi} with the
15584: appropriate options when creating the image.
15585:
15586: @cindex stack size, cache-friendly
15587: Note: For cache-friendly behaviour (i.e., good performance), you should
15588: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15589: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15590: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15591:
15592: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15593: @section Running Image Files
15594: @cindex running image files
15595: @cindex invoking image files
15596: @cindex image file invocation
15597:
15598: @cindex -i, invoke image file
15599: @cindex --image file, invoke image file
1.29 crook 15600: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15601: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15602: @example
1.29 crook 15603: gforth -i @i{image}
1.1 anton 15604: @end example
15605:
15606: @cindex executable image file
1.26 crook 15607: @cindex image file, executable
1.1 anton 15608: If your operating system supports starting scripts with a line of the
15609: form @code{#! ...}, you just have to type the image file name to start
15610: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15611: just a convention). I.e., to run Gforth with the image file @i{image},
15612: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15613: This works because every @code{.fi} file starts with a line of this
15614: format:
15615:
15616: @example
15617: #! /usr/local/bin/gforth-0.4.0 -i
15618: @end example
15619:
15620: The file and pathname for the Gforth engine specified on this line is
15621: the specific Gforth executable that it was built against; i.e. the value
15622: of the environment variable @code{GFORTH} at the time that
15623: @file{gforthmi} was executed.
1.1 anton 15624:
1.27 crook 15625: You can make use of the same shell capability to make a Forth source
15626: file into an executable. For example, if you place this text in a file:
1.26 crook 15627:
15628: @example
15629: #! /usr/local/bin/gforth
15630:
15631: ." Hello, world" CR
15632: bye
15633: @end example
15634:
15635: @noindent
1.27 crook 15636: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15637: directly from the command line. The sequence @code{#!} is used in two
15638: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15639: system@footnote{The Unix kernel actually recognises two types of files:
15640: executable files and files of data, where the data is processed by an
15641: interpreter that is specified on the ``interpreter line'' -- the first
15642: line of the file, starting with the sequence #!. There may be a small
15643: limit (e.g., 32) on the number of characters that may be specified on
15644: the interpreter line.} secondly it is treated as a comment character by
15645: Gforth. Because of the second usage, a space is required between
1.80 anton 15646: @code{#!} and the path to the executable (moreover, some Unixes
15647: require the sequence @code{#! /}).
1.27 crook 15648:
15649: The disadvantage of this latter technique, compared with using
1.80 anton 15650: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15651: compiled on-the-fly, each time the program is invoked.
1.26 crook 15652:
1.1 anton 15653: doc-#!
15654:
1.44 crook 15655:
1.1 anton 15656: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15657: @section Modifying the Startup Sequence
15658: @cindex startup sequence for image file
15659: @cindex image file initialization sequence
15660: @cindex initialization sequence of image file
15661:
1.120 anton 15662: You can add your own initialization to the startup sequence of an image
15663: through the deferred word @code{'cold}. @code{'cold} is invoked just
15664: before the image-specific command line processing (i.e., loading files
15665: and evaluating (@code{-e}) strings) starts.
1.1 anton 15666:
15667: A sequence for adding your initialization usually looks like this:
15668:
15669: @example
15670: :noname
15671: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15672: ... \ your stuff
15673: ; IS 'cold
15674: @end example
15675:
1.157 anton 15676: After @code{'cold}, Gforth processes the image options
15677: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15678: another deferred word. This normally prints Gforth's startup message
15679: and does nothing else.
15680:
1.1 anton 15681: @cindex turnkey image files
1.26 crook 15682: @cindex image file, turnkey applications
1.157 anton 15683: So, if you want to make a turnkey image (i.e., an image for an
15684: application instead of an extended Forth system), you can do this in
15685: two ways:
15686:
15687: @itemize @bullet
15688:
15689: @item
15690: If you want to do your interpretation of the OS command-line
15691: arguments, hook into @code{'cold}. In that case you probably also
15692: want to build the image with @code{gforthmi --application}
15693: (@pxref{gforthmi}) to keep the engine from processing OS command line
15694: options. You can then do your own command-line processing with
15695: @code{next-arg}
15696:
15697: @item
15698: If you want to have the normal Gforth processing of OS command-line
15699: arguments, hook into @code{bootmessage}.
15700:
15701: @end itemize
15702:
15703: In either case, you probably do not want the word that you execute in
15704: these hooks to exit normally, but use @code{bye} or @code{throw}.
15705: Otherwise the Gforth startup process would continue and eventually
15706: present the Forth command line to the user.
1.26 crook 15707:
15708: doc-'cold
1.157 anton 15709: doc-bootmessage
1.44 crook 15710:
1.1 anton 15711: @c ******************************************************************
1.113 anton 15712: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15713: @chapter Engine
15714: @cindex engine
15715: @cindex virtual machine
15716:
1.26 crook 15717: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15718: may be helpful for finding your way in the Gforth sources.
15719:
1.109 anton 15720: The ideas in this section have also been published in the following
15721: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15722: Forth-Tagung '93; M. Anton Ertl,
15723: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15724: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15725: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15726: Threaded code variations and optimizations (extended version)}},
15727: Forth-Tagung '02.
1.1 anton 15728:
15729: @menu
15730: * Portability::
15731: * Threading::
15732: * Primitives::
15733: * Performance::
15734: @end menu
15735:
15736: @node Portability, Threading, Engine, Engine
15737: @section Portability
15738: @cindex engine portability
15739:
1.26 crook 15740: An important goal of the Gforth Project is availability across a wide
15741: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15742: achieved this goal by manually coding the engine in assembly language
15743: for several then-popular processors. This approach is very
15744: labor-intensive and the results are short-lived due to progress in
15745: computer architecture.
1.1 anton 15746:
15747: @cindex C, using C for the engine
15748: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15749: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15750: particularly popular for UNIX-based Forths due to the large variety of
15751: architectures of UNIX machines. Unfortunately an implementation in C
15752: does not mix well with the goals of efficiency and with using
15753: traditional techniques: Indirect or direct threading cannot be expressed
15754: in C, and switch threading, the fastest technique available in C, is
15755: significantly slower. Another problem with C is that it is very
15756: cumbersome to express double integer arithmetic.
15757:
15758: @cindex GNU C for the engine
15759: @cindex long long
15760: Fortunately, there is a portable language that does not have these
15761: limitations: GNU C, the version of C processed by the GNU C compiler
15762: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15763: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15764: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15765: threading possible, its @code{long long} type (@pxref{Long Long, ,
15766: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15767: double numbers on many systems. GNU C is freely available on all
1.1 anton 15768: important (and many unimportant) UNIX machines, VMS, 80386s running
15769: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15770: on all these machines.
15771:
15772: Writing in a portable language has the reputation of producing code that
15773: is slower than assembly. For our Forth engine we repeatedly looked at
15774: the code produced by the compiler and eliminated most compiler-induced
15775: inefficiencies by appropriate changes in the source code.
15776:
15777: @cindex explicit register declarations
15778: @cindex --enable-force-reg, configuration flag
15779: @cindex -DFORCE_REG
15780: However, register allocation cannot be portably influenced by the
15781: programmer, leading to some inefficiencies on register-starved
15782: machines. We use explicit register declarations (@pxref{Explicit Reg
15783: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15784: improve the speed on some machines. They are turned on by using the
15785: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15786: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15787: machine, but also on the compiler version: On some machines some
15788: compiler versions produce incorrect code when certain explicit register
15789: declarations are used. So by default @code{-DFORCE_REG} is not used.
15790:
15791: @node Threading, Primitives, Portability, Engine
15792: @section Threading
15793: @cindex inner interpreter implementation
15794: @cindex threaded code implementation
15795:
15796: @cindex labels as values
15797: GNU C's labels as values extension (available since @code{gcc-2.0},
15798: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15799: makes it possible to take the address of @i{label} by writing
15800: @code{&&@i{label}}. This address can then be used in a statement like
15801: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15802: @code{goto x}.
15803:
1.26 crook 15804: @cindex @code{NEXT}, indirect threaded
1.1 anton 15805: @cindex indirect threaded inner interpreter
15806: @cindex inner interpreter, indirect threaded
1.26 crook 15807: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15808: @example
15809: cfa = *ip++;
15810: ca = *cfa;
15811: goto *ca;
15812: @end example
15813: @cindex instruction pointer
15814: For those unfamiliar with the names: @code{ip} is the Forth instruction
15815: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15816: execution token and points to the code field of the next word to be
15817: executed; The @code{ca} (code address) fetched from there points to some
15818: executable code, e.g., a primitive or the colon definition handler
15819: @code{docol}.
15820:
1.26 crook 15821: @cindex @code{NEXT}, direct threaded
1.1 anton 15822: @cindex direct threaded inner interpreter
15823: @cindex inner interpreter, direct threaded
15824: Direct threading is even simpler:
15825: @example
15826: ca = *ip++;
15827: goto *ca;
15828: @end example
15829:
15830: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15831: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15832:
15833: @menu
15834: * Scheduling::
15835: * Direct or Indirect Threaded?::
1.109 anton 15836: * Dynamic Superinstructions::
1.1 anton 15837: * DOES>::
15838: @end menu
15839:
15840: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15841: @subsection Scheduling
15842: @cindex inner interpreter optimization
15843:
15844: There is a little complication: Pipelined and superscalar processors,
15845: i.e., RISC and some modern CISC machines can process independent
15846: instructions while waiting for the results of an instruction. The
15847: compiler usually reorders (schedules) the instructions in a way that
15848: achieves good usage of these delay slots. However, on our first tries
15849: the compiler did not do well on scheduling primitives. E.g., for
15850: @code{+} implemented as
15851: @example
15852: n=sp[0]+sp[1];
15853: sp++;
15854: sp[0]=n;
15855: NEXT;
15856: @end example
1.81 anton 15857: the @code{NEXT} comes strictly after the other code, i.e., there is
15858: nearly no scheduling. After a little thought the problem becomes clear:
15859: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15860: addresses (and the version of @code{gcc} we used would not know it even
15861: if it was possible), so it could not move the load of the cfa above the
15862: store to the TOS. Indeed the pointers could be the same, if code on or
15863: very near the top of stack were executed. In the interest of speed we
15864: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15865: in scheduling: @code{NEXT} is divided into several parts:
15866: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15867: like:
1.1 anton 15868: @example
1.81 anton 15869: NEXT_P0;
1.1 anton 15870: n=sp[0]+sp[1];
15871: sp++;
15872: NEXT_P1;
15873: sp[0]=n;
15874: NEXT_P2;
15875: @end example
15876:
1.81 anton 15877: There are various schemes that distribute the different operations of
15878: NEXT between these parts in several ways; in general, different schemes
15879: perform best on different processors. We use a scheme for most
15880: architectures that performs well for most processors of this
1.109 anton 15881: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15882: the scheme on installation time.
15883:
1.1 anton 15884:
1.109 anton 15885: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15886: @subsection Direct or Indirect Threaded?
15887: @cindex threading, direct or indirect?
15888:
1.109 anton 15889: Threaded forth code consists of references to primitives (simple machine
15890: code routines like @code{+}) and to non-primitives (e.g., colon
15891: definitions, variables, constants); for a specific class of
15892: non-primitives (e.g., variables) there is one code routine (e.g.,
15893: @code{dovar}), but each variable needs a separate reference to its data.
15894:
15895: Traditionally Forth has been implemented as indirect threaded code,
15896: because this allows to use only one cell to reference a non-primitive
15897: (basically you point to the data, and find the code address there).
15898:
15899: @cindex primitive-centric threaded code
15900: However, threaded code in Gforth (since 0.6.0) uses two cells for
15901: non-primitives, one for the code address, and one for the data address;
15902: the data pointer is an immediate argument for the virtual machine
15903: instruction represented by the code address. We call this
15904: @emph{primitive-centric} threaded code, because all code addresses point
15905: to simple primitives. E.g., for a variable, the code address is for
15906: @code{lit} (also used for integer literals like @code{99}).
15907:
15908: Primitive-centric threaded code allows us to use (faster) direct
15909: threading as dispatch method, completely portably (direct threaded code
15910: in Gforth before 0.6.0 required architecture-specific code). It also
15911: eliminates the performance problems related to I-cache consistency that
15912: 386 implementations have with direct threaded code, and allows
15913: additional optimizations.
15914:
15915: @cindex hybrid direct/indirect threaded code
15916: There is a catch, however: the @var{xt} parameter of @code{execute} can
15917: occupy only one cell, so how do we pass non-primitives with their code
15918: @emph{and} data addresses to them? Our answer is to use indirect
15919: threaded dispatch for @code{execute} and other words that use a
15920: single-cell xt. So, normal threaded code in colon definitions uses
15921: direct threading, and @code{execute} and similar words, which dispatch
15922: to xts on the data stack, use indirect threaded code. We call this
15923: @emph{hybrid direct/indirect} threaded code.
15924:
15925: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15926: @cindex gforth engine
15927: @cindex gforth-fast engine
15928: The engines @command{gforth} and @command{gforth-fast} use hybrid
15929: direct/indirect threaded code. This means that with these engines you
15930: cannot use @code{,} to compile an xt. Instead, you have to use
15931: @code{compile,}.
15932:
15933: @cindex gforth-itc engine
1.115 anton 15934: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15935: This engine uses plain old indirect threaded code. It still compiles in
15936: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15937: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15938: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15939: and execute @code{' , is compile,}. Your program can check if it is
15940: running on a hybrid direct/indirect threaded engine or a pure indirect
15941: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15942:
15943:
15944: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15945: @subsection Dynamic Superinstructions
15946: @cindex Dynamic superinstructions with replication
15947: @cindex Superinstructions
15948: @cindex Replication
15949:
15950: The engines @command{gforth} and @command{gforth-fast} use another
15951: optimization: Dynamic superinstructions with replication. As an
15952: example, consider the following colon definition:
15953:
15954: @example
15955: : squared ( n1 -- n2 )
15956: dup * ;
15957: @end example
15958:
15959: Gforth compiles this into the threaded code sequence
15960:
15961: @example
15962: dup
15963: *
15964: ;s
15965: @end example
15966:
15967: In normal direct threaded code there is a code address occupying one
15968: cell for each of these primitives. Each code address points to a
15969: machine code routine, and the interpreter jumps to this machine code in
15970: order to execute the primitive. The routines for these three
15971: primitives are (in @command{gforth-fast} on the 386):
15972:
15973: @example
15974: Code dup
15975: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15976: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15977: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15978: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15979: end-code
15980: Code *
15981: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15982: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15983: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15984: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15985: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15986: end-code
15987: Code ;s
15988: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15989: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15990: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15991: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15992: end-code
15993: @end example
15994:
15995: With dynamic superinstructions and replication the compiler does not
15996: just lay down the threaded code, but also copies the machine code
15997: fragments, usually without the jump at the end.
15998:
15999: @example
16000: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
16001: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
16002: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
16003: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
16004: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
16005: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
16006: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
16007: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
16008: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
16009: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
16010: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
16011: @end example
16012:
16013: Only when a threaded-code control-flow change happens (e.g., in
16014: @code{;s}), the jump is appended. This optimization eliminates many of
16015: these jumps and makes the rest much more predictable. The speedup
16016: depends on the processor and the application; on the Athlon and Pentium
16017: III this optimization typically produces a speedup by a factor of 2.
16018:
16019: The code addresses in the direct-threaded code are set to point to the
16020: appropriate points in the copied machine code, in this example like
16021: this:
1.1 anton 16022:
1.109 anton 16023: @example
16024: primitive code address
16025: dup $4057D27D
16026: * $4057D286
16027: ;s $4057D292
16028: @end example
16029:
16030: Thus there can be threaded-code jumps to any place in this piece of
16031: code. This also simplifies decompilation quite a bit.
16032:
16033: @cindex --no-dynamic command-line option
16034: @cindex --no-super command-line option
16035: You can disable this optimization with @option{--no-dynamic}. You can
16036: use the copying without eliminating the jumps (i.e., dynamic
16037: replication, but without superinstructions) with @option{--no-super};
16038: this gives the branch prediction benefit alone; the effect on
1.110 anton 16039: performance depends on the CPU; on the Athlon and Pentium III the
16040: speedup is a little less than for dynamic superinstructions with
16041: replication.
16042:
16043: @cindex patching threaded code
16044: One use of these options is if you want to patch the threaded code.
16045: With superinstructions, many of the dispatch jumps are eliminated, so
16046: patching often has no effect. These options preserve all the dispatch
16047: jumps.
1.109 anton 16048:
16049: @cindex --dynamic command-line option
1.110 anton 16050: On some machines dynamic superinstructions are disabled by default,
16051: because it is unsafe on these machines. However, if you feel
16052: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 16053:
16054: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 16055: @subsection DOES>
16056: @cindex @code{DOES>} implementation
16057:
1.26 crook 16058: @cindex @code{dodoes} routine
16059: @cindex @code{DOES>}-code
1.1 anton 16060: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
16061: the chunk of code executed by every word defined by a
1.109 anton 16062: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
16063: this is only needed if the xt of the word is @code{execute}d. The main
16064: problem here is: How to find the Forth code to be executed, i.e. the
16065: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
16066: solutions:
1.1 anton 16067:
1.21 crook 16068: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 16069: @code{DOES>}-code address is stored in the cell after the code address
16070: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
16071: illegal in the Forth-79 and all later standards, because in fig-Forth
16072: this address lies in the body (which is illegal in these
16073: standards). However, by making the code field larger for all words this
16074: solution becomes legal again. We use this approach. Leaving a cell
16075: unused in most words is a bit wasteful, but on the machines we are
16076: targeting this is hardly a problem.
16077:
1.1 anton 16078:
16079: @node Primitives, Performance, Threading, Engine
16080: @section Primitives
16081: @cindex primitives, implementation
16082: @cindex virtual machine instructions, implementation
16083:
16084: @menu
16085: * Automatic Generation::
16086: * TOS Optimization::
16087: * Produced code::
16088: @end menu
16089:
16090: @node Automatic Generation, TOS Optimization, Primitives, Primitives
16091: @subsection Automatic Generation
16092: @cindex primitives, automatic generation
16093:
16094: @cindex @file{prims2x.fs}
1.109 anton 16095:
1.1 anton 16096: Since the primitives are implemented in a portable language, there is no
16097: longer any need to minimize the number of primitives. On the contrary,
16098: having many primitives has an advantage: speed. In order to reduce the
16099: number of errors in primitives and to make programming them easier, we
1.109 anton 16100: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
16101: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
16102: generates most (and sometimes all) of the C code for a primitive from
16103: the stack effect notation. The source for a primitive has the following
16104: form:
1.1 anton 16105:
16106: @cindex primitive source format
16107: @format
1.58 anton 16108: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 16109: [@code{""}@i{glossary entry}@code{""}]
16110: @i{C code}
1.1 anton 16111: [@code{:}
1.29 crook 16112: @i{Forth code}]
1.1 anton 16113: @end format
16114:
16115: The items in brackets are optional. The category and glossary fields
16116: are there for generating the documentation, the Forth code is there
16117: for manual implementations on machines without GNU C. E.g., the source
16118: for the primitive @code{+} is:
16119: @example
1.58 anton 16120: + ( n1 n2 -- n ) core plus
1.1 anton 16121: n = n1+n2;
16122: @end example
16123:
16124: This looks like a specification, but in fact @code{n = n1+n2} is C
16125: code. Our primitive generation tool extracts a lot of information from
16126: the stack effect notations@footnote{We use a one-stack notation, even
16127: though we have separate data and floating-point stacks; The separate
16128: notation can be generated easily from the unified notation.}: The number
16129: of items popped from and pushed on the stack, their type, and by what
16130: name they are referred to in the C code. It then generates a C code
16131: prelude and postlude for each primitive. The final C code for @code{+}
16132: looks like this:
16133:
16134: @example
1.46 pazsan 16135: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 16136: /* */ /* documentation */
1.81 anton 16137: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 16138: @{
16139: DEF_CA /* definition of variable ca (indirect threading) */
16140: Cell n1; /* definitions of variables */
16141: Cell n2;
16142: Cell n;
1.81 anton 16143: NEXT_P0; /* NEXT part 0 */
1.1 anton 16144: n1 = (Cell) sp[1]; /* input */
16145: n2 = (Cell) TOS;
16146: sp += 1; /* stack adjustment */
16147: @{
16148: n = n1+n2; /* C code taken from the source */
16149: @}
16150: NEXT_P1; /* NEXT part 1 */
16151: TOS = (Cell)n; /* output */
16152: NEXT_P2; /* NEXT part 2 */
16153: @}
16154: @end example
16155:
16156: This looks long and inefficient, but the GNU C compiler optimizes quite
16157: well and produces optimal code for @code{+} on, e.g., the R3000 and the
16158: HP RISC machines: Defining the @code{n}s does not produce any code, and
16159: using them as intermediate storage also adds no cost.
16160:
1.26 crook 16161: There are also other optimizations that are not illustrated by this
16162: example: assignments between simple variables are usually for free (copy
1.1 anton 16163: propagation). If one of the stack items is not used by the primitive
16164: (e.g. in @code{drop}), the compiler eliminates the load from the stack
16165: (dead code elimination). On the other hand, there are some things that
16166: the compiler does not do, therefore they are performed by
16167: @file{prims2x.fs}: The compiler does not optimize code away that stores
16168: a stack item to the place where it just came from (e.g., @code{over}).
16169:
16170: While programming a primitive is usually easy, there are a few cases
16171: where the programmer has to take the actions of the generator into
16172: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 16173: fall through to @code{NEXT}.
1.109 anton 16174:
16175: For more information
1.1 anton 16176:
16177: @node TOS Optimization, Produced code, Automatic Generation, Primitives
16178: @subsection TOS Optimization
16179: @cindex TOS optimization for primitives
16180: @cindex primitives, keeping the TOS in a register
16181:
16182: An important optimization for stack machine emulators, e.g., Forth
16183: engines, is keeping one or more of the top stack items in
1.29 crook 16184: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
16185: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 16186: @itemize @bullet
16187: @item
1.29 crook 16188: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 16189: due to fewer loads from and stores to the stack.
1.29 crook 16190: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
16191: @i{y<n}, due to additional moves between registers.
1.1 anton 16192: @end itemize
16193:
16194: @cindex -DUSE_TOS
16195: @cindex -DUSE_NO_TOS
16196: In particular, keeping one item in a register is never a disadvantage,
16197: if there are enough registers. Keeping two items in registers is a
16198: disadvantage for frequent words like @code{?branch}, constants,
16199: variables, literals and @code{i}. Therefore our generator only produces
16200: code that keeps zero or one items in registers. The generated C code
16201: covers both cases; the selection between these alternatives is made at
16202: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
16203: code for @code{+} is just a simple variable name in the one-item case,
16204: otherwise it is a macro that expands into @code{sp[0]}. Note that the
16205: GNU C compiler tries to keep simple variables like @code{TOS} in
16206: registers, and it usually succeeds, if there are enough registers.
16207:
16208: @cindex -DUSE_FTOS
16209: @cindex -DUSE_NO_FTOS
16210: The primitive generator performs the TOS optimization for the
16211: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16212: operations the benefit of this optimization is even larger:
16213: floating-point operations take quite long on most processors, but can be
16214: performed in parallel with other operations as long as their results are
16215: not used. If the FP-TOS is kept in a register, this works. If
16216: it is kept on the stack, i.e., in memory, the store into memory has to
16217: wait for the result of the floating-point operation, lengthening the
16218: execution time of the primitive considerably.
16219:
16220: The TOS optimization makes the automatic generation of primitives a
16221: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16222: @code{TOS} is not sufficient. There are some special cases to
16223: consider:
16224: @itemize @bullet
16225: @item In the case of @code{dup ( w -- w w )} the generator must not
16226: eliminate the store to the original location of the item on the stack,
16227: if the TOS optimization is turned on.
16228: @item Primitives with stack effects of the form @code{--}
1.29 crook 16229: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16230: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 16231: must load the TOS from the stack at the end. But for the null stack
16232: effect @code{--} no stores or loads should be generated.
16233: @end itemize
16234:
16235: @node Produced code, , TOS Optimization, Primitives
16236: @subsection Produced code
16237: @cindex primitives, assembly code listing
16238:
16239: @cindex @file{engine.s}
16240: To see what assembly code is produced for the primitives on your machine
16241: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 16242: look at the resulting file @file{engine.s}. Alternatively, you can also
16243: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 16244:
16245: @node Performance, , Primitives, Engine
16246: @section Performance
16247: @cindex performance of some Forth interpreters
16248: @cindex engine performance
16249: @cindex benchmarking Forth systems
16250: @cindex Gforth performance
16251:
16252: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 16253: impossible to write a significantly faster threaded-code engine.
1.1 anton 16254:
16255: On register-starved machines like the 386 architecture processors
16256: improvements are possible, because @code{gcc} does not utilize the
16257: registers as well as a human, even with explicit register declarations;
16258: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16259: and hand-tuned it for the 486; this system is 1.19 times faster on the
16260: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 16261: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
16262: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16263: registers fit in real registers (and we can even afford to use the TOS
16264: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 16265: earlier results. And dynamic superinstructions provide another speedup
16266: (but only around a factor 1.2 on the 486).
1.1 anton 16267:
16268: @cindex Win32Forth performance
16269: @cindex NT Forth performance
16270: @cindex eforth performance
16271: @cindex ThisForth performance
16272: @cindex PFE performance
16273: @cindex TILE performance
1.81 anton 16274: The potential advantage of assembly language implementations is not
1.112 anton 16275: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 16276: (direct threaded, compiled with @code{gcc-2.95.1} and
16277: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16278: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16279: (with and without peephole (aka pinhole) optimization of the threaded
16280: code); all these systems were written in assembly language. We also
16281: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16282: with @code{gcc-2.6.3} with the default configuration for Linux:
16283: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16284: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16285: employs peephole optimization of the threaded code) and TILE (compiled
16286: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16287: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16288: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16289: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16290: then extended it to run the benchmarks, added the peephole optimizer,
16291: ran the benchmarks and reported the results.
1.40 anton 16292:
1.1 anton 16293: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16294: matrix multiplication come from the Stanford integer benchmarks and have
16295: been translated into Forth by Martin Fraeman; we used the versions
16296: included in the TILE Forth package, but with bigger data set sizes; and
16297: a recursive Fibonacci number computation for benchmarking calling
16298: performance. The following table shows the time taken for the benchmarks
16299: scaled by the time taken by Gforth (in other words, it shows the speedup
16300: factor that Gforth achieved over the other systems).
16301:
16302: @example
1.112 anton 16303: relative Win32- NT eforth This-
16304: time Gforth Forth Forth eforth +opt PFE Forth TILE
16305: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
16306: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
16307: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
16308: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 16309: @end example
16310:
1.26 crook 16311: You may be quite surprised by the good performance of Gforth when
16312: compared with systems written in assembly language. One important reason
16313: for the disappointing performance of these other systems is probably
16314: that they are not written optimally for the 486 (e.g., they use the
16315: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16316: but costly method for relocating the Forth image: like @code{cforth}, it
16317: computes the actual addresses at run time, resulting in two address
16318: computations per @code{NEXT} (@pxref{Image File Background}).
16319:
1.1 anton 16320: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16321: explained with the self-imposed restriction of the latter systems to
16322: standard C, which makes efficient threading impossible (however, the
1.4 anton 16323: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 16324: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16325: Moreover, current C compilers have a hard time optimizing other aspects
16326: of the ThisForth and the TILE source.
16327:
1.26 crook 16328: The performance of Gforth on 386 architecture processors varies widely
16329: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16330: allocate any of the virtual machine registers into real machine
16331: registers by itself and would not work correctly with explicit register
1.112 anton 16332: declarations, giving a significantly slower engine (on a 486DX2/66
16333: running the Sieve) than the one measured above.
1.1 anton 16334:
1.26 crook 16335: Note that there have been several releases of Win32Forth since the
16336: release presented here, so the results presented above may have little
1.40 anton 16337: predictive value for the performance of Win32Forth today (results for
16338: the current release on an i486DX2/66 are welcome).
1.1 anton 16339:
16340: @cindex @file{Benchres}
1.66 anton 16341: In
16342: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16343: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 16344: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 16345: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16346: several native code systems; that version of Gforth is slower on a 486
1.112 anton 16347: than the version used here. You can find a newer version of these
16348: measurements at
1.47 crook 16349: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 16350: find numbers for Gforth on various machines in @file{Benchres}.
16351:
1.26 crook 16352: @c ******************************************************************
1.113 anton 16353: @c @node Binding to System Library, Cross Compiler, Engine, Top
16354: @c @chapter Binding to System Library
1.13 pazsan 16355:
1.113 anton 16356: @c ****************************************************************
16357: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 16358: @chapter Cross Compiler
1.47 crook 16359: @cindex @file{cross.fs}
16360: @cindex cross-compiler
16361: @cindex metacompiler
16362: @cindex target compiler
1.13 pazsan 16363:
1.46 pazsan 16364: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16365: mostly written in Forth, including crucial parts like the outer
16366: interpreter and compiler, it needs compiled Forth code to get
16367: started. The cross compiler allows to create new images for other
16368: architectures, even running under another Forth system.
1.13 pazsan 16369:
16370: @menu
1.67 anton 16371: * Using the Cross Compiler::
16372: * How the Cross Compiler Works::
1.13 pazsan 16373: @end menu
16374:
1.21 crook 16375: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 16376: @section Using the Cross Compiler
1.46 pazsan 16377:
16378: The cross compiler uses a language that resembles Forth, but isn't. The
16379: main difference is that you can execute Forth code after definition,
16380: while you usually can't execute the code compiled by cross, because the
16381: code you are compiling is typically for a different computer than the
16382: one you are compiling on.
16383:
1.81 anton 16384: @c anton: This chapter is somewhat different from waht I would expect: I
16385: @c would expect an explanation of the cross language and how to create an
16386: @c application image with it. The section explains some aspects of
16387: @c creating a Gforth kernel.
16388:
1.46 pazsan 16389: The Makefile is already set up to allow you to create kernels for new
16390: architectures with a simple make command. The generic kernels using the
16391: GCC compiled virtual machine are created in the normal build process
16392: with @code{make}. To create a embedded Gforth executable for e.g. the
16393: 8086 processor (running on a DOS machine), type
16394:
16395: @example
16396: make kernl-8086.fi
16397: @end example
16398:
16399: This will use the machine description from the @file{arch/8086}
16400: directory to create a new kernel. A machine file may look like that:
16401:
16402: @example
16403: \ Parameter for target systems 06oct92py
16404:
16405: 4 Constant cell \ cell size in bytes
16406: 2 Constant cell<< \ cell shift to bytes
16407: 5 Constant cell>bit \ cell shift to bits
16408: 8 Constant bits/char \ bits per character
16409: 8 Constant bits/byte \ bits per byte [default: 8]
16410: 8 Constant float \ bytes per float
16411: 8 Constant /maxalign \ maximum alignment in bytes
16412: false Constant bigendian \ byte order
16413: ( true=big, false=little )
16414:
16415: include machpc.fs \ feature list
16416: @end example
16417:
16418: This part is obligatory for the cross compiler itself, the feature list
16419: is used by the kernel to conditionally compile some features in and out,
16420: depending on whether the target supports these features.
16421:
16422: There are some optional features, if you define your own primitives,
16423: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 16424: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 16425: @code{prims-include} includes primitives, and @code{>boot} prepares for
16426: booting.
16427:
16428: @example
16429: : asm-include ." Include assembler" cr
16430: s" arch/8086/asm.fs" included ;
16431:
16432: : prims-include ." Include primitives" cr
16433: s" arch/8086/prim.fs" included ;
16434:
16435: : >boot ." Prepare booting" cr
16436: s" ' boot >body into-forth 1+ !" evaluate ;
16437: @end example
16438:
16439: These words are used as sort of macro during the cross compilation in
1.81 anton 16440: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 16441: be possible --- but more complicated --- to write a new kernel project
16442: file, too.
16443:
16444: @file{kernel/main.fs} expects the machine description file name on the
16445: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16446: @code{mach-file} leaves a counted string on the stack, or
16447: @code{machine-file} leaves an address, count pair of the filename on the
16448: stack.
16449:
16450: The feature list is typically controlled using @code{SetValue}, generic
16451: files that are used by several projects can use @code{DefaultValue}
16452: instead. Both functions work like @code{Value}, when the value isn't
16453: defined, but @code{SetValue} works like @code{to} if the value is
16454: defined, and @code{DefaultValue} doesn't set anything, if the value is
16455: defined.
16456:
16457: @example
16458: \ generic mach file for pc gforth 03sep97jaw
16459:
16460: true DefaultValue NIL \ relocating
16461:
16462: >ENVIRON
16463:
16464: true DefaultValue file \ controls the presence of the
16465: \ file access wordset
16466: true DefaultValue OS \ flag to indicate a operating system
16467:
16468: true DefaultValue prims \ true: primitives are c-code
16469:
16470: true DefaultValue floating \ floating point wordset is present
16471:
16472: true DefaultValue glocals \ gforth locals are present
16473: \ will be loaded
16474: true DefaultValue dcomps \ double number comparisons
16475:
16476: true DefaultValue hash \ hashing primitives are loaded/present
16477:
16478: true DefaultValue xconds \ used together with glocals,
16479: \ special conditionals supporting gforths'
16480: \ local variables
16481: true DefaultValue header \ save a header information
16482:
16483: true DefaultValue backtrace \ enables backtrace code
16484:
16485: false DefaultValue ec
16486: false DefaultValue crlf
16487:
16488: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16489:
16490: &16 KB DefaultValue stack-size
16491: &15 KB &512 + DefaultValue fstack-size
16492: &15 KB DefaultValue rstack-size
16493: &14 KB &512 + DefaultValue lstack-size
16494: @end example
1.13 pazsan 16495:
1.48 anton 16496: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16497: @section How the Cross Compiler Works
1.13 pazsan 16498:
16499: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16500: @appendix Bugs
1.1 anton 16501: @cindex bug reporting
16502:
1.21 crook 16503: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16504:
1.103 anton 16505: If you find a bug, please submit a bug report through
16506: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16507:
16508: @itemize @bullet
16509: @item
1.81 anton 16510: A program (or a sequence of keyboard commands) that reproduces the bug.
16511: @item
16512: A description of what you think constitutes the buggy behaviour.
16513: @item
1.21 crook 16514: The Gforth version used (it is announced at the start of an
16515: interactive Gforth session).
16516: @item
16517: The machine and operating system (on Unix
16518: systems @code{uname -a} will report this information).
16519: @item
1.81 anton 16520: The installation options (you can find the configure options at the
16521: start of @file{config.status}) and configuration (@code{configure}
16522: output or @file{config.cache}).
1.21 crook 16523: @item
16524: A complete list of changes (if any) you (or your installer) have made to the
16525: Gforth sources.
16526: @end itemize
1.1 anton 16527:
16528: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16529: to Report Bugs, gcc.info, GNU C Manual}.
16530:
16531:
1.21 crook 16532: @node Origin, Forth-related information, Bugs, Top
16533: @appendix Authors and Ancestors of Gforth
1.1 anton 16534:
16535: @section Authors and Contributors
16536: @cindex authors of Gforth
16537: @cindex contributors to Gforth
16538:
16539: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16540: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16541: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16542: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16543: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16544: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16545: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16546: working on automatic support for calling C libraries. Helpful comments
16547: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16548: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16549: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16550: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16551: comments from many others; thank you all, sorry for not listing you
16552: here (but digging through my mailbox to extract your names is on my
16553: to-do list).
1.1 anton 16554:
16555: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16556: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16557: was developed across the Internet, and its authors did not meet
1.20 pazsan 16558: physically for the first 4 years of development.
1.1 anton 16559:
16560: @section Pedigree
1.26 crook 16561: @cindex pedigree of Gforth
1.1 anton 16562:
1.81 anton 16563: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16564: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16565:
1.20 pazsan 16566: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16567: 32 bit native code version of VolksForth for the Atari ST, written
16568: mostly by Dietrich Weineck.
16569:
1.81 anton 16570: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16571: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16572: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16573:
1.147 anton 16574: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16575: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16576:
16577: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16578: 1979. Robert Selzer and Bill Ragsdale developed the original
16579: implementation of fig-Forth for the 6502 based on microForth.
16580:
16581: The principal architect of microForth was Dean Sanderson. microForth was
16582: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16583: the 1802, and subsequently implemented on the 8080, the 6800 and the
16584: Z80.
16585:
16586: All earlier Forth systems were custom-made, usually by Charles Moore,
16587: who discovered (as he puts it) Forth during the late 60s. The first full
16588: Forth existed in 1971.
16589:
1.81 anton 16590: A part of the information in this section comes from
1.228 anton 16591: @cite{@uref{http://www.forth.com/resources/evolution/index.html,The
1.81 anton 16592: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16593: Charles H. Moore, presented at the HOPL-II conference and preprinted
16594: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16595: genealogical information about Forth there. For a more general (and
16596: graphical) Forth family tree look see
16597: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16598: Forth Family Tree and Timeline}.
1.1 anton 16599:
1.81 anton 16600: @c ------------------------------------------------------------------
1.113 anton 16601: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16602: @appendix Other Forth-related information
16603: @cindex Forth-related information
16604:
1.81 anton 16605: @c anton: I threw most of this stuff out, because it can be found through
16606: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16607:
16608: @cindex comp.lang.forth
16609: @cindex frequently asked questions
1.81 anton 16610: There is an active news group (comp.lang.forth) discussing Forth
16611: (including Gforth) and Forth-related issues. Its
16612: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16613: (frequently asked questions and their answers) contains a lot of
16614: information on Forth. You should read it before posting to
16615: comp.lang.forth.
1.21 crook 16616:
1.81 anton 16617: The ANS Forth standard is most usable in its
16618: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16619:
1.113 anton 16620: @c ---------------------------------------------------
16621: @node Licenses, Word Index, Forth-related information, Top
16622: @appendix Licenses
16623:
16624: @menu
16625: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 16626: * Copying:: GPL (for copying this software).
1.113 anton 16627: @end menu
16628:
1.192 anton 16629: @node GNU Free Documentation License, Copying, Licenses, Licenses
16630: @appendixsec GNU Free Documentation License
1.113 anton 16631: @include fdl.texi
16632:
1.192 anton 16633: @node Copying, , GNU Free Documentation License, Licenses
16634: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16635: @include gpl.texi
16636:
16637:
16638:
1.81 anton 16639: @c ------------------------------------------------------------------
1.113 anton 16640: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16641: @unnumbered Word Index
16642:
1.26 crook 16643: This index is a list of Forth words that have ``glossary'' entries
16644: within this manual. Each word is listed with its stack effect and
16645: wordset.
1.1 anton 16646:
16647: @printindex fn
16648:
1.81 anton 16649: @c anton: the name index seems superfluous given the word and concept indices.
16650:
16651: @c @node Name Index, Concept Index, Word Index, Top
16652: @c @unnumbered Name Index
1.41 anton 16653:
1.81 anton 16654: @c This index is a list of Forth words that have ``glossary'' entries
16655: @c within this manual.
1.41 anton 16656:
1.81 anton 16657: @c @printindex ky
1.41 anton 16658:
1.113 anton 16659: @c -------------------------------------------------------
1.81 anton 16660: @node Concept Index, , Word Index, Top
1.1 anton 16661: @unnumbered Concept and Word Index
16662:
1.26 crook 16663: Not all entries listed in this index are present verbatim in the
16664: text. This index also duplicates, in abbreviated form, all of the words
16665: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16666:
16667: @printindex cp
16668:
16669: @bye
1.81 anton 16670:
16671:
1.1 anton 16672:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>