Annotation of gforth/doc/gforth.ds, revision 1.205
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.197 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.204 anton 148: * Startup speed:: When 14ms is not fast enough ...
1.48 anton 149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.190 anton 177: * Floating Point Tutorial::
1.87 anton 178: * Files Tutorial::
1.48 anton 179: * Interpretation and Compilation Semantics and Immediacy Tutorial::
180: * Execution Tokens Tutorial::
181: * Exceptions Tutorial::
182: * Defining Words Tutorial::
183: * Arrays and Records Tutorial::
184: * POSTPONE Tutorial::
185: * Literal Tutorial::
186: * Advanced macros Tutorial::
187: * Compilation Tokens Tutorial::
188: * Wordlists and Search Order Tutorial::
1.29 crook 189:
1.24 anton 190: An Introduction to ANS Forth
191:
1.67 anton 192: * Introducing the Text Interpreter::
193: * Stacks and Postfix notation::
194: * Your first definition::
195: * How does that work?::
196: * Forth is written in Forth::
197: * Review - elements of a Forth system::
198: * Where to go next::
199: * Exercises::
1.24 anton 200:
1.12 anton 201: Forth Words
202:
203: * Notation::
1.65 anton 204: * Case insensitivity::
205: * Comments::
206: * Boolean Flags::
1.12 anton 207: * Arithmetic::
208: * Stack Manipulation::
209: * Memory::
210: * Control Structures::
211: * Defining Words::
1.65 anton 212: * Interpretation and Compilation Semantics::
1.47 crook 213: * Tokens for Words::
1.81 anton 214: * Compiling words::
1.65 anton 215: * The Text Interpreter::
1.111 anton 216: * The Input Stream::
1.65 anton 217: * Word Lists::
218: * Environmental Queries::
1.12 anton 219: * Files::
220: * Blocks::
221: * Other I/O::
1.121 anton 222: * OS command line arguments::
1.78 anton 223: * Locals::
224: * Structures::
225: * Object-oriented Forth::
1.12 anton 226: * Programming Tools::
1.150 anton 227: * C Interface::
1.12 anton 228: * Assembler and Code Words::
229: * Threading Words::
1.65 anton 230: * Passing Commands to the OS::
231: * Keeping track of Time::
232: * Miscellaneous Words::
1.12 anton 233:
234: Arithmetic
235:
236: * Single precision::
1.67 anton 237: * Double precision:: Double-cell integer arithmetic
1.12 anton 238: * Bitwise operations::
1.67 anton 239: * Numeric comparison::
1.32 anton 240: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 241: * Floating Point::
242:
243: Stack Manipulation
244:
245: * Data stack::
246: * Floating point stack::
247: * Return stack::
248: * Locals stack::
249: * Stack pointer manipulation::
250:
251: Memory
252:
1.32 anton 253: * Memory model::
254: * Dictionary allocation::
255: * Heap Allocation::
256: * Memory Access::
257: * Address arithmetic::
258: * Memory Blocks::
1.12 anton 259:
260: Control Structures
261:
1.41 anton 262: * Selection:: IF ... ELSE ... ENDIF
263: * Simple Loops:: BEGIN ...
1.32 anton 264: * Counted Loops:: DO
1.67 anton 265: * Arbitrary control structures::
266: * Calls and returns::
1.12 anton 267: * Exception Handling::
268:
269: Defining Words
270:
1.67 anton 271: * CREATE::
1.44 crook 272: * Variables:: Variables and user variables
1.67 anton 273: * Constants::
1.44 crook 274: * Values:: Initialised variables
1.67 anton 275: * Colon Definitions::
1.44 crook 276: * Anonymous Definitions:: Definitions without names
1.71 anton 277: * Supplying names:: Passing definition names as strings
1.67 anton 278: * User-defined Defining Words::
1.170 pazsan 279: * Deferred Words:: Allow forward references
1.67 anton 280: * Aliases::
1.47 crook 281:
1.63 anton 282: User-defined Defining Words
283:
284: * CREATE..DOES> applications::
285: * CREATE..DOES> details::
286: * Advanced does> usage example::
1.155 anton 287: * Const-does>::
1.63 anton 288:
1.47 crook 289: Interpretation and Compilation Semantics
290:
1.67 anton 291: * Combined words::
1.12 anton 292:
1.71 anton 293: Tokens for Words
294:
295: * Execution token:: represents execution/interpretation semantics
296: * Compilation token:: represents compilation semantics
297: * Name token:: represents named words
298:
1.82 anton 299: Compiling words
300:
301: * Literals:: Compiling data values
302: * Macros:: Compiling words
303:
1.21 crook 304: The Text Interpreter
305:
1.67 anton 306: * Input Sources::
307: * Number Conversion::
308: * Interpret/Compile states::
309: * Interpreter Directives::
1.21 crook 310:
1.26 crook 311: Word Lists
312:
1.75 anton 313: * Vocabularies::
1.67 anton 314: * Why use word lists?::
1.75 anton 315: * Word list example::
1.26 crook 316:
317: Files
318:
1.48 anton 319: * Forth source files::
320: * General files::
1.167 anton 321: * Redirection::
1.48 anton 322: * Search Paths::
323:
324: Search Paths
325:
1.75 anton 326: * Source Search Paths::
1.26 crook 327: * General Search Paths::
328:
329: Other I/O
330:
1.32 anton 331: * Simple numeric output:: Predefined formats
332: * Formatted numeric output:: Formatted (pictured) output
333: * String Formats:: How Forth stores strings in memory
1.67 anton 334: * Displaying characters and strings:: Other stuff
1.178 anton 335: * Terminal output:: Cursor positioning etc.
1.181 anton 336: * Single-key input::
337: * Line input and conversion::
1.112 anton 338: * Pipes:: How to create your own pipes
1.149 pazsan 339: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 340:
341: Locals
342:
343: * Gforth locals::
344: * ANS Forth locals::
345:
346: Gforth locals
347:
348: * Where are locals visible by name?::
349: * How long do locals live?::
1.78 anton 350: * Locals programming style::
351: * Locals implementation::
1.26 crook 352:
1.12 anton 353: Structures
354:
355: * Why explicit structure support?::
356: * Structure Usage::
357: * Structure Naming Convention::
358: * Structure Implementation::
359: * Structure Glossary::
1.183 anton 360: * Forth200x Structures::
1.12 anton 361:
362: Object-oriented Forth
363:
1.48 anton 364: * Why object-oriented programming?::
365: * Object-Oriented Terminology::
366: * Objects::
367: * OOF::
368: * Mini-OOF::
1.23 crook 369: * Comparison with other object models::
1.12 anton 370:
1.24 anton 371: The @file{objects.fs} model
1.12 anton 372:
373: * Properties of the Objects model::
374: * Basic Objects Usage::
1.41 anton 375: * The Objects base class::
1.12 anton 376: * Creating objects::
377: * Object-Oriented Programming Style::
378: * Class Binding::
379: * Method conveniences::
380: * Classes and Scoping::
1.41 anton 381: * Dividing classes::
1.12 anton 382: * Object Interfaces::
383: * Objects Implementation::
384: * Objects Glossary::
385:
1.24 anton 386: The @file{oof.fs} model
1.12 anton 387:
1.67 anton 388: * Properties of the OOF model::
389: * Basic OOF Usage::
390: * The OOF base class::
391: * Class Declaration::
392: * Class Implementation::
1.12 anton 393:
1.24 anton 394: The @file{mini-oof.fs} model
1.23 crook 395:
1.48 anton 396: * Basic Mini-OOF Usage::
397: * Mini-OOF Example::
398: * Mini-OOF Implementation::
1.23 crook 399:
1.78 anton 400: Programming Tools
401:
1.150 anton 402: * Examining:: Data and Code.
403: * Forgetting words:: Usually before reloading.
1.78 anton 404: * Debugging:: Simple and quick.
405: * Assertions:: Making your programs self-checking.
406: * Singlestep Debugger:: Executing your program word by word.
407:
1.155 anton 408: C Interface
409:
410: * Calling C Functions::
411: * Declaring C Functions::
1.180 anton 412: * Calling C function pointers::
1.196 anton 413: * Defining library interfaces::
414: * Declaring OS-level libraries::
1.155 anton 415: * Callbacks::
1.178 anton 416: * C interface internals::
1.155 anton 417: * Low-Level C Interface Words::
418:
1.78 anton 419: Assembler and Code Words
420:
421: * Code and ;code::
422: * Common Assembler:: Assembler Syntax
423: * Common Disassembler::
424: * 386 Assembler:: Deviations and special cases
425: * Alpha Assembler:: Deviations and special cases
426: * MIPS assembler:: Deviations and special cases
1.167 anton 427: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 428: * ARM Assembler:: Deviations and special cases
1.78 anton 429: * Other assemblers:: How to write them
430:
1.12 anton 431: Tools
432:
433: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 434: * Stack depth changes:: Where does this stack item come from?
1.12 anton 435:
436: ANS conformance
437:
438: * The Core Words::
439: * The optional Block word set::
440: * The optional Double Number word set::
441: * The optional Exception word set::
442: * The optional Facility word set::
443: * The optional File-Access word set::
444: * The optional Floating-Point word set::
445: * The optional Locals word set::
446: * The optional Memory-Allocation word set::
447: * The optional Programming-Tools word set::
448: * The optional Search-Order word set::
449:
450: The Core Words
451:
452: * core-idef:: Implementation Defined Options
453: * core-ambcond:: Ambiguous Conditions
454: * core-other:: Other System Documentation
455:
456: The optional Block word set
457:
458: * block-idef:: Implementation Defined Options
459: * block-ambcond:: Ambiguous Conditions
460: * block-other:: Other System Documentation
461:
462: The optional Double Number word set
463:
464: * double-ambcond:: Ambiguous Conditions
465:
466: The optional Exception word set
467:
468: * exception-idef:: Implementation Defined Options
469:
470: The optional Facility word set
471:
472: * facility-idef:: Implementation Defined Options
473: * facility-ambcond:: Ambiguous Conditions
474:
475: The optional File-Access word set
476:
477: * file-idef:: Implementation Defined Options
478: * file-ambcond:: Ambiguous Conditions
479:
480: The optional Floating-Point word set
481:
482: * floating-idef:: Implementation Defined Options
483: * floating-ambcond:: Ambiguous Conditions
484:
485: The optional Locals word set
486:
487: * locals-idef:: Implementation Defined Options
488: * locals-ambcond:: Ambiguous Conditions
489:
490: The optional Memory-Allocation word set
491:
492: * memory-idef:: Implementation Defined Options
493:
494: The optional Programming-Tools word set
495:
496: * programming-idef:: Implementation Defined Options
497: * programming-ambcond:: Ambiguous Conditions
498:
499: The optional Search-Order word set
500:
501: * search-idef:: Implementation Defined Options
502: * search-ambcond:: Ambiguous Conditions
503:
1.109 anton 504: Emacs and Gforth
505:
506: * Installing gforth.el:: Making Emacs aware of Forth.
507: * Emacs Tags:: Viewing the source of a word in Emacs.
508: * Hilighting:: Making Forth code look prettier.
509: * Auto-Indentation:: Customizing auto-indentation.
510: * Blocks Files:: Reading and writing blocks files.
511:
1.12 anton 512: Image Files
513:
1.24 anton 514: * Image Licensing Issues:: Distribution terms for images.
515: * Image File Background:: Why have image files?
1.67 anton 516: * Non-Relocatable Image Files:: don't always work.
1.24 anton 517: * Data-Relocatable Image Files:: are better.
1.67 anton 518: * Fully Relocatable Image Files:: better yet.
1.24 anton 519: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 520: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 521: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 522:
523: Fully Relocatable Image Files
524:
1.27 crook 525: * gforthmi:: The normal way
1.12 anton 526: * cross.fs:: The hard way
527:
528: Engine
529:
530: * Portability::
531: * Threading::
532: * Primitives::
533: * Performance::
534:
535: Threading
536:
537: * Scheduling::
538: * Direct or Indirect Threaded?::
1.109 anton 539: * Dynamic Superinstructions::
1.12 anton 540: * DOES>::
541:
542: Primitives
543:
544: * Automatic Generation::
545: * TOS Optimization::
546: * Produced code::
1.13 pazsan 547:
548: Cross Compiler
549:
1.67 anton 550: * Using the Cross Compiler::
551: * How the Cross Compiler Works::
1.13 pazsan 552:
1.113 anton 553: Licenses
554:
555: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 556: * Copying:: GPL (for copying this software).
1.113 anton 557:
1.24 anton 558: @end detailmenu
1.1 anton 559: @end menu
560:
1.113 anton 561: @c ----------------------------------------------------------
1.1 anton 562: @iftex
563: @unnumbered Preface
564: @cindex Preface
1.21 crook 565: This manual documents Gforth. Some introductory material is provided for
566: readers who are unfamiliar with Forth or who are migrating to Gforth
567: from other Forth compilers. However, this manual is primarily a
568: reference manual.
1.1 anton 569: @end iftex
570:
1.28 crook 571: @comment TODO much more blurb here.
1.26 crook 572:
573: @c ******************************************************************
1.113 anton 574: @node Goals, Gforth Environment, Top, Top
1.26 crook 575: @comment node-name, next, previous, up
576: @chapter Goals of Gforth
577: @cindex goals of the Gforth project
578: The goal of the Gforth Project is to develop a standard model for
579: ANS Forth. This can be split into several subgoals:
580:
581: @itemize @bullet
582: @item
583: Gforth should conform to the ANS Forth Standard.
584: @item
585: It should be a model, i.e. it should define all the
586: implementation-dependent things.
587: @item
588: It should become standard, i.e. widely accepted and used. This goal
589: is the most difficult one.
590: @end itemize
591:
592: To achieve these goals Gforth should be
593: @itemize @bullet
594: @item
595: Similar to previous models (fig-Forth, F83)
596: @item
597: Powerful. It should provide for all the things that are considered
598: necessary today and even some that are not yet considered necessary.
599: @item
600: Efficient. It should not get the reputation of being exceptionally
601: slow.
602: @item
603: Free.
604: @item
605: Available on many machines/easy to port.
606: @end itemize
607:
608: Have we achieved these goals? Gforth conforms to the ANS Forth
609: standard. It may be considered a model, but we have not yet documented
610: which parts of the model are stable and which parts we are likely to
611: change. It certainly has not yet become a de facto standard, but it
612: appears to be quite popular. It has some similarities to and some
613: differences from previous models. It has some powerful features, but not
614: yet everything that we envisioned. We certainly have achieved our
1.65 anton 615: execution speed goals (@pxref{Performance})@footnote{However, in 1998
616: the bar was raised when the major commercial Forth vendors switched to
617: native code compilers.}. It is free and available on many machines.
1.29 crook 618:
1.26 crook 619: @c ******************************************************************
1.48 anton 620: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 621: @chapter Gforth Environment
622: @cindex Gforth environment
1.21 crook 623:
1.45 crook 624: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 625: material in this chapter.
1.21 crook 626:
627: @menu
1.29 crook 628: * Invoking Gforth:: Getting in
629: * Leaving Gforth:: Getting out
630: * Command-line editing::
1.48 anton 631: * Environment variables:: that affect how Gforth starts up
1.29 crook 632: * Gforth Files:: What gets installed and where
1.112 anton 633: * Gforth in pipes::
1.204 anton 634: * Startup speed:: When 14ms is not fast enough ...
1.21 crook 635: @end menu
636:
1.49 anton 637: For related information about the creation of images see @ref{Image Files}.
1.29 crook 638:
1.21 crook 639: @comment ----------------------------------------------
1.48 anton 640: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 641: @section Invoking Gforth
642: @cindex invoking Gforth
643: @cindex running Gforth
644: @cindex command-line options
645: @cindex options on the command line
646: @cindex flags on the command line
1.21 crook 647:
1.30 anton 648: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 649: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 650: will usually just say @code{gforth} -- this automatically loads the
651: default image file @file{gforth.fi}. In many other cases the default
652: Gforth image will be invoked like this:
1.21 crook 653: @example
1.30 anton 654: gforth [file | -e forth-code] ...
1.21 crook 655: @end example
1.29 crook 656: @noindent
657: This interprets the contents of the files and the Forth code in the order they
658: are given.
1.21 crook 659:
1.109 anton 660: In addition to the @command{gforth} engine, there is also an engine
661: called @command{gforth-fast}, which is faster, but gives less
662: informative error messages (@pxref{Error messages}) and may catch some
1.166 anton 663: errors (in particular, stack underflows and integer division errors)
664: later or not at all. You should use it for debugged,
1.109 anton 665: performance-critical programs.
666:
667: Moreover, there is an engine called @command{gforth-itc}, which is
668: useful in some backwards-compatibility situations (@pxref{Direct or
669: Indirect Threaded?}).
1.30 anton 670:
1.29 crook 671: In general, the command line looks like this:
1.21 crook 672:
673: @example
1.30 anton 674: gforth[-fast] [engine options] [image options]
1.21 crook 675: @end example
676:
1.30 anton 677: The engine options must come before the rest of the command
1.29 crook 678: line. They are:
1.26 crook 679:
1.29 crook 680: @table @code
681: @cindex -i, command-line option
682: @cindex --image-file, command-line option
683: @item --image-file @i{file}
684: @itemx -i @i{file}
685: Loads the Forth image @i{file} instead of the default
686: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 687:
1.39 anton 688: @cindex --appl-image, command-line option
689: @item --appl-image @i{file}
690: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 691: to the image (instead of processing them as engine options). This is
692: useful for building executable application images on Unix, built with
1.39 anton 693: @code{gforthmi --application ...}.
694:
1.29 crook 695: @cindex --path, command-line option
696: @cindex -p, command-line option
697: @item --path @i{path}
698: @itemx -p @i{path}
699: Uses @i{path} for searching the image file and Forth source code files
700: instead of the default in the environment variable @code{GFORTHPATH} or
701: the path specified at installation time (e.g.,
702: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
703: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 704:
1.29 crook 705: @cindex --dictionary-size, command-line option
706: @cindex -m, command-line option
707: @cindex @i{size} parameters for command-line options
708: @cindex size of the dictionary and the stacks
709: @item --dictionary-size @i{size}
710: @itemx -m @i{size}
711: Allocate @i{size} space for the Forth dictionary space instead of
712: using the default specified in the image (typically 256K). The
713: @i{size} specification for this and subsequent options consists of
714: an integer and a unit (e.g.,
715: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
716: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
717: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
718: @code{e} is used.
1.21 crook 719:
1.29 crook 720: @cindex --data-stack-size, command-line option
721: @cindex -d, command-line option
722: @item --data-stack-size @i{size}
723: @itemx -d @i{size}
724: Allocate @i{size} space for the data stack instead of using the
725: default specified in the image (typically 16K).
1.21 crook 726:
1.29 crook 727: @cindex --return-stack-size, command-line option
728: @cindex -r, command-line option
729: @item --return-stack-size @i{size}
730: @itemx -r @i{size}
731: Allocate @i{size} space for the return stack instead of using the
732: default specified in the image (typically 15K).
1.21 crook 733:
1.29 crook 734: @cindex --fp-stack-size, command-line option
735: @cindex -f, command-line option
736: @item --fp-stack-size @i{size}
737: @itemx -f @i{size}
738: Allocate @i{size} space for the floating point stack instead of
739: using the default specified in the image (typically 15.5K). In this case
740: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 741:
1.48 anton 742: @cindex --locals-stack-size, command-line option
743: @cindex -l, command-line option
744: @item --locals-stack-size @i{size}
745: @itemx -l @i{size}
746: Allocate @i{size} space for the locals stack instead of using the
747: default specified in the image (typically 14.5K).
748:
1.176 anton 749: @cindex --vm-commit, command-line option
750: @cindex overcommit memory for dictionary and stacks
751: @cindex memory overcommit for dictionary and stacks
752: @item --vm-commit
753: Normally, Gforth tries to start up even if there is not enough virtual
754: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
755: on OSs that support it); so you can ask for a really big dictionary
756: and/or stacks, and as long as you don't use more virtual memory than
757: is available, everything will be fine (but if you use more, processes
758: get killed). With this option you just use the default allocation
759: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
760: means that you cannot and should not ask for as big dictionary and
761: stacks, but once Gforth successfully starts up, out-of-memory won't
762: kill it.
763:
1.48 anton 764: @cindex -h, command-line option
765: @cindex --help, command-line option
766: @item --help
767: @itemx -h
768: Print a message about the command-line options
769:
770: @cindex -v, command-line option
771: @cindex --version, command-line option
772: @item --version
773: @itemx -v
774: Print version and exit
775:
776: @cindex --debug, command-line option
777: @item --debug
778: Print some information useful for debugging on startup.
779:
780: @cindex --offset-image, command-line option
781: @item --offset-image
782: Start the dictionary at a slightly different position than would be used
783: otherwise (useful for creating data-relocatable images,
784: @pxref{Data-Relocatable Image Files}).
785:
786: @cindex --no-offset-im, command-line option
787: @item --no-offset-im
788: Start the dictionary at the normal position.
789:
790: @cindex --clear-dictionary, command-line option
791: @item --clear-dictionary
792: Initialize all bytes in the dictionary to 0 before loading the image
793: (@pxref{Data-Relocatable Image Files}).
794:
795: @cindex --die-on-signal, command-line-option
796: @item --die-on-signal
797: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
798: or the segmentation violation SIGSEGV) by translating it into a Forth
799: @code{THROW}. With this option, Gforth exits if it receives such a
800: signal. This option is useful when the engine and/or the image might be
801: severely broken (such that it causes another signal before recovering
802: from the first); this option avoids endless loops in such cases.
1.109 anton 803:
1.119 anton 804: @cindex --no-dynamic, command-line option
805: @cindex --dynamic, command-line option
1.109 anton 806: @item --no-dynamic
807: @item --dynamic
808: Disable or enable dynamic superinstructions with replication
809: (@pxref{Dynamic Superinstructions}).
810:
1.119 anton 811: @cindex --no-super, command-line option
1.109 anton 812: @item --no-super
1.110 anton 813: Disable dynamic superinstructions, use just dynamic replication; this is
814: useful if you want to patch threaded code (@pxref{Dynamic
815: Superinstructions}).
1.119 anton 816:
817: @cindex --ss-number, command-line option
818: @item --ss-number=@var{N}
819: Use only the first @var{N} static superinstructions compiled into the
820: engine (default: use them all; note that only @code{gforth-fast} has
821: any). This option is useful for measuring the performance impact of
822: static superinstructions.
823:
824: @cindex --ss-min-..., command-line options
825: @item --ss-min-codesize
826: @item --ss-min-ls
827: @item --ss-min-lsu
828: @item --ss-min-nexts
829: Use specified metric for determining the cost of a primitive or static
830: superinstruction for static superinstruction selection. @code{Codesize}
831: is the native code size of the primive or static superinstruction,
832: @code{ls} is the number of loads and stores, @code{lsu} is the number of
833: loads, stores, and updates, and @code{nexts} is the number of dispatches
834: (not taking dynamic superinstructions into account), i.e. every
835: primitive or static superinstruction has cost 1. Default:
836: @code{codesize} if you use dynamic code generation, otherwise
837: @code{nexts}.
838:
839: @cindex --ss-greedy, command-line option
840: @item --ss-greedy
841: This option is useful for measuring the performance impact of static
842: superinstructions. By default, an optimal shortest-path algorithm is
843: used for selecting static superinstructions. With @option{--ss-greedy}
844: this algorithm is modified to assume that anything after the static
845: superinstruction currently under consideration is not combined into
846: static superinstructions. With @option{--ss-min-nexts} this produces
847: the same result as a greedy algorithm that always selects the longest
848: superinstruction available at the moment. E.g., if there are
849: superinstructions AB and BCD, then for the sequence A B C D the optimal
850: algorithm will select A BCD and the greedy algorithm will select AB C D.
851:
852: @cindex --print-metrics, command-line option
853: @item --print-metrics
854: Prints some metrics used during static superinstruction selection:
855: @code{code size} is the actual size of the dynamically generated code.
856: @code{Metric codesize} is the sum of the codesize metrics as seen by
857: static superinstruction selection; there is a difference from @code{code
858: size}, because not all primitives and static superinstructions are
859: compiled into dynamically generated code, and because of markers. The
860: other metrics correspond to the @option{ss-min-...} options. This
861: option is useful for evaluating the effects of the @option{--ss-...}
862: options.
1.109 anton 863:
1.48 anton 864: @end table
865:
866: @cindex loading files at startup
867: @cindex executing code on startup
868: @cindex batch processing with Gforth
869: As explained above, the image-specific command-line arguments for the
870: default image @file{gforth.fi} consist of a sequence of filenames and
871: @code{-e @var{forth-code}} options that are interpreted in the sequence
872: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 873: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
874: option takes only one argument; if you want to evaluate more Forth
875: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 876: after processing the command line (instead of entering interactive mode)
1.121 anton 877: append @code{-e bye} to the command line. You can also process the
878: command-line arguments with a Forth program (@pxref{OS command line
879: arguments}).
1.48 anton 880:
881: @cindex versions, invoking other versions of Gforth
882: If you have several versions of Gforth installed, @code{gforth} will
883: invoke the version that was installed last. @code{gforth-@i{version}}
884: invokes a specific version. If your environment contains the variable
885: @code{GFORTHPATH}, you may want to override it by using the
886: @code{--path} option.
887:
888: Not yet implemented:
889: On startup the system first executes the system initialization file
890: (unless the option @code{--no-init-file} is given; note that the system
891: resulting from using this option may not be ANS Forth conformant). Then
892: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 893: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 894: then in @file{~}, then in the normal path (see above).
895:
896:
897:
898: @comment ----------------------------------------------
899: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
900: @section Leaving Gforth
901: @cindex Gforth - leaving
902: @cindex leaving Gforth
903:
904: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
905: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
906: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 907: data are discarded. For ways of saving the state of the system before
908: leaving Gforth see @ref{Image Files}.
1.48 anton 909:
910: doc-bye
911:
912:
913: @comment ----------------------------------------------
1.65 anton 914: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 915: @section Command-line editing
916: @cindex command-line editing
917:
918: Gforth maintains a history file that records every line that you type to
919: the text interpreter. This file is preserved between sessions, and is
920: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
921: repeatedly you can recall successively older commands from this (or
922: previous) session(s). The full list of command-line editing facilities is:
923:
924: @itemize @bullet
925: @item
926: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
927: commands from the history buffer.
928: @item
929: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
930: from the history buffer.
931: @item
932: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
933: @item
934: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
935: @item
936: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
937: closing up the line.
938: @item
939: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
940: @item
941: @kbd{Ctrl-a} to move the cursor to the start of the line.
942: @item
943: @kbd{Ctrl-e} to move the cursor to the end of the line.
944: @item
945: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
946: line.
947: @item
948: @key{TAB} to step through all possible full-word completions of the word
949: currently being typed.
950: @item
1.65 anton 951: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
952: using @code{bye}).
953: @item
954: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
955: character under the cursor.
1.48 anton 956: @end itemize
957:
958: When editing, displayable characters are inserted to the left of the
959: cursor position; the line is always in ``insert'' (as opposed to
960: ``overstrike'') mode.
961:
962: @cindex history file
963: @cindex @file{.gforth-history}
964: On Unix systems, the history file is @file{~/.gforth-history} by
965: default@footnote{i.e. it is stored in the user's home directory.}. You
966: can find out the name and location of your history file using:
967:
968: @example
969: history-file type \ Unix-class systems
970:
971: history-file type \ Other systems
972: history-dir type
973: @end example
974:
975: If you enter long definitions by hand, you can use a text editor to
976: paste them out of the history file into a Forth source file for reuse at
977: a later time.
978:
979: Gforth never trims the size of the history file, so you should do this
980: periodically, if necessary.
981:
982: @comment this is all defined in history.fs
983: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
984: @comment chosen?
985:
986:
987: @comment ----------------------------------------------
1.65 anton 988: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 989: @section Environment variables
990: @cindex environment variables
991:
992: Gforth uses these environment variables:
993:
994: @itemize @bullet
995: @item
996: @cindex @code{GFORTHHIST} -- environment variable
997: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
998: open/create the history file, @file{.gforth-history}. Default:
999: @code{$HOME}.
1000:
1001: @item
1002: @cindex @code{GFORTHPATH} -- environment variable
1003: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1004: for Forth source-code files.
1005:
1006: @item
1.147 anton 1007: @cindex @code{LANG} -- environment variable
1008: @code{LANG} -- see @code{LC_CTYPE}
1009:
1010: @item
1011: @cindex @code{LC_ALL} -- environment variable
1012: @code{LC_ALL} -- see @code{LC_CTYPE}
1013:
1014: @item
1015: @cindex @code{LC_CTYPE} -- environment variable
1016: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1017: startup, Gforth uses the UTF-8 encoding for strings internally and
1018: expects its input and produces its output in UTF-8 encoding, otherwise
1019: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1020: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1021: that is unset, in @code{LANG}.
1022:
1023: @item
1.129 anton 1024: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1025:
1026: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1027: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1028: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1029: and the command are directly concatenated, so if a space between them is
1030: necessary, append it to the prefix.
1031:
1032: @item
1.48 anton 1033: @cindex @code{GFORTH} -- environment variable
1.49 anton 1034: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1035:
1036: @item
1037: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1038: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1039:
1040: @item
1041: @cindex @code{TMP}, @code{TEMP} - environment variable
1042: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1043: location for the history file.
1044: @end itemize
1045:
1046: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1047: @comment mentioning these.
1048:
1049: All the Gforth environment variables default to sensible values if they
1050: are not set.
1051:
1052:
1053: @comment ----------------------------------------------
1.112 anton 1054: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1055: @section Gforth files
1056: @cindex Gforth files
1057:
1058: When you install Gforth on a Unix system, it installs files in these
1059: locations by default:
1060:
1061: @itemize @bullet
1062: @item
1063: @file{/usr/local/bin/gforth}
1064: @item
1065: @file{/usr/local/bin/gforthmi}
1066: @item
1067: @file{/usr/local/man/man1/gforth.1} - man page.
1068: @item
1069: @file{/usr/local/info} - the Info version of this manual.
1070: @item
1071: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1072: @item
1073: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1074: @item
1075: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1076: @item
1077: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1078: @end itemize
1079:
1080: You can select different places for installation by using
1081: @code{configure} options (listed with @code{configure --help}).
1082:
1083: @comment ----------------------------------------------
1.112 anton 1084: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1085: @section Gforth in pipes
1086: @cindex pipes, Gforth as part of
1087:
1088: Gforth can be used in pipes created elsewhere (described here). It can
1089: also create pipes on its own (@pxref{Pipes}).
1090:
1091: @cindex input from pipes
1092: If you pipe into Gforth, your program should read with @code{read-file}
1093: or @code{read-line} from @code{stdin} (@pxref{General files}).
1094: @code{Key} does not recognize the end of input. Words like
1095: @code{accept} echo the input and are therefore usually not useful for
1096: reading from a pipe. You have to invoke the Forth program with an OS
1097: command-line option, as you have no chance to use the Forth command line
1098: (the text interpreter would try to interpret the pipe input).
1099:
1100: @cindex output in pipes
1101: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1102:
1103: @cindex silent exiting from Gforth
1104: When you write to a pipe that has been closed at the other end, Gforth
1105: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1106: into the exception @code{broken-pipe-error}. If your application does
1107: not catch that exception, the system catches it and exits, usually
1108: silently (unless you were working on the Forth command line; then it
1109: prints an error message and exits). This is usually the desired
1110: behaviour.
1111:
1112: If you do not like this behaviour, you have to catch the exception
1113: yourself, and react to it.
1114:
1115: Here's an example of an invocation of Gforth that is usable in a pipe:
1116:
1117: @example
1118: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1119: type repeat ; foo bye"
1120: @end example
1121:
1122: This example just copies the input verbatim to the output. A very
1123: simple pipe containing this example looks like this:
1124:
1125: @example
1126: cat startup.fs |
1127: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1128: type repeat ; foo bye"|
1129: head
1130: @end example
1131:
1132: @cindex stderr and pipes
1133: Pipes involving Gforth's @code{stderr} output do not work.
1134:
1135: @comment ----------------------------------------------
1136: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1137: @section Startup speed
1138: @cindex Startup speed
1139: @cindex speed, startup
1140:
1141: If Gforth is used for CGI scripts or in shell scripts, its startup
1.204 anton 1142: speed may become a problem. On a 3GHz Core 2 Duo E8400 under 64-bit
1143: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
1144: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
1145: with about 3.4ms user time and 1.2ms system time, because it subsumes
1146: some of the options discussed below).
1.48 anton 1147:
1148: If startup speed is a problem, you may consider the following ways to
1149: improve it; or you may consider ways to reduce the number of startups
1.204 anton 1150: (for example, by using Fast-CGI). Note that the first steps below
1151: improve the startup time at the cost of run-time (including
1152: compile-time), so whether they are profitable depends on the balance
1153: of these times in your application.
1154:
1155: An easy step that influences Gforth startup speed is the use of a
1156: number of options that increase run-time, but decrease image-loading
1157: time.
1158:
1159: The first of these that you should try is @code{--ss-number=0
1160: --ss-states=1} because this option buys relatively little run-time
1161: speedup and costs quite a bit of time at startup. @code{gforth-fast
1162: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
1163: system time.
1.48 anton 1164:
1.204 anton 1165: The next option is @code{--no-dynamic} which has a substantial impact
1166: on run-time (about a factor of 2 on several platforms), but still
1167: makes startup speed a little faster: @code{gforth-fast --ss-number=0
1168: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
1169: system time.
1170:
1171: The next step to improve startup speed is to use a data-relocatable
1172: image (@pxref{Data-Relocatable Image Files}). This avoids the
1173: relocation cost for the code in the image (but not for the data).
1174: Note that the image is then specific to the particular binary you are
1175: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
1176: the particular build). You create the data-relocatable image that
1177: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
1178: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
1179: required here or the image will not work). And you run it with
1180: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
1181: above don't matter here, because they only come into play on
1182: relocatable code). @code{gforth-fast -i gforthdr.fi -e bye} takes
1183: about 1.1ms user and 1.2ms system time.
1184:
1185: One step further is to avoid all relocation cost and part of the
1186: copy-on-write cost through using a non-relocatable image
1187: (@pxref{Non-Relocatable Image Files}). However, this has the
1188: disadvantage that it does not work on operating systems with address
1189: space randomization (the default in, e.g., Linux nowadays), or if the
1190: dictionary moves for any other reason (e.g., because of a change of
1191: the OS kernel or an updated library), so we cannot really recommend
1192: it. You create a non-relocatable image with @code{gforth-fast
1193: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
1194: is required here, too). And you run it with @code{gforth-fast -i
1195: gforthnr.fi ... -e bye} (again the flags discussed above don't
1196: matter). @code{gforth-fast -i gforthdr.fi -e bye} takes
1197: about 0.9ms user and 0.9ms system time.
1198:
1199: If the script you want to execute contains a significant amount of
1200: code, it may be profitable to compile it into the image to avoid the
1201: cost of compiling it at startup time.
1.48 anton 1202:
1203: @c ******************************************************************
1204: @node Tutorial, Introduction, Gforth Environment, Top
1205: @chapter Forth Tutorial
1206: @cindex Tutorial
1207: @cindex Forth Tutorial
1208:
1.67 anton 1209: @c Topics from nac's Introduction that could be mentioned:
1210: @c press <ret> after each line
1211: @c Prompt
1212: @c numbers vs. words in dictionary on text interpretation
1213: @c what happens on redefinition
1214: @c parsing words (in particular, defining words)
1215:
1.83 anton 1216: The difference of this chapter from the Introduction
1217: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1218: be used while sitting in front of a computer, and covers much more
1219: material, but does not explain how the Forth system works.
1220:
1.62 crook 1221: This tutorial can be used with any ANS-compliant Forth; any
1222: Gforth-specific features are marked as such and you can skip them if you
1223: work with another Forth. This tutorial does not explain all features of
1224: Forth, just enough to get you started and give you some ideas about the
1225: facilities available in Forth. Read the rest of the manual and the
1226: standard when you are through this.
1.48 anton 1227:
1228: The intended way to use this tutorial is that you work through it while
1229: sitting in front of the console, take a look at the examples and predict
1230: what they will do, then try them out; if the outcome is not as expected,
1231: find out why (e.g., by trying out variations of the example), so you
1232: understand what's going on. There are also some assignments that you
1233: should solve.
1234:
1235: This tutorial assumes that you have programmed before and know what,
1236: e.g., a loop is.
1237:
1238: @c !! explain compat library
1239:
1240: @menu
1241: * Starting Gforth Tutorial::
1242: * Syntax Tutorial::
1243: * Crash Course Tutorial::
1244: * Stack Tutorial::
1245: * Arithmetics Tutorial::
1246: * Stack Manipulation Tutorial::
1247: * Using files for Forth code Tutorial::
1248: * Comments Tutorial::
1249: * Colon Definitions Tutorial::
1250: * Decompilation Tutorial::
1251: * Stack-Effect Comments Tutorial::
1252: * Types Tutorial::
1253: * Factoring Tutorial::
1254: * Designing the stack effect Tutorial::
1255: * Local Variables Tutorial::
1256: * Conditional execution Tutorial::
1257: * Flags and Comparisons Tutorial::
1258: * General Loops Tutorial::
1259: * Counted loops Tutorial::
1260: * Recursion Tutorial::
1261: * Leaving definitions or loops Tutorial::
1262: * Return Stack Tutorial::
1263: * Memory Tutorial::
1264: * Characters and Strings Tutorial::
1265: * Alignment Tutorial::
1.190 anton 1266: * Floating Point Tutorial::
1.87 anton 1267: * Files Tutorial::
1.48 anton 1268: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1269: * Execution Tokens Tutorial::
1270: * Exceptions Tutorial::
1271: * Defining Words Tutorial::
1272: * Arrays and Records Tutorial::
1273: * POSTPONE Tutorial::
1274: * Literal Tutorial::
1275: * Advanced macros Tutorial::
1276: * Compilation Tokens Tutorial::
1277: * Wordlists and Search Order Tutorial::
1278: @end menu
1279:
1280: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1281: @section Starting Gforth
1.66 anton 1282: @cindex starting Gforth tutorial
1.48 anton 1283: You can start Gforth by typing its name:
1284:
1285: @example
1286: gforth
1287: @end example
1288:
1289: That puts you into interactive mode; you can leave Gforth by typing
1290: @code{bye}. While in Gforth, you can edit the command line and access
1291: the command line history with cursor keys, similar to bash.
1292:
1293:
1294: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1295: @section Syntax
1.66 anton 1296: @cindex syntax tutorial
1.48 anton 1297:
1.171 anton 1298: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1299: space). Words are separated by white space. E.g., each of the
1300: following lines contains exactly one word:
1301:
1302: @example
1303: word
1304: !@@#$%^&*()
1305: 1234567890
1306: 5!a
1307: @end example
1308:
1.205 ! anton 1309: A frequent beginner's error is to leave out necessary white space,
1.48 anton 1310: resulting in an error like @samp{Undefined word}; so if you see such an
1311: error, check if you have put spaces wherever necessary.
1312:
1313: @example
1314: ." hello, world" \ correct
1315: ."hello, world" \ gives an "Undefined word" error
1316: @end example
1317:
1.65 anton 1318: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1319: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1320: your system is case-sensitive, you may have to type all the examples
1321: given here in upper case.
1322:
1323:
1324: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1325: @section Crash Course
1326:
1327: Type
1328:
1329: @example
1330: 0 0 !
1331: here execute
1332: ' catch >body 20 erase abort
1333: ' (quit) >body 20 erase
1334: @end example
1335:
1336: The last two examples are guaranteed to destroy parts of Gforth (and
1337: most other systems), so you better leave Gforth afterwards (if it has
1338: not finished by itself). On some systems you may have to kill gforth
1339: from outside (e.g., in Unix with @code{kill}).
1340:
1341: Now that you know how to produce crashes (and that there's not much to
1342: them), let's learn how to produce meaningful programs.
1343:
1344:
1345: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1346: @section Stack
1.66 anton 1347: @cindex stack tutorial
1.48 anton 1348:
1349: The most obvious feature of Forth is the stack. When you type in a
1.205 ! anton 1350: number, it is pushed on the stack. You can display the contents of the
1.48 anton 1351: stack with @code{.s}.
1352:
1353: @example
1354: 1 2 .s
1355: 3 .s
1356: @end example
1357:
1358: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1359: appear in @code{.s} output as they appeared in the input.
1360:
1.205 ! anton 1361: You can print the top element of the stack with @code{.}.
1.48 anton 1362:
1363: @example
1364: 1 2 3 . . .
1365: @end example
1366:
1367: In general, words consume their stack arguments (@code{.s} is an
1368: exception).
1369:
1.141 anton 1370: @quotation Assignment
1.48 anton 1371: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1372: @end quotation
1.48 anton 1373:
1374:
1375: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1376: @section Arithmetics
1.66 anton 1377: @cindex arithmetics tutorial
1.48 anton 1378:
1379: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1380: operate on the top two stack items:
1381:
1382: @example
1.67 anton 1383: 2 2 .s
1384: + .s
1385: .
1.48 anton 1386: 2 1 - .
1387: 7 3 mod .
1388: @end example
1389:
1390: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1391: as in the corresponding infix expression (this is generally the case in
1392: Forth).
1393:
1394: Parentheses are superfluous (and not available), because the order of
1395: the words unambiguously determines the order of evaluation and the
1396: operands:
1397:
1398: @example
1399: 3 4 + 5 * .
1400: 3 4 5 * + .
1401: @end example
1402:
1.141 anton 1403: @quotation Assignment
1.48 anton 1404: What are the infix expressions corresponding to the Forth code above?
1405: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1406: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1407: @end quotation
1.48 anton 1408:
1409: To change the sign, use @code{negate}:
1410:
1411: @example
1412: 2 negate .
1413: @end example
1414:
1.141 anton 1415: @quotation Assignment
1.48 anton 1416: Convert -(-3)*4-5 to Forth.
1.141 anton 1417: @end quotation
1.48 anton 1418:
1419: @code{/mod} performs both @code{/} and @code{mod}.
1420:
1421: @example
1422: 7 3 /mod . .
1423: @end example
1424:
1.66 anton 1425: Reference: @ref{Arithmetic}.
1426:
1427:
1.48 anton 1428: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1429: @section Stack Manipulation
1.66 anton 1430: @cindex stack manipulation tutorial
1.48 anton 1431:
1432: Stack manipulation words rearrange the data on the stack.
1433:
1434: @example
1435: 1 .s drop .s
1436: 1 .s dup .s drop drop .s
1437: 1 2 .s over .s drop drop drop
1438: 1 2 .s swap .s drop drop
1439: 1 2 3 .s rot .s drop drop drop
1440: @end example
1441:
1442: These are the most important stack manipulation words. There are also
1443: variants that manipulate twice as many stack items:
1444:
1445: @example
1446: 1 2 3 4 .s 2swap .s 2drop 2drop
1447: @end example
1448:
1449: Two more stack manipulation words are:
1450:
1451: @example
1452: 1 2 .s nip .s drop
1453: 1 2 .s tuck .s 2drop drop
1454: @end example
1455:
1.141 anton 1456: @quotation Assignment
1.48 anton 1457: Replace @code{nip} and @code{tuck} with combinations of other stack
1458: manipulation words.
1459:
1460: @example
1461: Given: How do you get:
1462: 1 2 3 3 2 1
1463: 1 2 3 1 2 3 2
1464: 1 2 3 1 2 3 3
1465: 1 2 3 1 3 3
1466: 1 2 3 2 1 3
1467: 1 2 3 4 4 3 2 1
1468: 1 2 3 1 2 3 1 2 3
1469: 1 2 3 4 1 2 3 4 1 2
1470: 1 2 3
1471: 1 2 3 1 2 3 4
1472: 1 2 3 1 3
1473: @end example
1.141 anton 1474: @end quotation
1.48 anton 1475:
1476: @example
1477: 5 dup * .
1478: @end example
1479:
1.141 anton 1480: @quotation Assignment
1.48 anton 1481: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1482: Write a piece of Forth code that expects two numbers on the stack
1483: (@var{a} and @var{b}, with @var{b} on top) and computes
1484: @code{(a-b)(a+1)}.
1.141 anton 1485: @end quotation
1.48 anton 1486:
1.66 anton 1487: Reference: @ref{Stack Manipulation}.
1488:
1489:
1.48 anton 1490: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1491: @section Using files for Forth code
1.66 anton 1492: @cindex loading Forth code, tutorial
1493: @cindex files containing Forth code, tutorial
1.48 anton 1494:
1495: While working at the Forth command line is convenient for one-line
1496: examples and short one-off code, you probably want to store your source
1497: code in files for convenient editing and persistence. You can use your
1498: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1499: Gforth}) to create @var{file.fs} and use
1.48 anton 1500:
1501: @example
1.102 anton 1502: s" @var{file.fs}" included
1.48 anton 1503: @end example
1504:
1505: to load it into your Forth system. The file name extension I use for
1506: Forth files is @samp{.fs}.
1507:
1508: You can easily start Gforth with some files loaded like this:
1509:
1510: @example
1.102 anton 1511: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1512: @end example
1513:
1514: If an error occurs during loading these files, Gforth terminates,
1515: whereas an error during @code{INCLUDED} within Gforth usually gives you
1516: a Gforth command line. Starting the Forth system every time gives you a
1517: clean start every time, without interference from the results of earlier
1518: tries.
1519:
1520: I often put all the tests in a file, then load the code and run the
1521: tests with
1522:
1523: @example
1.102 anton 1524: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1525: @end example
1526:
1527: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1528: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1529: restart this command without ado.
1530:
1531: The advantage of this approach is that the tests can be repeated easily
1532: every time the program ist changed, making it easy to catch bugs
1533: introduced by the change.
1534:
1.66 anton 1535: Reference: @ref{Forth source files}.
1536:
1.48 anton 1537:
1538: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1539: @section Comments
1.66 anton 1540: @cindex comments tutorial
1.48 anton 1541:
1542: @example
1543: \ That's a comment; it ends at the end of the line
1544: ( Another comment; it ends here: ) .s
1545: @end example
1546:
1547: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1548: separated with white space from the following text.
1549:
1550: @example
1551: \This gives an "Undefined word" error
1552: @end example
1553:
1554: The first @code{)} ends a comment started with @code{(}, so you cannot
1555: nest @code{(}-comments; and you cannot comment out text containing a
1556: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1557: avoid @code{)} in word names.}.
1558:
1559: I use @code{\}-comments for descriptive text and for commenting out code
1560: of one or more line; I use @code{(}-comments for describing the stack
1561: effect, the stack contents, or for commenting out sub-line pieces of
1562: code.
1563:
1564: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1565: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1566: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1567: with @kbd{M-q}.
1568:
1.66 anton 1569: Reference: @ref{Comments}.
1570:
1.48 anton 1571:
1572: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1573: @section Colon Definitions
1.66 anton 1574: @cindex colon definitions, tutorial
1575: @cindex definitions, tutorial
1576: @cindex procedures, tutorial
1577: @cindex functions, tutorial
1.48 anton 1578:
1579: are similar to procedures and functions in other programming languages.
1580:
1581: @example
1582: : squared ( n -- n^2 )
1583: dup * ;
1584: 5 squared .
1585: 7 squared .
1586: @end example
1587:
1588: @code{:} starts the colon definition; its name is @code{squared}. The
1589: following comment describes its stack effect. The words @code{dup *}
1590: are not executed, but compiled into the definition. @code{;} ends the
1591: colon definition.
1592:
1593: The newly-defined word can be used like any other word, including using
1594: it in other definitions:
1595:
1596: @example
1597: : cubed ( n -- n^3 )
1598: dup squared * ;
1599: -5 cubed .
1600: : fourth-power ( n -- n^4 )
1601: squared squared ;
1602: 3 fourth-power .
1603: @end example
1604:
1.141 anton 1605: @quotation Assignment
1.48 anton 1606: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1607: @code{/mod} in terms of other Forth words, and check if they work (hint:
1608: test your tests on the originals first). Don't let the
1609: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1610: @end quotation
1.48 anton 1611:
1.66 anton 1612: Reference: @ref{Colon Definitions}.
1613:
1.48 anton 1614:
1615: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1616: @section Decompilation
1.66 anton 1617: @cindex decompilation tutorial
1618: @cindex see tutorial
1.48 anton 1619:
1620: You can decompile colon definitions with @code{see}:
1621:
1622: @example
1623: see squared
1624: see cubed
1625: @end example
1626:
1627: In Gforth @code{see} shows you a reconstruction of the source code from
1628: the executable code. Informations that were present in the source, but
1629: not in the executable code, are lost (e.g., comments).
1630:
1.65 anton 1631: You can also decompile the predefined words:
1632:
1633: @example
1634: see .
1635: see +
1636: @end example
1637:
1638:
1.48 anton 1639: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1640: @section Stack-Effect Comments
1.66 anton 1641: @cindex stack-effect comments, tutorial
1642: @cindex --, tutorial
1.48 anton 1643: By convention the comment after the name of a definition describes the
1.171 anton 1644: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1645: the stack before the execution of the definition, i.e., the parameters
1646: that are passed into the colon definition; the part behind the @samp{--}
1647: is the state of the stack after the execution of the definition, i.e.,
1648: the results of the definition. The stack comment only shows the top
1649: stack items that the definition accesses and/or changes.
1650:
1651: You should put a correct stack effect on every definition, even if it is
1652: just @code{( -- )}. You should also add some descriptive comment to
1653: more complicated words (I usually do this in the lines following
1654: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1655: you have to work through every definition before you can understand
1.48 anton 1656: any).
1657:
1.141 anton 1658: @quotation Assignment
1.48 anton 1659: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1660: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1661: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1662: are done, you can compare your stack effects to those in this manual
1.48 anton 1663: (@pxref{Word Index}).
1.141 anton 1664: @end quotation
1.48 anton 1665:
1666: Sometimes programmers put comments at various places in colon
1667: definitions that describe the contents of the stack at that place (stack
1668: comments); i.e., they are like the first part of a stack-effect
1669: comment. E.g.,
1670:
1671: @example
1672: : cubed ( n -- n^3 )
1673: dup squared ( n n^2 ) * ;
1674: @end example
1675:
1676: In this case the stack comment is pretty superfluous, because the word
1677: is simple enough. If you think it would be a good idea to add such a
1678: comment to increase readability, you should also consider factoring the
1679: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1680: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1681: however, if you decide not to refactor it, then having such a comment is
1682: better than not having it.
1683:
1684: The names of the stack items in stack-effect and stack comments in the
1685: standard, in this manual, and in many programs specify the type through
1686: a type prefix, similar to Fortran and Hungarian notation. The most
1687: frequent prefixes are:
1688:
1689: @table @code
1690: @item n
1691: signed integer
1692: @item u
1693: unsigned integer
1694: @item c
1695: character
1696: @item f
1697: Boolean flags, i.e. @code{false} or @code{true}.
1698: @item a-addr,a-
1699: Cell-aligned address
1700: @item c-addr,c-
1701: Char-aligned address (note that a Char may have two bytes in Windows NT)
1702: @item xt
1703: Execution token, same size as Cell
1704: @item w,x
1705: Cell, can contain an integer or an address. It usually takes 32, 64 or
1706: 16 bits (depending on your platform and Forth system). A cell is more
1707: commonly known as machine word, but the term @emph{word} already means
1708: something different in Forth.
1709: @item d
1710: signed double-cell integer
1711: @item ud
1712: unsigned double-cell integer
1713: @item r
1714: Float (on the FP stack)
1715: @end table
1716:
1717: You can find a more complete list in @ref{Notation}.
1718:
1.141 anton 1719: @quotation Assignment
1.48 anton 1720: Write stack-effect comments for all definitions you have written up to
1721: now.
1.141 anton 1722: @end quotation
1.48 anton 1723:
1724:
1725: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1726: @section Types
1.66 anton 1727: @cindex types tutorial
1.48 anton 1728:
1729: In Forth the names of the operations are not overloaded; so similar
1730: operations on different types need different names; e.g., @code{+} adds
1731: integers, and you have to use @code{f+} to add floating-point numbers.
1732: The following prefixes are often used for related operations on
1733: different types:
1734:
1735: @table @code
1736: @item (none)
1737: signed integer
1738: @item u
1739: unsigned integer
1740: @item c
1741: character
1742: @item d
1743: signed double-cell integer
1744: @item ud, du
1745: unsigned double-cell integer
1746: @item 2
1747: two cells (not-necessarily double-cell numbers)
1748: @item m, um
1749: mixed single-cell and double-cell operations
1750: @item f
1751: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1752: and @samp{r} represents FP numbers).
1.48 anton 1753: @end table
1754:
1755: If there are no differences between the signed and the unsigned variant
1756: (e.g., for @code{+}), there is only the prefix-less variant.
1757:
1758: Forth does not perform type checking, neither at compile time, nor at
1759: run time. If you use the wrong oeration, the data are interpreted
1760: incorrectly:
1761:
1762: @example
1763: -1 u.
1764: @end example
1765:
1766: If you have only experience with type-checked languages until now, and
1767: have heard how important type-checking is, don't panic! In my
1768: experience (and that of other Forthers), type errors in Forth code are
1769: usually easy to find (once you get used to it), the increased vigilance
1770: of the programmer tends to catch some harder errors in addition to most
1771: type errors, and you never have to work around the type system, so in
1772: most situations the lack of type-checking seems to be a win (projects to
1773: add type checking to Forth have not caught on).
1774:
1775:
1776: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1777: @section Factoring
1.66 anton 1778: @cindex factoring tutorial
1.48 anton 1779:
1780: If you try to write longer definitions, you will soon find it hard to
1781: keep track of the stack contents. Therefore, good Forth programmers
1782: tend to write only short definitions (e.g., three lines). The art of
1783: finding meaningful short definitions is known as factoring (as in
1784: factoring polynomials).
1785:
1786: Well-factored programs offer additional advantages: smaller, more
1787: general words, are easier to test and debug and can be reused more and
1788: better than larger, specialized words.
1789:
1790: So, if you run into difficulties with stack management, when writing
1791: code, try to define meaningful factors for the word, and define the word
1792: in terms of those. Even if a factor contains only two words, it is
1793: often helpful.
1794:
1.65 anton 1795: Good factoring is not easy, and it takes some practice to get the knack
1796: for it; but even experienced Forth programmers often don't find the
1797: right solution right away, but only when rewriting the program. So, if
1798: you don't come up with a good solution immediately, keep trying, don't
1799: despair.
1.48 anton 1800:
1801: @c example !!
1802:
1803:
1804: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1805: @section Designing the stack effect
1.66 anton 1806: @cindex Stack effect design, tutorial
1807: @cindex design of stack effects, tutorial
1.48 anton 1808:
1809: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1810: function; and since there is only one result, you don't have to deal with
1.48 anton 1811: the order of results, either.
1812:
1.117 anton 1813: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1814: parameter and result order of a definition is important and should be
1815: designed well. The general guideline is to design the stack effect such
1816: that the word is simple to use in most cases, even if that complicates
1817: the implementation of the word. Some concrete rules are:
1818:
1819: @itemize @bullet
1820:
1821: @item
1822: Words consume all of their parameters (e.g., @code{.}).
1823:
1824: @item
1825: If there is a convention on the order of parameters (e.g., from
1826: mathematics or another programming language), stick with it (e.g.,
1827: @code{-}).
1828:
1829: @item
1830: If one parameter usually requires only a short computation (e.g., it is
1831: a constant), pass it on the top of the stack. Conversely, parameters
1832: that usually require a long sequence of code to compute should be passed
1833: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1834: read, because the reader does not need to keep track of the bottom item
1.48 anton 1835: through a long sequence of code (or, alternatively, through stack
1.49 anton 1836: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1837: address on top of the stack because it is usually simpler to compute
1838: than the stored value (often the address is just a variable).
1839:
1840: @item
1841: Similarly, results that are usually consumed quickly should be returned
1842: on the top of stack, whereas a result that is often used in long
1843: computations should be passed as bottom result. E.g., the file words
1844: like @code{open-file} return the error code on the top of stack, because
1845: it is usually consumed quickly by @code{throw}; moreover, the error code
1846: has to be checked before doing anything with the other results.
1847:
1848: @end itemize
1849:
1850: These rules are just general guidelines, don't lose sight of the overall
1851: goal to make the words easy to use. E.g., if the convention rule
1852: conflicts with the computation-length rule, you might decide in favour
1853: of the convention if the word will be used rarely, and in favour of the
1854: computation-length rule if the word will be used frequently (because
1855: with frequent use the cost of breaking the computation-length rule would
1856: be quite high, and frequent use makes it easier to remember an
1857: unconventional order).
1858:
1859: @c example !! structure package
1860:
1.65 anton 1861:
1.48 anton 1862: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1863: @section Local Variables
1.66 anton 1864: @cindex local variables, tutorial
1.48 anton 1865:
1866: You can define local variables (@emph{locals}) in a colon definition:
1867:
1868: @example
1869: : swap @{ a b -- b a @}
1870: b a ;
1871: 1 2 swap .s 2drop
1872: @end example
1873:
1874: (If your Forth system does not support this syntax, include
1.187 anton 1875: @file{compat/anslocal.fs} first).
1.48 anton 1876:
1877: In this example @code{@{ a b -- b a @}} is the locals definition; it
1878: takes two cells from the stack, puts the top of stack in @code{b} and
1879: the next stack element in @code{a}. @code{--} starts a comment ending
1880: with @code{@}}. After the locals definition, using the name of the
1881: local will push its value on the stack. You can leave the comment
1882: part (@code{-- b a}) away:
1883:
1884: @example
1885: : swap ( x1 x2 -- x2 x1 )
1886: @{ a b @} b a ;
1887: @end example
1888:
1889: In Gforth you can have several locals definitions, anywhere in a colon
1890: definition; in contrast, in a standard program you can have only one
1891: locals definition per colon definition, and that locals definition must
1.163 anton 1892: be outside any control structure.
1.48 anton 1893:
1894: With locals you can write slightly longer definitions without running
1895: into stack trouble. However, I recommend trying to write colon
1896: definitions without locals for exercise purposes to help you gain the
1897: essential factoring skills.
1898:
1.141 anton 1899: @quotation Assignment
1.48 anton 1900: Rewrite your definitions until now with locals
1.141 anton 1901: @end quotation
1.48 anton 1902:
1.66 anton 1903: Reference: @ref{Locals}.
1904:
1.48 anton 1905:
1906: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1907: @section Conditional execution
1.66 anton 1908: @cindex conditionals, tutorial
1909: @cindex if, tutorial
1.48 anton 1910:
1911: In Forth you can use control structures only inside colon definitions.
1912: An @code{if}-structure looks like this:
1913:
1914: @example
1915: : abs ( n1 -- +n2 )
1916: dup 0 < if
1917: negate
1918: endif ;
1919: 5 abs .
1920: -5 abs .
1921: @end example
1922:
1923: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1924: the following code is performed, otherwise execution continues after the
1.51 pazsan 1925: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1926: elements and produces a flag:
1.48 anton 1927:
1928: @example
1929: 1 2 < .
1930: 2 1 < .
1931: 1 1 < .
1932: @end example
1933:
1934: Actually the standard name for @code{endif} is @code{then}. This
1935: tutorial presents the examples using @code{endif}, because this is often
1936: less confusing for people familiar with other programming languages
1937: where @code{then} has a different meaning. If your system does not have
1938: @code{endif}, define it with
1939:
1940: @example
1941: : endif postpone then ; immediate
1942: @end example
1943:
1944: You can optionally use an @code{else}-part:
1945:
1946: @example
1947: : min ( n1 n2 -- n )
1948: 2dup < if
1949: drop
1950: else
1951: nip
1952: endif ;
1953: 2 3 min .
1954: 3 2 min .
1955: @end example
1956:
1.141 anton 1957: @quotation Assignment
1.48 anton 1958: Write @code{min} without @code{else}-part (hint: what's the definition
1959: of @code{nip}?).
1.141 anton 1960: @end quotation
1.48 anton 1961:
1.66 anton 1962: Reference: @ref{Selection}.
1963:
1.48 anton 1964:
1965: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1966: @section Flags and Comparisons
1.66 anton 1967: @cindex flags tutorial
1968: @cindex comparison tutorial
1.48 anton 1969:
1970: In a false-flag all bits are clear (0 when interpreted as integer). In
1971: a canonical true-flag all bits are set (-1 as a twos-complement signed
1972: integer); in many contexts (e.g., @code{if}) any non-zero value is
1973: treated as true flag.
1974:
1975: @example
1976: false .
1977: true .
1978: true hex u. decimal
1979: @end example
1980:
1981: Comparison words produce canonical flags:
1982:
1983: @example
1984: 1 1 = .
1985: 1 0= .
1986: 0 1 < .
1987: 0 0 < .
1988: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1989: -1 1 < .
1990: @end example
1991:
1.66 anton 1992: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1993: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1994: these combinations are standard (for details see the standard,
1995: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1996:
1.171 anton 1997: You can use @code{and or xor invert} as operations on canonical flags.
1998: Actually they are bitwise operations:
1.48 anton 1999:
2000: @example
2001: 1 2 and .
2002: 1 2 or .
2003: 1 3 xor .
2004: 1 invert .
2005: @end example
2006:
2007: You can convert a zero/non-zero flag into a canonical flag with
2008: @code{0<>} (and complement it on the way with @code{0=}).
2009:
2010: @example
2011: 1 0= .
2012: 1 0<> .
2013: @end example
2014:
1.65 anton 2015: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2016: operation of the Boolean operations to avoid @code{if}s:
2017:
2018: @example
2019: : foo ( n1 -- n2 )
2020: 0= if
2021: 14
2022: else
2023: 0
2024: endif ;
2025: 0 foo .
2026: 1 foo .
2027:
2028: : foo ( n1 -- n2 )
2029: 0= 14 and ;
2030: 0 foo .
2031: 1 foo .
2032: @end example
2033:
1.141 anton 2034: @quotation Assignment
1.48 anton 2035: Write @code{min} without @code{if}.
1.141 anton 2036: @end quotation
1.48 anton 2037:
1.66 anton 2038: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2039: @ref{Bitwise operations}.
2040:
1.48 anton 2041:
2042: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2043: @section General Loops
1.66 anton 2044: @cindex loops, indefinite, tutorial
1.48 anton 2045:
2046: The endless loop is the most simple one:
2047:
2048: @example
2049: : endless ( -- )
2050: 0 begin
2051: dup . 1+
2052: again ;
2053: endless
2054: @end example
2055:
2056: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2057: does nothing at run-time, @code{again} jumps back to @code{begin}.
2058:
2059: A loop with one exit at any place looks like this:
2060:
2061: @example
2062: : log2 ( +n1 -- n2 )
2063: \ logarithmus dualis of n1>0, rounded down to the next integer
2064: assert( dup 0> )
2065: 2/ 0 begin
2066: over 0> while
2067: 1+ swap 2/ swap
2068: repeat
2069: nip ;
2070: 7 log2 .
2071: 8 log2 .
2072: @end example
2073:
2074: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2075: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2076: continues behind the @code{while}. @code{Repeat} jumps back to
2077: @code{begin}, just like @code{again}.
2078:
2079: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2080: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2081: one bit (arithmetic shift right):
2082:
2083: @example
2084: -5 2 / .
2085: -5 2/ .
2086: @end example
2087:
2088: @code{assert(} is no standard word, but you can get it on systems other
1.198 anton 2089: than Gforth by including @file{compat/assert.fs}. You can see what it
1.48 anton 2090: does by trying
2091:
2092: @example
2093: 0 log2 .
2094: @end example
2095:
2096: Here's a loop with an exit at the end:
2097:
2098: @example
2099: : log2 ( +n1 -- n2 )
2100: \ logarithmus dualis of n1>0, rounded down to the next integer
2101: assert( dup 0 > )
2102: -1 begin
2103: 1+ swap 2/ swap
2104: over 0 <=
2105: until
2106: nip ;
2107: @end example
2108:
2109: @code{Until} consumes a flag; if it is non-zero, execution continues at
2110: the @code{begin}, otherwise after the @code{until}.
2111:
1.141 anton 2112: @quotation Assignment
1.48 anton 2113: Write a definition for computing the greatest common divisor.
1.141 anton 2114: @end quotation
1.48 anton 2115:
1.66 anton 2116: Reference: @ref{Simple Loops}.
2117:
1.48 anton 2118:
2119: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2120: @section Counted loops
1.66 anton 2121: @cindex loops, counted, tutorial
1.48 anton 2122:
2123: @example
2124: : ^ ( n1 u -- n )
1.171 anton 2125: \ n = the uth power of n1
1.48 anton 2126: 1 swap 0 u+do
2127: over *
2128: loop
2129: nip ;
2130: 3 2 ^ .
2131: 4 3 ^ .
2132: @end example
2133:
2134: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2135: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2136: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2137: times (or not at all, if @code{u3-u4<0}).
2138:
2139: You can see the stack effect design rules at work in the stack effect of
2140: the loop start words: Since the start value of the loop is more
2141: frequently constant than the end value, the start value is passed on
2142: the top-of-stack.
2143:
2144: You can access the counter of a counted loop with @code{i}:
2145:
2146: @example
2147: : fac ( u -- u! )
2148: 1 swap 1+ 1 u+do
2149: i *
2150: loop ;
2151: 5 fac .
2152: 7 fac .
2153: @end example
2154:
2155: There is also @code{+do}, which expects signed numbers (important for
2156: deciding whether to enter the loop).
2157:
1.141 anton 2158: @quotation Assignment
1.48 anton 2159: Write a definition for computing the nth Fibonacci number.
1.141 anton 2160: @end quotation
1.48 anton 2161:
1.65 anton 2162: You can also use increments other than 1:
2163:
2164: @example
2165: : up2 ( n1 n2 -- )
2166: +do
2167: i .
2168: 2 +loop ;
2169: 10 0 up2
2170:
2171: : down2 ( n1 n2 -- )
2172: -do
2173: i .
2174: 2 -loop ;
2175: 0 10 down2
2176: @end example
1.48 anton 2177:
1.66 anton 2178: Reference: @ref{Counted Loops}.
2179:
1.48 anton 2180:
2181: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2182: @section Recursion
1.66 anton 2183: @cindex recursion tutorial
1.48 anton 2184:
2185: Usually the name of a definition is not visible in the definition; but
2186: earlier definitions are usually visible:
2187:
2188: @example
1.166 anton 2189: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2190: : / ( n1 n2 -- n )
2191: dup 0= if
2192: -10 throw \ report division by zero
2193: endif
2194: / \ old version
2195: ;
2196: 1 0 /
2197: @end example
2198:
2199: For recursive definitions you can use @code{recursive} (non-standard) or
2200: @code{recurse}:
2201:
2202: @example
2203: : fac1 ( n -- n! ) recursive
2204: dup 0> if
2205: dup 1- fac1 *
2206: else
2207: drop 1
2208: endif ;
2209: 7 fac1 .
2210:
2211: : fac2 ( n -- n! )
2212: dup 0> if
2213: dup 1- recurse *
2214: else
2215: drop 1
2216: endif ;
2217: 8 fac2 .
2218: @end example
2219:
1.141 anton 2220: @quotation Assignment
1.48 anton 2221: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2222: @end quotation
1.48 anton 2223:
1.66 anton 2224: Reference (including indirect recursion): @xref{Calls and returns}.
2225:
1.48 anton 2226:
2227: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2228: @section Leaving definitions or loops
1.66 anton 2229: @cindex leaving definitions, tutorial
2230: @cindex leaving loops, tutorial
1.48 anton 2231:
2232: @code{EXIT} exits the current definition right away. For every counted
2233: loop that is left in this way, an @code{UNLOOP} has to be performed
2234: before the @code{EXIT}:
2235:
2236: @c !! real examples
2237: @example
2238: : ...
2239: ... u+do
2240: ... if
2241: ... unloop exit
2242: endif
2243: ...
2244: loop
2245: ... ;
2246: @end example
2247:
2248: @code{LEAVE} leaves the innermost counted loop right away:
2249:
2250: @example
2251: : ...
2252: ... u+do
2253: ... if
2254: ... leave
2255: endif
2256: ...
2257: loop
2258: ... ;
2259: @end example
2260:
1.65 anton 2261: @c !! example
1.48 anton 2262:
1.66 anton 2263: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2264:
2265:
1.48 anton 2266: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2267: @section Return Stack
1.66 anton 2268: @cindex return stack tutorial
1.48 anton 2269:
2270: In addition to the data stack Forth also has a second stack, the return
2271: stack; most Forth systems store the return addresses of procedure calls
2272: there (thus its name). Programmers can also use this stack:
2273:
2274: @example
2275: : foo ( n1 n2 -- )
2276: .s
2277: >r .s
1.50 anton 2278: r@@ .
1.48 anton 2279: >r .s
1.50 anton 2280: r@@ .
1.48 anton 2281: r> .
1.50 anton 2282: r@@ .
1.48 anton 2283: r> . ;
2284: 1 2 foo
2285: @end example
2286:
2287: @code{>r} takes an element from the data stack and pushes it onto the
2288: return stack; conversely, @code{r>} moves an elementm from the return to
2289: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2290: on the data stack.
1.48 anton 2291:
2292: Forth programmers usually use the return stack for storing data
2293: temporarily, if using the data stack alone would be too complex, and
2294: factoring and locals are not an option:
2295:
2296: @example
2297: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2298: rot >r rot r> ;
2299: @end example
2300:
2301: The return address of the definition and the loop control parameters of
2302: counted loops usually reside on the return stack, so you have to take
2303: all items, that you have pushed on the return stack in a colon
2304: definition or counted loop, from the return stack before the definition
2305: or loop ends. You cannot access items that you pushed on the return
2306: stack outside some definition or loop within the definition of loop.
2307:
2308: If you miscount the return stack items, this usually ends in a crash:
2309:
2310: @example
2311: : crash ( n -- )
2312: >r ;
2313: 5 crash
2314: @end example
2315:
2316: You cannot mix using locals and using the return stack (according to the
2317: standard; Gforth has no problem). However, they solve the same
2318: problems, so this shouldn't be an issue.
2319:
1.141 anton 2320: @quotation Assignment
1.48 anton 2321: Can you rewrite any of the definitions you wrote until now in a better
2322: way using the return stack?
1.141 anton 2323: @end quotation
1.48 anton 2324:
1.66 anton 2325: Reference: @ref{Return stack}.
2326:
1.48 anton 2327:
2328: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2329: @section Memory
1.66 anton 2330: @cindex memory access/allocation tutorial
1.48 anton 2331:
2332: You can create a global variable @code{v} with
2333:
2334: @example
2335: variable v ( -- addr )
2336: @end example
2337:
2338: @code{v} pushes the address of a cell in memory on the stack. This cell
2339: was reserved by @code{variable}. You can use @code{!} (store) to store
2340: values into this cell and @code{@@} (fetch) to load the value from the
2341: stack into memory:
2342:
2343: @example
2344: v .
2345: 5 v ! .s
1.50 anton 2346: v @@ .
1.48 anton 2347: @end example
2348:
1.65 anton 2349: You can see a raw dump of memory with @code{dump}:
2350:
2351: @example
2352: v 1 cells .s dump
2353: @end example
2354:
2355: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2356: generally, address units (aus)) that @code{n1 cells} occupy. You can
2357: also reserve more memory:
1.48 anton 2358:
2359: @example
2360: create v2 20 cells allot
1.65 anton 2361: v2 20 cells dump
1.48 anton 2362: @end example
2363:
1.65 anton 2364: creates a word @code{v2} and reserves 20 uninitialized cells; the
2365: address pushed by @code{v2} points to the start of these 20 cells. You
2366: can use address arithmetic to access these cells:
1.48 anton 2367:
2368: @example
2369: 3 v2 5 cells + !
1.65 anton 2370: v2 20 cells dump
1.48 anton 2371: @end example
2372:
2373: You can reserve and initialize memory with @code{,}:
2374:
2375: @example
2376: create v3
2377: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2378: v3 @@ .
2379: v3 cell+ @@ .
2380: v3 2 cells + @@ .
1.65 anton 2381: v3 5 cells dump
1.48 anton 2382: @end example
2383:
1.141 anton 2384: @quotation Assignment
1.48 anton 2385: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2386: @code{u} cells, with the first of these cells at @code{addr}, the next
2387: one at @code{addr cell+} etc.
1.141 anton 2388: @end quotation
1.48 anton 2389:
2390: You can also reserve memory without creating a new word:
2391:
2392: @example
1.60 anton 2393: here 10 cells allot .
2394: here .
1.48 anton 2395: @end example
2396:
2397: @code{Here} pushes the start address of the memory area. You should
2398: store it somewhere, or you will have a hard time finding the memory area
2399: again.
2400:
2401: @code{Allot} manages dictionary memory. The dictionary memory contains
2402: the system's data structures for words etc. on Gforth and most other
2403: Forth systems. It is managed like a stack: You can free the memory that
2404: you have just @code{allot}ed with
2405:
2406: @example
2407: -10 cells allot
1.60 anton 2408: here .
1.48 anton 2409: @end example
2410:
2411: Note that you cannot do this if you have created a new word in the
2412: meantime (because then your @code{allot}ed memory is no longer on the
2413: top of the dictionary ``stack'').
2414:
2415: Alternatively, you can use @code{allocate} and @code{free} which allow
2416: freeing memory in any order:
2417:
2418: @example
2419: 10 cells allocate throw .s
2420: 20 cells allocate throw .s
2421: swap
2422: free throw
2423: free throw
2424: @end example
2425:
2426: The @code{throw}s deal with errors (e.g., out of memory).
2427:
1.65 anton 2428: And there is also a
2429: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2430: garbage collector}, which eliminates the need to @code{free} memory
2431: explicitly.
1.48 anton 2432:
1.66 anton 2433: Reference: @ref{Memory}.
2434:
1.48 anton 2435:
2436: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2437: @section Characters and Strings
1.66 anton 2438: @cindex strings tutorial
2439: @cindex characters tutorial
1.48 anton 2440:
2441: On the stack characters take up a cell, like numbers. In memory they
2442: have their own size (one 8-bit byte on most systems), and therefore
2443: require their own words for memory access:
2444:
2445: @example
2446: create v4
2447: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2448: v4 4 chars + c@@ .
1.65 anton 2449: v4 5 chars dump
1.48 anton 2450: @end example
2451:
2452: The preferred representation of strings on the stack is @code{addr
2453: u-count}, where @code{addr} is the address of the first character and
2454: @code{u-count} is the number of characters in the string.
2455:
2456: @example
2457: v4 5 type
2458: @end example
2459:
2460: You get a string constant with
2461:
2462: @example
2463: s" hello, world" .s
2464: type
2465: @end example
2466:
2467: Make sure you have a space between @code{s"} and the string; @code{s"}
2468: is a normal Forth word and must be delimited with white space (try what
2469: happens when you remove the space).
2470:
2471: However, this interpretive use of @code{s"} is quite restricted: the
2472: string exists only until the next call of @code{s"} (some Forth systems
2473: keep more than one of these strings, but usually they still have a
1.62 crook 2474: limited lifetime).
1.48 anton 2475:
2476: @example
2477: s" hello," s" world" .s
2478: type
2479: type
2480: @end example
2481:
1.62 crook 2482: You can also use @code{s"} in a definition, and the resulting
2483: strings then live forever (well, for as long as the definition):
1.48 anton 2484:
2485: @example
2486: : foo s" hello," s" world" ;
2487: foo .s
2488: type
2489: type
2490: @end example
2491:
1.141 anton 2492: @quotation Assignment
1.48 anton 2493: @code{Emit ( c -- )} types @code{c} as character (not a number).
2494: Implement @code{type ( addr u -- )}.
1.141 anton 2495: @end quotation
1.48 anton 2496:
1.66 anton 2497: Reference: @ref{Memory Blocks}.
2498:
2499:
1.190 anton 2500: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2501: @section Alignment
1.66 anton 2502: @cindex alignment tutorial
2503: @cindex memory alignment tutorial
1.48 anton 2504:
2505: On many processors cells have to be aligned in memory, if you want to
2506: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2507: not require alignment, access to aligned cells is faster).
1.48 anton 2508:
2509: @code{Create} aligns @code{here} (i.e., the place where the next
2510: allocation will occur, and that the @code{create}d word points to).
2511: Likewise, the memory produced by @code{allocate} starts at an aligned
2512: address. Adding a number of @code{cells} to an aligned address produces
2513: another aligned address.
2514:
2515: However, address arithmetic involving @code{char+} and @code{chars} can
2516: create an address that is not cell-aligned. @code{Aligned ( addr --
2517: a-addr )} produces the next aligned address:
2518:
2519: @example
1.50 anton 2520: v3 char+ aligned .s @@ .
2521: v3 char+ .s @@ .
1.48 anton 2522: @end example
2523:
2524: Similarly, @code{align} advances @code{here} to the next aligned
2525: address:
2526:
2527: @example
2528: create v5 97 c,
2529: here .
2530: align here .
2531: 1000 ,
2532: @end example
2533:
2534: Note that you should use aligned addresses even if your processor does
2535: not require them, if you want your program to be portable.
2536:
1.66 anton 2537: Reference: @ref{Address arithmetic}.
2538:
1.190 anton 2539: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2540: @section Floating Point
2541: @cindex floating point tutorial
2542: @cindex FP tutorial
2543:
2544: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2545: might expect, but there are a few things worth noting:
2546:
2547: The first point is not specific to Forth, but so important and yet not
2548: universally known that I mention it here: FP numbers are not reals.
2549: Many properties (e.g., arithmetic laws) that reals have and that one
2550: expects of all kinds of numbers do not hold for FP numbers. If you
2551: want to use FP computations, you should learn about their problems and
2552: how to avoid them; a good starting point is @cite{David Goldberg,
2553: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2554: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2555: Computing Surveys 23(1):5@minus{}48, March 1991}.
2556:
2557: In Forth source code literal FP numbers need an exponent, e.g.,
2558: @code{1e0}; this can also be written shorter as @code{1e},
2559: @code{+1.0e+0}, and many variations in between. The reason for this
2560: is that, for historical reasons, Forth interprets a decimal point
2561: alone (e.g., @code{1.}) as indicating a double-cell integer. Another
2562: requirement for literal FP numbers is that the current base is
2563: decimal; with a hex base @code{1e} is interpreted as an integer.
2564:
2565: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2566: ANS Forth system may implement the FP stack on the data stack, but
2567: virtually all systems implement a separate FP stack; and programming
2568: in a way that accommodates all models is so cumbersome that nobody
2569: does it.} One advantage of this model is that cells are not in the
2570: way when accessing FP values, and vice versa. Forth has a set of
2571: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2572: frot} and (non-standard) @code{fnip ftuck fpick}.
2573:
2574: FP arithmetic words are prefixed with @code{F}. There is the usual
2575: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2576: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2577: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2578: computation results are usually inaccurate, so exact comparison is
2579: usually a mistake, and one should use approximate comparison.
2580: Unfortunately, @code{f~}, the standard word for that purpose, is not
2581: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2582: well.
2583:
2584: And of course there are words for accessing FP numbers in memory
2585: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2586: faligned}). There are also variants of these words with an @code{sf}
2587: and @code{df} prefix for accessing IEEE format single-precision and
2588: double-precision numbers in memory; their main purpose is for
2589: accessing external FP data (e.g., that has been read from or will be
2590: written to a file).
2591:
2592: Here is an example of a dot-product word and its use:
2593:
2594: @example
2595: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2596: >r swap 2swap swap 0e r> 0 ?DO
2597: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2598: LOOP
2599: 2drop 2drop ;
1.48 anton 2600:
1.190 anton 2601: create v 1.23e f, 4.56e f, 7.89e f,
2602:
2603: v 1 floats v 1 floats 3 v* f.
2604: @end example
2605:
2606: @quotation Assignment
2607: Write a program to solve a quadratic equation. Then read @cite{Henry
2608: G. Baker,
2609: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2610: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2611: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2612: program. Finally, find a test case where the original and the
2613: improved version produce different results.
2614: @end quotation
2615:
2616: Reference: @ref{Floating Point}; @ref{Floating point stack};
2617: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2618: arithmetic}.
2619:
2620: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84 pazsan 2621: @section Files
2622: @cindex files tutorial
2623:
2624: This section gives a short introduction into how to use files inside
2625: Forth. It's broken up into five easy steps:
2626:
2627: @enumerate 1
2628: @item Opened an ASCII text file for input
2629: @item Opened a file for output
2630: @item Read input file until string matched (or some other condition matched)
2631: @item Wrote some lines from input ( modified or not) to output
2632: @item Closed the files.
2633: @end enumerate
2634:
1.153 anton 2635: Reference: @ref{General files}.
2636:
1.84 pazsan 2637: @subsection Open file for input
2638:
2639: @example
2640: s" foo.in" r/o open-file throw Value fd-in
2641: @end example
2642:
2643: @subsection Create file for output
2644:
2645: @example
2646: s" foo.out" w/o create-file throw Value fd-out
2647: @end example
2648:
2649: The available file modes are r/o for read-only access, r/w for
2650: read-write access, and w/o for write-only access. You could open both
2651: files with r/w, too, if you like. All file words return error codes; for
2652: most applications, it's best to pass there error codes with @code{throw}
2653: to the outer error handler.
2654:
2655: If you want words for opening and assigning, define them as follows:
2656:
2657: @example
2658: 0 Value fd-in
2659: 0 Value fd-out
2660: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2661: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2662: @end example
2663:
2664: Usage example:
2665:
2666: @example
2667: s" foo.in" open-input
2668: s" foo.out" open-output
2669: @end example
2670:
2671: @subsection Scan file for a particular line
2672:
2673: @example
2674: 256 Constant max-line
2675: Create line-buffer max-line 2 + allot
2676:
2677: : scan-file ( addr u -- )
2678: begin
2679: line-buffer max-line fd-in read-line throw
2680: while
2681: >r 2dup line-buffer r> compare 0=
2682: until
2683: else
2684: drop
2685: then
2686: 2drop ;
2687: @end example
2688:
2689: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2690: the buffer at addr, and returns the number of bytes read, a flag that is
2691: false when the end of file is reached, and an error code.
1.84 pazsan 2692:
2693: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2694: returns zero if both strings are equal. It returns a positive number if
2695: the first string is lexically greater, a negative if the second string
2696: is lexically greater.
2697:
2698: We haven't seen this loop here; it has two exits. Since the @code{while}
2699: exits with the number of bytes read on the stack, we have to clean up
2700: that separately; that's after the @code{else}.
2701:
2702: Usage example:
2703:
2704: @example
2705: s" The text I search is here" scan-file
2706: @end example
2707:
2708: @subsection Copy input to output
2709:
2710: @example
2711: : copy-file ( -- )
2712: begin
2713: line-buffer max-line fd-in read-line throw
2714: while
1.194 anton 2715: line-buffer swap fd-out write-line throw
1.84 pazsan 2716: repeat ;
2717: @end example
1.194 anton 2718: @c !! does not handle long lines, no newline at end of file
1.84 pazsan 2719:
2720: @subsection Close files
2721:
2722: @example
2723: fd-in close-file throw
2724: fd-out close-file throw
2725: @end example
2726:
2727: Likewise, you can put that into definitions, too:
2728:
2729: @example
2730: : close-input ( -- ) fd-in close-file throw ;
2731: : close-output ( -- ) fd-out close-file throw ;
2732: @end example
2733:
1.141 anton 2734: @quotation Assignment
1.84 pazsan 2735: How could you modify @code{copy-file} so that it copies until a second line is
2736: matched? Can you write a program that extracts a section of a text file,
2737: given the line that starts and the line that terminates that section?
1.141 anton 2738: @end quotation
1.84 pazsan 2739:
2740: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2741: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2742: @cindex semantics tutorial
2743: @cindex interpretation semantics tutorial
2744: @cindex compilation semantics tutorial
2745: @cindex immediate, tutorial
1.48 anton 2746:
2747: When a word is compiled, it behaves differently from being interpreted.
2748: E.g., consider @code{+}:
2749:
2750: @example
2751: 1 2 + .
2752: : foo + ;
2753: @end example
2754:
2755: These two behaviours are known as compilation and interpretation
2756: semantics. For normal words (e.g., @code{+}), the compilation semantics
2757: is to append the interpretation semantics to the currently defined word
2758: (@code{foo} in the example above). I.e., when @code{foo} is executed
2759: later, the interpretation semantics of @code{+} (i.e., adding two
2760: numbers) will be performed.
2761:
2762: However, there are words with non-default compilation semantics, e.g.,
2763: the control-flow words like @code{if}. You can use @code{immediate} to
2764: change the compilation semantics of the last defined word to be equal to
2765: the interpretation semantics:
2766:
2767: @example
2768: : [FOO] ( -- )
2769: 5 . ; immediate
2770:
2771: [FOO]
2772: : bar ( -- )
2773: [FOO] ;
2774: bar
2775: see bar
2776: @end example
2777:
1.198 anton 2778: Two conventions to mark words with non-default compilation semantics are
1.48 anton 2779: names with brackets (more frequently used) and to write them all in
2780: upper case (less frequently used).
2781:
2782: In Gforth (and many other systems) you can also remove the
2783: interpretation semantics with @code{compile-only} (the compilation
2784: semantics is derived from the original interpretation semantics):
2785:
2786: @example
2787: : flip ( -- )
2788: 6 . ; compile-only \ but not immediate
2789: flip
2790:
2791: : flop ( -- )
2792: flip ;
2793: flop
2794: @end example
2795:
2796: In this example the interpretation semantics of @code{flop} is equal to
2797: the original interpretation semantics of @code{flip}.
2798:
2799: The text interpreter has two states: in interpret state, it performs the
2800: interpretation semantics of words it encounters; in compile state, it
2801: performs the compilation semantics of these words.
2802:
2803: Among other things, @code{:} switches into compile state, and @code{;}
2804: switches back to interpret state. They contain the factors @code{]}
2805: (switch to compile state) and @code{[} (switch to interpret state), that
2806: do nothing but switch the state.
2807:
2808: @example
2809: : xxx ( -- )
2810: [ 5 . ]
2811: ;
2812:
2813: xxx
2814: see xxx
2815: @end example
2816:
2817: These brackets are also the source of the naming convention mentioned
2818: above.
2819:
1.66 anton 2820: Reference: @ref{Interpretation and Compilation Semantics}.
2821:
1.48 anton 2822:
2823: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2824: @section Execution Tokens
1.66 anton 2825: @cindex execution tokens tutorial
2826: @cindex XT tutorial
1.48 anton 2827:
2828: @code{' word} gives you the execution token (XT) of a word. The XT is a
2829: cell representing the interpretation semantics of a word. You can
2830: execute this semantics with @code{execute}:
2831:
2832: @example
2833: ' + .s
2834: 1 2 rot execute .
2835: @end example
2836:
2837: The XT is similar to a function pointer in C. However, parameter
2838: passing through the stack makes it a little more flexible:
2839:
2840: @example
2841: : map-array ( ... addr u xt -- ... )
1.50 anton 2842: \ executes xt ( ... x -- ... ) for every element of the array starting
2843: \ at addr and containing u elements
1.48 anton 2844: @{ xt @}
2845: cells over + swap ?do
1.50 anton 2846: i @@ xt execute
1.48 anton 2847: 1 cells +loop ;
2848:
2849: create a 3 , 4 , 2 , -1 , 4 ,
2850: a 5 ' . map-array .s
2851: 0 a 5 ' + map-array .
2852: s" max-n" environment? drop .s
2853: a 5 ' min map-array .
2854: @end example
2855:
2856: You can use map-array with the XTs of words that consume one element
2857: more than they produce. In theory you can also use it with other XTs,
2858: but the stack effect then depends on the size of the array, which is
2859: hard to understand.
2860:
1.51 pazsan 2861: Since XTs are cell-sized, you can store them in memory and manipulate
2862: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2863: word with @code{compile,}:
2864:
2865: @example
2866: : foo1 ( n1 n2 -- n )
2867: [ ' + compile, ] ;
2868: see foo
2869: @end example
2870:
2871: This is non-standard, because @code{compile,} has no compilation
2872: semantics in the standard, but it works in good Forth systems. For the
2873: broken ones, use
2874:
2875: @example
2876: : [compile,] compile, ; immediate
2877:
2878: : foo1 ( n1 n2 -- n )
2879: [ ' + ] [compile,] ;
2880: see foo
2881: @end example
2882:
2883: @code{'} is a word with default compilation semantics; it parses the
2884: next word when its interpretation semantics are executed, not during
2885: compilation:
2886:
2887: @example
2888: : foo ( -- xt )
2889: ' ;
2890: see foo
2891: : bar ( ... "word" -- ... )
2892: ' execute ;
2893: see bar
1.60 anton 2894: 1 2 bar + .
1.48 anton 2895: @end example
2896:
2897: You often want to parse a word during compilation and compile its XT so
2898: it will be pushed on the stack at run-time. @code{[']} does this:
2899:
2900: @example
2901: : xt-+ ( -- xt )
2902: ['] + ;
2903: see xt-+
2904: 1 2 xt-+ execute .
2905: @end example
2906:
2907: Many programmers tend to see @code{'} and the word it parses as one
2908: unit, and expect it to behave like @code{[']} when compiled, and are
2909: confused by the actual behaviour. If you are, just remember that the
2910: Forth system just takes @code{'} as one unit and has no idea that it is
2911: a parsing word (attempts to convenience programmers in this issue have
2912: usually resulted in even worse pitfalls, see
1.66 anton 2913: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2914: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2915:
2916: Note that the state of the interpreter does not come into play when
1.51 pazsan 2917: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2918: compile state, it still gives you the interpretation semantics. And
2919: whatever that state is, @code{execute} performs the semantics
1.66 anton 2920: represented by the XT (i.e., for XTs produced with @code{'} the
2921: interpretation semantics).
2922:
2923: Reference: @ref{Tokens for Words}.
1.48 anton 2924:
2925:
2926: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2927: @section Exceptions
1.66 anton 2928: @cindex exceptions tutorial
1.48 anton 2929:
2930: @code{throw ( n -- )} causes an exception unless n is zero.
2931:
2932: @example
2933: 100 throw .s
2934: 0 throw .s
2935: @end example
2936:
2937: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2938: it catches exceptions and pushes the number of the exception on the
2939: stack (or 0, if the xt executed without exception). If there was an
2940: exception, the stacks have the same depth as when entering @code{catch}:
2941:
2942: @example
2943: .s
2944: 3 0 ' / catch .s
2945: 3 2 ' / catch .s
2946: @end example
2947:
1.141 anton 2948: @quotation Assignment
1.48 anton 2949: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2950: @end quotation
1.48 anton 2951:
2952: @code{Throw} always jumps to the dynamically next enclosing
2953: @code{catch}, even if it has to leave several call levels to achieve
2954: this:
2955:
2956: @example
2957: : foo 100 throw ;
2958: : foo1 foo ." after foo" ;
1.51 pazsan 2959: : bar ['] foo1 catch ;
1.60 anton 2960: bar .
1.48 anton 2961: @end example
2962:
2963: It is often important to restore a value upon leaving a definition, even
2964: if the definition is left through an exception. You can ensure this
2965: like this:
2966:
2967: @example
2968: : ...
2969: save-x
1.51 pazsan 2970: ['] word-changing-x catch ( ... n )
1.48 anton 2971: restore-x
2972: ( ... n ) throw ;
2973: @end example
2974:
1.172 anton 2975: However, this is still not safe against, e.g., the user pressing
2976: @kbd{Ctrl-C} when execution is between the @code{catch} and
2977: @code{restore-x}.
2978:
2979: Gforth provides an alternative exception handling syntax that is safe
2980: against such cases: @code{try ... restore ... endtry}. If the code
2981: between @code{try} and @code{endtry} has an exception, the stack
2982: depths are restored, the exception number is pushed on the stack, and
2983: the execution continues right after @code{restore}.
1.48 anton 2984:
1.172 anton 2985: The safer equivalent to the restoration code above is
1.48 anton 2986:
2987: @example
2988: : ...
2989: save-x
2990: try
1.92 anton 2991: word-changing-x 0
1.172 anton 2992: restore
2993: restore-x
2994: endtry
1.48 anton 2995: throw ;
2996: @end example
2997:
1.66 anton 2998: Reference: @ref{Exception Handling}.
2999:
1.48 anton 3000:
3001: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3002: @section Defining Words
1.66 anton 3003: @cindex defining words tutorial
3004: @cindex does> tutorial
3005: @cindex create...does> tutorial
3006:
3007: @c before semantics?
1.48 anton 3008:
3009: @code{:}, @code{create}, and @code{variable} are definition words: They
3010: define other words. @code{Constant} is another definition word:
3011:
3012: @example
3013: 5 constant foo
3014: foo .
3015: @end example
3016:
3017: You can also use the prefixes @code{2} (double-cell) and @code{f}
3018: (floating point) with @code{variable} and @code{constant}.
3019:
3020: You can also define your own defining words. E.g.:
3021:
3022: @example
3023: : variable ( "name" -- )
3024: create 0 , ;
3025: @end example
3026:
3027: You can also define defining words that create words that do something
3028: other than just producing their address:
3029:
3030: @example
3031: : constant ( n "name" -- )
3032: create ,
3033: does> ( -- n )
1.50 anton 3034: ( addr ) @@ ;
1.48 anton 3035:
3036: 5 constant foo
3037: foo .
3038: @end example
3039:
3040: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3041: @code{does>} replaces @code{;}, but it also does something else: It
3042: changes the last defined word such that it pushes the address of the
3043: body of the word and then performs the code after the @code{does>}
3044: whenever it is called.
3045:
3046: In the example above, @code{constant} uses @code{,} to store 5 into the
3047: body of @code{foo}. When @code{foo} executes, it pushes the address of
3048: the body onto the stack, then (in the code after the @code{does>})
3049: fetches the 5 from there.
3050:
3051: The stack comment near the @code{does>} reflects the stack effect of the
3052: defined word, not the stack effect of the code after the @code{does>}
3053: (the difference is that the code expects the address of the body that
3054: the stack comment does not show).
3055:
3056: You can use these definition words to do factoring in cases that involve
3057: (other) definition words. E.g., a field offset is always added to an
3058: address. Instead of defining
3059:
3060: @example
3061: 2 cells constant offset-field1
3062: @end example
3063:
3064: and using this like
3065:
3066: @example
3067: ( addr ) offset-field1 +
3068: @end example
3069:
3070: you can define a definition word
3071:
3072: @example
3073: : simple-field ( n "name" -- )
3074: create ,
3075: does> ( n1 -- n1+n )
1.50 anton 3076: ( addr ) @@ + ;
1.48 anton 3077: @end example
1.21 crook 3078:
1.48 anton 3079: Definition and use of field offsets now look like this:
1.21 crook 3080:
1.48 anton 3081: @example
3082: 2 cells simple-field field1
1.60 anton 3083: create mystruct 4 cells allot
3084: mystruct .s field1 .s drop
1.48 anton 3085: @end example
1.21 crook 3086:
1.48 anton 3087: If you want to do something with the word without performing the code
3088: after the @code{does>}, you can access the body of a @code{create}d word
3089: with @code{>body ( xt -- addr )}:
1.21 crook 3090:
1.48 anton 3091: @example
3092: : value ( n "name" -- )
3093: create ,
3094: does> ( -- n1 )
1.50 anton 3095: @@ ;
1.48 anton 3096: : to ( n "name" -- )
3097: ' >body ! ;
1.21 crook 3098:
1.48 anton 3099: 5 value foo
3100: foo .
3101: 7 to foo
3102: foo .
3103: @end example
1.21 crook 3104:
1.141 anton 3105: @quotation Assignment
1.48 anton 3106: Define @code{defer ( "name" -- )}, which creates a word that stores an
3107: XT (at the start the XT of @code{abort}), and upon execution
3108: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3109: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3110: recursion is one application of @code{defer}.
1.141 anton 3111: @end quotation
1.29 crook 3112:
1.66 anton 3113: Reference: @ref{User-defined Defining Words}.
3114:
3115:
1.48 anton 3116: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3117: @section Arrays and Records
1.66 anton 3118: @cindex arrays tutorial
3119: @cindex records tutorial
3120: @cindex structs tutorial
1.29 crook 3121:
1.48 anton 3122: Forth has no standard words for defining data structures such as arrays
3123: and records (structs in C terminology), but you can build them yourself
3124: based on address arithmetic. You can also define words for defining
3125: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3126:
1.48 anton 3127: One of the first projects a Forth newcomer sets out upon when learning
3128: about defining words is an array defining word (possibly for
3129: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3130: learn something from it. However, don't be disappointed when you later
3131: learn that you have little use for these words (inappropriate use would
1.198 anton 3132: be even worse). I have not found a set of useful array words yet;
1.48 anton 3133: the needs are just too diverse, and named, global arrays (the result of
3134: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3135: consider how to pass them as parameters). Another such project is a set
3136: of words to help dealing with strings.
1.29 crook 3137:
1.48 anton 3138: On the other hand, there is a useful set of record words, and it has
3139: been defined in @file{compat/struct.fs}; these words are predefined in
3140: Gforth. They are explained in depth elsewhere in this manual (see
3141: @pxref{Structures}). The @code{simple-field} example above is
3142: simplified variant of fields in this package.
1.21 crook 3143:
3144:
1.48 anton 3145: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3146: @section @code{POSTPONE}
1.66 anton 3147: @cindex postpone tutorial
1.21 crook 3148:
1.48 anton 3149: You can compile the compilation semantics (instead of compiling the
3150: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3151:
1.48 anton 3152: @example
3153: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3154: POSTPONE + ; immediate
1.48 anton 3155: : foo ( n1 n2 -- n )
3156: MY-+ ;
3157: 1 2 foo .
3158: see foo
3159: @end example
1.21 crook 3160:
1.48 anton 3161: During the definition of @code{foo} the text interpreter performs the
3162: compilation semantics of @code{MY-+}, which performs the compilation
3163: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3164:
3165: This example also displays separate stack comments for the compilation
3166: semantics and for the stack effect of the compiled code. For words with
3167: default compilation semantics these stack effects are usually not
3168: displayed; the stack effect of the compilation semantics is always
3169: @code{( -- )} for these words, the stack effect for the compiled code is
3170: the stack effect of the interpretation semantics.
3171:
3172: Note that the state of the interpreter does not come into play when
3173: performing the compilation semantics in this way. You can also perform
3174: it interpretively, e.g.:
3175:
3176: @example
3177: : foo2 ( n1 n2 -- n )
3178: [ MY-+ ] ;
3179: 1 2 foo .
3180: see foo
3181: @end example
1.21 crook 3182:
1.48 anton 3183: However, there are some broken Forth systems where this does not always
1.62 crook 3184: work, and therefore this practice was been declared non-standard in
1.48 anton 3185: 1999.
3186: @c !! repair.fs
3187:
3188: Here is another example for using @code{POSTPONE}:
1.44 crook 3189:
1.48 anton 3190: @example
3191: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3192: POSTPONE negate POSTPONE + ; immediate compile-only
3193: : bar ( n1 n2 -- n )
3194: MY-- ;
3195: 2 1 bar .
3196: see bar
3197: @end example
1.21 crook 3198:
1.48 anton 3199: You can define @code{ENDIF} in this way:
1.21 crook 3200:
1.48 anton 3201: @example
3202: : ENDIF ( Compilation: orig -- )
3203: POSTPONE then ; immediate
3204: @end example
1.21 crook 3205:
1.141 anton 3206: @quotation Assignment
1.48 anton 3207: Write @code{MY-2DUP} that has compilation semantics equivalent to
3208: @code{2dup}, but compiles @code{over over}.
1.141 anton 3209: @end quotation
1.29 crook 3210:
1.66 anton 3211: @c !! @xref{Macros} for reference
3212:
3213:
1.48 anton 3214: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3215: @section @code{Literal}
1.66 anton 3216: @cindex literal tutorial
1.29 crook 3217:
1.48 anton 3218: You cannot @code{POSTPONE} numbers:
1.21 crook 3219:
1.48 anton 3220: @example
3221: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3222: @end example
3223:
1.48 anton 3224: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3225:
1.48 anton 3226: @example
3227: : [FOO] ( compilation: --; run-time: -- n )
3228: 500 POSTPONE literal ; immediate
1.29 crook 3229:
1.60 anton 3230: : flip [FOO] ;
1.48 anton 3231: flip .
3232: see flip
3233: @end example
1.29 crook 3234:
1.48 anton 3235: @code{LITERAL} consumes a number at compile-time (when it's compilation
3236: semantics are executed) and pushes it at run-time (when the code it
3237: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3238: number computed at compile time into the current word:
1.29 crook 3239:
1.48 anton 3240: @example
3241: : bar ( -- n )
3242: [ 2 2 + ] literal ;
3243: see bar
3244: @end example
1.29 crook 3245:
1.141 anton 3246: @quotation Assignment
1.48 anton 3247: Write @code{]L} which allows writing the example above as @code{: bar (
3248: -- n ) [ 2 2 + ]L ;}
1.141 anton 3249: @end quotation
1.48 anton 3250:
1.66 anton 3251: @c !! @xref{Macros} for reference
3252:
1.48 anton 3253:
3254: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3255: @section Advanced macros
1.66 anton 3256: @cindex macros, advanced tutorial
3257: @cindex run-time code generation, tutorial
1.48 anton 3258:
1.66 anton 3259: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3260: Execution Tokens}. It frequently performs @code{execute}, a relatively
3261: expensive operation in some Forth implementations. You can use
1.48 anton 3262: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3263: and produce a word that contains the word to be performed directly:
3264:
3265: @c use ]] ... [[
3266: @example
3267: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3268: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3269: \ array beginning at addr and containing u elements
3270: @{ xt @}
3271: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3272: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3273: 1 cells POSTPONE literal POSTPONE +loop ;
3274:
3275: : sum-array ( addr u -- n )
3276: 0 rot rot [ ' + compile-map-array ] ;
3277: see sum-array
3278: a 5 sum-array .
3279: @end example
3280:
3281: You can use the full power of Forth for generating the code; here's an
3282: example where the code is generated in a loop:
3283:
3284: @example
3285: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3286: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3287: POSTPONE tuck POSTPONE @@
1.48 anton 3288: POSTPONE literal POSTPONE * POSTPONE +
3289: POSTPONE swap POSTPONE cell+ ;
3290:
3291: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3292: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3293: 0 postpone literal postpone swap
3294: [ ' compile-vmul-step compile-map-array ]
3295: postpone drop ;
3296: see compile-vmul
3297:
3298: : a-vmul ( addr -- n )
1.51 pazsan 3299: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3300: [ a 5 compile-vmul ] ;
3301: see a-vmul
3302: a a-vmul .
3303: @end example
3304:
3305: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3306: also use @code{map-array} instead (try it now!).
1.48 anton 3307:
3308: You can use this technique for efficient multiplication of large
3309: matrices. In matrix multiplication, you multiply every line of one
3310: matrix with every column of the other matrix. You can generate the code
3311: for one line once, and use it for every column. The only downside of
3312: this technique is that it is cumbersome to recover the memory consumed
3313: by the generated code when you are done (and in more complicated cases
3314: it is not possible portably).
3315:
1.66 anton 3316: @c !! @xref{Macros} for reference
3317:
3318:
1.48 anton 3319: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3320: @section Compilation Tokens
1.66 anton 3321: @cindex compilation tokens, tutorial
3322: @cindex CT, tutorial
1.48 anton 3323:
3324: This section is Gforth-specific. You can skip it.
3325:
3326: @code{' word compile,} compiles the interpretation semantics. For words
3327: with default compilation semantics this is the same as performing the
3328: compilation semantics. To represent the compilation semantics of other
3329: words (e.g., words like @code{if} that have no interpretation
3330: semantics), Gforth has the concept of a compilation token (CT,
3331: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3332: You can perform the compilation semantics represented by a CT with
3333: @code{execute}:
1.29 crook 3334:
1.48 anton 3335: @example
3336: : foo2 ( n1 n2 -- n )
3337: [ comp' + execute ] ;
3338: see foo
3339: @end example
1.29 crook 3340:
1.48 anton 3341: You can compile the compilation semantics represented by a CT with
3342: @code{postpone,}:
1.30 anton 3343:
1.48 anton 3344: @example
3345: : foo3 ( -- )
3346: [ comp' + postpone, ] ;
3347: see foo3
3348: @end example
1.30 anton 3349:
1.51 pazsan 3350: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3351: @code{comp'} is particularly useful for words that have no
3352: interpretation semantics:
1.29 crook 3353:
1.30 anton 3354: @example
1.48 anton 3355: ' if
1.60 anton 3356: comp' if .s 2drop
1.30 anton 3357: @end example
3358:
1.66 anton 3359: Reference: @ref{Tokens for Words}.
3360:
1.29 crook 3361:
1.48 anton 3362: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3363: @section Wordlists and Search Order
1.66 anton 3364: @cindex wordlists tutorial
3365: @cindex search order, tutorial
1.48 anton 3366:
3367: The dictionary is not just a memory area that allows you to allocate
3368: memory with @code{allot}, it also contains the Forth words, arranged in
3369: several wordlists. When searching for a word in a wordlist,
3370: conceptually you start searching at the youngest and proceed towards
3371: older words (in reality most systems nowadays use hash-tables); i.e., if
3372: you define a word with the same name as an older word, the new word
3373: shadows the older word.
3374:
3375: Which wordlists are searched in which order is determined by the search
3376: order. You can display the search order with @code{order}. It displays
3377: first the search order, starting with the wordlist searched first, then
3378: it displays the wordlist that will contain newly defined words.
1.21 crook 3379:
1.48 anton 3380: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3381:
1.48 anton 3382: @example
3383: wordlist constant mywords
3384: @end example
1.21 crook 3385:
1.48 anton 3386: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3387: defined words (the @emph{current} wordlist):
1.21 crook 3388:
1.48 anton 3389: @example
3390: mywords set-current
3391: order
3392: @end example
1.26 crook 3393:
1.48 anton 3394: Gforth does not display a name for the wordlist in @code{mywords}
3395: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3396:
1.48 anton 3397: You can get the current wordlist with @code{get-current ( -- wid)}. If
3398: you want to put something into a specific wordlist without overall
3399: effect on the current wordlist, this typically looks like this:
1.21 crook 3400:
1.48 anton 3401: @example
3402: get-current mywords set-current ( wid )
3403: create someword
3404: ( wid ) set-current
3405: @end example
1.21 crook 3406:
1.48 anton 3407: You can write the search order with @code{set-order ( wid1 .. widn n --
3408: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3409: searched wordlist is topmost.
1.21 crook 3410:
1.48 anton 3411: @example
3412: get-order mywords swap 1+ set-order
3413: order
3414: @end example
1.21 crook 3415:
1.48 anton 3416: Yes, the order of wordlists in the output of @code{order} is reversed
3417: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3418:
1.141 anton 3419: @quotation Assignment
1.48 anton 3420: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3421: wordlist to the search order. Define @code{previous ( -- )}, which
3422: removes the first searched wordlist from the search order. Experiment
3423: with boundary conditions (you will see some crashes or situations that
3424: are hard or impossible to leave).
1.141 anton 3425: @end quotation
1.21 crook 3426:
1.48 anton 3427: The search order is a powerful foundation for providing features similar
3428: to Modula-2 modules and C++ namespaces. However, trying to modularize
3429: programs in this way has disadvantages for debugging and reuse/factoring
3430: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3431: though). These disadvantages are not so clear in other
1.82 anton 3432: languages/programming environments, because these languages are not so
1.48 anton 3433: strong in debugging and reuse.
1.21 crook 3434:
1.66 anton 3435: @c !! example
3436:
3437: Reference: @ref{Word Lists}.
1.21 crook 3438:
1.29 crook 3439: @c ******************************************************************
1.48 anton 3440: @node Introduction, Words, Tutorial, Top
1.29 crook 3441: @comment node-name, next, previous, up
3442: @chapter An Introduction to ANS Forth
3443: @cindex Forth - an introduction
1.21 crook 3444:
1.83 anton 3445: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3446: that it is slower-paced in its examples, but uses them to dive deep into
3447: explaining Forth internals (not covered by the Tutorial). Apart from
3448: that, this chapter covers far less material. It is suitable for reading
3449: without using a computer.
3450:
1.29 crook 3451: The primary purpose of this manual is to document Gforth. However, since
3452: Forth is not a widely-known language and there is a lack of up-to-date
3453: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3454: material. For other sources of Forth-related
3455: information, see @ref{Forth-related information}.
1.21 crook 3456:
1.29 crook 3457: The examples in this section should work on any ANS Forth; the
3458: output shown was produced using Gforth. Each example attempts to
3459: reproduce the exact output that Gforth produces. If you try out the
3460: examples (and you should), what you should type is shown @kbd{like this}
3461: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3462: that, where the example shows @key{RET} it means that you should
1.29 crook 3463: press the ``carriage return'' key. Unfortunately, some output formats for
3464: this manual cannot show the difference between @kbd{this} and
3465: @code{this} which will make trying out the examples harder (but not
3466: impossible).
1.21 crook 3467:
1.29 crook 3468: Forth is an unusual language. It provides an interactive development
3469: environment which includes both an interpreter and compiler. Forth
3470: programming style encourages you to break a problem down into many
3471: @cindex factoring
3472: small fragments (@dfn{factoring}), and then to develop and test each
3473: fragment interactively. Forth advocates assert that breaking the
3474: edit-compile-test cycle used by conventional programming languages can
3475: lead to great productivity improvements.
1.21 crook 3476:
1.29 crook 3477: @menu
1.67 anton 3478: * Introducing the Text Interpreter::
3479: * Stacks and Postfix notation::
3480: * Your first definition::
3481: * How does that work?::
3482: * Forth is written in Forth::
3483: * Review - elements of a Forth system::
3484: * Where to go next::
3485: * Exercises::
1.29 crook 3486: @end menu
1.21 crook 3487:
1.29 crook 3488: @comment ----------------------------------------------
3489: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3490: @section Introducing the Text Interpreter
3491: @cindex text interpreter
3492: @cindex outer interpreter
1.21 crook 3493:
1.30 anton 3494: @c IMO this is too detailed and the pace is too slow for
3495: @c an introduction. If you know German, take a look at
3496: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3497: @c to see how I do it - anton
3498:
1.44 crook 3499: @c nac-> Where I have accepted your comments 100% and modified the text
3500: @c accordingly, I have deleted your comments. Elsewhere I have added a
3501: @c response like this to attempt to rationalise what I have done. Of
3502: @c course, this is a very clumsy mechanism for something that would be
3503: @c done far more efficiently over a beer. Please delete any dialogue
3504: @c you consider closed.
3505:
1.29 crook 3506: When you invoke the Forth image, you will see a startup banner printed
3507: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3508: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3509: its command line interpreter, which is called the @dfn{Text Interpreter}
3510: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3511: about the text interpreter as you read through this chapter, for more
3512: detail @pxref{The Text Interpreter}).
1.21 crook 3513:
1.29 crook 3514: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3515: input. Type a number and press the @key{RET} key:
1.21 crook 3516:
1.26 crook 3517: @example
1.30 anton 3518: @kbd{45@key{RET}} ok
1.26 crook 3519: @end example
1.21 crook 3520:
1.29 crook 3521: Rather than give you a prompt to invite you to input something, the text
3522: interpreter prints a status message @i{after} it has processed a line
3523: of input. The status message in this case (``@code{ ok}'' followed by
3524: carriage-return) indicates that the text interpreter was able to process
3525: all of your input successfully. Now type something illegal:
3526:
3527: @example
1.30 anton 3528: @kbd{qwer341@key{RET}}
1.134 anton 3529: *the terminal*:2: Undefined word
3530: >>>qwer341<<<
3531: Backtrace:
3532: $2A95B42A20 throw
3533: $2A95B57FB8 no.extensions
1.29 crook 3534: @end example
1.23 crook 3535:
1.134 anton 3536: The exact text, other than the ``Undefined word'' may differ slightly
3537: on your system, but the effect is the same; when the text interpreter
1.29 crook 3538: detects an error, it discards any remaining text on a line, resets
1.134 anton 3539: certain internal state and prints an error message. For a detailed
3540: description of error messages see @ref{Error messages}.
1.23 crook 3541:
1.29 crook 3542: The text interpreter waits for you to press carriage-return, and then
3543: processes your input line. Starting at the beginning of the line, it
3544: breaks the line into groups of characters separated by spaces. For each
3545: group of characters in turn, it makes two attempts to do something:
1.23 crook 3546:
1.29 crook 3547: @itemize @bullet
3548: @item
1.44 crook 3549: @cindex name dictionary
1.29 crook 3550: It tries to treat it as a command. It does this by searching a @dfn{name
3551: dictionary}. If the group of characters matches an entry in the name
3552: dictionary, the name dictionary provides the text interpreter with
3553: information that allows the text interpreter perform some actions. In
3554: Forth jargon, we say that the group
3555: @cindex word
3556: @cindex definition
3557: @cindex execution token
3558: @cindex xt
3559: of characters names a @dfn{word}, that the dictionary search returns an
3560: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3561: word, and that the text interpreter executes the xt. Often, the terms
3562: @dfn{word} and @dfn{definition} are used interchangeably.
3563: @item
3564: If the text interpreter fails to find a match in the name dictionary, it
3565: tries to treat the group of characters as a number in the current number
3566: base (when you start up Forth, the current number base is base 10). If
3567: the group of characters legitimately represents a number, the text
3568: interpreter pushes the number onto a stack (we'll learn more about that
3569: in the next section).
3570: @end itemize
1.23 crook 3571:
1.29 crook 3572: If the text interpreter is unable to do either of these things with any
3573: group of characters, it discards the group of characters and the rest of
3574: the line, then prints an error message. If the text interpreter reaches
3575: the end of the line without error, it prints the status message ``@code{ ok}''
3576: followed by carriage-return.
1.21 crook 3577:
1.29 crook 3578: This is the simplest command we can give to the text interpreter:
1.23 crook 3579:
3580: @example
1.30 anton 3581: @key{RET} ok
1.23 crook 3582: @end example
1.21 crook 3583:
1.29 crook 3584: The text interpreter did everything we asked it to do (nothing) without
3585: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3586: command:
1.21 crook 3587:
1.23 crook 3588: @example
1.30 anton 3589: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3590: *the terminal*:3: Undefined word
3591: 12 dup >>>fred<<< dup
3592: Backtrace:
3593: $2A95B42A20 throw
3594: $2A95B57FB8 no.extensions
1.23 crook 3595: @end example
1.21 crook 3596:
1.29 crook 3597: When you press the carriage-return key, the text interpreter starts to
3598: work its way along the line:
1.21 crook 3599:
1.29 crook 3600: @itemize @bullet
3601: @item
3602: When it gets to the space after the @code{2}, it takes the group of
3603: characters @code{12} and looks them up in the name
3604: dictionary@footnote{We can't tell if it found them or not, but assume
3605: for now that it did not}. There is no match for this group of characters
3606: in the name dictionary, so it tries to treat them as a number. It is
3607: able to do this successfully, so it puts the number, 12, ``on the stack''
3608: (whatever that means).
3609: @item
3610: The text interpreter resumes scanning the line and gets the next group
3611: of characters, @code{dup}. It looks it up in the name dictionary and
3612: (you'll have to take my word for this) finds it, and executes the word
3613: @code{dup} (whatever that means).
3614: @item
3615: Once again, the text interpreter resumes scanning the line and gets the
3616: group of characters @code{fred}. It looks them up in the name
3617: dictionary, but can't find them. It tries to treat them as a number, but
3618: they don't represent any legal number.
3619: @end itemize
1.21 crook 3620:
1.29 crook 3621: At this point, the text interpreter gives up and prints an error
3622: message. The error message shows exactly how far the text interpreter
3623: got in processing the line. In particular, it shows that the text
3624: interpreter made no attempt to do anything with the final character
3625: group, @code{dup}, even though we have good reason to believe that the
3626: text interpreter would have no problem looking that word up and
3627: executing it a second time.
1.21 crook 3628:
3629:
1.29 crook 3630: @comment ----------------------------------------------
3631: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3632: @section Stacks, postfix notation and parameter passing
3633: @cindex text interpreter
3634: @cindex outer interpreter
1.21 crook 3635:
1.29 crook 3636: In procedural programming languages (like C and Pascal), the
3637: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3638: functions or procedures are called with @dfn{explicit parameters}. For
3639: example, in C we might write:
1.21 crook 3640:
1.23 crook 3641: @example
1.29 crook 3642: total = total + new_volume(length,height,depth);
1.23 crook 3643: @end example
1.21 crook 3644:
1.23 crook 3645: @noindent
1.29 crook 3646: where new_volume is a function-call to another piece of code, and total,
3647: length, height and depth are all variables. length, height and depth are
3648: parameters to the function-call.
1.21 crook 3649:
1.29 crook 3650: In Forth, the equivalent of the function or procedure is the
3651: @dfn{definition} and parameters are implicitly passed between
3652: definitions using a shared stack that is visible to the
3653: programmer. Although Forth does support variables, the existence of the
3654: stack means that they are used far less often than in most other
3655: programming languages. When the text interpreter encounters a number, it
3656: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3657: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3658: used for any operation is implied unambiguously by the operation being
3659: performed. The stack used for all integer operations is called the @dfn{data
3660: stack} and, since this is the stack used most commonly, references to
3661: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3662:
1.29 crook 3663: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3664:
1.23 crook 3665: @example
1.30 anton 3666: @kbd{1 2 3@key{RET}} ok
1.23 crook 3667: @end example
1.21 crook 3668:
1.29 crook 3669: Then this instructs the text interpreter to placed three numbers on the
3670: (data) stack. An analogy for the behaviour of the stack is to take a
3671: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3672: the table. The 3 was the last card onto the pile (``last-in'') and if
3673: you take a card off the pile then, unless you're prepared to fiddle a
3674: bit, the card that you take off will be the 3 (``first-out''). The
3675: number that will be first-out of the stack is called the @dfn{top of
3676: stack}, which
3677: @cindex TOS definition
3678: is often abbreviated to @dfn{TOS}.
1.21 crook 3679:
1.29 crook 3680: To understand how parameters are passed in Forth, consider the
3681: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3682: be surprised to learn that this definition performs addition. More
3683: precisely, it adds two number together and produces a result. Where does
3684: it get the two numbers from? It takes the top two numbers off the
3685: stack. Where does it place the result? On the stack. You can act-out the
3686: behaviour of @code{+} with your playing cards like this:
1.21 crook 3687:
3688: @itemize @bullet
3689: @item
1.29 crook 3690: Pick up two cards from the stack on the table
1.21 crook 3691: @item
1.29 crook 3692: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3693: numbers''
1.21 crook 3694: @item
1.29 crook 3695: Decide that the answer is 5
1.21 crook 3696: @item
1.29 crook 3697: Shuffle the two cards back into the pack and find a 5
1.21 crook 3698: @item
1.29 crook 3699: Put a 5 on the remaining ace that's on the table.
1.21 crook 3700: @end itemize
3701:
1.29 crook 3702: If you don't have a pack of cards handy but you do have Forth running,
3703: you can use the definition @code{.s} to show the current state of the stack,
3704: without affecting the stack. Type:
1.21 crook 3705:
3706: @example
1.124 anton 3707: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3708: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3709: @end example
3710:
1.124 anton 3711: The text interpreter looks up the word @code{clearstacks} and executes
3712: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3713: left on it by earlier examples. The text interpreter pushes each of the
3714: three numbers in turn onto the stack. Finally, the text interpreter
3715: looks up the word @code{.s} and executes it. The effect of executing
3716: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3717: followed by a list of all the items on the stack; the item on the far
3718: right-hand side is the TOS.
1.21 crook 3719:
1.29 crook 3720: You can now type:
1.21 crook 3721:
1.29 crook 3722: @example
1.30 anton 3723: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3724: @end example
1.21 crook 3725:
1.29 crook 3726: @noindent
3727: which is correct; there are now 2 items on the stack and the result of
3728: the addition is 5.
1.23 crook 3729:
1.29 crook 3730: If you're playing with cards, try doing a second addition: pick up the
3731: two cards, work out that their sum is 6, shuffle them into the pack,
3732: look for a 6 and place that on the table. You now have just one item on
3733: the stack. What happens if you try to do a third addition? Pick up the
3734: first card, pick up the second card -- ah! There is no second card. This
3735: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3736: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3737: Underflow or an Invalid Memory Address error).
1.23 crook 3738:
1.29 crook 3739: The opposite situation to a stack underflow is a @dfn{stack overflow},
3740: which simply accepts that there is a finite amount of storage space
3741: reserved for the stack. To stretch the playing card analogy, if you had
3742: enough packs of cards and you piled the cards up on the table, you would
3743: eventually be unable to add another card; you'd hit the ceiling. Gforth
3744: allows you to set the maximum size of the stacks. In general, the only
3745: time that you will get a stack overflow is because a definition has a
3746: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3747:
1.29 crook 3748: There's one final use for the playing card analogy. If you model your
3749: stack using a pack of playing cards, the maximum number of items on
3750: your stack will be 52 (I assume you didn't use the Joker). The maximum
3751: @i{value} of any item on the stack is 13 (the King). In fact, the only
3752: possible numbers are positive integer numbers 1 through 13; you can't
3753: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3754: think about some of the cards, you can accommodate different
3755: numbers. For example, you could think of the Jack as representing 0,
3756: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3757: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3758: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3759:
1.29 crook 3760: In that analogy, the limit was the amount of information that a single
3761: stack entry could hold, and Forth has a similar limit. In Forth, the
3762: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3763: implementation dependent and affects the maximum value that a stack
3764: entry can hold. A Standard Forth provides a cell size of at least
3765: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3766:
1.29 crook 3767: Forth does not do any type checking for you, so you are free to
3768: manipulate and combine stack items in any way you wish. A convenient way
3769: of treating stack items is as 2's complement signed integers, and that
3770: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3771:
1.29 crook 3772: @example
1.30 anton 3773: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3774: @end example
1.21 crook 3775:
1.29 crook 3776: If you use numbers and definitions like @code{+} in order to turn Forth
3777: into a great big pocket calculator, you will realise that it's rather
3778: different from a normal calculator. Rather than typing 2 + 3 = you had
3779: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3780: result). The terminology used to describe this difference is to say that
3781: your calculator uses @dfn{Infix Notation} (parameters and operators are
3782: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3783: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3784:
1.29 crook 3785: Whilst postfix notation might look confusing to begin with, it has
3786: several important advantages:
1.21 crook 3787:
1.23 crook 3788: @itemize @bullet
3789: @item
1.29 crook 3790: it is unambiguous
1.23 crook 3791: @item
1.29 crook 3792: it is more concise
1.23 crook 3793: @item
1.29 crook 3794: it fits naturally with a stack-based system
1.23 crook 3795: @end itemize
1.21 crook 3796:
1.29 crook 3797: To examine these claims in more detail, consider these sums:
1.21 crook 3798:
1.29 crook 3799: @example
3800: 6 + 5 * 4 =
3801: 4 * 5 + 6 =
3802: @end example
1.21 crook 3803:
1.29 crook 3804: If you're just learning maths or your maths is very rusty, you will
3805: probably come up with the answer 44 for the first and 26 for the
3806: second. If you are a bit of a whizz at maths you will remember the
3807: @i{convention} that multiplication takes precendence over addition, and
3808: you'd come up with the answer 26 both times. To explain the answer 26
3809: to someone who got the answer 44, you'd probably rewrite the first sum
3810: like this:
1.21 crook 3811:
1.29 crook 3812: @example
3813: 6 + (5 * 4) =
3814: @end example
1.21 crook 3815:
1.29 crook 3816: If what you really wanted was to perform the addition before the
3817: multiplication, you would have to use parentheses to force it.
1.21 crook 3818:
1.29 crook 3819: If you did the first two sums on a pocket calculator you would probably
3820: get the right answers, unless you were very cautious and entered them using
3821: these keystroke sequences:
1.21 crook 3822:
1.29 crook 3823: 6 + 5 = * 4 =
3824: 4 * 5 = + 6 =
1.21 crook 3825:
1.29 crook 3826: Postfix notation is unambiguous because the order that the operators
3827: are applied is always explicit; that also means that parentheses are
3828: never required. The operators are @i{active} (the act of quoting the
3829: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3830:
1.29 crook 3831: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3832: equivalent ways:
1.26 crook 3833:
3834: @example
1.29 crook 3835: 6 5 4 * + or:
3836: 5 4 * 6 +
1.26 crook 3837: @end example
1.23 crook 3838:
1.29 crook 3839: An important thing that you should notice about this notation is that
3840: the @i{order} of the numbers does not change; if you want to subtract
3841: 2 from 10 you type @code{10 2 -}.
1.1 anton 3842:
1.29 crook 3843: The reason that Forth uses postfix notation is very simple to explain: it
3844: makes the implementation extremely simple, and it follows naturally from
3845: using the stack as a mechanism for passing parameters. Another way of
3846: thinking about this is to realise that all Forth definitions are
3847: @i{active}; they execute as they are encountered by the text
3848: interpreter. The result of this is that the syntax of Forth is trivially
3849: simple.
1.1 anton 3850:
3851:
3852:
1.29 crook 3853: @comment ----------------------------------------------
3854: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3855: @section Your first Forth definition
3856: @cindex first definition
1.1 anton 3857:
1.29 crook 3858: Until now, the examples we've seen have been trivial; we've just been
3859: using Forth as a bigger-than-pocket calculator. Also, each calculation
3860: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3861: again@footnote{That's not quite true. If you press the up-arrow key on
3862: your keyboard you should be able to scroll back to any earlier command,
3863: edit it and re-enter it.} In this section we'll see how to add new
3864: words to Forth's vocabulary.
1.1 anton 3865:
1.29 crook 3866: The easiest way to create a new word is to use a @dfn{colon
3867: definition}. We'll define a few and try them out before worrying too
3868: much about how they work. Try typing in these examples; be careful to
3869: copy the spaces accurately:
1.1 anton 3870:
1.29 crook 3871: @example
3872: : add-two 2 + . ;
3873: : greet ." Hello and welcome" ;
3874: : demo 5 add-two ;
3875: @end example
1.1 anton 3876:
1.29 crook 3877: @noindent
3878: Now try them out:
1.1 anton 3879:
1.29 crook 3880: @example
1.30 anton 3881: @kbd{greet@key{RET}} Hello and welcome ok
3882: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3883: @kbd{4 add-two@key{RET}} 6 ok
3884: @kbd{demo@key{RET}} 7 ok
3885: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3886: @end example
1.1 anton 3887:
1.29 crook 3888: The first new thing that we've introduced here is the pair of words
3889: @code{:} and @code{;}. These are used to start and terminate a new
3890: definition, respectively. The first word after the @code{:} is the name
3891: for the new definition.
1.1 anton 3892:
1.29 crook 3893: As you can see from the examples, a definition is built up of words that
3894: have already been defined; Forth makes no distinction between
3895: definitions that existed when you started the system up, and those that
3896: you define yourself.
1.1 anton 3897:
1.29 crook 3898: The examples also introduce the words @code{.} (dot), @code{."}
3899: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3900: the stack and displays it. It's like @code{.s} except that it only
3901: displays the top item of the stack and it is destructive; after it has
3902: executed, the number is no longer on the stack. There is always one
3903: space printed after the number, and no spaces before it. Dot-quote
3904: defines a string (a sequence of characters) that will be printed when
3905: the word is executed. The string can contain any printable characters
3906: except @code{"}. A @code{"} has a special function; it is not a Forth
3907: word but it acts as a delimiter (the way that delimiters work is
3908: described in the next section). Finally, @code{dup} duplicates the value
3909: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3910:
1.29 crook 3911: We already know that the text interpreter searches through the
3912: dictionary to locate names. If you've followed the examples earlier, you
3913: will already have a definition called @code{add-two}. Lets try modifying
3914: it by typing in a new definition:
1.1 anton 3915:
1.29 crook 3916: @example
1.30 anton 3917: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3918: @end example
1.5 anton 3919:
1.29 crook 3920: Forth recognised that we were defining a word that already exists, and
3921: printed a message to warn us of that fact. Let's try out the new
3922: definition:
1.5 anton 3923:
1.29 crook 3924: @example
1.30 anton 3925: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3926: @end example
1.1 anton 3927:
1.29 crook 3928: @noindent
3929: All that we've actually done here, though, is to create a new
3930: definition, with a particular name. The fact that there was already a
3931: definition with the same name did not make any difference to the way
3932: that the new definition was created (except that Forth printed a warning
3933: message). The old definition of add-two still exists (try @code{demo}
3934: again to see that this is true). Any new definition will use the new
3935: definition of @code{add-two}, but old definitions continue to use the
3936: version that already existed at the time that they were @code{compiled}.
1.1 anton 3937:
1.29 crook 3938: Before you go on to the next section, try defining and redefining some
3939: words of your own.
1.1 anton 3940:
1.29 crook 3941: @comment ----------------------------------------------
3942: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3943: @section How does that work?
3944: @cindex parsing words
1.1 anton 3945:
1.30 anton 3946: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3947:
3948: @c Is it a good idea to talk about the interpretation semantics of a
3949: @c number? We don't have an xt to go along with it. - anton
3950:
3951: @c Now that I have eliminated execution semantics, I wonder if it would not
3952: @c be better to keep them (or add run-time semantics), to make it easier to
3953: @c explain what compilation semantics usually does. - anton
3954:
1.44 crook 3955: @c nac-> I removed the term ``default compilation sematics'' from the
3956: @c introductory chapter. Removing ``execution semantics'' was making
3957: @c everything simpler to explain, then I think the use of this term made
3958: @c everything more complex again. I replaced it with ``default
3959: @c semantics'' (which is used elsewhere in the manual) by which I mean
3960: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3961: @c flag set''.
3962:
3963: @c anton: I have eliminated default semantics (except in one place where it
3964: @c means "default interpretation and compilation semantics"), because it
3965: @c makes no sense in the presence of combined words. I reverted to
3966: @c "execution semantics" where necessary.
3967:
3968: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3969: @c section (and, unusually for me, I think I even made it shorter!). See
3970: @c what you think -- I know I have not addressed your primary concern
3971: @c that it is too heavy-going for an introduction. From what I understood
3972: @c of your course notes it looks as though they might be a good framework.
3973: @c Things that I've tried to capture here are some things that came as a
3974: @c great revelation here when I first understood them. Also, I like the
3975: @c fact that a very simple code example shows up almost all of the issues
3976: @c that you need to understand to see how Forth works. That's unique and
3977: @c worthwhile to emphasise.
3978:
1.83 anton 3979: @c anton: I think it's a good idea to present the details, especially those
3980: @c that you found to be a revelation, and probably the tutorial tries to be
3981: @c too superficial and does not get some of the things across that make
3982: @c Forth special. I do believe that most of the time these things should
3983: @c be discussed at the end of a section or in separate sections instead of
3984: @c in the middle of a section (e.g., the stuff you added in "User-defined
3985: @c defining words" leads in a completely different direction from the rest
3986: @c of the section).
3987:
1.29 crook 3988: Now we're going to take another look at the definition of @code{add-two}
3989: from the previous section. From our knowledge of the way that the text
3990: interpreter works, we would have expected this result when we tried to
3991: define @code{add-two}:
1.21 crook 3992:
1.29 crook 3993: @example
1.44 crook 3994: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3995: *the terminal*:4: Undefined word
3996: : >>>add-two<<< 2 + . ;
1.29 crook 3997: @end example
1.28 crook 3998:
1.29 crook 3999: The reason that this didn't happen is bound up in the way that @code{:}
4000: works. The word @code{:} does two special things. The first special
4001: thing that it does prevents the text interpreter from ever seeing the
4002: characters @code{add-two}. The text interpreter uses a variable called
4003: @cindex modifying >IN
1.44 crook 4004: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 4005: input line. When it encounters the word @code{:} it behaves in exactly
4006: the same way as it does for any other word; it looks it up in the name
4007: dictionary, finds its xt and executes it. When @code{:} executes, it
4008: looks at the input buffer, finds the word @code{add-two} and advances the
4009: value of @code{>IN} to point past it. It then does some other stuff
4010: associated with creating the new definition (including creating an entry
4011: for @code{add-two} in the name dictionary). When the execution of @code{:}
4012: completes, control returns to the text interpreter, which is oblivious
4013: to the fact that it has been tricked into ignoring part of the input
4014: line.
1.21 crook 4015:
1.29 crook 4016: @cindex parsing words
4017: Words like @code{:} -- words that advance the value of @code{>IN} and so
4018: prevent the text interpreter from acting on the whole of the input line
4019: -- are called @dfn{parsing words}.
1.21 crook 4020:
1.29 crook 4021: @cindex @code{state} - effect on the text interpreter
4022: @cindex text interpreter - effect of state
4023: The second special thing that @code{:} does is change the value of a
4024: variable called @code{state}, which affects the way that the text
4025: interpreter behaves. When Gforth starts up, @code{state} has the value
4026: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4027: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4028: the text interpreter is said to be @dfn{compiling}.
4029:
4030: In this example, the text interpreter is compiling when it processes the
4031: string ``@code{2 + . ;}''. It still breaks the string down into
4032: character sequences in the same way. However, instead of pushing the
4033: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4034: into the definition of @code{add-two} that will make the number @code{2} get
4035: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4036: the behaviours of @code{+} and @code{.} are also compiled into the
4037: definition.
4038:
4039: One category of words don't get compiled. These so-called @dfn{immediate
4040: words} get executed (performed @i{now}) regardless of whether the text
4041: interpreter is interpreting or compiling. The word @code{;} is an
4042: immediate word. Rather than being compiled into the definition, it
4043: executes. Its effect is to terminate the current definition, which
4044: includes changing the value of @code{state} back to 0.
4045:
4046: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4047: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4048: definition.
1.28 crook 4049:
1.30 anton 4050: In Forth, every word or number can be described in terms of two
1.29 crook 4051: properties:
1.28 crook 4052:
4053: @itemize @bullet
4054: @item
1.29 crook 4055: @cindex interpretation semantics
1.44 crook 4056: Its @dfn{interpretation semantics} describe how it will behave when the
4057: text interpreter encounters it in @dfn{interpret} state. The
4058: interpretation semantics of a word are represented by an @dfn{execution
4059: token}.
1.28 crook 4060: @item
1.29 crook 4061: @cindex compilation semantics
1.44 crook 4062: Its @dfn{compilation semantics} describe how it will behave when the
4063: text interpreter encounters it in @dfn{compile} state. The compilation
4064: semantics of a word are represented in an implementation-dependent way;
4065: Gforth uses a @dfn{compilation token}.
1.29 crook 4066: @end itemize
4067:
4068: @noindent
4069: Numbers are always treated in a fixed way:
4070:
4071: @itemize @bullet
1.28 crook 4072: @item
1.44 crook 4073: When the number is @dfn{interpreted}, its behaviour is to push the
4074: number onto the stack.
1.28 crook 4075: @item
1.30 anton 4076: When the number is @dfn{compiled}, a piece of code is appended to the
4077: current definition that pushes the number when it runs. (In other words,
4078: the compilation semantics of a number are to postpone its interpretation
4079: semantics until the run-time of the definition that it is being compiled
4080: into.)
1.29 crook 4081: @end itemize
4082:
1.44 crook 4083: Words don't behave in such a regular way, but most have @i{default
4084: semantics} which means that they behave like this:
1.29 crook 4085:
4086: @itemize @bullet
1.28 crook 4087: @item
1.30 anton 4088: The @dfn{interpretation semantics} of the word are to do something useful.
4089: @item
1.29 crook 4090: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4091: @dfn{interpretation semantics} to the current definition (so that its
4092: run-time behaviour is to do something useful).
1.28 crook 4093: @end itemize
4094:
1.30 anton 4095: @cindex immediate words
1.44 crook 4096: The actual behaviour of any particular word can be controlled by using
4097: the words @code{immediate} and @code{compile-only} when the word is
4098: defined. These words set flags in the name dictionary entry of the most
4099: recently defined word, and these flags are retrieved by the text
4100: interpreter when it finds the word in the name dictionary.
4101:
4102: A word that is marked as @dfn{immediate} has compilation semantics that
4103: are identical to its interpretation semantics. In other words, it
4104: behaves like this:
1.29 crook 4105:
4106: @itemize @bullet
4107: @item
1.30 anton 4108: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4109: @item
1.30 anton 4110: The @dfn{compilation semantics} of the word are to do something useful
4111: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4112: @end itemize
1.28 crook 4113:
1.44 crook 4114: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4115: performing the interpretation semantics of the word directly; an attempt
4116: to do so will generate an error. It is never necessary to use
4117: @code{compile-only} (and it is not even part of ANS Forth, though it is
4118: provided by many implementations) but it is good etiquette to apply it
4119: to a word that will not behave correctly (and might have unexpected
4120: side-effects) in interpret state. For example, it is only legal to use
4121: the conditional word @code{IF} within a definition. If you forget this
4122: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4123: @code{compile-only} allows the text interpreter to generate a helpful
4124: error message rather than subjecting you to the consequences of your
4125: folly.
4126:
1.29 crook 4127: This example shows the difference between an immediate and a
4128: non-immediate word:
1.28 crook 4129:
1.29 crook 4130: @example
4131: : show-state state @@ . ;
4132: : show-state-now show-state ; immediate
4133: : word1 show-state ;
4134: : word2 show-state-now ;
1.28 crook 4135: @end example
1.23 crook 4136:
1.29 crook 4137: The word @code{immediate} after the definition of @code{show-state-now}
4138: makes that word an immediate word. These definitions introduce a new
4139: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4140: variable, and leaves it on the stack. Therefore, the behaviour of
4141: @code{show-state} is to print a number that represents the current value
4142: of @code{state}.
1.28 crook 4143:
1.29 crook 4144: When you execute @code{word1}, it prints the number 0, indicating that
4145: the system is interpreting. When the text interpreter compiled the
4146: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4147: compilation semantics are to append its interpretation semantics to the
1.29 crook 4148: current definition. When you execute @code{word1}, it performs the
1.30 anton 4149: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4150: (and therefore @code{show-state}) are executed, the system is
4151: interpreting.
1.28 crook 4152:
1.30 anton 4153: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4154: you should have seen the number -1 printed, followed by ``@code{
4155: ok}''. When the text interpreter compiled the definition of
4156: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4157: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4158: semantics. It is executed straight away (even before the text
4159: interpreter has moved on to process another group of characters; the
4160: @code{;} in this example). The effect of executing it are to display the
4161: value of @code{state} @i{at the time that the definition of}
4162: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4163: system is compiling at this time. If you execute @code{word2} it does
4164: nothing at all.
1.28 crook 4165:
1.29 crook 4166: @cindex @code{."}, how it works
4167: Before leaving the subject of immediate words, consider the behaviour of
4168: @code{."} in the definition of @code{greet}, in the previous
4169: section. This word is both a parsing word and an immediate word. Notice
4170: that there is a space between @code{."} and the start of the text
4171: @code{Hello and welcome}, but that there is no space between the last
4172: letter of @code{welcome} and the @code{"} character. The reason for this
4173: is that @code{."} is a Forth word; it must have a space after it so that
4174: the text interpreter can identify it. The @code{"} is not a Forth word;
4175: it is a @dfn{delimiter}. The examples earlier show that, when the string
4176: is displayed, there is neither a space before the @code{H} nor after the
4177: @code{e}. Since @code{."} is an immediate word, it executes at the time
4178: that @code{greet} is defined. When it executes, its behaviour is to
4179: search forward in the input line looking for the delimiter. When it
4180: finds the delimiter, it updates @code{>IN} to point past the
4181: delimiter. It also compiles some magic code into the definition of
4182: @code{greet}; the xt of a run-time routine that prints a text string. It
4183: compiles the string @code{Hello and welcome} into memory so that it is
4184: available to be printed later. When the text interpreter gains control,
4185: the next word it finds in the input stream is @code{;} and so it
4186: terminates the definition of @code{greet}.
1.28 crook 4187:
4188:
4189: @comment ----------------------------------------------
1.29 crook 4190: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4191: @section Forth is written in Forth
4192: @cindex structure of Forth programs
4193:
4194: When you start up a Forth compiler, a large number of definitions
4195: already exist. In Forth, you develop a new application using bottom-up
4196: programming techniques to create new definitions that are defined in
4197: terms of existing definitions. As you create each definition you can
4198: test and debug it interactively.
4199:
4200: If you have tried out the examples in this section, you will probably
4201: have typed them in by hand; when you leave Gforth, your definitions will
4202: be lost. You can avoid this by using a text editor to enter Forth source
4203: code into a file, and then loading code from the file using
1.49 anton 4204: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4205: processed by the text interpreter, just as though you had typed it in by
4206: hand@footnote{Actually, there are some subtle differences -- see
4207: @ref{The Text Interpreter}.}.
4208:
4209: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4210: files for program entry (@pxref{Blocks}).
1.28 crook 4211:
1.29 crook 4212: In common with many, if not most, Forth compilers, most of Gforth is
4213: actually written in Forth. All of the @file{.fs} files in the
4214: installation directory@footnote{For example,
1.30 anton 4215: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4216: study to see examples of Forth programming.
1.28 crook 4217:
1.29 crook 4218: Gforth maintains a history file that records every line that you type to
4219: the text interpreter. This file is preserved between sessions, and is
4220: used to provide a command-line recall facility. If you enter long
4221: definitions by hand, you can use a text editor to paste them out of the
4222: history file into a Forth source file for reuse at a later time
1.49 anton 4223: (for more information @pxref{Command-line editing}).
1.28 crook 4224:
4225:
4226: @comment ----------------------------------------------
1.29 crook 4227: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4228: @section Review - elements of a Forth system
4229: @cindex elements of a Forth system
1.28 crook 4230:
1.29 crook 4231: To summarise this chapter:
1.28 crook 4232:
4233: @itemize @bullet
4234: @item
1.29 crook 4235: Forth programs use @dfn{factoring} to break a problem down into small
4236: fragments called @dfn{words} or @dfn{definitions}.
4237: @item
4238: Forth program development is an interactive process.
4239: @item
4240: The main command loop that accepts input, and controls both
4241: interpretation and compilation, is called the @dfn{text interpreter}
4242: (also known as the @dfn{outer interpreter}).
4243: @item
4244: Forth has a very simple syntax, consisting of words and numbers
4245: separated by spaces or carriage-return characters. Any additional syntax
4246: is imposed by @dfn{parsing words}.
4247: @item
4248: Forth uses a stack to pass parameters between words. As a result, it
4249: uses postfix notation.
4250: @item
4251: To use a word that has previously been defined, the text interpreter
4252: searches for the word in the @dfn{name dictionary}.
4253: @item
1.30 anton 4254: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4255: @item
1.29 crook 4256: The text interpreter uses the value of @code{state} to select between
4257: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4258: semantics} of a word that it encounters.
1.28 crook 4259: @item
1.30 anton 4260: The relationship between the @dfn{interpretation semantics} and
4261: @dfn{compilation semantics} for a word
1.29 crook 4262: depend upon the way in which the word was defined (for example, whether
4263: it is an @dfn{immediate} word).
1.28 crook 4264: @item
1.29 crook 4265: Forth definitions can be implemented in Forth (called @dfn{high-level
4266: definitions}) or in some other way (usually a lower-level language and
4267: as a result often called @dfn{low-level definitions}, @dfn{code
4268: definitions} or @dfn{primitives}).
1.28 crook 4269: @item
1.29 crook 4270: Many Forth systems are implemented mainly in Forth.
1.28 crook 4271: @end itemize
4272:
4273:
1.29 crook 4274: @comment ----------------------------------------------
1.48 anton 4275: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4276: @section Where To Go Next
4277: @cindex where to go next
1.28 crook 4278:
1.29 crook 4279: Amazing as it may seem, if you have read (and understood) this far, you
4280: know almost all the fundamentals about the inner workings of a Forth
4281: system. You certainly know enough to be able to read and understand the
4282: rest of this manual and the ANS Forth document, to learn more about the
4283: facilities that Forth in general and Gforth in particular provide. Even
4284: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4285: However, that's not a good idea just yet... better to try writing some
1.29 crook 4286: programs in Gforth.
1.28 crook 4287:
1.29 crook 4288: Forth has such a rich vocabulary that it can be hard to know where to
4289: start in learning it. This section suggests a few sets of words that are
4290: enough to write small but useful programs. Use the word index in this
4291: document to learn more about each word, then try it out and try to write
4292: small definitions using it. Start by experimenting with these words:
1.28 crook 4293:
4294: @itemize @bullet
4295: @item
1.29 crook 4296: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4297: @item
4298: Comparison: @code{MIN MAX =}
4299: @item
4300: Logic: @code{AND OR XOR NOT}
4301: @item
4302: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4303: @item
1.29 crook 4304: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4305: @item
1.29 crook 4306: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4307: @item
1.29 crook 4308: Defining words: @code{: ; CREATE}
1.28 crook 4309: @item
1.29 crook 4310: Memory allocation words: @code{ALLOT ,}
1.28 crook 4311: @item
1.29 crook 4312: Tools: @code{SEE WORDS .S MARKER}
4313: @end itemize
4314:
4315: When you have mastered those, go on to:
4316:
4317: @itemize @bullet
1.28 crook 4318: @item
1.29 crook 4319: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4320: @item
1.29 crook 4321: Memory access: @code{@@ !}
1.28 crook 4322: @end itemize
1.23 crook 4323:
1.29 crook 4324: When you have mastered these, there's nothing for it but to read through
4325: the whole of this manual and find out what you've missed.
4326:
4327: @comment ----------------------------------------------
1.48 anton 4328: @node Exercises, , Where to go next, Introduction
1.29 crook 4329: @section Exercises
4330: @cindex exercises
4331:
4332: TODO: provide a set of programming excercises linked into the stuff done
4333: already and into other sections of the manual. Provide solutions to all
4334: the exercises in a .fs file in the distribution.
4335:
4336: @c Get some inspiration from Starting Forth and Kelly&Spies.
4337:
4338: @c excercises:
4339: @c 1. take inches and convert to feet and inches.
4340: @c 2. take temperature and convert from fahrenheight to celcius;
4341: @c may need to care about symmetric vs floored??
4342: @c 3. take input line and do character substitution
4343: @c to encipher or decipher
4344: @c 4. as above but work on a file for in and out
4345: @c 5. take input line and convert to pig-latin
4346: @c
4347: @c thing of sets of things to exercise then come up with
4348: @c problems that need those things.
4349:
4350:
1.26 crook 4351: @c ******************************************************************
1.29 crook 4352: @node Words, Error messages, Introduction, Top
1.1 anton 4353: @chapter Forth Words
1.26 crook 4354: @cindex words
1.1 anton 4355:
4356: @menu
4357: * Notation::
1.65 anton 4358: * Case insensitivity::
4359: * Comments::
4360: * Boolean Flags::
1.1 anton 4361: * Arithmetic::
4362: * Stack Manipulation::
1.5 anton 4363: * Memory::
1.1 anton 4364: * Control Structures::
4365: * Defining Words::
1.65 anton 4366: * Interpretation and Compilation Semantics::
1.47 crook 4367: * Tokens for Words::
1.81 anton 4368: * Compiling words::
1.65 anton 4369: * The Text Interpreter::
1.111 anton 4370: * The Input Stream::
1.65 anton 4371: * Word Lists::
4372: * Environmental Queries::
1.12 anton 4373: * Files::
4374: * Blocks::
4375: * Other I/O::
1.121 anton 4376: * OS command line arguments::
1.78 anton 4377: * Locals::
4378: * Structures::
4379: * Object-oriented Forth::
1.12 anton 4380: * Programming Tools::
1.150 anton 4381: * C Interface::
1.12 anton 4382: * Assembler and Code Words::
4383: * Threading Words::
1.65 anton 4384: * Passing Commands to the OS::
4385: * Keeping track of Time::
4386: * Miscellaneous Words::
1.1 anton 4387: @end menu
4388:
1.65 anton 4389: @node Notation, Case insensitivity, Words, Words
1.1 anton 4390: @section Notation
4391: @cindex notation of glossary entries
4392: @cindex format of glossary entries
4393: @cindex glossary notation format
4394: @cindex word glossary entry format
4395:
4396: The Forth words are described in this section in the glossary notation
1.67 anton 4397: that has become a de-facto standard for Forth texts:
1.1 anton 4398:
4399: @format
1.29 crook 4400: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4401: @end format
1.29 crook 4402: @i{Description}
1.1 anton 4403:
4404: @table @var
4405: @item word
1.28 crook 4406: The name of the word.
1.1 anton 4407:
4408: @item Stack effect
4409: @cindex stack effect
1.29 crook 4410: The stack effect is written in the notation @code{@i{before} --
4411: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4412: stack entries before and after the execution of the word. The rest of
4413: the stack is not touched by the word. The top of stack is rightmost,
4414: i.e., a stack sequence is written as it is typed in. Note that Gforth
4415: uses a separate floating point stack, but a unified stack
1.29 crook 4416: notation. Also, return stack effects are not shown in @i{stack
4417: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4418: the type and/or the function of the item. See below for a discussion of
4419: the types.
4420:
4421: All words have two stack effects: A compile-time stack effect and a
4422: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4423: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4424: this standard behaviour, or the word does other unusual things at
4425: compile time, both stack effects are shown; otherwise only the run-time
4426: stack effect is shown.
4427:
4428: @cindex pronounciation of words
4429: @item pronunciation
4430: How the word is pronounced.
4431:
4432: @cindex wordset
1.67 anton 4433: @cindex environment wordset
1.1 anton 4434: @item wordset
1.21 crook 4435: The ANS Forth standard is divided into several word sets. A standard
4436: system need not support all of them. Therefore, in theory, the fewer
4437: word sets your program uses the more portable it will be. However, we
4438: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4439: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4440: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4441: describes words that will work in future releases of Gforth;
4442: @code{gforth-internal} words are more volatile. Environmental query
4443: strings are also displayed like words; you can recognize them by the
1.21 crook 4444: @code{environment} in the word set field.
1.1 anton 4445:
4446: @item Description
4447: A description of the behaviour of the word.
4448: @end table
4449:
4450: @cindex types of stack items
4451: @cindex stack item types
4452: The type of a stack item is specified by the character(s) the name
4453: starts with:
4454:
4455: @table @code
4456: @item f
4457: @cindex @code{f}, stack item type
4458: Boolean flags, i.e. @code{false} or @code{true}.
4459: @item c
4460: @cindex @code{c}, stack item type
4461: Char
4462: @item w
4463: @cindex @code{w}, stack item type
4464: Cell, can contain an integer or an address
4465: @item n
4466: @cindex @code{n}, stack item type
4467: signed integer
4468: @item u
4469: @cindex @code{u}, stack item type
4470: unsigned integer
4471: @item d
4472: @cindex @code{d}, stack item type
4473: double sized signed integer
4474: @item ud
4475: @cindex @code{ud}, stack item type
4476: double sized unsigned integer
4477: @item r
4478: @cindex @code{r}, stack item type
4479: Float (on the FP stack)
1.21 crook 4480: @item a-
1.1 anton 4481: @cindex @code{a_}, stack item type
4482: Cell-aligned address
1.21 crook 4483: @item c-
1.1 anton 4484: @cindex @code{c_}, stack item type
4485: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4486: @item f-
1.1 anton 4487: @cindex @code{f_}, stack item type
4488: Float-aligned address
1.21 crook 4489: @item df-
1.1 anton 4490: @cindex @code{df_}, stack item type
4491: Address aligned for IEEE double precision float
1.21 crook 4492: @item sf-
1.1 anton 4493: @cindex @code{sf_}, stack item type
4494: Address aligned for IEEE single precision float
4495: @item xt
4496: @cindex @code{xt}, stack item type
4497: Execution token, same size as Cell
4498: @item wid
4499: @cindex @code{wid}, stack item type
1.21 crook 4500: Word list ID, same size as Cell
1.68 anton 4501: @item ior, wior
4502: @cindex ior type description
4503: @cindex wior type description
4504: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4505: @item f83name
4506: @cindex @code{f83name}, stack item type
4507: Pointer to a name structure
4508: @item "
4509: @cindex @code{"}, stack item type
1.12 anton 4510: string in the input stream (not on the stack). The terminating character
4511: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4512: quotes.
4513: @end table
4514:
1.65 anton 4515: @comment ----------------------------------------------
4516: @node Case insensitivity, Comments, Notation, Words
4517: @section Case insensitivity
4518: @cindex case sensitivity
4519: @cindex upper and lower case
4520:
4521: Gforth is case-insensitive; you can enter definitions and invoke
4522: Standard words using upper, lower or mixed case (however,
4523: @pxref{core-idef, Implementation-defined options, Implementation-defined
4524: options}).
4525:
4526: ANS Forth only @i{requires} implementations to recognise Standard words
4527: when they are typed entirely in upper case. Therefore, a Standard
4528: program must use upper case for all Standard words. You can use whatever
4529: case you like for words that you define, but in a Standard program you
4530: have to use the words in the same case that you defined them.
4531:
4532: Gforth supports case sensitivity through @code{table}s (case-sensitive
4533: wordlists, @pxref{Word Lists}).
4534:
4535: Two people have asked how to convert Gforth to be case-sensitive; while
4536: we think this is a bad idea, you can change all wordlists into tables
4537: like this:
4538:
4539: @example
4540: ' table-find forth-wordlist wordlist-map @ !
4541: @end example
4542:
4543: Note that you now have to type the predefined words in the same case
4544: that we defined them, which are varying. You may want to convert them
4545: to your favourite case before doing this operation (I won't explain how,
4546: because if you are even contemplating doing this, you'd better have
4547: enough knowledge of Forth systems to know this already).
4548:
4549: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4550: @section Comments
1.26 crook 4551: @cindex comments
1.21 crook 4552:
1.29 crook 4553: Forth supports two styles of comment; the traditional @i{in-line} comment,
4554: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4555:
1.44 crook 4556:
1.23 crook 4557: doc-(
1.21 crook 4558: doc-\
1.23 crook 4559: doc-\G
1.21 crook 4560:
1.44 crook 4561:
1.21 crook 4562: @node Boolean Flags, Arithmetic, Comments, Words
4563: @section Boolean Flags
1.26 crook 4564: @cindex Boolean flags
1.21 crook 4565:
4566: A Boolean flag is cell-sized. A cell with all bits clear represents the
4567: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4568: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4569: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4570: @c on and off to Memory?
4571: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4572:
1.21 crook 4573: doc-true
4574: doc-false
1.29 crook 4575: doc-on
4576: doc-off
1.21 crook 4577:
1.44 crook 4578:
1.21 crook 4579: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4580: @section Arithmetic
4581: @cindex arithmetic words
4582:
4583: @cindex division with potentially negative operands
4584: Forth arithmetic is not checked, i.e., you will not hear about integer
4585: overflow on addition or multiplication, you may hear about division by
4586: zero if you are lucky. The operator is written after the operands, but
4587: the operands are still in the original order. I.e., the infix @code{2-1}
4588: corresponds to @code{2 1 -}. Forth offers a variety of division
4589: operators. If you perform division with potentially negative operands,
4590: you do not want to use @code{/} or @code{/mod} with its undefined
4591: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4592: former, @pxref{Mixed precision}).
1.26 crook 4593: @comment TODO discuss the different division forms and the std approach
1.1 anton 4594:
4595: @menu
4596: * Single precision::
1.67 anton 4597: * Double precision:: Double-cell integer arithmetic
1.1 anton 4598: * Bitwise operations::
1.67 anton 4599: * Numeric comparison::
1.29 crook 4600: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4601: * Floating Point::
4602: @end menu
4603:
1.67 anton 4604: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4605: @subsection Single precision
4606: @cindex single precision arithmetic words
4607:
1.67 anton 4608: @c !! cell undefined
4609:
4610: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4611: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4612: treat them. For the rules used by the text interpreter for recognising
4613: single-precision integers see @ref{Number Conversion}.
1.21 crook 4614:
1.67 anton 4615: These words are all defined for signed operands, but some of them also
4616: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4617: @code{*}.
1.44 crook 4618:
1.1 anton 4619: doc-+
1.21 crook 4620: doc-1+
1.128 anton 4621: doc-under+
1.1 anton 4622: doc--
1.21 crook 4623: doc-1-
1.1 anton 4624: doc-*
4625: doc-/
4626: doc-mod
4627: doc-/mod
4628: doc-negate
4629: doc-abs
4630: doc-min
4631: doc-max
1.27 crook 4632: doc-floored
1.1 anton 4633:
1.44 crook 4634:
1.67 anton 4635: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4636: @subsection Double precision
4637: @cindex double precision arithmetic words
4638:
1.49 anton 4639: For the rules used by the text interpreter for
4640: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4641:
4642: A double precision number is represented by a cell pair, with the most
1.67 anton 4643: significant cell at the TOS. It is trivial to convert an unsigned single
4644: to a double: simply push a @code{0} onto the TOS. Since numbers are
4645: represented by Gforth using 2's complement arithmetic, converting a
4646: signed single to a (signed) double requires sign-extension across the
4647: most significant cell. This can be achieved using @code{s>d}. The moral
4648: of the story is that you cannot convert a number without knowing whether
4649: it represents an unsigned or a signed number.
1.21 crook 4650:
1.67 anton 4651: These words are all defined for signed operands, but some of them also
4652: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4653:
1.21 crook 4654: doc-s>d
1.67 anton 4655: doc-d>s
1.21 crook 4656: doc-d+
4657: doc-d-
4658: doc-dnegate
4659: doc-dabs
4660: doc-dmin
4661: doc-dmax
4662:
1.44 crook 4663:
1.67 anton 4664: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4665: @subsection Bitwise operations
4666: @cindex bitwise operation words
4667:
4668:
4669: doc-and
4670: doc-or
4671: doc-xor
4672: doc-invert
4673: doc-lshift
4674: doc-rshift
4675: doc-2*
4676: doc-d2*
4677: doc-2/
4678: doc-d2/
4679:
4680:
4681: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4682: @subsection Numeric comparison
4683: @cindex numeric comparison words
4684:
1.67 anton 4685: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4686: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4687:
1.28 crook 4688: doc-<
4689: doc-<=
4690: doc-<>
4691: doc-=
4692: doc->
4693: doc->=
4694:
1.21 crook 4695: doc-0<
1.23 crook 4696: doc-0<=
1.21 crook 4697: doc-0<>
4698: doc-0=
1.23 crook 4699: doc-0>
4700: doc-0>=
1.28 crook 4701:
4702: doc-u<
4703: doc-u<=
1.44 crook 4704: @c u<> and u= exist but are the same as <> and =
1.31 anton 4705: @c doc-u<>
4706: @c doc-u=
1.28 crook 4707: doc-u>
4708: doc-u>=
4709:
4710: doc-within
4711:
4712: doc-d<
4713: doc-d<=
4714: doc-d<>
4715: doc-d=
4716: doc-d>
4717: doc-d>=
1.23 crook 4718:
1.21 crook 4719: doc-d0<
1.23 crook 4720: doc-d0<=
4721: doc-d0<>
1.21 crook 4722: doc-d0=
1.23 crook 4723: doc-d0>
4724: doc-d0>=
4725:
1.21 crook 4726: doc-du<
1.28 crook 4727: doc-du<=
1.44 crook 4728: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4729: @c doc-du<>
4730: @c doc-du=
1.28 crook 4731: doc-du>
4732: doc-du>=
1.1 anton 4733:
1.44 crook 4734:
1.21 crook 4735: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4736: @subsection Mixed precision
4737: @cindex mixed precision arithmetic words
4738:
1.44 crook 4739:
1.1 anton 4740: doc-m+
4741: doc-*/
4742: doc-*/mod
4743: doc-m*
4744: doc-um*
4745: doc-m*/
4746: doc-um/mod
4747: doc-fm/mod
4748: doc-sm/rem
4749:
1.44 crook 4750:
1.21 crook 4751: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4752: @subsection Floating Point
4753: @cindex floating point arithmetic words
4754:
1.49 anton 4755: For the rules used by the text interpreter for
4756: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4757:
1.67 anton 4758: Gforth has a separate floating point stack, but the documentation uses
4759: the unified notation.@footnote{It's easy to generate the separate
4760: notation from that by just separating the floating-point numbers out:
4761: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4762: r3 )}.}
1.1 anton 4763:
4764: @cindex floating-point arithmetic, pitfalls
4765: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4766: unwary (e.g., floating point addition is not associative) and even a
4767: few for the wary. You should not use them unless you know what you are
4768: doing or you don't care that the results you get are totally bogus. If
4769: you want to learn about the problems of floating point numbers (and
4770: how to avoid them), you might start with @cite{David Goldberg,
4771: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4772: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4773: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4774:
1.44 crook 4775:
1.21 crook 4776: doc-d>f
4777: doc-f>d
1.1 anton 4778: doc-f+
4779: doc-f-
4780: doc-f*
4781: doc-f/
4782: doc-fnegate
4783: doc-fabs
4784: doc-fmax
4785: doc-fmin
4786: doc-floor
4787: doc-fround
4788: doc-f**
4789: doc-fsqrt
4790: doc-fexp
4791: doc-fexpm1
4792: doc-fln
4793: doc-flnp1
4794: doc-flog
4795: doc-falog
1.32 anton 4796: doc-f2*
4797: doc-f2/
4798: doc-1/f
4799: doc-precision
4800: doc-set-precision
4801:
4802: @cindex angles in trigonometric operations
4803: @cindex trigonometric operations
4804: Angles in floating point operations are given in radians (a full circle
4805: has 2 pi radians).
4806:
1.1 anton 4807: doc-fsin
4808: doc-fcos
4809: doc-fsincos
4810: doc-ftan
4811: doc-fasin
4812: doc-facos
4813: doc-fatan
4814: doc-fatan2
4815: doc-fsinh
4816: doc-fcosh
4817: doc-ftanh
4818: doc-fasinh
4819: doc-facosh
4820: doc-fatanh
1.21 crook 4821: doc-pi
1.28 crook 4822:
1.32 anton 4823: @cindex equality of floats
4824: @cindex floating-point comparisons
1.31 anton 4825: One particular problem with floating-point arithmetic is that comparison
4826: for equality often fails when you would expect it to succeed. For this
4827: reason approximate equality is often preferred (but you still have to
1.67 anton 4828: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4829: differently from what you might expect. The comparison words are:
1.31 anton 4830:
4831: doc-f~rel
4832: doc-f~abs
1.68 anton 4833: doc-f~
1.31 anton 4834: doc-f=
4835: doc-f<>
4836:
4837: doc-f<
4838: doc-f<=
4839: doc-f>
4840: doc-f>=
4841:
1.21 crook 4842: doc-f0<
1.28 crook 4843: doc-f0<=
4844: doc-f0<>
1.21 crook 4845: doc-f0=
1.28 crook 4846: doc-f0>
4847: doc-f0>=
4848:
1.1 anton 4849:
4850: @node Stack Manipulation, Memory, Arithmetic, Words
4851: @section Stack Manipulation
4852: @cindex stack manipulation words
4853:
4854: @cindex floating-point stack in the standard
1.21 crook 4855: Gforth maintains a number of separate stacks:
4856:
1.29 crook 4857: @cindex data stack
4858: @cindex parameter stack
1.21 crook 4859: @itemize @bullet
4860: @item
1.29 crook 4861: A data stack (also known as the @dfn{parameter stack}) -- for
4862: characters, cells, addresses, and double cells.
1.21 crook 4863:
1.29 crook 4864: @cindex floating-point stack
1.21 crook 4865: @item
1.44 crook 4866: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4867:
1.29 crook 4868: @cindex return stack
1.21 crook 4869: @item
1.44 crook 4870: A return stack -- for holding the return addresses of colon
1.32 anton 4871: definitions and other (non-FP) data.
1.21 crook 4872:
1.29 crook 4873: @cindex locals stack
1.21 crook 4874: @item
1.44 crook 4875: A locals stack -- for holding local variables.
1.21 crook 4876: @end itemize
4877:
1.1 anton 4878: @menu
4879: * Data stack::
4880: * Floating point stack::
4881: * Return stack::
4882: * Locals stack::
4883: * Stack pointer manipulation::
4884: @end menu
4885:
4886: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4887: @subsection Data stack
4888: @cindex data stack manipulation words
4889: @cindex stack manipulations words, data stack
4890:
1.44 crook 4891:
1.1 anton 4892: doc-drop
4893: doc-nip
4894: doc-dup
4895: doc-over
4896: doc-tuck
4897: doc-swap
1.21 crook 4898: doc-pick
1.1 anton 4899: doc-rot
4900: doc--rot
4901: doc-?dup
4902: doc-roll
4903: doc-2drop
4904: doc-2nip
4905: doc-2dup
4906: doc-2over
4907: doc-2tuck
4908: doc-2swap
4909: doc-2rot
4910:
1.44 crook 4911:
1.1 anton 4912: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4913: @subsection Floating point stack
4914: @cindex floating-point stack manipulation words
4915: @cindex stack manipulation words, floating-point stack
4916:
1.32 anton 4917: Whilst every sane Forth has a separate floating-point stack, it is not
4918: strictly required; an ANS Forth system could theoretically keep
4919: floating-point numbers on the data stack. As an additional difficulty,
4920: you don't know how many cells a floating-point number takes. It is
4921: reportedly possible to write words in a way that they work also for a
4922: unified stack model, but we do not recommend trying it. Instead, just
4923: say that your program has an environmental dependency on a separate
4924: floating-point stack.
4925:
4926: doc-floating-stack
4927:
1.1 anton 4928: doc-fdrop
4929: doc-fnip
4930: doc-fdup
4931: doc-fover
4932: doc-ftuck
4933: doc-fswap
1.21 crook 4934: doc-fpick
1.1 anton 4935: doc-frot
4936:
1.44 crook 4937:
1.1 anton 4938: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4939: @subsection Return stack
4940: @cindex return stack manipulation words
4941: @cindex stack manipulation words, return stack
4942:
1.32 anton 4943: @cindex return stack and locals
4944: @cindex locals and return stack
4945: A Forth system is allowed to keep local variables on the
4946: return stack. This is reasonable, as local variables usually eliminate
4947: the need to use the return stack explicitly. So, if you want to produce
4948: a standard compliant program and you are using local variables in a
4949: word, forget about return stack manipulations in that word (refer to the
4950: standard document for the exact rules).
4951:
1.1 anton 4952: doc->r
4953: doc-r>
4954: doc-r@
4955: doc-rdrop
4956: doc-2>r
4957: doc-2r>
4958: doc-2r@
4959: doc-2rdrop
4960:
1.44 crook 4961:
1.1 anton 4962: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4963: @subsection Locals stack
4964:
1.78 anton 4965: Gforth uses an extra locals stack. It is described, along with the
4966: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4967:
1.1 anton 4968: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4969: @subsection Stack pointer manipulation
4970: @cindex stack pointer manipulation words
4971:
1.44 crook 4972: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4973: doc-sp0
1.1 anton 4974: doc-sp@
4975: doc-sp!
1.21 crook 4976: doc-fp0
1.1 anton 4977: doc-fp@
4978: doc-fp!
1.21 crook 4979: doc-rp0
1.1 anton 4980: doc-rp@
4981: doc-rp!
1.21 crook 4982: doc-lp0
1.1 anton 4983: doc-lp@
4984: doc-lp!
4985:
1.44 crook 4986:
1.1 anton 4987: @node Memory, Control Structures, Stack Manipulation, Words
4988: @section Memory
1.26 crook 4989: @cindex memory words
1.1 anton 4990:
1.32 anton 4991: @menu
4992: * Memory model::
4993: * Dictionary allocation::
4994: * Heap Allocation::
4995: * Memory Access::
4996: * Address arithmetic::
4997: * Memory Blocks::
4998: @end menu
4999:
1.67 anton 5000: In addition to the standard Forth memory allocation words, there is also
5001: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5002: garbage collector}.
5003:
1.32 anton 5004: @node Memory model, Dictionary allocation, Memory, Memory
5005: @subsection ANS Forth and Gforth memory models
5006:
5007: @c The ANS Forth description is a mess (e.g., is the heap part of
5008: @c the dictionary?), so let's not stick to closely with it.
5009:
1.67 anton 5010: ANS Forth considers a Forth system as consisting of several address
5011: spaces, of which only @dfn{data space} is managed and accessible with
5012: the memory words. Memory not necessarily in data space includes the
5013: stacks, the code (called code space) and the headers (called name
5014: space). In Gforth everything is in data space, but the code for the
5015: primitives is usually read-only.
1.32 anton 5016:
5017: Data space is divided into a number of areas: The (data space portion of
5018: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5019: refer to the search data structure embodied in word lists and headers,
5020: because it is used for looking up names, just as you would in a
5021: conventional dictionary.}, the heap, and a number of system-allocated
5022: buffers.
5023:
1.68 anton 5024: @cindex address arithmetic restrictions, ANS vs. Gforth
5025: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5026: In ANS Forth data space is also divided into contiguous regions. You
5027: can only use address arithmetic within a contiguous region, not between
5028: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5029: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5030: allocation}).
5031:
5032: Gforth provides one big address space, and address arithmetic can be
5033: performed between any addresses. However, in the dictionary headers or
5034: code are interleaved with data, so almost the only contiguous data space
5035: regions there are those described by ANS Forth as contiguous; but you
5036: can be sure that the dictionary is allocated towards increasing
5037: addresses even between contiguous regions. The memory order of
5038: allocations in the heap is platform-dependent (and possibly different
5039: from one run to the next).
5040:
1.27 crook 5041:
1.32 anton 5042: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5043: @subsection Dictionary allocation
1.27 crook 5044: @cindex reserving data space
5045: @cindex data space - reserving some
5046:
1.32 anton 5047: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5048: you want to deallocate X, you also deallocate everything
5049: allocated after X.
5050:
1.68 anton 5051: @cindex contiguous regions in dictionary allocation
1.32 anton 5052: The allocations using the words below are contiguous and grow the region
5053: towards increasing addresses. Other words that allocate dictionary
5054: memory of any kind (i.e., defining words including @code{:noname}) end
5055: the contiguous region and start a new one.
5056:
5057: In ANS Forth only @code{create}d words are guaranteed to produce an
5058: address that is the start of the following contiguous region. In
5059: particular, the cell allocated by @code{variable} is not guaranteed to
5060: be contiguous with following @code{allot}ed memory.
5061:
5062: You can deallocate memory by using @code{allot} with a negative argument
5063: (with some restrictions, see @code{allot}). For larger deallocations use
5064: @code{marker}.
1.27 crook 5065:
1.29 crook 5066:
1.27 crook 5067: doc-here
5068: doc-unused
5069: doc-allot
5070: doc-c,
1.29 crook 5071: doc-f,
1.27 crook 5072: doc-,
5073: doc-2,
5074:
1.32 anton 5075: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5076: course you should allocate memory in an aligned way, too. I.e., before
5077: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5078: The words below align @code{here} if it is not already. Basically it is
5079: only already aligned for a type, if the last allocation was a multiple
5080: of the size of this type and if @code{here} was aligned for this type
5081: before.
5082:
5083: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5084: ANS Forth (@code{maxalign}ed in Gforth).
5085:
5086: doc-align
5087: doc-falign
5088: doc-sfalign
5089: doc-dfalign
5090: doc-maxalign
5091: doc-cfalign
5092:
5093:
5094: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5095: @subsection Heap allocation
5096: @cindex heap allocation
5097: @cindex dynamic allocation of memory
5098: @cindex memory-allocation word set
5099:
1.68 anton 5100: @cindex contiguous regions and heap allocation
1.32 anton 5101: Heap allocation supports deallocation of allocated memory in any
5102: order. Dictionary allocation is not affected by it (i.e., it does not
5103: end a contiguous region). In Gforth, these words are implemented using
5104: the standard C library calls malloc(), free() and resize().
5105:
1.68 anton 5106: The memory region produced by one invocation of @code{allocate} or
5107: @code{resize} is internally contiguous. There is no contiguity between
5108: such a region and any other region (including others allocated from the
5109: heap).
5110:
1.32 anton 5111: doc-allocate
5112: doc-free
5113: doc-resize
5114:
1.27 crook 5115:
1.32 anton 5116: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5117: @subsection Memory Access
5118: @cindex memory access words
5119:
5120: doc-@
5121: doc-!
5122: doc-+!
5123: doc-c@
5124: doc-c!
5125: doc-2@
5126: doc-2!
5127: doc-f@
5128: doc-f!
5129: doc-sf@
5130: doc-sf!
5131: doc-df@
5132: doc-df!
1.144 anton 5133: doc-sw@
5134: doc-uw@
5135: doc-w!
5136: doc-sl@
5137: doc-ul@
5138: doc-l!
1.68 anton 5139:
1.32 anton 5140: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5141: @subsection Address arithmetic
1.1 anton 5142: @cindex address arithmetic words
5143:
1.67 anton 5144: Address arithmetic is the foundation on which you can build data
5145: structures like arrays, records (@pxref{Structures}) and objects
5146: (@pxref{Object-oriented Forth}).
1.32 anton 5147:
1.68 anton 5148: @cindex address unit
5149: @cindex au (address unit)
1.1 anton 5150: ANS Forth does not specify the sizes of the data types. Instead, it
5151: offers a number of words for computing sizes and doing address
1.29 crook 5152: arithmetic. Address arithmetic is performed in terms of address units
5153: (aus); on most systems the address unit is one byte. Note that a
5154: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5155: platforms where it is a noop, it compiles to nothing).
1.1 anton 5156:
1.67 anton 5157: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5158: you have the address of a cell, perform @code{1 cells +}, and you will
5159: have the address of the next cell.
5160:
1.68 anton 5161: @cindex contiguous regions and address arithmetic
1.67 anton 5162: In ANS Forth you can perform address arithmetic only within a contiguous
5163: region, i.e., if you have an address into one region, you can only add
5164: and subtract such that the result is still within the region; you can
5165: only subtract or compare addresses from within the same contiguous
5166: region. Reasons: several contiguous regions can be arranged in memory
5167: in any way; on segmented systems addresses may have unusual
5168: representations, such that address arithmetic only works within a
5169: region. Gforth provides a few more guarantees (linear address space,
5170: dictionary grows upwards), but in general I have found it easy to stay
5171: within contiguous regions (exception: computing and comparing to the
5172: address just beyond the end of an array).
5173:
1.1 anton 5174: @cindex alignment of addresses for types
5175: ANS Forth also defines words for aligning addresses for specific
5176: types. Many computers require that accesses to specific data types
5177: must only occur at specific addresses; e.g., that cells may only be
5178: accessed at addresses divisible by 4. Even if a machine allows unaligned
5179: accesses, it can usually perform aligned accesses faster.
5180:
5181: For the performance-conscious: alignment operations are usually only
5182: necessary during the definition of a data structure, not during the
5183: (more frequent) accesses to it.
5184:
5185: ANS Forth defines no words for character-aligning addresses. This is not
5186: an oversight, but reflects the fact that addresses that are not
5187: char-aligned have no use in the standard and therefore will not be
5188: created.
5189:
5190: @cindex @code{CREATE} and alignment
1.29 crook 5191: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5192: are cell-aligned; in addition, Gforth guarantees that these addresses
5193: are aligned for all purposes.
5194:
1.26 crook 5195: Note that the ANS Forth word @code{char} has nothing to do with address
5196: arithmetic.
1.1 anton 5197:
1.44 crook 5198:
1.1 anton 5199: doc-chars
5200: doc-char+
5201: doc-cells
5202: doc-cell+
5203: doc-cell
5204: doc-aligned
5205: doc-floats
5206: doc-float+
5207: doc-float
5208: doc-faligned
5209: doc-sfloats
5210: doc-sfloat+
5211: doc-sfaligned
5212: doc-dfloats
5213: doc-dfloat+
5214: doc-dfaligned
5215: doc-maxaligned
5216: doc-cfaligned
5217: doc-address-unit-bits
1.145 anton 5218: doc-/w
5219: doc-/l
1.44 crook 5220:
1.32 anton 5221: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5222: @subsection Memory Blocks
5223: @cindex memory block words
1.27 crook 5224: @cindex character strings - moving and copying
5225:
1.49 anton 5226: Memory blocks often represent character strings; For ways of storing
5227: character strings in memory see @ref{String Formats}. For other
5228: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5229:
1.67 anton 5230: A few of these words work on address unit blocks. In that case, you
5231: usually have to insert @code{CHARS} before the word when working on
5232: character strings. Most words work on character blocks, and expect a
5233: char-aligned address.
5234:
5235: When copying characters between overlapping memory regions, use
5236: @code{chars move} or choose carefully between @code{cmove} and
5237: @code{cmove>}.
1.44 crook 5238:
1.1 anton 5239: doc-move
5240: doc-erase
5241: doc-cmove
5242: doc-cmove>
5243: doc-fill
5244: doc-blank
1.21 crook 5245: doc-compare
1.111 anton 5246: doc-str=
5247: doc-str<
5248: doc-string-prefix?
1.21 crook 5249: doc-search
1.27 crook 5250: doc--trailing
5251: doc-/string
1.82 anton 5252: doc-bounds
1.141 anton 5253: doc-pad
1.111 anton 5254:
1.27 crook 5255: @comment TODO examples
5256:
1.1 anton 5257:
1.26 crook 5258: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5259: @section Control Structures
5260: @cindex control structures
5261:
1.33 anton 5262: Control structures in Forth cannot be used interpretively, only in a
5263: colon definition@footnote{To be precise, they have no interpretation
5264: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5265: not like this limitation, but have not seen a satisfying way around it
5266: yet, although many schemes have been proposed.
1.1 anton 5267:
5268: @menu
1.33 anton 5269: * Selection:: IF ... ELSE ... ENDIF
5270: * Simple Loops:: BEGIN ...
1.29 crook 5271: * Counted Loops:: DO
1.67 anton 5272: * Arbitrary control structures::
5273: * Calls and returns::
1.1 anton 5274: * Exception Handling::
5275: @end menu
5276:
5277: @node Selection, Simple Loops, Control Structures, Control Structures
5278: @subsection Selection
5279: @cindex selection control structures
5280: @cindex control structures for selection
5281:
5282: @cindex @code{IF} control structure
5283: @example
1.29 crook 5284: @i{flag}
1.1 anton 5285: IF
1.29 crook 5286: @i{code}
1.1 anton 5287: ENDIF
5288: @end example
1.21 crook 5289: @noindent
1.33 anton 5290:
1.44 crook 5291: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5292: with any bit set represents truth) @i{code} is executed.
1.33 anton 5293:
1.1 anton 5294: @example
1.29 crook 5295: @i{flag}
1.1 anton 5296: IF
1.29 crook 5297: @i{code1}
1.1 anton 5298: ELSE
1.29 crook 5299: @i{code2}
1.1 anton 5300: ENDIF
5301: @end example
5302:
1.44 crook 5303: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5304: executed.
1.33 anton 5305:
1.1 anton 5306: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5307: standard, and @code{ENDIF} is not, although it is quite popular. We
5308: recommend using @code{ENDIF}, because it is less confusing for people
5309: who also know other languages (and is not prone to reinforcing negative
5310: prejudices against Forth in these people). Adding @code{ENDIF} to a
5311: system that only supplies @code{THEN} is simple:
5312: @example
1.82 anton 5313: : ENDIF POSTPONE then ; immediate
1.1 anton 5314: @end example
5315:
5316: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5317: (adv.)} has the following meanings:
5318: @quotation
5319: ... 2b: following next after in order ... 3d: as a necessary consequence
5320: (if you were there, then you saw them).
5321: @end quotation
5322: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5323: and many other programming languages has the meaning 3d.]
5324:
1.21 crook 5325: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5326: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5327: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5328: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5329: @file{compat/control.fs}.
5330:
5331: @cindex @code{CASE} control structure
5332: @example
1.29 crook 5333: @i{n}
1.1 anton 5334: CASE
1.29 crook 5335: @i{n1} OF @i{code1} ENDOF
5336: @i{n2} OF @i{code2} ENDOF
1.1 anton 5337: @dots{}
1.68 anton 5338: ( n ) @i{default-code} ( n )
1.131 anton 5339: ENDCASE ( )
1.1 anton 5340: @end example
5341:
1.131 anton 5342: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5343: no @i{ni} matches, the optional @i{default-code} is executed. The
5344: optional default case can be added by simply writing the code after
5345: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5346: but must not consume it. The value @i{n} is consumed by this
5347: construction (either by a OF that matches, or by the ENDCASE, if no OF
5348: matches).
1.1 anton 5349:
1.69 anton 5350: @progstyle
1.131 anton 5351: To keep the code understandable, you should ensure that you change the
5352: stack in the same way (wrt. number and types of stack items consumed
5353: and pushed) on all paths through a selection construct.
1.69 anton 5354:
1.1 anton 5355: @node Simple Loops, Counted Loops, Selection, Control Structures
5356: @subsection Simple Loops
5357: @cindex simple loops
5358: @cindex loops without count
5359:
5360: @cindex @code{WHILE} loop
5361: @example
5362: BEGIN
1.29 crook 5363: @i{code1}
5364: @i{flag}
1.1 anton 5365: WHILE
1.29 crook 5366: @i{code2}
1.1 anton 5367: REPEAT
5368: @end example
5369:
1.29 crook 5370: @i{code1} is executed and @i{flag} is computed. If it is true,
5371: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5372: false, execution continues after the @code{REPEAT}.
5373:
5374: @cindex @code{UNTIL} loop
5375: @example
5376: BEGIN
1.29 crook 5377: @i{code}
5378: @i{flag}
1.1 anton 5379: UNTIL
5380: @end example
5381:
1.29 crook 5382: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5383:
1.69 anton 5384: @progstyle
5385: To keep the code understandable, a complete iteration of the loop should
5386: not change the number and types of the items on the stacks.
5387:
1.1 anton 5388: @cindex endless loop
5389: @cindex loops, endless
5390: @example
5391: BEGIN
1.29 crook 5392: @i{code}
1.1 anton 5393: AGAIN
5394: @end example
5395:
5396: This is an endless loop.
5397:
5398: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5399: @subsection Counted Loops
5400: @cindex counted loops
5401: @cindex loops, counted
5402: @cindex @code{DO} loops
5403:
5404: The basic counted loop is:
5405: @example
1.29 crook 5406: @i{limit} @i{start}
1.1 anton 5407: ?DO
1.29 crook 5408: @i{body}
1.1 anton 5409: LOOP
5410: @end example
5411:
1.29 crook 5412: This performs one iteration for every integer, starting from @i{start}
5413: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5414: accessed with @code{i}. For example, the loop:
1.1 anton 5415: @example
5416: 10 0 ?DO
5417: i .
5418: LOOP
5419: @end example
1.21 crook 5420: @noindent
5421: prints @code{0 1 2 3 4 5 6 7 8 9}
5422:
1.1 anton 5423: The index of the innermost loop can be accessed with @code{i}, the index
5424: of the next loop with @code{j}, and the index of the third loop with
5425: @code{k}.
5426:
1.44 crook 5427:
1.1 anton 5428: doc-i
5429: doc-j
5430: doc-k
5431:
1.44 crook 5432:
1.1 anton 5433: The loop control data are kept on the return stack, so there are some
1.21 crook 5434: restrictions on mixing return stack accesses and counted loop words. In
5435: particuler, if you put values on the return stack outside the loop, you
5436: cannot read them inside the loop@footnote{well, not in a way that is
5437: portable.}. If you put values on the return stack within a loop, you
5438: have to remove them before the end of the loop and before accessing the
5439: index of the loop.
1.1 anton 5440:
5441: There are several variations on the counted loop:
5442:
1.21 crook 5443: @itemize @bullet
5444: @item
5445: @code{LEAVE} leaves the innermost counted loop immediately; execution
5446: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5447:
5448: @example
5449: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5450: @end example
5451: prints @code{0 1 2 3}
5452:
1.1 anton 5453:
1.21 crook 5454: @item
5455: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5456: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5457: return stack so @code{EXIT} can get to its return address. For example:
5458:
5459: @example
5460: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5461: @end example
5462: prints @code{0 1 2 3}
5463:
5464:
5465: @item
1.29 crook 5466: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5467: (and @code{LOOP} iterates until they become equal by wrap-around
5468: arithmetic). This behaviour is usually not what you want. Therefore,
5469: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5470: @code{?DO}), which do not enter the loop if @i{start} is greater than
5471: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5472: unsigned loop parameters.
5473:
1.21 crook 5474: @item
5475: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5476: the loop, independent of the loop parameters. Do not use @code{DO}, even
5477: if you know that the loop is entered in any case. Such knowledge tends
5478: to become invalid during maintenance of a program, and then the
5479: @code{DO} will make trouble.
5480:
5481: @item
1.29 crook 5482: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5483: index by @i{n} instead of by 1. The loop is terminated when the border
5484: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5485:
1.21 crook 5486: @example
5487: 4 0 +DO i . 2 +LOOP
5488: @end example
5489: @noindent
5490: prints @code{0 2}
5491:
5492: @example
5493: 4 1 +DO i . 2 +LOOP
5494: @end example
5495: @noindent
5496: prints @code{1 3}
1.1 anton 5497:
1.68 anton 5498: @item
1.1 anton 5499: @cindex negative increment for counted loops
5500: @cindex counted loops with negative increment
1.29 crook 5501: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5502:
1.21 crook 5503: @example
5504: -1 0 ?DO i . -1 +LOOP
5505: @end example
5506: @noindent
5507: prints @code{0 -1}
1.1 anton 5508:
1.21 crook 5509: @example
5510: 0 0 ?DO i . -1 +LOOP
5511: @end example
5512: prints nothing.
1.1 anton 5513:
1.29 crook 5514: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5515: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5516: index by @i{u} each iteration. The loop is terminated when the border
5517: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5518: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5519:
1.21 crook 5520: @example
5521: -2 0 -DO i . 1 -LOOP
5522: @end example
5523: @noindent
5524: prints @code{0 -1}
1.1 anton 5525:
1.21 crook 5526: @example
5527: -1 0 -DO i . 1 -LOOP
5528: @end example
5529: @noindent
5530: prints @code{0}
5531:
5532: @example
5533: 0 0 -DO i . 1 -LOOP
5534: @end example
5535: @noindent
5536: prints nothing.
1.1 anton 5537:
1.21 crook 5538: @end itemize
1.1 anton 5539:
5540: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5541: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5542: for these words that uses only standard words is provided in
5543: @file{compat/loops.fs}.
1.1 anton 5544:
5545:
5546: @cindex @code{FOR} loops
1.26 crook 5547: Another counted loop is:
1.1 anton 5548: @example
1.29 crook 5549: @i{n}
1.1 anton 5550: FOR
1.29 crook 5551: @i{body}
1.1 anton 5552: NEXT
5553: @end example
5554: This is the preferred loop of native code compiler writers who are too
1.26 crook 5555: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5556: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5557: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5558: Forth systems may behave differently, even if they support @code{FOR}
5559: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5560:
5561: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5562: @subsection Arbitrary control structures
5563: @cindex control structures, user-defined
5564:
5565: @cindex control-flow stack
5566: ANS Forth permits and supports using control structures in a non-nested
5567: way. Information about incomplete control structures is stored on the
5568: control-flow stack. This stack may be implemented on the Forth data
5569: stack, and this is what we have done in Gforth.
5570:
5571: @cindex @code{orig}, control-flow stack item
5572: @cindex @code{dest}, control-flow stack item
5573: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5574: entry represents a backward branch target. A few words are the basis for
5575: building any control structure possible (except control structures that
5576: need storage, like calls, coroutines, and backtracking).
5577:
1.44 crook 5578:
1.1 anton 5579: doc-if
5580: doc-ahead
5581: doc-then
5582: doc-begin
5583: doc-until
5584: doc-again
5585: doc-cs-pick
5586: doc-cs-roll
5587:
1.44 crook 5588:
1.21 crook 5589: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5590: manipulate the control-flow stack in a portable way. Without them, you
5591: would need to know how many stack items are occupied by a control-flow
5592: entry (many systems use one cell. In Gforth they currently take three,
5593: but this may change in the future).
5594:
1.1 anton 5595: Some standard control structure words are built from these words:
5596:
1.44 crook 5597:
1.1 anton 5598: doc-else
5599: doc-while
5600: doc-repeat
5601:
1.44 crook 5602:
5603: @noindent
1.1 anton 5604: Gforth adds some more control-structure words:
5605:
1.44 crook 5606:
1.1 anton 5607: doc-endif
5608: doc-?dup-if
5609: doc-?dup-0=-if
5610:
1.44 crook 5611:
5612: @noindent
1.1 anton 5613: Counted loop words constitute a separate group of words:
5614:
1.44 crook 5615:
1.1 anton 5616: doc-?do
5617: doc-+do
5618: doc-u+do
5619: doc--do
5620: doc-u-do
5621: doc-do
5622: doc-for
5623: doc-loop
5624: doc-+loop
5625: doc--loop
5626: doc-next
5627: doc-leave
5628: doc-?leave
5629: doc-unloop
5630: doc-done
5631:
1.44 crook 5632:
1.21 crook 5633: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5634: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5635: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5636: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5637: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5638: resolved (by using one of the loop-ending words or @code{DONE}).
5639:
1.44 crook 5640: @noindent
1.26 crook 5641: Another group of control structure words are:
1.1 anton 5642:
1.44 crook 5643:
1.1 anton 5644: doc-case
5645: doc-endcase
5646: doc-of
5647: doc-endof
5648:
1.44 crook 5649:
1.21 crook 5650: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5651: @code{CS-ROLL}.
1.1 anton 5652:
5653: @subsubsection Programming Style
1.47 crook 5654: @cindex control structures programming style
5655: @cindex programming style, arbitrary control structures
1.1 anton 5656:
5657: In order to ensure readability we recommend that you do not create
5658: arbitrary control structures directly, but define new control structure
5659: words for the control structure you want and use these words in your
1.26 crook 5660: program. For example, instead of writing:
1.1 anton 5661:
5662: @example
1.26 crook 5663: BEGIN
1.1 anton 5664: ...
1.26 crook 5665: IF [ 1 CS-ROLL ]
1.1 anton 5666: ...
1.26 crook 5667: AGAIN THEN
1.1 anton 5668: @end example
5669:
1.21 crook 5670: @noindent
1.1 anton 5671: we recommend defining control structure words, e.g.,
5672:
5673: @example
1.26 crook 5674: : WHILE ( DEST -- ORIG DEST )
5675: POSTPONE IF
5676: 1 CS-ROLL ; immediate
5677:
5678: : REPEAT ( orig dest -- )
5679: POSTPONE AGAIN
5680: POSTPONE THEN ; immediate
1.1 anton 5681: @end example
5682:
1.21 crook 5683: @noindent
1.1 anton 5684: and then using these to create the control structure:
5685:
5686: @example
1.26 crook 5687: BEGIN
1.1 anton 5688: ...
1.26 crook 5689: WHILE
1.1 anton 5690: ...
1.26 crook 5691: REPEAT
1.1 anton 5692: @end example
5693:
5694: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5695: @code{WHILE} are predefined, so in this example it would not be
5696: necessary to define them.
5697:
5698: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5699: @subsection Calls and returns
5700: @cindex calling a definition
5701: @cindex returning from a definition
5702:
1.3 anton 5703: @cindex recursive definitions
5704: A definition can be called simply be writing the name of the definition
1.26 crook 5705: to be called. Normally a definition is invisible during its own
1.3 anton 5706: definition. If you want to write a directly recursive definition, you
1.26 crook 5707: can use @code{recursive} to make the current definition visible, or
5708: @code{recurse} to call the current definition directly.
1.3 anton 5709:
1.44 crook 5710:
1.3 anton 5711: doc-recursive
5712: doc-recurse
5713:
1.44 crook 5714:
1.21 crook 5715: @comment TODO add example of the two recursion methods
1.12 anton 5716: @quotation
5717: @progstyle
5718: I prefer using @code{recursive} to @code{recurse}, because calling the
5719: definition by name is more descriptive (if the name is well-chosen) than
5720: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5721: implementation, it is much better to read (and think) ``now sort the
5722: partitions'' than to read ``now do a recursive call''.
5723: @end quotation
1.3 anton 5724:
1.29 crook 5725: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5726:
5727: @example
1.28 crook 5728: Defer foo
1.3 anton 5729:
5730: : bar ( ... -- ... )
5731: ... foo ... ;
5732:
5733: :noname ( ... -- ... )
5734: ... bar ... ;
5735: IS foo
5736: @end example
5737:
1.170 pazsan 5738: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5739:
1.26 crook 5740: The current definition returns control to the calling definition when
1.33 anton 5741: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5742:
5743: doc-exit
5744: doc-;s
5745:
1.44 crook 5746:
1.1 anton 5747: @node Exception Handling, , Calls and returns, Control Structures
5748: @subsection Exception Handling
1.26 crook 5749: @cindex exceptions
1.1 anton 5750:
1.68 anton 5751: @c quit is a very bad idea for error handling,
5752: @c because it does not translate into a THROW
5753: @c it also does not belong into this chapter
5754:
5755: If a word detects an error condition that it cannot handle, it can
5756: @code{throw} an exception. In the simplest case, this will terminate
5757: your program, and report an appropriate error.
1.21 crook 5758:
1.68 anton 5759: doc-throw
1.1 anton 5760:
1.69 anton 5761: @code{Throw} consumes a cell-sized error number on the stack. There are
5762: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5763: Gforth (and most other systems) you can use the iors produced by various
5764: words as error numbers (e.g., a typical use of @code{allocate} is
5765: @code{allocate throw}). Gforth also provides the word @code{exception}
5766: to define your own error numbers (with decent error reporting); an ANS
5767: Forth version of this word (but without the error messages) is available
5768: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5769: numbers (anything outside the range -4095..0), but won't get nice error
5770: messages, only numbers. For example, try:
5771:
5772: @example
1.69 anton 5773: -10 throw \ ANS defined
5774: -267 throw \ system defined
5775: s" my error" exception throw \ user defined
5776: 7 throw \ arbitrary number
1.68 anton 5777: @end example
5778:
5779: doc---exception-exception
1.1 anton 5780:
1.69 anton 5781: A common idiom to @code{THROW} a specific error if a flag is true is
5782: this:
5783:
5784: @example
5785: @code{( flag ) 0<> @i{errno} and throw}
5786: @end example
5787:
5788: Your program can provide exception handlers to catch exceptions. An
5789: exception handler can be used to correct the problem, or to clean up
5790: some data structures and just throw the exception to the next exception
5791: handler. Note that @code{throw} jumps to the dynamically innermost
5792: exception handler. The system's exception handler is outermost, and just
5793: prints an error and restarts command-line interpretation (or, in batch
5794: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5795:
1.68 anton 5796: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5797:
1.68 anton 5798: doc-catch
1.160 anton 5799: doc-nothrow
1.68 anton 5800:
5801: The most common use of exception handlers is to clean up the state when
5802: an error happens. E.g.,
1.1 anton 5803:
1.26 crook 5804: @example
1.68 anton 5805: base @ >r hex \ actually the hex should be inside foo, or we h
5806: ['] foo catch ( nerror|0 )
5807: r> base !
1.69 anton 5808: ( nerror|0 ) throw \ pass it on
1.26 crook 5809: @end example
1.1 anton 5810:
1.69 anton 5811: A use of @code{catch} for handling the error @code{myerror} might look
5812: like this:
1.44 crook 5813:
1.68 anton 5814: @example
1.69 anton 5815: ['] foo catch
5816: CASE
1.160 anton 5817: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5818: dup throw \ default: pass other errors on, do nothing on non-errors
5819: ENDCASE
1.68 anton 5820: @end example
1.44 crook 5821:
1.68 anton 5822: Having to wrap the code into a separate word is often cumbersome,
5823: therefore Gforth provides an alternative syntax:
1.1 anton 5824:
5825: @example
1.69 anton 5826: TRY
1.68 anton 5827: @i{code1}
1.172 anton 5828: IFERROR
5829: @i{code2}
5830: THEN
5831: @i{code3}
1.69 anton 5832: ENDTRY
1.1 anton 5833: @end example
5834:
1.172 anton 5835: This performs @i{code1}. If @i{code1} completes normally, execution
1.201 anton 5836: continues with @i{code3}. If there is an exception in @i{code1} or
5837: before @code{endtry}, the stacks are reset to the depth during
1.172 anton 5838: @code{try}, the throw value is pushed on the data stack, and execution
1.201 anton 5839: constinues at @i{code2}, and finally falls through to @i{code3}.
1.26 crook 5840:
1.68 anton 5841: doc-try
5842: doc-endtry
1.172 anton 5843: doc-iferror
5844:
5845: If you don't need @i{code2}, you can write @code{restore} instead of
5846: @code{iferror then}:
5847:
5848: @example
5849: TRY
5850: @i{code1}
5851: RESTORE
5852: @i{code3}
5853: ENDTRY
5854: @end example
1.26 crook 5855:
1.172 anton 5856: @cindex unwind-protect
1.69 anton 5857: The cleanup example from above in this syntax:
1.26 crook 5858:
1.68 anton 5859: @example
1.174 anton 5860: base @@ @{ oldbase @}
1.172 anton 5861: TRY
1.68 anton 5862: hex foo \ now the hex is placed correctly
1.69 anton 5863: 0 \ value for throw
1.172 anton 5864: RESTORE
5865: oldbase base !
5866: ENDTRY
5867: throw
1.1 anton 5868: @end example
5869:
1.172 anton 5870: An additional advantage of this variant is that an exception between
5871: @code{restore} and @code{endtry} (e.g., from the user pressing
5872: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5873: so the base will be restored under all circumstances.
5874:
5875: However, you have to ensure that this code does not cause an exception
5876: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5877: Moreover, you should also make sure that the stack contents needed by
5878: the @code{iferror}/@code{restore} code exist everywhere between
5879: @code{try} and @code{endtry}; in our example this is achived by
5880: putting the data in a local before the @code{try} (you cannot use the
5881: return stack because the exception frame (@i{sys1}) is in the way
5882: there).
5883:
5884: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5885:
5886: @cindex @code{recover} (old Gforth versions)
5887: If you do not want this exception-restarting behaviour, you achieve
5888: this as follows:
5889:
5890: @example
5891: TRY
5892: @i{code1}
5893: ENDTRY-IFERROR
5894: @i{code2}
5895: THEN
5896: @end example
5897:
5898: If there is an exception in @i{code1}, then @i{code2} is executed,
5899: otherwise execution continues behind the @code{then} (or in a possible
5900: @code{else} branch). This corresponds to the construct
5901:
5902: @example
5903: TRY
5904: @i{code1}
5905: RECOVER
5906: @i{code2}
5907: ENDTRY
5908: @end example
5909:
5910: in Gforth before version 0.7. So you can directly replace
5911: @code{recover}-using code; however, we recommend that you check if it
5912: would not be better to use one of the other @code{try} variants while
5913: you are at it.
5914:
1.173 anton 5915: To ease the transition, Gforth provides two compatibility files:
5916: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5917: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5918: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5919: ... endtry} syntax on new systems, so you can use that file as a
5920: stopgap to run old programs. Both files work on any system (they just
5921: do nothing if the system already has the syntax it implements), so you
5922: can unconditionally @code{require} one of these files, even if you use
5923: a mix old and new systems.
5924:
1.172 anton 5925: doc-restore
5926: doc-endtry-iferror
5927:
5928: Here's the error handling example:
1.1 anton 5929:
1.68 anton 5930: @example
1.69 anton 5931: TRY
1.68 anton 5932: foo
1.172 anton 5933: ENDTRY-IFERROR
1.69 anton 5934: CASE
1.160 anton 5935: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5936: throw \ pass other errors on
5937: ENDCASE
1.172 anton 5938: THEN
1.68 anton 5939: @end example
1.1 anton 5940:
1.69 anton 5941: @progstyle
5942: As usual, you should ensure that the stack depth is statically known at
5943: the end: either after the @code{throw} for passing on errors, or after
5944: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5945: selection construct for handling the error).
5946:
1.68 anton 5947: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5948: and you can provide an error message. @code{Abort} just produces an
5949: ``Aborted'' error.
1.1 anton 5950:
1.68 anton 5951: The problem with these words is that exception handlers cannot
5952: differentiate between different @code{abort"}s; they just look like
5953: @code{-2 throw} to them (the error message cannot be accessed by
5954: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5955: exception handlers.
1.44 crook 5956:
1.68 anton 5957: doc-abort"
1.26 crook 5958: doc-abort
1.29 crook 5959:
5960:
1.44 crook 5961:
1.29 crook 5962: @c -------------------------------------------------------------
1.47 crook 5963: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5964: @section Defining Words
5965: @cindex defining words
5966:
1.47 crook 5967: Defining words are used to extend Forth by creating new entries in the dictionary.
5968:
1.29 crook 5969: @menu
1.67 anton 5970: * CREATE::
1.44 crook 5971: * Variables:: Variables and user variables
1.67 anton 5972: * Constants::
1.44 crook 5973: * Values:: Initialised variables
1.67 anton 5974: * Colon Definitions::
1.44 crook 5975: * Anonymous Definitions:: Definitions without names
1.69 anton 5976: * Supplying names:: Passing definition names as strings
1.67 anton 5977: * User-defined Defining Words::
1.170 pazsan 5978: * Deferred Words:: Allow forward references
1.67 anton 5979: * Aliases::
1.29 crook 5980: @end menu
5981:
1.44 crook 5982: @node CREATE, Variables, Defining Words, Defining Words
5983: @subsection @code{CREATE}
1.29 crook 5984: @cindex simple defining words
5985: @cindex defining words, simple
5986:
5987: Defining words are used to create new entries in the dictionary. The
5988: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5989: this:
5990:
5991: @example
5992: CREATE new-word1
5993: @end example
5994:
1.69 anton 5995: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5996: input stream (@code{new-word1} in our example). It generates a
5997: dictionary entry for @code{new-word1}. When @code{new-word1} is
5998: executed, all that it does is leave an address on the stack. The address
5999: represents the value of the data space pointer (@code{HERE}) at the time
6000: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6001: associating a name with the address of a region of memory.
1.29 crook 6002:
1.34 anton 6003: doc-create
6004:
1.69 anton 6005: Note that in ANS Forth guarantees only for @code{create} that its body
6006: is in dictionary data space (i.e., where @code{here}, @code{allot}
6007: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6008: @code{create}d words can be modified with @code{does>}
6009: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6010: can only be applied to @code{create}d words.
6011:
1.29 crook 6012: By extending this example to reserve some memory in data space, we end
1.69 anton 6013: up with something like a @i{variable}. Here are two different ways to do
6014: it:
1.29 crook 6015:
6016: @example
6017: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6018: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6019: @end example
6020:
6021: The variable can be examined and modified using @code{@@} (``fetch'') and
6022: @code{!} (``store'') like this:
6023:
6024: @example
6025: new-word2 @@ . \ get address, fetch from it and display
6026: 1234 new-word2 ! \ new value, get address, store to it
6027: @end example
6028:
1.44 crook 6029: @cindex arrays
6030: A similar mechanism can be used to create arrays. For example, an
6031: 80-character text input buffer:
1.29 crook 6032:
6033: @example
1.44 crook 6034: CREATE text-buf 80 chars allot
6035:
1.168 anton 6036: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6037: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6038: @end example
1.29 crook 6039:
1.44 crook 6040: You can build arbitrarily complex data structures by allocating
1.49 anton 6041: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6042: learn about some Gforth tools that make it easier,
1.49 anton 6043: @xref{Structures}.
1.44 crook 6044:
6045:
6046: @node Variables, Constants, CREATE, Defining Words
6047: @subsection Variables
6048: @cindex variables
6049:
6050: The previous section showed how a sequence of commands could be used to
6051: generate a variable. As a final refinement, the whole code sequence can
6052: be wrapped up in a defining word (pre-empting the subject of the next
6053: section), making it easier to create new variables:
6054:
6055: @example
6056: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6057: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6058:
6059: myvariableX foo \ variable foo starts off with an unknown value
6060: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6061:
6062: 45 3 * foo ! \ set foo to 135
6063: 1234 joe ! \ set joe to 1234
6064: 3 joe +! \ increment joe by 3.. to 1237
6065: @end example
6066:
6067: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6068: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6069: guarantee that a @code{Variable} is initialised when it is created
6070: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6071: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6072: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6073: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6074: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6075: store a boolean, you can use @code{on} and @code{off} to toggle its
6076: state.
1.29 crook 6077:
1.34 anton 6078: doc-variable
6079: doc-2variable
6080: doc-fvariable
6081:
1.29 crook 6082: @cindex user variables
6083: @cindex user space
6084: The defining word @code{User} behaves in the same way as @code{Variable}.
6085: The difference is that it reserves space in @i{user (data) space} rather
6086: than normal data space. In a Forth system that has a multi-tasker, each
6087: task has its own set of user variables.
6088:
1.34 anton 6089: doc-user
1.67 anton 6090: @c doc-udp
6091: @c doc-uallot
1.34 anton 6092:
1.29 crook 6093: @comment TODO is that stuff about user variables strictly correct? Is it
6094: @comment just terminal tasks that have user variables?
6095: @comment should document tasker.fs (with some examples) elsewhere
6096: @comment in this manual, then expand on user space and user variables.
6097:
1.44 crook 6098: @node Constants, Values, Variables, Defining Words
6099: @subsection Constants
6100: @cindex constants
6101:
6102: @code{Constant} allows you to declare a fixed value and refer to it by
6103: name. For example:
1.29 crook 6104:
6105: @example
6106: 12 Constant INCHES-PER-FOOT
6107: 3E+08 fconstant SPEED-O-LIGHT
6108: @end example
6109:
6110: A @code{Variable} can be both read and written, so its run-time
6111: behaviour is to supply an address through which its current value can be
6112: manipulated. In contrast, the value of a @code{Constant} cannot be
6113: changed once it has been declared@footnote{Well, often it can be -- but
6114: not in a Standard, portable way. It's safer to use a @code{Value} (read
6115: on).} so it's not necessary to supply the address -- it is more
6116: efficient to return the value of the constant directly. That's exactly
6117: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6118: the top of the stack (You can find one
6119: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6120:
1.69 anton 6121: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6122: double and floating-point constants, respectively.
6123:
1.34 anton 6124: doc-constant
6125: doc-2constant
6126: doc-fconstant
6127:
6128: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6129: @c nac-> How could that not be true in an ANS Forth? You can't define a
6130: @c constant, use it and then delete the definition of the constant..
1.69 anton 6131:
6132: @c anton->An ANS Forth system can compile a constant to a literal; On
6133: @c decompilation you would see only the number, just as if it had been used
6134: @c in the first place. The word will stay, of course, but it will only be
6135: @c used by the text interpreter (no run-time duties, except when it is
6136: @c POSTPONEd or somesuch).
6137:
6138: @c nac:
1.44 crook 6139: @c I agree that it's rather deep, but IMO it is an important difference
6140: @c relative to other programming languages.. often it's annoying: it
6141: @c certainly changes my programming style relative to C.
6142:
1.69 anton 6143: @c anton: In what way?
6144:
1.29 crook 6145: Constants in Forth behave differently from their equivalents in other
6146: programming languages. In other languages, a constant (such as an EQU in
6147: assembler or a #define in C) only exists at compile-time; in the
6148: executable program the constant has been translated into an absolute
6149: number and, unless you are using a symbolic debugger, it's impossible to
6150: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6151: an entry in the header space and remains there after the code that uses
6152: it has been defined. In fact, it must remain in the dictionary since it
6153: has run-time duties to perform. For example:
1.29 crook 6154:
6155: @example
6156: 12 Constant INCHES-PER-FOOT
6157: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6158: @end example
6159:
6160: @cindex in-lining of constants
6161: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6162: associated with the constant @code{INCHES-PER-FOOT}. If you use
6163: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6164: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6165: attempt to optimise constants by in-lining them where they are used. You
6166: can force Gforth to in-line a constant like this:
6167:
6168: @example
6169: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6170: @end example
6171:
6172: If you use @code{see} to decompile @i{this} version of
6173: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6174: longer present. To understand how this works, read
6175: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6176:
6177: In-lining constants in this way might improve execution time
6178: fractionally, and can ensure that a constant is now only referenced at
6179: compile-time. However, the definition of the constant still remains in
6180: the dictionary. Some Forth compilers provide a mechanism for controlling
6181: a second dictionary for holding transient words such that this second
6182: dictionary can be deleted later in order to recover memory
6183: space. However, there is no standard way of doing this.
6184:
6185:
1.44 crook 6186: @node Values, Colon Definitions, Constants, Defining Words
6187: @subsection Values
6188: @cindex values
1.34 anton 6189:
1.69 anton 6190: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6191: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6192: (not in ANS Forth) you can access (and change) a @code{value} also with
6193: @code{>body}.
6194:
6195: Here are some
6196: examples:
1.29 crook 6197:
6198: @example
1.69 anton 6199: 12 Value APPLES \ Define APPLES with an initial value of 12
6200: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6201: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6202: APPLES \ puts 35 on the top of the stack.
1.29 crook 6203: @end example
6204:
1.44 crook 6205: doc-value
6206: doc-to
1.29 crook 6207:
1.35 anton 6208:
1.69 anton 6209:
1.44 crook 6210: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6211: @subsection Colon Definitions
6212: @cindex colon definitions
1.35 anton 6213:
6214: @example
1.44 crook 6215: : name ( ... -- ... )
6216: word1 word2 word3 ;
1.29 crook 6217: @end example
6218:
1.44 crook 6219: @noindent
6220: Creates a word called @code{name} that, upon execution, executes
6221: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6222:
1.49 anton 6223: The explanation above is somewhat superficial. For simple examples of
6224: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6225: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6226: Compilation Semantics}.
1.29 crook 6227:
1.44 crook 6228: doc-:
6229: doc-;
1.1 anton 6230:
1.34 anton 6231:
1.69 anton 6232: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6233: @subsection Anonymous Definitions
6234: @cindex colon definitions
6235: @cindex defining words without name
1.34 anton 6236:
1.44 crook 6237: Sometimes you want to define an @dfn{anonymous word}; a word without a
6238: name. You can do this with:
1.1 anton 6239:
1.44 crook 6240: doc-:noname
1.1 anton 6241:
1.44 crook 6242: This leaves the execution token for the word on the stack after the
6243: closing @code{;}. Here's an example in which a deferred word is
6244: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6245:
1.29 crook 6246: @example
1.44 crook 6247: Defer deferred
6248: :noname ( ... -- ... )
6249: ... ;
6250: IS deferred
1.29 crook 6251: @end example
1.26 crook 6252:
1.44 crook 6253: @noindent
6254: Gforth provides an alternative way of doing this, using two separate
6255: words:
1.27 crook 6256:
1.44 crook 6257: doc-noname
6258: @cindex execution token of last defined word
1.116 anton 6259: doc-latestxt
1.1 anton 6260:
1.44 crook 6261: @noindent
6262: The previous example can be rewritten using @code{noname} and
1.116 anton 6263: @code{latestxt}:
1.1 anton 6264:
1.26 crook 6265: @example
1.44 crook 6266: Defer deferred
6267: noname : ( ... -- ... )
6268: ... ;
1.116 anton 6269: latestxt IS deferred
1.26 crook 6270: @end example
1.1 anton 6271:
1.29 crook 6272: @noindent
1.44 crook 6273: @code{noname} works with any defining word, not just @code{:}.
6274:
1.116 anton 6275: @code{latestxt} also works when the last word was not defined as
1.71 anton 6276: @code{noname}. It does not work for combined words, though. It also has
6277: the useful property that is is valid as soon as the header for a
6278: definition has been built. Thus:
1.44 crook 6279:
6280: @example
1.116 anton 6281: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6282: @end example
1.1 anton 6283:
1.44 crook 6284: @noindent
6285: prints 3 numbers; the last two are the same.
1.26 crook 6286:
1.69 anton 6287: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6288: @subsection Supplying the name of a defined word
6289: @cindex names for defined words
6290: @cindex defining words, name given in a string
6291:
6292: By default, a defining word takes the name for the defined word from the
6293: input stream. Sometimes you want to supply the name from a string. You
6294: can do this with:
6295:
6296: doc-nextname
6297:
6298: For example:
6299:
6300: @example
6301: s" foo" nextname create
6302: @end example
6303:
6304: @noindent
6305: is equivalent to:
6306:
6307: @example
6308: create foo
6309: @end example
6310:
6311: @noindent
6312: @code{nextname} works with any defining word.
6313:
1.1 anton 6314:
1.170 pazsan 6315: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6316: @subsection User-defined Defining Words
6317: @cindex user-defined defining words
6318: @cindex defining words, user-defined
1.1 anton 6319:
1.29 crook 6320: You can create a new defining word by wrapping defining-time code around
6321: an existing defining word and putting the sequence in a colon
1.69 anton 6322: definition.
6323:
6324: @c anton: This example is very complex and leads in a quite different
6325: @c direction from the CREATE-DOES> stuff that follows. It should probably
6326: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6327: @c subsection of Defining Words)
6328:
6329: For example, suppose that you have a word @code{stats} that
1.29 crook 6330: gathers statistics about colon definitions given the @i{xt} of the
6331: definition, and you want every colon definition in your application to
6332: make a call to @code{stats}. You can define and use a new version of
6333: @code{:} like this:
6334:
6335: @example
6336: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6337: ... ; \ other code
6338:
1.116 anton 6339: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6340:
6341: my: foo + - ;
6342: @end example
6343:
6344: When @code{foo} is defined using @code{my:} these steps occur:
6345:
6346: @itemize @bullet
6347: @item
6348: @code{my:} is executed.
6349: @item
6350: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6351: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6352: the input stream for a name, builds a dictionary header for the name
6353: @code{foo} and switches @code{state} from interpret to compile.
6354: @item
1.116 anton 6355: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6356: being defined -- @code{foo} -- onto the stack.
6357: @item
6358: The code that was produced by @code{postpone literal} is executed; this
6359: causes the value on the stack to be compiled as a literal in the code
6360: area of @code{foo}.
6361: @item
6362: The code @code{['] stats} compiles a literal into the definition of
6363: @code{my:}. When @code{compile,} is executed, that literal -- the
6364: execution token for @code{stats} -- is layed down in the code area of
6365: @code{foo} , following the literal@footnote{Strictly speaking, the
6366: mechanism that @code{compile,} uses to convert an @i{xt} into something
6367: in the code area is implementation-dependent. A threaded implementation
6368: might spit out the execution token directly whilst another
6369: implementation might spit out a native code sequence.}.
6370: @item
6371: At this point, the execution of @code{my:} is complete, and control
6372: returns to the text interpreter. The text interpreter is in compile
6373: state, so subsequent text @code{+ -} is compiled into the definition of
6374: @code{foo} and the @code{;} terminates the definition as always.
6375: @end itemize
6376:
6377: You can use @code{see} to decompile a word that was defined using
6378: @code{my:} and see how it is different from a normal @code{:}
6379: definition. For example:
6380:
6381: @example
6382: : bar + - ; \ like foo but using : rather than my:
6383: see bar
6384: : bar
6385: + - ;
6386: see foo
6387: : foo
6388: 107645672 stats + - ;
6389:
1.140 anton 6390: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6391: @end example
6392:
6393: You can use techniques like this to make new defining words in terms of
6394: @i{any} existing defining word.
1.1 anton 6395:
6396:
1.29 crook 6397: @cindex defining defining words
1.26 crook 6398: @cindex @code{CREATE} ... @code{DOES>}
6399: If you want the words defined with your defining words to behave
6400: differently from words defined with standard defining words, you can
6401: write your defining word like this:
1.1 anton 6402:
6403: @example
1.26 crook 6404: : def-word ( "name" -- )
1.29 crook 6405: CREATE @i{code1}
1.26 crook 6406: DOES> ( ... -- ... )
1.29 crook 6407: @i{code2} ;
1.26 crook 6408:
6409: def-word name
1.1 anton 6410: @end example
6411:
1.29 crook 6412: @cindex child words
6413: This fragment defines a @dfn{defining word} @code{def-word} and then
6414: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6415: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6416: is not executed at this time. The word @code{name} is sometimes called a
6417: @dfn{child} of @code{def-word}.
6418:
6419: When you execute @code{name}, the address of the body of @code{name} is
6420: put on the data stack and @i{code2} is executed (the address of the body
6421: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6422: @code{CREATE}, i.e., the address a @code{create}d word returns by
6423: default).
6424:
6425: @c anton:
6426: @c www.dictionary.com says:
6427: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6428: @c several generations of absence, usually caused by the chance
6429: @c recombination of genes. 2.An individual or a part that exhibits
6430: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6431: @c of previous behavior after a period of absence.
6432: @c
6433: @c Doesn't seem to fit.
1.29 crook 6434:
1.69 anton 6435: @c @cindex atavism in child words
1.33 anton 6436: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6437: similarly; they all have a common run-time behaviour determined by
6438: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6439: body of the child word. The structure of the data is common to all
6440: children of @code{def-word}, but the data values are specific -- and
6441: private -- to each child word. When a child word is executed, the
6442: address of its private data area is passed as a parameter on TOS to be
6443: used and manipulated@footnote{It is legitimate both to read and write to
6444: this data area.} by @i{code2}.
1.29 crook 6445:
6446: The two fragments of code that make up the defining words act (are
6447: executed) at two completely separate times:
1.1 anton 6448:
1.29 crook 6449: @itemize @bullet
6450: @item
6451: At @i{define time}, the defining word executes @i{code1} to generate a
6452: child word
6453: @item
6454: At @i{child execution time}, when a child word is invoked, @i{code2}
6455: is executed, using parameters (data) that are private and specific to
6456: the child word.
6457: @end itemize
6458:
1.44 crook 6459: Another way of understanding the behaviour of @code{def-word} and
6460: @code{name} is to say that, if you make the following definitions:
1.33 anton 6461: @example
6462: : def-word1 ( "name" -- )
6463: CREATE @i{code1} ;
6464:
6465: : action1 ( ... -- ... )
6466: @i{code2} ;
6467:
6468: def-word1 name1
6469: @end example
6470:
1.44 crook 6471: @noindent
6472: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6473:
1.29 crook 6474: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6475:
1.1 anton 6476: @example
1.29 crook 6477: : CONSTANT ( w "name" -- )
6478: CREATE ,
1.26 crook 6479: DOES> ( -- w )
6480: @@ ;
1.1 anton 6481: @end example
6482:
1.29 crook 6483: @comment There is a beautiful description of how this works and what
6484: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6485: @comment commentary on the Counting Fruits problem.
6486:
6487: When you create a constant with @code{5 CONSTANT five}, a set of
6488: define-time actions take place; first a new word @code{five} is created,
6489: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6490: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6491: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6492: no code of its own; it simply contains a data field and a pointer to the
6493: code that follows @code{DOES>} in its defining word. That makes words
6494: created in this way very compact.
6495:
6496: The final example in this section is intended to remind you that space
6497: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6498: both read and written by a Standard program@footnote{Exercise: use this
6499: example as a starting point for your own implementation of @code{Value}
6500: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6501: @code{[']}.}:
6502:
6503: @example
6504: : foo ( "name" -- )
6505: CREATE -1 ,
6506: DOES> ( -- )
1.33 anton 6507: @@ . ;
1.29 crook 6508:
6509: foo first-word
6510: foo second-word
6511:
6512: 123 ' first-word >BODY !
6513: @end example
6514:
6515: If @code{first-word} had been a @code{CREATE}d word, we could simply
6516: have executed it to get the address of its data field. However, since it
6517: was defined to have @code{DOES>} actions, its execution semantics are to
6518: perform those @code{DOES>} actions. To get the address of its data field
6519: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6520: translate the xt into the address of the data field. When you execute
6521: @code{first-word}, it will display @code{123}. When you execute
6522: @code{second-word} it will display @code{-1}.
1.26 crook 6523:
6524: @cindex stack effect of @code{DOES>}-parts
6525: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6526: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6527: the stack effect of the defined words, not the stack effect of the
6528: following code (the following code expects the address of the body on
6529: the top of stack, which is not reflected in the stack comment). This is
6530: the convention that I use and recommend (it clashes a bit with using
6531: locals declarations for stack effect specification, though).
1.1 anton 6532:
1.53 anton 6533: @menu
6534: * CREATE..DOES> applications::
6535: * CREATE..DOES> details::
1.63 anton 6536: * Advanced does> usage example::
1.155 anton 6537: * Const-does>::
1.53 anton 6538: @end menu
6539:
6540: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6541: @subsubsection Applications of @code{CREATE..DOES>}
6542: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6543:
1.26 crook 6544: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6545:
1.26 crook 6546: @cindex factoring similar colon definitions
6547: When you see a sequence of code occurring several times, and you can
6548: identify a meaning, you will factor it out as a colon definition. When
6549: you see similar colon definitions, you can factor them using
6550: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6551: that look very similar:
1.1 anton 6552: @example
1.26 crook 6553: : ori, ( reg-target reg-source n -- )
6554: 0 asm-reg-reg-imm ;
6555: : andi, ( reg-target reg-source n -- )
6556: 1 asm-reg-reg-imm ;
1.1 anton 6557: @end example
6558:
1.26 crook 6559: @noindent
6560: This could be factored with:
6561: @example
6562: : reg-reg-imm ( op-code -- )
6563: CREATE ,
6564: DOES> ( reg-target reg-source n -- )
6565: @@ asm-reg-reg-imm ;
6566:
6567: 0 reg-reg-imm ori,
6568: 1 reg-reg-imm andi,
6569: @end example
1.1 anton 6570:
1.26 crook 6571: @cindex currying
6572: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6573: supply a part of the parameters for a word (known as @dfn{currying} in
6574: the functional language community). E.g., @code{+} needs two
6575: parameters. Creating versions of @code{+} with one parameter fixed can
6576: be done like this:
1.82 anton 6577:
1.1 anton 6578: @example
1.82 anton 6579: : curry+ ( n1 "name" -- )
1.26 crook 6580: CREATE ,
6581: DOES> ( n2 -- n1+n2 )
6582: @@ + ;
6583:
6584: 3 curry+ 3+
6585: -2 curry+ 2-
1.1 anton 6586: @end example
6587:
1.91 anton 6588:
1.63 anton 6589: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6590: @subsubsection The gory details of @code{CREATE..DOES>}
6591: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6592:
1.26 crook 6593: doc-does>
1.1 anton 6594:
1.26 crook 6595: @cindex @code{DOES>} in a separate definition
6596: This means that you need not use @code{CREATE} and @code{DOES>} in the
6597: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6598: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6599: @example
6600: : does1
6601: DOES> ( ... -- ... )
1.44 crook 6602: ... ;
6603:
6604: : does2
6605: DOES> ( ... -- ... )
6606: ... ;
6607:
6608: : def-word ( ... -- ... )
6609: create ...
6610: IF
6611: does1
6612: ELSE
6613: does2
6614: ENDIF ;
6615: @end example
6616:
6617: In this example, the selection of whether to use @code{does1} or
1.69 anton 6618: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6619: @code{CREATE}d.
6620:
6621: @cindex @code{DOES>} in interpretation state
6622: In a standard program you can apply a @code{DOES>}-part only if the last
6623: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6624: will override the behaviour of the last word defined in any case. In a
6625: standard program, you can use @code{DOES>} only in a colon
6626: definition. In Gforth, you can also use it in interpretation state, in a
6627: kind of one-shot mode; for example:
6628: @example
6629: CREATE name ( ... -- ... )
6630: @i{initialization}
6631: DOES>
6632: @i{code} ;
6633: @end example
6634:
6635: @noindent
6636: is equivalent to the standard:
6637: @example
6638: :noname
6639: DOES>
6640: @i{code} ;
6641: CREATE name EXECUTE ( ... -- ... )
6642: @i{initialization}
6643: @end example
6644:
1.53 anton 6645: doc->body
6646:
1.152 pazsan 6647: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6648: @subsubsection Advanced does> usage example
6649:
6650: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6651: for disassembling instructions, that follow a very repetetive scheme:
6652:
6653: @example
6654: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6655: @var{entry-num} cells @var{table} + !
6656: @end example
6657:
6658: Of course, this inspires the idea to factor out the commonalities to
6659: allow a definition like
6660:
6661: @example
6662: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6663: @end example
6664:
6665: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6666: correlated. Moreover, before I wrote the disassembler, there already
6667: existed code that defines instructions like this:
1.63 anton 6668:
6669: @example
6670: @var{entry-num} @var{inst-format} @var{inst-name}
6671: @end example
6672:
6673: This code comes from the assembler and resides in
6674: @file{arch/mips/insts.fs}.
6675:
6676: So I had to define the @var{inst-format} words that performed the scheme
6677: above when executed. At first I chose to use run-time code-generation:
6678:
6679: @example
6680: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6681: :noname Postpone @var{disasm-operands}
6682: name Postpone sliteral Postpone type Postpone ;
6683: swap cells @var{table} + ! ;
6684: @end example
6685:
6686: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6687:
1.63 anton 6688: An alternative would have been to write this using
6689: @code{create}/@code{does>}:
6690:
6691: @example
6692: : @var{inst-format} ( entry-num "name" -- )
6693: here name string, ( entry-num c-addr ) \ parse and save "name"
6694: noname create , ( entry-num )
1.116 anton 6695: latestxt swap cells @var{table} + !
1.63 anton 6696: does> ( addr w -- )
6697: \ disassemble instruction w at addr
6698: @@ >r
6699: @var{disasm-operands}
6700: r> count type ;
6701: @end example
6702:
6703: Somehow the first solution is simpler, mainly because it's simpler to
6704: shift a string from definition-time to use-time with @code{sliteral}
6705: than with @code{string,} and friends.
6706:
6707: I wrote a lot of words following this scheme and soon thought about
6708: factoring out the commonalities among them. Note that this uses a
6709: two-level defining word, i.e., a word that defines ordinary defining
6710: words.
6711:
6712: This time a solution involving @code{postpone} and friends seemed more
6713: difficult (try it as an exercise), so I decided to use a
6714: @code{create}/@code{does>} word; since I was already at it, I also used
6715: @code{create}/@code{does>} for the lower level (try using
6716: @code{postpone} etc. as an exercise), resulting in the following
6717: definition:
6718:
6719: @example
6720: : define-format ( disasm-xt table-xt -- )
6721: \ define an instruction format that uses disasm-xt for
6722: \ disassembling and enters the defined instructions into table
6723: \ table-xt
6724: create 2,
6725: does> ( u "inst" -- )
6726: \ defines an anonymous word for disassembling instruction inst,
6727: \ and enters it as u-th entry into table-xt
6728: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6729: noname create 2, \ define anonymous word
1.116 anton 6730: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6731: does> ( addr w -- )
6732: \ disassemble instruction w at addr
6733: 2@@ >r ( addr w disasm-xt R: c-addr )
6734: execute ( R: c-addr ) \ disassemble operands
6735: r> count type ; \ print name
6736: @end example
6737:
6738: Note that the tables here (in contrast to above) do the @code{cells +}
6739: by themselves (that's why you have to pass an xt). This word is used in
6740: the following way:
6741:
6742: @example
6743: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6744: @end example
6745:
1.71 anton 6746: As shown above, the defined instruction format is then used like this:
6747:
6748: @example
6749: @var{entry-num} @var{inst-format} @var{inst-name}
6750: @end example
6751:
1.63 anton 6752: In terms of currying, this kind of two-level defining word provides the
6753: parameters in three stages: first @var{disasm-operands} and @var{table},
6754: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6755: the instruction to be disassembled.
6756:
6757: Of course this did not quite fit all the instruction format names used
6758: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6759: the parameters into the right form.
6760:
6761: If you have trouble following this section, don't worry. First, this is
6762: involved and takes time (and probably some playing around) to
6763: understand; second, this is the first two-level
6764: @code{create}/@code{does>} word I have written in seventeen years of
6765: Forth; and if I did not have @file{insts.fs} to start with, I may well
6766: have elected to use just a one-level defining word (with some repeating
6767: of parameters when using the defining word). So it is not necessary to
6768: understand this, but it may improve your understanding of Forth.
1.44 crook 6769:
6770:
1.152 pazsan 6771: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6772: @subsubsection @code{Const-does>}
6773:
6774: A frequent use of @code{create}...@code{does>} is for transferring some
6775: values from definition-time to run-time. Gforth supports this use with
6776:
6777: doc-const-does>
6778:
6779: A typical use of this word is:
6780:
6781: @example
6782: : curry+ ( n1 "name" -- )
6783: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6784: + ;
6785:
6786: 3 curry+ 3+
6787: @end example
6788:
6789: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6790: definition to run-time.
6791:
6792: The advantages of using @code{const-does>} are:
6793:
6794: @itemize
6795:
6796: @item
6797: You don't have to deal with storing and retrieving the values, i.e.,
6798: your program becomes more writable and readable.
6799:
6800: @item
6801: When using @code{does>}, you have to introduce a @code{@@} that cannot
6802: be optimized away (because you could change the data using
6803: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6804:
6805: @end itemize
6806:
6807: An ANS Forth implementation of @code{const-does>} is available in
6808: @file{compat/const-does.fs}.
6809:
6810:
1.170 pazsan 6811: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6812: @subsection Deferred Words
1.44 crook 6813: @cindex deferred words
6814:
6815: The defining word @code{Defer} allows you to define a word by name
6816: without defining its behaviour; the definition of its behaviour is
6817: deferred. Here are two situation where this can be useful:
6818:
6819: @itemize @bullet
6820: @item
6821: Where you want to allow the behaviour of a word to be altered later, and
6822: for all precompiled references to the word to change when its behaviour
6823: is changed.
6824: @item
6825: For mutual recursion; @xref{Calls and returns}.
6826: @end itemize
6827:
6828: In the following example, @code{foo} always invokes the version of
6829: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6830: always invokes the version that prints ``@code{Hello}''. There is no way
6831: of getting @code{foo} to use the later version without re-ordering the
6832: source code and recompiling it.
6833:
6834: @example
6835: : greet ." Good morning" ;
6836: : foo ... greet ... ;
6837: : greet ." Hello" ;
6838: : bar ... greet ... ;
6839: @end example
6840:
6841: This problem can be solved by defining @code{greet} as a @code{Defer}red
6842: word. The behaviour of a @code{Defer}red word can be defined and
6843: redefined at any time by using @code{IS} to associate the xt of a
6844: previously-defined word with it. The previous example becomes:
6845:
6846: @example
1.69 anton 6847: Defer greet ( -- )
1.44 crook 6848: : foo ... greet ... ;
6849: : bar ... greet ... ;
1.69 anton 6850: : greet1 ( -- ) ." Good morning" ;
6851: : greet2 ( -- ) ." Hello" ;
1.132 anton 6852: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6853: @end example
6854:
1.69 anton 6855: @progstyle
6856: You should write a stack comment for every deferred word, and put only
6857: XTs into deferred words that conform to this stack effect. Otherwise
6858: it's too difficult to use the deferred word.
6859:
1.44 crook 6860: A deferred word can be used to improve the statistics-gathering example
6861: from @ref{User-defined Defining Words}; rather than edit the
6862: application's source code to change every @code{:} to a @code{my:}, do
6863: this:
6864:
6865: @example
6866: : real: : ; \ retain access to the original
6867: defer : \ redefine as a deferred word
1.132 anton 6868: ' my: IS : \ use special version of :
1.44 crook 6869: \
6870: \ load application here
6871: \
1.132 anton 6872: ' real: IS : \ go back to the original
1.44 crook 6873: @end example
6874:
6875:
1.132 anton 6876: One thing to note is that @code{IS} has special compilation semantics,
6877: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6878:
6879: @example
6880: : set-greet ( xt -- )
1.132 anton 6881: IS greet ;
1.44 crook 6882:
6883: ' greet1 set-greet
6884: @end example
6885:
1.132 anton 6886: In situations where @code{IS} does not fit, use @code{defer!} instead.
6887:
1.69 anton 6888: A deferred word can only inherit execution semantics from the xt
6889: (because that is all that an xt can represent -- for more discussion of
6890: this @pxref{Tokens for Words}); by default it will have default
6891: interpretation and compilation semantics deriving from this execution
6892: semantics. However, you can change the interpretation and compilation
6893: semantics of the deferred word in the usual ways:
1.44 crook 6894:
6895: @example
1.132 anton 6896: : bar .... ; immediate
1.44 crook 6897: Defer fred immediate
6898: Defer jim
6899:
1.132 anton 6900: ' bar IS jim \ jim has default semantics
6901: ' bar IS fred \ fred is immediate
1.44 crook 6902: @end example
6903:
6904: doc-defer
1.132 anton 6905: doc-defer!
1.44 crook 6906: doc-is
1.132 anton 6907: doc-defer@
6908: doc-action-of
1.44 crook 6909: @comment TODO document these: what's defers [is]
6910: doc-defers
6911:
6912: @c Use @code{words-deferred} to see a list of deferred words.
6913:
1.132 anton 6914: Definitions of these words (except @code{defers}) in ANS Forth are
6915: provided in @file{compat/defer.fs}.
1.44 crook 6916:
6917:
1.170 pazsan 6918: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6919: @subsection Aliases
6920: @cindex aliases
1.1 anton 6921:
1.44 crook 6922: The defining word @code{Alias} allows you to define a word by name that
6923: has the same behaviour as some other word. Here are two situation where
6924: this can be useful:
1.1 anton 6925:
1.44 crook 6926: @itemize @bullet
6927: @item
6928: When you want access to a word's definition from a different word list
6929: (for an example of this, see the definition of the @code{Root} word list
6930: in the Gforth source).
6931: @item
6932: When you want to create a synonym; a definition that can be known by
6933: either of two names (for example, @code{THEN} and @code{ENDIF} are
6934: aliases).
6935: @end itemize
1.1 anton 6936:
1.69 anton 6937: Like deferred words, an alias has default compilation and interpretation
6938: semantics at the beginning (not the modifications of the other word),
6939: but you can change them in the usual ways (@code{immediate},
6940: @code{compile-only}). For example:
1.1 anton 6941:
6942: @example
1.44 crook 6943: : foo ... ; immediate
6944:
6945: ' foo Alias bar \ bar is not an immediate word
6946: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6947: @end example
6948:
1.44 crook 6949: Words that are aliases have the same xt, different headers in the
6950: dictionary, and consequently different name tokens (@pxref{Tokens for
6951: Words}) and possibly different immediate flags. An alias can only have
6952: default or immediate compilation semantics; you can define aliases for
6953: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6954:
1.44 crook 6955: doc-alias
1.1 anton 6956:
6957:
1.47 crook 6958: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6959: @section Interpretation and Compilation Semantics
1.26 crook 6960: @cindex semantics, interpretation and compilation
1.1 anton 6961:
1.71 anton 6962: @c !! state and ' are used without explanation
6963: @c example for immediate/compile-only? or is the tutorial enough
6964:
1.26 crook 6965: @cindex interpretation semantics
1.71 anton 6966: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6967: interpreter does when it encounters the word in interpret state. It also
6968: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6969: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6970: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6971: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6972:
1.26 crook 6973: @cindex compilation semantics
1.71 anton 6974: The @dfn{compilation semantics} of a (named) word are what the text
6975: interpreter does when it encounters the word in compile state. It also
6976: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6977: compiles@footnote{In standard terminology, ``appends to the current
6978: definition''.} the compilation semantics of @i{word}.
1.1 anton 6979:
1.26 crook 6980: @cindex execution semantics
6981: The standard also talks about @dfn{execution semantics}. They are used
6982: only for defining the interpretation and compilation semantics of many
6983: words. By default, the interpretation semantics of a word are to
6984: @code{execute} its execution semantics, and the compilation semantics of
6985: a word are to @code{compile,} its execution semantics.@footnote{In
6986: standard terminology: The default interpretation semantics are its
6987: execution semantics; the default compilation semantics are to append its
6988: execution semantics to the execution semantics of the current
6989: definition.}
6990:
1.71 anton 6991: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6992: the text interpreter, ticked, or @code{postpone}d, so they have no
6993: interpretation or compilation semantics. Their behaviour is represented
6994: by their XT (@pxref{Tokens for Words}), and we call it execution
6995: semantics, too.
6996:
1.26 crook 6997: @comment TODO expand, make it co-operate with new sections on text interpreter.
6998:
6999: @cindex immediate words
7000: @cindex compile-only words
7001: You can change the semantics of the most-recently defined word:
7002:
1.44 crook 7003:
1.26 crook 7004: doc-immediate
7005: doc-compile-only
7006: doc-restrict
7007:
1.82 anton 7008: By convention, words with non-default compilation semantics (e.g.,
7009: immediate words) often have names surrounded with brackets (e.g.,
7010: @code{[']}, @pxref{Execution token}).
1.44 crook 7011:
1.26 crook 7012: Note that ticking (@code{'}) a compile-only word gives an error
7013: (``Interpreting a compile-only word'').
1.1 anton 7014:
1.47 crook 7015: @menu
1.67 anton 7016: * Combined words::
1.47 crook 7017: @end menu
1.44 crook 7018:
1.71 anton 7019:
1.48 anton 7020: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7021: @subsection Combined Words
7022: @cindex combined words
7023:
7024: Gforth allows you to define @dfn{combined words} -- words that have an
7025: arbitrary combination of interpretation and compilation semantics.
7026:
1.26 crook 7027: doc-interpret/compile:
1.1 anton 7028:
1.26 crook 7029: This feature was introduced for implementing @code{TO} and @code{S"}. I
7030: recommend that you do not define such words, as cute as they may be:
7031: they make it hard to get at both parts of the word in some contexts.
7032: E.g., assume you want to get an execution token for the compilation
7033: part. Instead, define two words, one that embodies the interpretation
7034: part, and one that embodies the compilation part. Once you have done
7035: that, you can define a combined word with @code{interpret/compile:} for
7036: the convenience of your users.
1.1 anton 7037:
1.26 crook 7038: You might try to use this feature to provide an optimizing
7039: implementation of the default compilation semantics of a word. For
7040: example, by defining:
1.1 anton 7041: @example
1.26 crook 7042: :noname
7043: foo bar ;
7044: :noname
7045: POSTPONE foo POSTPONE bar ;
1.29 crook 7046: interpret/compile: opti-foobar
1.1 anton 7047: @end example
1.26 crook 7048:
1.23 crook 7049: @noindent
1.26 crook 7050: as an optimizing version of:
7051:
1.1 anton 7052: @example
1.26 crook 7053: : foobar
7054: foo bar ;
1.1 anton 7055: @end example
7056:
1.26 crook 7057: Unfortunately, this does not work correctly with @code{[compile]},
7058: because @code{[compile]} assumes that the compilation semantics of all
7059: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7060: opti-foobar} would compile compilation semantics, whereas
7061: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7062:
1.26 crook 7063: @cindex state-smart words (are a bad idea)
1.82 anton 7064: @anchor{state-smartness}
1.29 crook 7065: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7066: by @code{interpret/compile:} (words are state-smart if they check
7067: @code{STATE} during execution). E.g., they would try to code
7068: @code{foobar} like this:
1.1 anton 7069:
1.26 crook 7070: @example
7071: : foobar
7072: STATE @@
7073: IF ( compilation state )
7074: POSTPONE foo POSTPONE bar
7075: ELSE
7076: foo bar
7077: ENDIF ; immediate
7078: @end example
1.1 anton 7079:
1.26 crook 7080: Although this works if @code{foobar} is only processed by the text
7081: interpreter, it does not work in other contexts (like @code{'} or
7082: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7083: for a state-smart word, not for the interpretation semantics of the
7084: original @code{foobar}; when you execute this execution token (directly
7085: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7086: state, the result will not be what you expected (i.e., it will not
7087: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7088: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7089: M. Anton Ertl,
7090: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7091: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7092:
1.26 crook 7093: @cindex defining words with arbitrary semantics combinations
7094: It is also possible to write defining words that define words with
7095: arbitrary combinations of interpretation and compilation semantics. In
7096: general, they look like this:
1.1 anton 7097:
1.26 crook 7098: @example
7099: : def-word
7100: create-interpret/compile
1.29 crook 7101: @i{code1}
1.26 crook 7102: interpretation>
1.29 crook 7103: @i{code2}
1.26 crook 7104: <interpretation
7105: compilation>
1.29 crook 7106: @i{code3}
1.26 crook 7107: <compilation ;
7108: @end example
1.1 anton 7109:
1.29 crook 7110: For a @i{word} defined with @code{def-word}, the interpretation
7111: semantics are to push the address of the body of @i{word} and perform
7112: @i{code2}, and the compilation semantics are to push the address of
7113: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7114: can also be defined like this (except that the defined constants don't
7115: behave correctly when @code{[compile]}d):
1.1 anton 7116:
1.26 crook 7117: @example
7118: : constant ( n "name" -- )
7119: create-interpret/compile
7120: ,
7121: interpretation> ( -- n )
7122: @@
7123: <interpretation
7124: compilation> ( compilation. -- ; run-time. -- n )
7125: @@ postpone literal
7126: <compilation ;
7127: @end example
1.1 anton 7128:
1.44 crook 7129:
1.26 crook 7130: doc-create-interpret/compile
7131: doc-interpretation>
7132: doc-<interpretation
7133: doc-compilation>
7134: doc-<compilation
1.1 anton 7135:
1.44 crook 7136:
1.29 crook 7137: Words defined with @code{interpret/compile:} and
1.26 crook 7138: @code{create-interpret/compile} have an extended header structure that
7139: differs from other words; however, unless you try to access them with
7140: plain address arithmetic, you should not notice this. Words for
7141: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7142: @code{'} @i{word} @code{>body} also gives you the body of a word created
7143: with @code{create-interpret/compile}.
1.1 anton 7144:
1.44 crook 7145:
1.47 crook 7146: @c -------------------------------------------------------------
1.81 anton 7147: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7148: @section Tokens for Words
7149: @cindex tokens for words
7150:
7151: This section describes the creation and use of tokens that represent
7152: words.
7153:
1.71 anton 7154: @menu
7155: * Execution token:: represents execution/interpretation semantics
7156: * Compilation token:: represents compilation semantics
7157: * Name token:: represents named words
7158: @end menu
1.47 crook 7159:
1.71 anton 7160: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7161: @subsection Execution token
1.47 crook 7162:
7163: @cindex xt
7164: @cindex execution token
1.71 anton 7165: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7166: You can use @code{execute} to invoke this behaviour.
1.47 crook 7167:
1.71 anton 7168: @cindex tick (')
7169: You can use @code{'} to get an execution token that represents the
7170: interpretation semantics of a named word:
1.47 crook 7171:
7172: @example
1.97 anton 7173: 5 ' . ( n xt )
7174: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7175: @end example
1.47 crook 7176:
1.71 anton 7177: doc-'
7178:
7179: @code{'} parses at run-time; there is also a word @code{[']} that parses
7180: when it is compiled, and compiles the resulting XT:
7181:
7182: @example
7183: : foo ['] . execute ;
7184: 5 foo
7185: : bar ' execute ; \ by contrast,
7186: 5 bar . \ ' parses "." when bar executes
7187: @end example
7188:
7189: doc-[']
7190:
7191: If you want the execution token of @i{word}, write @code{['] @i{word}}
7192: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7193: @code{'} and @code{[']} behave somewhat unusually by complaining about
7194: compile-only words (because these words have no interpretation
7195: semantics). You might get what you want by using @code{COMP' @i{word}
7196: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7197: token}).
7198:
1.116 anton 7199: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7200: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7201: for the only behaviour the word has (the execution semantics). For
1.116 anton 7202: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7203: would produce if the word was defined anonymously.
7204:
7205: @example
7206: :noname ." hello" ;
7207: execute
1.47 crook 7208: @end example
7209:
1.71 anton 7210: An XT occupies one cell and can be manipulated like any other cell.
7211:
1.47 crook 7212: @cindex code field address
7213: @cindex CFA
1.71 anton 7214: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7215: operations that produce or consume it). For old hands: In Gforth, the
7216: XT is implemented as a code field address (CFA).
7217:
7218: doc-execute
7219: doc-perform
7220:
7221: @node Compilation token, Name token, Execution token, Tokens for Words
7222: @subsection Compilation token
1.47 crook 7223:
7224: @cindex compilation token
1.71 anton 7225: @cindex CT (compilation token)
7226: Gforth represents the compilation semantics of a named word by a
1.47 crook 7227: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7228: @i{xt} is an execution token. The compilation semantics represented by
7229: the compilation token can be performed with @code{execute}, which
7230: consumes the whole compilation token, with an additional stack effect
7231: determined by the represented compilation semantics.
7232:
7233: At present, the @i{w} part of a compilation token is an execution token,
7234: and the @i{xt} part represents either @code{execute} or
7235: @code{compile,}@footnote{Depending upon the compilation semantics of the
7236: word. If the word has default compilation semantics, the @i{xt} will
7237: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7238: @i{xt} will represent @code{execute}.}. However, don't rely on that
7239: knowledge, unless necessary; future versions of Gforth may introduce
7240: unusual compilation tokens (e.g., a compilation token that represents
7241: the compilation semantics of a literal).
7242:
1.71 anton 7243: You can perform the compilation semantics represented by the compilation
7244: token with @code{execute}. You can compile the compilation semantics
7245: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7246: equivalent to @code{postpone @i{word}}.
7247:
7248: doc-[comp']
7249: doc-comp'
7250: doc-postpone,
7251:
7252: @node Name token, , Compilation token, Tokens for Words
7253: @subsection Name token
1.47 crook 7254:
7255: @cindex name token
1.116 anton 7256: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7257: token is an abstract data type that occurs as argument or result of the
7258: words below.
7259:
7260: @c !! put this elswhere?
1.47 crook 7261: @cindex name field address
7262: @cindex NFA
1.116 anton 7263: The closest thing to the nt in older Forth systems is the name field
7264: address (NFA), but there are significant differences: in older Forth
7265: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7266: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7267: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7268: is a link field in the structure identified by the name token, but
7269: searching usually uses a hash table external to these structures; the
7270: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7271: implemented as the address of that count field.
1.47 crook 7272:
7273: doc-find-name
1.116 anton 7274: doc-latest
7275: doc->name
1.47 crook 7276: doc-name>int
7277: doc-name?int
7278: doc-name>comp
7279: doc-name>string
1.109 anton 7280: doc-id.
7281: doc-.name
7282: doc-.id
1.47 crook 7283:
1.81 anton 7284: @c ----------------------------------------------------------
7285: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7286: @section Compiling words
7287: @cindex compiling words
7288: @cindex macros
7289:
7290: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7291: between compilation and run-time. E.g., you can run arbitrary code
7292: between defining words (or for computing data used by defining words
7293: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7294: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7295: running arbitrary code while compiling a colon definition (exception:
7296: you must not allot dictionary space).
7297:
7298: @menu
7299: * Literals:: Compiling data values
7300: * Macros:: Compiling words
7301: @end menu
7302:
7303: @node Literals, Macros, Compiling words, Compiling words
7304: @subsection Literals
7305: @cindex Literals
7306:
7307: The simplest and most frequent example is to compute a literal during
7308: compilation. E.g., the following definition prints an array of strings,
7309: one string per line:
7310:
7311: @example
7312: : .strings ( addr u -- ) \ gforth
7313: 2* cells bounds U+DO
7314: cr i 2@@ type
7315: 2 cells +LOOP ;
7316: @end example
1.81 anton 7317:
1.82 anton 7318: With a simple-minded compiler like Gforth's, this computes @code{2
7319: cells} on every loop iteration. You can compute this value once and for
7320: all at compile time and compile it into the definition like this:
7321:
7322: @example
7323: : .strings ( addr u -- ) \ gforth
7324: 2* cells bounds U+DO
7325: cr i 2@@ type
7326: [ 2 cells ] literal +LOOP ;
7327: @end example
7328:
7329: @code{[} switches the text interpreter to interpret state (you will get
7330: an @code{ok} prompt if you type this example interactively and insert a
7331: newline between @code{[} and @code{]}), so it performs the
7332: interpretation semantics of @code{2 cells}; this computes a number.
7333: @code{]} switches the text interpreter back into compile state. It then
7334: performs @code{Literal}'s compilation semantics, which are to compile
7335: this number into the current word. You can decompile the word with
7336: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7337:
1.82 anton 7338: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7339: *} in this way.
1.81 anton 7340:
1.82 anton 7341: doc-[
7342: doc-]
1.81 anton 7343: doc-literal
7344: doc-]L
1.82 anton 7345:
7346: There are also words for compiling other data types than single cells as
7347: literals:
7348:
1.81 anton 7349: doc-2literal
7350: doc-fliteral
1.82 anton 7351: doc-sliteral
7352:
7353: @cindex colon-sys, passing data across @code{:}
7354: @cindex @code{:}, passing data across
7355: You might be tempted to pass data from outside a colon definition to the
7356: inside on the data stack. This does not work, because @code{:} puhes a
7357: colon-sys, making stuff below unaccessible. E.g., this does not work:
7358:
7359: @example
7360: 5 : foo literal ; \ error: "unstructured"
7361: @end example
7362:
7363: Instead, you have to pass the value in some other way, e.g., through a
7364: variable:
7365:
7366: @example
7367: variable temp
7368: 5 temp !
7369: : foo [ temp @@ ] literal ;
7370: @end example
7371:
7372:
7373: @node Macros, , Literals, Compiling words
7374: @subsection Macros
7375: @cindex Macros
7376: @cindex compiling compilation semantics
7377:
7378: @code{Literal} and friends compile data values into the current
7379: definition. You can also write words that compile other words into the
7380: current definition. E.g.,
7381:
7382: @example
7383: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7384: POSTPONE + ;
7385:
7386: : foo ( n1 n2 -- n )
7387: [ compile-+ ] ;
7388: 1 2 foo .
7389: @end example
7390:
7391: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7392: What happens in this example? @code{Postpone} compiles the compilation
7393: semantics of @code{+} into @code{compile-+}; later the text interpreter
7394: executes @code{compile-+} and thus the compilation semantics of +, which
7395: compile (the execution semantics of) @code{+} into
7396: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7397: should only be executed in compile state, so this example is not
7398: guaranteed to work on all standard systems, but on any decent system it
7399: will work.}
7400:
7401: doc-postpone
7402: doc-[compile]
7403:
7404: Compiling words like @code{compile-+} are usually immediate (or similar)
7405: so you do not have to switch to interpret state to execute them;
7406: mopifying the last example accordingly produces:
7407:
7408: @example
7409: : [compile-+] ( compilation: --; interpretation: -- )
7410: \ compiled code: ( n1 n2 -- n )
7411: POSTPONE + ; immediate
7412:
7413: : foo ( n1 n2 -- n )
7414: [compile-+] ;
7415: 1 2 foo .
7416: @end example
7417:
7418: Immediate compiling words are similar to macros in other languages (in
7419: particular, Lisp). The important differences to macros in, e.g., C are:
7420:
7421: @itemize @bullet
7422:
7423: @item
7424: You use the same language for defining and processing macros, not a
7425: separate preprocessing language and processor.
7426:
7427: @item
7428: Consequently, the full power of Forth is available in macro definitions.
7429: E.g., you can perform arbitrarily complex computations, or generate
7430: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7431: Tutorial}). This power is very useful when writing a parser generators
7432: or other code-generating software.
7433:
7434: @item
7435: Macros defined using @code{postpone} etc. deal with the language at a
7436: higher level than strings; name binding happens at macro definition
7437: time, so you can avoid the pitfalls of name collisions that can happen
7438: in C macros. Of course, Forth is a liberal language and also allows to
7439: shoot yourself in the foot with text-interpreted macros like
7440:
7441: @example
7442: : [compile-+] s" +" evaluate ; immediate
7443: @end example
7444:
7445: Apart from binding the name at macro use time, using @code{evaluate}
7446: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7447: @end itemize
7448:
7449: You may want the macro to compile a number into a word. The word to do
7450: it is @code{literal}, but you have to @code{postpone} it, so its
7451: compilation semantics take effect when the macro is executed, not when
7452: it is compiled:
7453:
7454: @example
7455: : [compile-5] ( -- ) \ compiled code: ( -- n )
7456: 5 POSTPONE literal ; immediate
7457:
7458: : foo [compile-5] ;
7459: foo .
7460: @end example
7461:
7462: You may want to pass parameters to a macro, that the macro should
7463: compile into the current definition. If the parameter is a number, then
7464: you can use @code{postpone literal} (similar for other values).
7465:
7466: If you want to pass a word that is to be compiled, the usual way is to
7467: pass an execution token and @code{compile,} it:
7468:
7469: @example
7470: : twice1 ( xt -- ) \ compiled code: ... -- ...
7471: dup compile, compile, ;
7472:
7473: : 2+ ( n1 -- n2 )
7474: [ ' 1+ twice1 ] ;
7475: @end example
7476:
7477: doc-compile,
7478:
7479: An alternative available in Gforth, that allows you to pass compile-only
7480: words as parameters is to use the compilation token (@pxref{Compilation
7481: token}). The same example in this technique:
7482:
7483: @example
7484: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7485: 2dup 2>r execute 2r> execute ;
7486:
7487: : 2+ ( n1 -- n2 )
7488: [ comp' 1+ twice ] ;
7489: @end example
7490:
7491: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7492: works even if the executed compilation semantics has an effect on the
7493: data stack.
7494:
7495: You can also define complete definitions with these words; this provides
7496: an alternative to using @code{does>} (@pxref{User-defined Defining
7497: Words}). E.g., instead of
7498:
7499: @example
7500: : curry+ ( n1 "name" -- )
7501: CREATE ,
7502: DOES> ( n2 -- n1+n2 )
7503: @@ + ;
7504: @end example
7505:
7506: you could define
7507:
7508: @example
7509: : curry+ ( n1 "name" -- )
7510: \ name execution: ( n2 -- n1+n2 )
7511: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7512:
1.82 anton 7513: -3 curry+ 3-
7514: see 3-
7515: @end example
1.81 anton 7516:
1.82 anton 7517: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7518: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7519:
1.82 anton 7520: This way of writing defining words is sometimes more, sometimes less
7521: convenient than using @code{does>} (@pxref{Advanced does> usage
7522: example}). One advantage of this method is that it can be optimized
7523: better, because the compiler knows that the value compiled with
7524: @code{literal} is fixed, whereas the data associated with a
7525: @code{create}d word can be changed.
1.47 crook 7526:
1.26 crook 7527: @c ----------------------------------------------------------
1.111 anton 7528: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7529: @section The Text Interpreter
7530: @cindex interpreter - outer
7531: @cindex text interpreter
7532: @cindex outer interpreter
1.1 anton 7533:
1.34 anton 7534: @c Should we really describe all these ugly details? IMO the text
7535: @c interpreter should be much cleaner, but that may not be possible within
7536: @c ANS Forth. - anton
1.44 crook 7537: @c nac-> I wanted to explain how it works to show how you can exploit
7538: @c it in your own programs. When I was writing a cross-compiler, figuring out
7539: @c some of these gory details was very helpful to me. None of the textbooks
7540: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7541: @c seems to positively avoid going into too much detail for some of
7542: @c the internals.
1.34 anton 7543:
1.71 anton 7544: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7545: @c it is; for the ugly details, I would prefer another place. I wonder
7546: @c whether we should have a chapter before "Words" that describes some
7547: @c basic concepts referred to in words, and a chapter after "Words" that
7548: @c describes implementation details.
7549:
1.29 crook 7550: The text interpreter@footnote{This is an expanded version of the
7551: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7552: that processes input from the current input device. It is also called
7553: the outer interpreter, in contrast to the inner interpreter
7554: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7555: implementations.
1.27 crook 7556:
1.29 crook 7557: @cindex interpret state
7558: @cindex compile state
7559: The text interpreter operates in one of two states: @dfn{interpret
7560: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7561: aptly-named variable @code{state}.
1.29 crook 7562:
7563: This section starts by describing how the text interpreter behaves when
7564: it is in interpret state, processing input from the user input device --
7565: the keyboard. This is the mode that a Forth system is in after it starts
7566: up.
7567:
7568: @cindex input buffer
7569: @cindex terminal input buffer
7570: The text interpreter works from an area of memory called the @dfn{input
7571: buffer}@footnote{When the text interpreter is processing input from the
7572: keyboard, this area of memory is called the @dfn{terminal input buffer}
7573: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7574: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7575: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7576: leading spaces (called @dfn{delimiters}) then parses a string (a
7577: sequence of non-space characters) until it reaches either a space
7578: character or the end of the buffer. Having parsed a string, it makes two
7579: attempts to process it:
1.27 crook 7580:
1.29 crook 7581: @cindex dictionary
1.27 crook 7582: @itemize @bullet
7583: @item
1.29 crook 7584: It looks for the string in a @dfn{dictionary} of definitions. If the
7585: string is found, the string names a @dfn{definition} (also known as a
7586: @dfn{word}) and the dictionary search returns information that allows
7587: the text interpreter to perform the word's @dfn{interpretation
7588: semantics}. In most cases, this simply means that the word will be
7589: executed.
1.27 crook 7590: @item
7591: If the string is not found in the dictionary, the text interpreter
1.29 crook 7592: attempts to treat it as a number, using the rules described in
7593: @ref{Number Conversion}. If the string represents a legal number in the
7594: current radix, the number is pushed onto a parameter stack (the data
7595: stack for integers, the floating-point stack for floating-point
7596: numbers).
7597: @end itemize
7598:
7599: If both attempts fail, or if the word is found in the dictionary but has
7600: no interpretation semantics@footnote{This happens if the word was
7601: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7602: remainder of the input buffer, issues an error message and waits for
7603: more input. If one of the attempts succeeds, the text interpreter
7604: repeats the parsing process until the whole of the input buffer has been
7605: processed, at which point it prints the status message ``@code{ ok}''
7606: and waits for more input.
7607:
1.71 anton 7608: @c anton: this should be in the input stream subsection (or below it)
7609:
1.29 crook 7610: @cindex parse area
7611: The text interpreter keeps track of its position in the input buffer by
7612: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7613: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7614: of the input buffer. The region from offset @code{>IN @@} to the end of
7615: the input buffer is called the @dfn{parse area}@footnote{In other words,
7616: the text interpreter processes the contents of the input buffer by
7617: parsing strings from the parse area until the parse area is empty.}.
7618: This example shows how @code{>IN} changes as the text interpreter parses
7619: the input buffer:
7620:
7621: @example
7622: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7623: CR ." ->" TYPE ." <-" ; IMMEDIATE
7624:
7625: 1 2 3 remaining + remaining .
7626:
7627: : foo 1 2 3 remaining SWAP remaining ;
7628: @end example
7629:
7630: @noindent
7631: The result is:
7632:
7633: @example
7634: ->+ remaining .<-
7635: ->.<-5 ok
7636:
7637: ->SWAP remaining ;-<
7638: ->;<- ok
7639: @end example
7640:
7641: @cindex parsing words
7642: The value of @code{>IN} can also be modified by a word in the input
7643: buffer that is executed by the text interpreter. This means that a word
7644: can ``trick'' the text interpreter into either skipping a section of the
7645: input buffer@footnote{This is how parsing words work.} or into parsing a
7646: section twice. For example:
1.27 crook 7647:
1.29 crook 7648: @example
1.71 anton 7649: : lat ." <<foo>>" ;
7650: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7651: @end example
7652:
7653: @noindent
7654: When @code{flat} is executed, this output is produced@footnote{Exercise
7655: for the reader: what would happen if the @code{3} were replaced with
7656: @code{4}?}:
7657:
7658: @example
1.71 anton 7659: <<bar>><<foo>>
1.29 crook 7660: @end example
7661:
1.71 anton 7662: This technique can be used to work around some of the interoperability
7663: problems of parsing words. Of course, it's better to avoid parsing
7664: words where possible.
7665:
1.29 crook 7666: @noindent
7667: Two important notes about the behaviour of the text interpreter:
1.27 crook 7668:
7669: @itemize @bullet
7670: @item
7671: It processes each input string to completion before parsing additional
1.29 crook 7672: characters from the input buffer.
7673: @item
7674: It treats the input buffer as a read-only region (and so must your code).
7675: @end itemize
7676:
7677: @noindent
7678: When the text interpreter is in compile state, its behaviour changes in
7679: these ways:
7680:
7681: @itemize @bullet
7682: @item
7683: If a parsed string is found in the dictionary, the text interpreter will
7684: perform the word's @dfn{compilation semantics}. In most cases, this
7685: simply means that the execution semantics of the word will be appended
7686: to the current definition.
1.27 crook 7687: @item
1.29 crook 7688: When a number is encountered, it is compiled into the current definition
7689: (as a literal) rather than being pushed onto a parameter stack.
7690: @item
7691: If an error occurs, @code{state} is modified to put the text interpreter
7692: back into interpret state.
7693: @item
7694: Each time a line is entered from the keyboard, Gforth prints
7695: ``@code{ compiled}'' rather than `` @code{ok}''.
7696: @end itemize
7697:
7698: @cindex text interpreter - input sources
7699: When the text interpreter is using an input device other than the
7700: keyboard, its behaviour changes in these ways:
7701:
7702: @itemize @bullet
7703: @item
7704: When the parse area is empty, the text interpreter attempts to refill
7705: the input buffer from the input source. When the input source is
1.71 anton 7706: exhausted, the input source is set back to the previous input source.
1.29 crook 7707: @item
7708: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7709: time the parse area is emptied.
7710: @item
7711: If an error occurs, the input source is set back to the user input
7712: device.
1.27 crook 7713: @end itemize
1.21 crook 7714:
1.49 anton 7715: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7716:
1.26 crook 7717: doc->in
1.27 crook 7718: doc-source
7719:
1.26 crook 7720: doc-tib
7721: doc-#tib
1.1 anton 7722:
1.44 crook 7723:
1.26 crook 7724: @menu
1.67 anton 7725: * Input Sources::
7726: * Number Conversion::
7727: * Interpret/Compile states::
7728: * Interpreter Directives::
1.26 crook 7729: @end menu
1.1 anton 7730:
1.29 crook 7731: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7732: @subsection Input Sources
7733: @cindex input sources
7734: @cindex text interpreter - input sources
7735:
1.44 crook 7736: By default, the text interpreter processes input from the user input
1.29 crook 7737: device (the keyboard) when Forth starts up. The text interpreter can
7738: process input from any of these sources:
7739:
7740: @itemize @bullet
7741: @item
7742: The user input device -- the keyboard.
7743: @item
7744: A file, using the words described in @ref{Forth source files}.
7745: @item
7746: A block, using the words described in @ref{Blocks}.
7747: @item
7748: A text string, using @code{evaluate}.
7749: @end itemize
7750:
7751: A program can identify the current input device from the values of
7752: @code{source-id} and @code{blk}.
7753:
1.44 crook 7754:
1.29 crook 7755: doc-source-id
7756: doc-blk
7757:
7758: doc-save-input
7759: doc-restore-input
7760:
7761: doc-evaluate
1.111 anton 7762: doc-query
1.1 anton 7763:
1.29 crook 7764:
1.44 crook 7765:
1.29 crook 7766: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7767: @subsection Number Conversion
7768: @cindex number conversion
7769: @cindex double-cell numbers, input format
7770: @cindex input format for double-cell numbers
7771: @cindex single-cell numbers, input format
7772: @cindex input format for single-cell numbers
7773: @cindex floating-point numbers, input format
7774: @cindex input format for floating-point numbers
1.1 anton 7775:
1.29 crook 7776: This section describes the rules that the text interpreter uses when it
7777: tries to convert a string into a number.
1.1 anton 7778:
1.26 crook 7779: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7780: number base@footnote{For example, 0-9 when the number base is decimal or
7781: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7782:
1.26 crook 7783: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7784:
1.29 crook 7785: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7786: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7787:
1.26 crook 7788: Let * represent any number of instances of the previous character
7789: (including none).
1.1 anton 7790:
1.26 crook 7791: Let any other character represent itself.
1.1 anton 7792:
1.29 crook 7793: @noindent
1.26 crook 7794: Now, the conversion rules are:
1.21 crook 7795:
1.26 crook 7796: @itemize @bullet
7797: @item
7798: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7799: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7800: @item
7801: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7802: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7803: arithmetic. Examples are -45 -5681 -0
7804: @item
7805: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7806: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7807: (all three of these represent the same number).
1.26 crook 7808: @item
7809: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7810: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7811: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7812: -34.65 (all three of these represent the same number).
1.26 crook 7813: @item
1.29 crook 7814: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7815: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7816: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7817: number) +12.E-4
1.26 crook 7818: @end itemize
1.1 anton 7819:
1.174 anton 7820: By default, the number base used for integer number conversion is
7821: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7822: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7823: change @code{base} anywhere, make sure to save the old value and
7824: restore it afterwards; better yet, use @code{base-execute}, which does
7825: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7826: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7827:
1.29 crook 7828: doc-dpl
1.174 anton 7829: doc-base-execute
1.26 crook 7830: doc-base
7831: doc-hex
7832: doc-decimal
1.1 anton 7833:
1.26 crook 7834: @cindex '-prefix for character strings
7835: @cindex &-prefix for decimal numbers
1.133 anton 7836: @cindex #-prefix for decimal numbers
1.26 crook 7837: @cindex %-prefix for binary numbers
7838: @cindex $-prefix for hexadecimal numbers
1.133 anton 7839: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7840: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7841: prefix@footnote{Some Forth implementations provide a similar scheme by
7842: implementing @code{$} etc. as parsing words that process the subsequent
7843: number in the input stream and push it onto the stack. For example, see
7844: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7845: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7846: is required between the prefix and the number.} before the first digit
1.133 anton 7847: of an (integer) number. The following prefixes are supported:
1.1 anton 7848:
1.26 crook 7849: @itemize @bullet
7850: @item
1.35 anton 7851: @code{&} -- decimal
1.26 crook 7852: @item
1.133 anton 7853: @code{#} -- decimal
7854: @item
1.35 anton 7855: @code{%} -- binary
1.26 crook 7856: @item
1.35 anton 7857: @code{$} -- hexadecimal
1.26 crook 7858: @item
1.133 anton 7859: @code{0x} -- hexadecimal, if base<33.
7860: @item
7861: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7862: optional @code{'} may be present after the character.
1.26 crook 7863: @end itemize
1.1 anton 7864:
1.26 crook 7865: Here are some examples, with the equivalent decimal number shown after
7866: in braces:
1.1 anton 7867:
1.26 crook 7868: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7869: 'A (65),
7870: -'a' (-97),
1.26 crook 7871: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7872:
1.26 crook 7873: @cindex number conversion - traps for the unwary
1.29 crook 7874: @noindent
1.26 crook 7875: Number conversion has a number of traps for the unwary:
1.1 anton 7876:
1.26 crook 7877: @itemize @bullet
7878: @item
7879: You cannot determine the current number base using the code sequence
1.35 anton 7880: @code{base @@ .} -- the number base is always 10 in the current number
7881: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7882: @item
7883: If the number base is set to a value greater than 14 (for example,
7884: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7885: it to be intepreted as either a single-precision integer or a
7886: floating-point number (Gforth treats it as an integer). The ambiguity
7887: can be resolved by explicitly stating the sign of the mantissa and/or
7888: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7889: ambiguity arises; either representation will be treated as a
7890: floating-point number.
7891: @item
1.29 crook 7892: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7893: It is used to specify file types.
7894: @item
1.72 anton 7895: ANS Forth requires the @code{.} of a double-precision number to be the
7896: final character in the string. Gforth allows the @code{.} to be
7897: anywhere after the first digit.
1.26 crook 7898: @item
7899: The number conversion process does not check for overflow.
7900: @item
1.72 anton 7901: In an ANS Forth program @code{base} is required to be decimal when
7902: converting floating-point numbers. In Gforth, number conversion to
7903: floating-point numbers always uses base &10, irrespective of the value
7904: of @code{base}.
1.26 crook 7905: @end itemize
1.1 anton 7906:
1.49 anton 7907: You can read numbers into your programs with the words described in
1.181 anton 7908: @ref{Line input and conversion}.
1.1 anton 7909:
1.82 anton 7910: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7911: @subsection Interpret/Compile states
7912: @cindex Interpret/Compile states
1.1 anton 7913:
1.29 crook 7914: A standard program is not permitted to change @code{state}
7915: explicitly. However, it can change @code{state} implicitly, using the
7916: words @code{[} and @code{]}. When @code{[} is executed it switches
7917: @code{state} to interpret state, and therefore the text interpreter
7918: starts interpreting. When @code{]} is executed it switches @code{state}
7919: to compile state and therefore the text interpreter starts
1.44 crook 7920: compiling. The most common usage for these words is for switching into
7921: interpret state and back from within a colon definition; this technique
1.49 anton 7922: can be used to compile a literal (for an example, @pxref{Literals}) or
7923: for conditional compilation (for an example, @pxref{Interpreter
7924: Directives}).
1.44 crook 7925:
1.35 anton 7926:
7927: @c This is a bad example: It's non-standard, and it's not necessary.
7928: @c However, I can't think of a good example for switching into compile
7929: @c state when there is no current word (@code{state}-smart words are not a
7930: @c good reason). So maybe we should use an example for switching into
7931: @c interpret @code{state} in a colon def. - anton
1.44 crook 7932: @c nac-> I agree. I started out by putting in the example, then realised
7933: @c that it was non-ANS, so wrote more words around it. I hope this
7934: @c re-written version is acceptable to you. I do want to keep the example
7935: @c as it is helpful for showing what is and what is not portable, particularly
7936: @c where it outlaws a style in common use.
7937:
1.72 anton 7938: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7939: @c that, we can also show what's not. In any case, I have written a
7940: @c section Compiling Words which also deals with [ ].
1.35 anton 7941:
1.95 anton 7942: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7943:
1.95 anton 7944: @c @code{[} and @code{]} also give you the ability to switch into compile
7945: @c state and back, but we cannot think of any useful Standard application
7946: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7947:
7948: @c @example
7949: @c : AA ." this is A" ;
7950: @c : BB ." this is B" ;
7951: @c : CC ." this is C" ;
7952:
7953: @c create table ] aa bb cc [
7954:
7955: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7956: @c cells table + @@ execute ;
7957: @c @end example
7958:
7959: @c This example builds a jump table; @code{0 go} will display ``@code{this
7960: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7961: @c defining @code{table} like this:
7962:
7963: @c @example
7964: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7965: @c @end example
7966:
7967: @c The problem with this code is that the definition of @code{table} is not
7968: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7969: @c @i{may} work on systems where code space and data space co-incide, the
7970: @c Standard only allows data space to be assigned for a @code{CREATE}d
7971: @c word. In addition, the Standard only allows @code{@@} to access data
7972: @c space, whilst this example is using it to access code space. The only
7973: @c portable, Standard way to build this table is to build it in data space,
7974: @c like this:
7975:
7976: @c @example
7977: @c create table ' aa , ' bb , ' cc ,
7978: @c @end example
1.29 crook 7979:
1.95 anton 7980: @c doc-state
1.44 crook 7981:
1.29 crook 7982:
1.82 anton 7983: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7984: @subsection Interpreter Directives
7985: @cindex interpreter directives
1.72 anton 7986: @cindex conditional compilation
1.1 anton 7987:
1.29 crook 7988: These words are usually used in interpret state; typically to control
7989: which parts of a source file are processed by the text
1.26 crook 7990: interpreter. There are only a few ANS Forth Standard words, but Gforth
7991: supplements these with a rich set of immediate control structure words
7992: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7993: used in compile state (@pxref{Control Structures}). Typical usages:
7994:
7995: @example
1.72 anton 7996: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7997: .
7998: .
1.72 anton 7999: HAVE-ASSEMBLER [IF]
1.29 crook 8000: : ASSEMBLER-FEATURE
8001: ...
8002: ;
8003: [ENDIF]
8004: .
8005: .
8006: : SEE
8007: ... \ general-purpose SEE code
1.72 anton 8008: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 8009: ... \ assembler-specific SEE code
8010: [ [ENDIF] ]
8011: ;
8012: @end example
1.1 anton 8013:
1.44 crook 8014:
1.26 crook 8015: doc-[IF]
8016: doc-[ELSE]
8017: doc-[THEN]
8018: doc-[ENDIF]
1.1 anton 8019:
1.26 crook 8020: doc-[IFDEF]
8021: doc-[IFUNDEF]
1.1 anton 8022:
1.26 crook 8023: doc-[?DO]
8024: doc-[DO]
8025: doc-[FOR]
8026: doc-[LOOP]
8027: doc-[+LOOP]
8028: doc-[NEXT]
1.1 anton 8029:
1.26 crook 8030: doc-[BEGIN]
8031: doc-[UNTIL]
8032: doc-[AGAIN]
8033: doc-[WHILE]
8034: doc-[REPEAT]
1.1 anton 8035:
1.27 crook 8036:
1.26 crook 8037: @c -------------------------------------------------------------
1.111 anton 8038: @node The Input Stream, Word Lists, The Text Interpreter, Words
8039: @section The Input Stream
8040: @cindex input stream
8041:
8042: @c !! integrate this better with the "Text Interpreter" section
8043: The text interpreter reads from the input stream, which can come from
8044: several sources (@pxref{Input Sources}). Some words, in particular
8045: defining words, but also words like @code{'}, read parameters from the
8046: input stream instead of from the stack.
8047:
8048: Such words are called parsing words, because they parse the input
8049: stream. Parsing words are hard to use in other words, because it is
8050: hard to pass program-generated parameters through the input stream.
8051: They also usually have an unintuitive combination of interpretation and
8052: compilation semantics when implemented naively, leading to various
8053: approaches that try to produce a more intuitive behaviour
8054: (@pxref{Combined words}).
8055:
8056: It should be obvious by now that parsing words are a bad idea. If you
8057: want to implement a parsing word for convenience, also provide a factor
8058: of the word that does not parse, but takes the parameters on the stack.
8059: To implement the parsing word on top if it, you can use the following
8060: words:
8061:
8062: @c anton: these belong in the input stream section
8063: doc-parse
1.138 anton 8064: doc-parse-name
1.111 anton 8065: doc-parse-word
8066: doc-name
8067: doc-word
8068: doc-refill
8069:
8070: Conversely, if you have the bad luck (or lack of foresight) to have to
8071: deal with parsing words without having such factors, how do you pass a
8072: string that is not in the input stream to it?
8073:
8074: doc-execute-parsing
8075:
1.146 anton 8076: A definition of this word in ANS Forth is provided in
8077: @file{compat/execute-parsing.fs}.
8078:
1.111 anton 8079: If you want to run a parsing word on a file, the following word should
8080: help:
8081:
8082: doc-execute-parsing-file
8083:
8084: @c -------------------------------------------------------------
8085: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8086: @section Word Lists
8087: @cindex word lists
1.32 anton 8088: @cindex header space
1.1 anton 8089:
1.36 anton 8090: A wordlist is a list of named words; you can add new words and look up
8091: words by name (and you can remove words in a restricted way with
8092: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8093:
8094: @cindex search order stack
8095: The text interpreter searches the wordlists present in the search order
8096: (a stack of wordlists), from the top to the bottom. Within each
8097: wordlist, the search starts conceptually at the newest word; i.e., if
8098: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8099:
1.26 crook 8100: @cindex compilation word list
1.36 anton 8101: New words are added to the @dfn{compilation wordlist} (aka current
8102: wordlist).
1.1 anton 8103:
1.36 anton 8104: @cindex wid
8105: A word list is identified by a cell-sized word list identifier (@i{wid})
8106: in much the same way as a file is identified by a file handle. The
8107: numerical value of the wid has no (portable) meaning, and might change
8108: from session to session.
1.1 anton 8109:
1.29 crook 8110: The ANS Forth ``Search order'' word set is intended to provide a set of
8111: low-level tools that allow various different schemes to be
1.74 anton 8112: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8113: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8114: Forth.
1.1 anton 8115:
1.27 crook 8116: @comment TODO: locals section refers to here, saying that every word list (aka
8117: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8118: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8119:
1.45 crook 8120: @comment TODO: document markers, reveal, tables, mappedwordlist
8121:
8122: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8123: @comment word from the source files, rather than some alias.
1.44 crook 8124:
1.26 crook 8125: doc-forth-wordlist
8126: doc-definitions
8127: doc-get-current
8128: doc-set-current
8129: doc-get-order
1.185 anton 8130: doc-set-order
1.26 crook 8131: doc-wordlist
1.30 anton 8132: doc-table
1.79 anton 8133: doc->order
1.36 anton 8134: doc-previous
1.26 crook 8135: doc-also
1.185 anton 8136: doc-forth
1.26 crook 8137: doc-only
1.185 anton 8138: doc-order
1.15 anton 8139:
1.26 crook 8140: doc-find
8141: doc-search-wordlist
1.15 anton 8142:
1.26 crook 8143: doc-words
8144: doc-vlist
1.44 crook 8145: @c doc-words-deferred
1.1 anton 8146:
1.74 anton 8147: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8148: doc-root
8149: doc-vocabulary
8150: doc-seal
8151: doc-vocs
8152: doc-current
8153: doc-context
1.1 anton 8154:
1.44 crook 8155:
1.26 crook 8156: @menu
1.75 anton 8157: * Vocabularies::
1.67 anton 8158: * Why use word lists?::
1.75 anton 8159: * Word list example::
1.26 crook 8160: @end menu
8161:
1.75 anton 8162: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8163: @subsection Vocabularies
8164: @cindex Vocabularies, detailed explanation
8165:
8166: Here is an example of creating and using a new wordlist using ANS
8167: Forth words:
8168:
8169: @example
8170: wordlist constant my-new-words-wordlist
8171: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8172:
8173: \ add it to the search order
8174: also my-new-words
8175:
8176: \ alternatively, add it to the search order and make it
8177: \ the compilation word list
8178: also my-new-words definitions
8179: \ type "order" to see the problem
8180: @end example
8181:
8182: The problem with this example is that @code{order} has no way to
8183: associate the name @code{my-new-words} with the wid of the word list (in
8184: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8185: that has no associated name). There is no Standard way of associating a
8186: name with a wid.
8187:
8188: In Gforth, this example can be re-coded using @code{vocabulary}, which
8189: associates a name with a wid:
8190:
8191: @example
8192: vocabulary my-new-words
8193:
8194: \ add it to the search order
8195: also my-new-words
8196:
8197: \ alternatively, add it to the search order and make it
8198: \ the compilation word list
8199: my-new-words definitions
8200: \ type "order" to see that the problem is solved
8201: @end example
8202:
8203:
8204: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8205: @subsection Why use word lists?
8206: @cindex word lists - why use them?
8207:
1.74 anton 8208: Here are some reasons why people use wordlists:
1.26 crook 8209:
8210: @itemize @bullet
1.74 anton 8211:
8212: @c anton: Gforth's hashing implementation makes the search speed
8213: @c independent from the number of words. But it is linear with the number
8214: @c of wordlists that have to be searched, so in effect using more wordlists
8215: @c actually slows down compilation.
8216:
8217: @c @item
8218: @c To improve compilation speed by reducing the number of header space
8219: @c entries that must be searched. This is achieved by creating a new
8220: @c word list that contains all of the definitions that are used in the
8221: @c definition of a Forth system but which would not usually be used by
8222: @c programs running on that system. That word list would be on the search
8223: @c list when the Forth system was compiled but would be removed from the
8224: @c search list for normal operation. This can be a useful technique for
8225: @c low-performance systems (for example, 8-bit processors in embedded
8226: @c systems) but is unlikely to be necessary in high-performance desktop
8227: @c systems.
8228:
1.26 crook 8229: @item
8230: To prevent a set of words from being used outside the context in which
8231: they are valid. Two classic examples of this are an integrated editor
8232: (all of the edit commands are defined in a separate word list; the
8233: search order is set to the editor word list when the editor is invoked;
8234: the old search order is restored when the editor is terminated) and an
8235: integrated assembler (the op-codes for the machine are defined in a
8236: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8237:
8238: @item
8239: To organize the words of an application or library into a user-visible
8240: set (in @code{forth-wordlist} or some other common wordlist) and a set
8241: of helper words used just for the implementation (hidden in a separate
1.75 anton 8242: wordlist). This keeps @code{words}' output smaller, separates
8243: implementation and interface, and reduces the chance of name conflicts
8244: within the common wordlist.
1.74 anton 8245:
1.26 crook 8246: @item
8247: To prevent a name-space clash between multiple definitions with the same
8248: name. For example, when building a cross-compiler you might have a word
8249: @code{IF} that generates conditional code for your target system. By
8250: placing this definition in a different word list you can control whether
8251: the host system's @code{IF} or the target system's @code{IF} get used in
8252: any particular context by controlling the order of the word lists on the
8253: search order stack.
1.74 anton 8254:
1.26 crook 8255: @end itemize
1.1 anton 8256:
1.74 anton 8257: The downsides of using wordlists are:
8258:
8259: @itemize
8260:
8261: @item
8262: Debugging becomes more cumbersome.
8263:
8264: @item
8265: Name conflicts worked around with wordlists are still there, and you
8266: have to arrange the search order carefully to get the desired results;
8267: if you forget to do that, you get hard-to-find errors (as in any case
8268: where you read the code differently from the compiler; @code{see} can
1.75 anton 8269: help seeing which of several possible words the name resolves to in such
8270: cases). @code{See} displays just the name of the words, not what
8271: wordlist they belong to, so it might be misleading. Using unique names
8272: is a better approach to avoid name conflicts.
1.74 anton 8273:
8274: @item
8275: You have to explicitly undo any changes to the search order. In many
8276: cases it would be more convenient if this happened implicitly. Gforth
8277: currently does not provide such a feature, but it may do so in the
8278: future.
8279: @end itemize
8280:
8281:
1.75 anton 8282: @node Word list example, , Why use word lists?, Word Lists
8283: @subsection Word list example
8284: @cindex word lists - example
1.1 anton 8285:
1.74 anton 8286: The following example is from the
8287: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8288: garbage collector} and uses wordlists to separate public words from
8289: helper words:
8290:
8291: @example
8292: get-current ( wid )
8293: vocabulary garbage-collector also garbage-collector definitions
8294: ... \ define helper words
8295: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8296: ... \ define the public (i.e., API) words
8297: \ they can refer to the helper words
8298: previous \ restore original search order (helper words become invisible)
8299: @end example
8300:
1.26 crook 8301: @c -------------------------------------------------------------
8302: @node Environmental Queries, Files, Word Lists, Words
8303: @section Environmental Queries
8304: @cindex environmental queries
1.21 crook 8305:
1.26 crook 8306: ANS Forth introduced the idea of ``environmental queries'' as a way
8307: for a program running on a system to determine certain characteristics of the system.
8308: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8309:
1.32 anton 8310: The Standard requires that the header space used for environmental queries
8311: be distinct from the header space used for definitions.
1.21 crook 8312:
1.26 crook 8313: Typically, environmental queries are supported by creating a set of
1.29 crook 8314: definitions in a word list that is @i{only} used during environmental
1.26 crook 8315: queries; that is what Gforth does. There is no Standard way of adding
8316: definitions to the set of recognised environmental queries, but any
8317: implementation that supports the loading of optional word sets must have
8318: some mechanism for doing this (after loading the word set, the
8319: associated environmental query string must return @code{true}). In
8320: Gforth, the word list used to honour environmental queries can be
8321: manipulated just like any other word list.
1.21 crook 8322:
1.44 crook 8323:
1.26 crook 8324: doc-environment?
8325: doc-environment-wordlist
1.21 crook 8326:
1.26 crook 8327: doc-gforth
8328: doc-os-class
1.21 crook 8329:
1.44 crook 8330:
1.26 crook 8331: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8332: returning two items on the stack, querying it using @code{environment?}
8333: will return an additional item; the @code{true} flag that shows that the
8334: string was recognised.
1.21 crook 8335:
1.26 crook 8336: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8337:
1.26 crook 8338: Here are some examples of using environmental queries:
1.21 crook 8339:
1.26 crook 8340: @example
8341: s" address-unit-bits" environment? 0=
8342: [IF]
8343: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8344: [ELSE]
8345: drop \ ensure balanced stack effect
1.26 crook 8346: [THEN]
1.21 crook 8347:
1.75 anton 8348: \ this might occur in the prelude of a standard program that uses THROW
8349: s" exception" environment? [IF]
8350: 0= [IF]
8351: : throw abort" exception thrown" ;
8352: [THEN]
8353: [ELSE] \ we don't know, so make sure
8354: : throw abort" exception thrown" ;
8355: [THEN]
1.21 crook 8356:
1.26 crook 8357: s" gforth" environment? [IF] .( Gforth version ) TYPE
8358: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8359:
8360: \ a program using v*
8361: s" gforth" environment? [IF]
8362: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8363: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8364: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8365: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8366: LOOP
8367: 2drop 2drop ;
8368: [THEN]
8369: [ELSE] \
8370: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8371: ...
8372: [THEN]
1.26 crook 8373: @end example
1.21 crook 8374:
1.26 crook 8375: Here is an example of adding a definition to the environment word list:
1.21 crook 8376:
1.26 crook 8377: @example
8378: get-current environment-wordlist set-current
8379: true constant block
8380: true constant block-ext
8381: set-current
8382: @end example
1.21 crook 8383:
1.26 crook 8384: You can see what definitions are in the environment word list like this:
1.21 crook 8385:
1.26 crook 8386: @example
1.79 anton 8387: environment-wordlist >order words previous
1.26 crook 8388: @end example
1.21 crook 8389:
8390:
1.26 crook 8391: @c -------------------------------------------------------------
8392: @node Files, Blocks, Environmental Queries, Words
8393: @section Files
1.28 crook 8394: @cindex files
8395: @cindex I/O - file-handling
1.21 crook 8396:
1.26 crook 8397: Gforth provides facilities for accessing files that are stored in the
8398: host operating system's file-system. Files that are processed by Gforth
8399: can be divided into two categories:
1.21 crook 8400:
1.23 crook 8401: @itemize @bullet
8402: @item
1.29 crook 8403: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8404: @item
1.29 crook 8405: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8406: @end itemize
8407:
8408: @menu
1.48 anton 8409: * Forth source files::
8410: * General files::
1.167 anton 8411: * Redirection::
1.48 anton 8412: * Search Paths::
1.26 crook 8413: @end menu
8414:
8415: @c -------------------------------------------------------------
8416: @node Forth source files, General files, Files, Files
8417: @subsection Forth source files
8418: @cindex including files
8419: @cindex Forth source files
1.21 crook 8420:
1.26 crook 8421: The simplest way to interpret the contents of a file is to use one of
8422: these two formats:
1.21 crook 8423:
1.26 crook 8424: @example
8425: include mysource.fs
8426: s" mysource.fs" included
8427: @end example
1.21 crook 8428:
1.75 anton 8429: You usually want to include a file only if it is not included already
1.26 crook 8430: (by, say, another source file). In that case, you can use one of these
1.45 crook 8431: three formats:
1.21 crook 8432:
1.26 crook 8433: @example
8434: require mysource.fs
8435: needs mysource.fs
8436: s" mysource.fs" required
8437: @end example
1.21 crook 8438:
1.26 crook 8439: @cindex stack effect of included files
8440: @cindex including files, stack effect
1.45 crook 8441: It is good practice to write your source files such that interpreting them
8442: does not change the stack. Source files designed in this way can be used with
1.26 crook 8443: @code{required} and friends without complications. For example:
1.21 crook 8444:
1.26 crook 8445: @example
1.75 anton 8446: 1024 require foo.fs drop
1.26 crook 8447: @end example
1.21 crook 8448:
1.75 anton 8449: Here you want to pass the argument 1024 (e.g., a buffer size) to
8450: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8451: ), which allows its use with @code{require}. Of course with such
8452: parameters to required files, you have to ensure that the first
8453: @code{require} fits for all uses (i.e., @code{require} it early in the
8454: master load file).
1.44 crook 8455:
1.26 crook 8456: doc-include-file
8457: doc-included
1.28 crook 8458: doc-included?
1.26 crook 8459: doc-include
8460: doc-required
8461: doc-require
8462: doc-needs
1.75 anton 8463: @c doc-init-included-files @c internal
8464: doc-sourcefilename
8465: doc-sourceline#
1.44 crook 8466:
1.26 crook 8467: A definition in ANS Forth for @code{required} is provided in
8468: @file{compat/required.fs}.
1.21 crook 8469:
1.26 crook 8470: @c -------------------------------------------------------------
1.167 anton 8471: @node General files, Redirection, Forth source files, Files
1.26 crook 8472: @subsection General files
8473: @cindex general files
8474: @cindex file-handling
1.21 crook 8475:
1.75 anton 8476: Files are opened/created by name and type. The following file access
8477: methods (FAMs) are recognised:
1.44 crook 8478:
1.75 anton 8479: @cindex fam (file access method)
1.26 crook 8480: doc-r/o
8481: doc-r/w
8482: doc-w/o
8483: doc-bin
1.1 anton 8484:
1.44 crook 8485:
1.26 crook 8486: When a file is opened/created, it returns a file identifier,
1.29 crook 8487: @i{wfileid} that is used for all other file commands. All file
8488: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8489: successful operation and an implementation-defined non-zero value in the
8490: case of an error.
1.21 crook 8491:
1.44 crook 8492:
1.26 crook 8493: doc-open-file
8494: doc-create-file
1.21 crook 8495:
1.26 crook 8496: doc-close-file
8497: doc-delete-file
8498: doc-rename-file
8499: doc-read-file
8500: doc-read-line
1.154 anton 8501: doc-key-file
8502: doc-key?-file
1.26 crook 8503: doc-write-file
8504: doc-write-line
8505: doc-emit-file
8506: doc-flush-file
1.21 crook 8507:
1.26 crook 8508: doc-file-status
8509: doc-file-position
8510: doc-reposition-file
8511: doc-file-size
8512: doc-resize-file
1.21 crook 8513:
1.93 anton 8514: doc-slurp-file
8515: doc-slurp-fid
1.112 anton 8516: doc-stdin
8517: doc-stdout
8518: doc-stderr
1.44 crook 8519:
1.26 crook 8520: @c ---------------------------------------------------------
1.167 anton 8521: @node Redirection, Search Paths, General files, Files
8522: @subsection Redirection
8523: @cindex Redirection
8524: @cindex Input Redirection
8525: @cindex Output Redirection
8526:
8527: You can redirect the output of @code{type} and @code{emit} and all the
8528: words that use them (all output words that don't have an explicit
1.174 anton 8529: target file) to an arbitrary file with the @code{outfile-execute},
8530: used like this:
1.167 anton 8531:
8532: @example
1.174 anton 8533: : some-warning ( n -- )
8534: cr ." warning# " . ;
8535:
1.167 anton 8536: : print-some-warning ( n -- )
1.174 anton 8537: ['] some-warning stderr outfile-execute ;
1.167 anton 8538: @end example
8539:
1.174 anton 8540: After @code{some-warning} is executed, the original output direction
8541: is restored; this construct is safe against exceptions. Similarly,
8542: there is @code{infile-execute} for redirecting the input of @code{key}
8543: and its users (any input word that does not take a file explicitly).
8544:
8545: doc-outfile-execute
8546: doc-infile-execute
1.167 anton 8547:
8548: If you do not want to redirect the input or output to a file, you can
8549: also make use of the fact that @code{key}, @code{emit} and @code{type}
8550: are deferred words (@pxref{Deferred Words}). However, in that case
8551: you have to worry about the restoration and the protection against
8552: exceptions yourself; also, note that for redirecting the output in
8553: this way, you have to redirect both @code{emit} and @code{type}.
8554:
8555: @c ---------------------------------------------------------
8556: @node Search Paths, , Redirection, Files
1.26 crook 8557: @subsection Search Paths
8558: @cindex path for @code{included}
8559: @cindex file search path
8560: @cindex @code{include} search path
8561: @cindex search path for files
1.21 crook 8562:
1.26 crook 8563: If you specify an absolute filename (i.e., a filename starting with
8564: @file{/} or @file{~}, or with @file{:} in the second position (as in
8565: @samp{C:...})) for @code{included} and friends, that file is included
8566: just as you would expect.
1.21 crook 8567:
1.75 anton 8568: If the filename starts with @file{./}, this refers to the directory that
8569: the present file was @code{included} from. This allows files to include
8570: other files relative to their own position (irrespective of the current
8571: working directory or the absolute position). This feature is essential
8572: for libraries consisting of several files, where a file may include
8573: other files from the library. It corresponds to @code{#include "..."}
8574: in C. If the current input source is not a file, @file{.} refers to the
8575: directory of the innermost file being included, or, if there is no file
8576: being included, to the current working directory.
8577:
8578: For relative filenames (not starting with @file{./}), Gforth uses a
8579: search path similar to Forth's search order (@pxref{Word Lists}). It
8580: tries to find the given filename in the directories present in the path,
8581: and includes the first one it finds. There are separate search paths for
8582: Forth source files and general files. If the search path contains the
8583: directory @file{.}, this refers to the directory of the current file, or
8584: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8585:
1.26 crook 8586: Use @file{~+} to refer to the current working directory (as in the
8587: @code{bash}).
1.1 anton 8588:
1.75 anton 8589: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8590:
1.48 anton 8591: @menu
1.75 anton 8592: * Source Search Paths::
1.48 anton 8593: * General Search Paths::
8594: @end menu
8595:
1.26 crook 8596: @c ---------------------------------------------------------
1.75 anton 8597: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8598: @subsubsection Source Search Paths
8599: @cindex search path control, source files
1.5 anton 8600:
1.26 crook 8601: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8602: Gforth}). You can display it and change it using @code{fpath} in
8603: combination with the general path handling words.
1.5 anton 8604:
1.75 anton 8605: doc-fpath
8606: @c the functionality of the following words is easily available through
8607: @c fpath and the general path words. The may go away.
8608: @c doc-.fpath
8609: @c doc-fpath+
8610: @c doc-fpath=
8611: @c doc-open-fpath-file
1.44 crook 8612:
8613: @noindent
1.26 crook 8614: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8615:
1.26 crook 8616: @example
1.75 anton 8617: fpath path= /usr/lib/forth/|./
1.26 crook 8618: require timer.fs
8619: @end example
1.5 anton 8620:
1.75 anton 8621:
1.26 crook 8622: @c ---------------------------------------------------------
1.75 anton 8623: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8624: @subsubsection General Search Paths
1.75 anton 8625: @cindex search path control, source files
1.5 anton 8626:
1.26 crook 8627: Your application may need to search files in several directories, like
8628: @code{included} does. To facilitate this, Gforth allows you to define
8629: and use your own search paths, by providing generic equivalents of the
8630: Forth search path words:
1.5 anton 8631:
1.75 anton 8632: doc-open-path-file
8633: doc-path-allot
8634: doc-clear-path
8635: doc-also-path
1.26 crook 8636: doc-.path
8637: doc-path+
8638: doc-path=
1.5 anton 8639:
1.75 anton 8640: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8641:
1.75 anton 8642: Here's an example of creating an empty search path:
8643: @c
1.26 crook 8644: @example
1.75 anton 8645: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8646: @end example
1.5 anton 8647:
1.26 crook 8648: @c -------------------------------------------------------------
8649: @node Blocks, Other I/O, Files, Words
8650: @section Blocks
1.28 crook 8651: @cindex I/O - blocks
8652: @cindex blocks
8653:
8654: When you run Gforth on a modern desk-top computer, it runs under the
8655: control of an operating system which provides certain services. One of
8656: these services is @var{file services}, which allows Forth source code
8657: and data to be stored in files and read into Gforth (@pxref{Files}).
8658:
8659: Traditionally, Forth has been an important programming language on
8660: systems where it has interfaced directly to the underlying hardware with
8661: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8662: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8663:
8664: A block is a 1024-byte data area, which can be used to hold data or
8665: Forth source code. No structure is imposed on the contents of the
8666: block. A block is identified by its number; blocks are numbered
8667: contiguously from 1 to an implementation-defined maximum.
8668:
8669: A typical system that used blocks but no operating system might use a
8670: single floppy-disk drive for mass storage, with the disks formatted to
8671: provide 256-byte sectors. Blocks would be implemented by assigning the
8672: first four sectors of the disk to block 1, the second four sectors to
8673: block 2 and so on, up to the limit of the capacity of the disk. The disk
8674: would not contain any file system information, just the set of blocks.
8675:
1.29 crook 8676: @cindex blocks file
1.28 crook 8677: On systems that do provide file services, blocks are typically
1.29 crook 8678: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8679: file}. The size of the blocks file will be an exact multiple of 1024
8680: bytes, corresponding to the number of blocks it contains. This is the
8681: mechanism that Gforth uses.
8682:
1.29 crook 8683: @cindex @file{blocks.fb}
1.75 anton 8684: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8685: having specified a blocks file, Gforth defaults to the blocks file
8686: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8687: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8688:
1.29 crook 8689: @cindex block buffers
1.28 crook 8690: When you read and write blocks under program control, Gforth uses a
1.29 crook 8691: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8692: not used when you use @code{load} to interpret the contents of a block.
8693:
1.75 anton 8694: The behaviour of the block buffers is analagous to that of a cache.
8695: Each block buffer has three states:
1.28 crook 8696:
8697: @itemize @bullet
8698: @item
8699: Unassigned
8700: @item
8701: Assigned-clean
8702: @item
8703: Assigned-dirty
8704: @end itemize
8705:
1.29 crook 8706: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8707: block, the block (specified by its block number) must be assigned to a
8708: block buffer.
8709:
8710: The assignment of a block to a block buffer is performed by @code{block}
8711: or @code{buffer}. Use @code{block} when you wish to modify the existing
8712: contents of a block. Use @code{buffer} when you don't care about the
8713: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8714: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8715: with the particular block is already stored in a block buffer due to an
8716: earlier @code{block} command, @code{buffer} will return that block
8717: buffer and the existing contents of the block will be
8718: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8719: block buffer for the block.}.
1.28 crook 8720:
1.47 crook 8721: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8722: @code{buffer}, that block buffer becomes the @i{current block
8723: buffer}. Data may only be manipulated (read or written) within the
8724: current block buffer.
1.47 crook 8725:
8726: When the contents of the current block buffer has been modified it is
1.48 anton 8727: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8728: either abandon the changes (by doing nothing) or mark the block as
8729: changed (assigned-dirty), using @code{update}. Using @code{update} does
8730: not change the blocks file; it simply changes a block buffer's state to
8731: @i{assigned-dirty}. The block will be written implicitly when it's
8732: buffer is needed for another block, or explicitly by @code{flush} or
8733: @code{save-buffers}.
8734:
8735: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8736: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8737: @code{flush}.
1.28 crook 8738:
1.29 crook 8739: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8740: algorithm to assign a block buffer to a block. That means that any
8741: particular block can only be assigned to one specific block buffer,
1.29 crook 8742: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8743: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8744: the new block immediately. If it is @i{assigned-dirty} its current
8745: contents are written back to the blocks file on disk before it is
1.28 crook 8746: allocated to the new block.
8747:
8748: Although no structure is imposed on the contents of a block, it is
8749: traditional to display the contents as 16 lines each of 64 characters. A
8750: block provides a single, continuous stream of input (for example, it
8751: acts as a single parse area) -- there are no end-of-line characters
8752: within a block, and no end-of-file character at the end of a
8753: block. There are two consequences of this:
1.26 crook 8754:
1.28 crook 8755: @itemize @bullet
8756: @item
8757: The last character of one line wraps straight into the first character
8758: of the following line
8759: @item
8760: The word @code{\} -- comment to end of line -- requires special
8761: treatment; in the context of a block it causes all characters until the
8762: end of the current 64-character ``line'' to be ignored.
8763: @end itemize
8764:
8765: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8766: the current blocks file will be extended to the appropriate size and the
1.28 crook 8767: block buffer will be initialised with spaces.
8768:
1.47 crook 8769: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8770: for details) but doesn't encourage the use of blocks; the mechanism is
8771: only provided for backward compatibility -- ANS Forth requires blocks to
8772: be available when files are.
1.28 crook 8773:
8774: Common techniques that are used when working with blocks include:
8775:
8776: @itemize @bullet
8777: @item
8778: A screen editor that allows you to edit blocks without leaving the Forth
8779: environment.
8780: @item
8781: Shadow screens; where every code block has an associated block
8782: containing comments (for example: code in odd block numbers, comments in
8783: even block numbers). Typically, the block editor provides a convenient
8784: mechanism to toggle between code and comments.
8785: @item
8786: Load blocks; a single block (typically block 1) contains a number of
8787: @code{thru} commands which @code{load} the whole of the application.
8788: @end itemize
1.26 crook 8789:
1.29 crook 8790: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8791: integrated into a Forth programming environment.
1.26 crook 8792:
8793: @comment TODO what about errors on open-blocks?
1.44 crook 8794:
1.26 crook 8795: doc-open-blocks
8796: doc-use
1.75 anton 8797: doc-block-offset
1.26 crook 8798: doc-get-block-fid
8799: doc-block-position
1.28 crook 8800:
1.75 anton 8801: doc-list
1.28 crook 8802: doc-scr
8803:
1.184 anton 8804: doc-block
1.28 crook 8805: doc-buffer
8806:
1.75 anton 8807: doc-empty-buffers
8808: doc-empty-buffer
1.26 crook 8809: doc-update
1.28 crook 8810: doc-updated?
1.26 crook 8811: doc-save-buffers
1.75 anton 8812: doc-save-buffer
1.26 crook 8813: doc-flush
1.28 crook 8814:
1.26 crook 8815: doc-load
8816: doc-thru
8817: doc-+load
8818: doc-+thru
1.45 crook 8819: doc---gforthman--->
1.26 crook 8820: doc-block-included
8821:
1.44 crook 8822:
1.26 crook 8823: @c -------------------------------------------------------------
1.126 pazsan 8824: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8825: @section Other I/O
1.28 crook 8826: @cindex I/O - keyboard and display
1.26 crook 8827:
8828: @menu
8829: * Simple numeric output:: Predefined formats
8830: * Formatted numeric output:: Formatted (pictured) output
8831: * String Formats:: How Forth stores strings in memory
1.67 anton 8832: * Displaying characters and strings:: Other stuff
1.175 anton 8833: * Terminal output:: Cursor positioning etc.
1.181 anton 8834: * Single-key input::
8835: * Line input and conversion::
1.112 anton 8836: * Pipes:: How to create your own pipes
1.149 pazsan 8837: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8838: @end menu
8839:
8840: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8841: @subsection Simple numeric output
1.28 crook 8842: @cindex numeric output - simple/free-format
1.5 anton 8843:
1.26 crook 8844: The simplest output functions are those that display numbers from the
8845: data or floating-point stacks. Floating-point output is always displayed
8846: using base 10. Numbers displayed from the data stack use the value stored
8847: in @code{base}.
1.5 anton 8848:
1.44 crook 8849:
1.26 crook 8850: doc-.
8851: doc-dec.
8852: doc-hex.
8853: doc-u.
8854: doc-.r
8855: doc-u.r
8856: doc-d.
8857: doc-ud.
8858: doc-d.r
8859: doc-ud.r
8860: doc-f.
8861: doc-fe.
8862: doc-fs.
1.111 anton 8863: doc-f.rdp
1.44 crook 8864:
1.26 crook 8865: Examples of printing the number 1234.5678E23 in the different floating-point output
8866: formats are shown below:
1.5 anton 8867:
8868: @example
1.26 crook 8869: f. 123456779999999000000000000.
8870: fe. 123.456779999999E24
8871: fs. 1.23456779999999E26
1.5 anton 8872: @end example
8873:
8874:
1.26 crook 8875: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8876: @subsection Formatted numeric output
1.28 crook 8877: @cindex formatted numeric output
1.26 crook 8878: @cindex pictured numeric output
1.28 crook 8879: @cindex numeric output - formatted
1.26 crook 8880:
1.29 crook 8881: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8882: output} for formatted printing of integers. In this technique, digits
8883: are extracted from the number (using the current output radix defined by
8884: @code{base}), converted to ASCII codes and appended to a string that is
8885: built in a scratch-pad area of memory (@pxref{core-idef,
8886: Implementation-defined options, Implementation-defined
8887: options}). Arbitrary characters can be appended to the string during the
8888: extraction process. The completed string is specified by an address
8889: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8890: under program control.
1.5 anton 8891:
1.75 anton 8892: All of the integer output words described in the previous section
8893: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8894: numeric output.
1.5 anton 8895:
1.47 crook 8896: Three important things to remember about pictured numeric output:
1.5 anton 8897:
1.26 crook 8898: @itemize @bullet
8899: @item
1.28 crook 8900: It always operates on double-precision numbers; to display a
1.49 anton 8901: single-precision number, convert it first (for ways of doing this
8902: @pxref{Double precision}).
1.26 crook 8903: @item
1.28 crook 8904: It always treats the double-precision number as though it were
8905: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8906: @item
8907: The string is built up from right to left; least significant digit first.
8908: @end itemize
1.5 anton 8909:
1.44 crook 8910:
1.26 crook 8911: doc-<#
1.47 crook 8912: doc-<<#
1.26 crook 8913: doc-#
8914: doc-#s
8915: doc-hold
8916: doc-sign
8917: doc-#>
1.47 crook 8918: doc-#>>
1.5 anton 8919:
1.26 crook 8920: doc-represent
1.111 anton 8921: doc-f>str-rdp
8922: doc-f>buf-rdp
1.5 anton 8923:
1.44 crook 8924:
8925: @noindent
1.26 crook 8926: Here are some examples of using pictured numeric output:
1.5 anton 8927:
8928: @example
1.26 crook 8929: : my-u. ( u -- )
8930: \ Simplest use of pns.. behaves like Standard u.
8931: 0 \ convert to unsigned double
1.75 anton 8932: <<# \ start conversion
1.26 crook 8933: #s \ convert all digits
8934: #> \ complete conversion
1.75 anton 8935: TYPE SPACE \ display, with trailing space
8936: #>> ; \ release hold area
1.5 anton 8937:
1.26 crook 8938: : cents-only ( u -- )
8939: 0 \ convert to unsigned double
1.75 anton 8940: <<# \ start conversion
1.26 crook 8941: # # \ convert two least-significant digits
8942: #> \ complete conversion, discard other digits
1.75 anton 8943: TYPE SPACE \ display, with trailing space
8944: #>> ; \ release hold area
1.5 anton 8945:
1.26 crook 8946: : dollars-and-cents ( u -- )
8947: 0 \ convert to unsigned double
1.75 anton 8948: <<# \ start conversion
1.26 crook 8949: # # \ convert two least-significant digits
8950: [char] . hold \ insert decimal point
8951: #s \ convert remaining digits
8952: [char] $ hold \ append currency symbol
8953: #> \ complete conversion
1.75 anton 8954: TYPE SPACE \ display, with trailing space
8955: #>> ; \ release hold area
1.5 anton 8956:
1.26 crook 8957: : my-. ( n -- )
8958: \ handling negatives.. behaves like Standard .
8959: s>d \ convert to signed double
8960: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8961: <<# \ start conversion
1.26 crook 8962: #s \ convert all digits
8963: rot sign \ get at sign byte, append "-" if needed
8964: #> \ complete conversion
1.75 anton 8965: TYPE SPACE \ display, with trailing space
8966: #>> ; \ release hold area
1.5 anton 8967:
1.26 crook 8968: : account. ( n -- )
1.75 anton 8969: \ accountants don't like minus signs, they use parentheses
1.26 crook 8970: \ for negative numbers
8971: s>d \ convert to signed double
8972: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8973: <<# \ start conversion
1.26 crook 8974: 2 pick \ get copy of sign byte
8975: 0< IF [char] ) hold THEN \ right-most character of output
8976: #s \ convert all digits
8977: rot \ get at sign byte
8978: 0< IF [char] ( hold THEN
8979: #> \ complete conversion
1.75 anton 8980: TYPE SPACE \ display, with trailing space
8981: #>> ; \ release hold area
8982:
1.5 anton 8983: @end example
8984:
1.26 crook 8985: Here are some examples of using these words:
1.5 anton 8986:
8987: @example
1.26 crook 8988: 1 my-u. 1
8989: hex -1 my-u. decimal FFFFFFFF
8990: 1 cents-only 01
8991: 1234 cents-only 34
8992: 2 dollars-and-cents $0.02
8993: 1234 dollars-and-cents $12.34
8994: 123 my-. 123
8995: -123 my. -123
8996: 123 account. 123
8997: -456 account. (456)
1.5 anton 8998: @end example
8999:
9000:
1.26 crook 9001: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
9002: @subsection String Formats
1.27 crook 9003: @cindex strings - see character strings
9004: @cindex character strings - formats
1.28 crook 9005: @cindex I/O - see character strings
1.75 anton 9006: @cindex counted strings
9007:
9008: @c anton: this does not really belong here; maybe the memory section,
9009: @c or the principles chapter
1.26 crook 9010:
1.27 crook 9011: Forth commonly uses two different methods for representing character
9012: strings:
1.26 crook 9013:
9014: @itemize @bullet
9015: @item
9016: @cindex address of counted string
1.45 crook 9017: @cindex counted string
1.29 crook 9018: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9019: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9020: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9021: memory.
9022: @item
1.29 crook 9023: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9024: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9025: first byte of the string.
9026: @end itemize
9027:
9028: ANS Forth encourages the use of the second format when representing
1.75 anton 9029: strings.
1.26 crook 9030:
1.44 crook 9031:
1.26 crook 9032: doc-count
9033:
1.44 crook 9034:
1.49 anton 9035: For words that move, copy and search for strings see @ref{Memory
9036: Blocks}. For words that display characters and strings see
9037: @ref{Displaying characters and strings}.
1.26 crook 9038:
1.175 anton 9039: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9040: @subsection Displaying characters and strings
1.27 crook 9041: @cindex characters - compiling and displaying
9042: @cindex character strings - compiling and displaying
1.26 crook 9043:
9044: This section starts with a glossary of Forth words and ends with a set
9045: of examples.
9046:
9047: doc-bl
9048: doc-space
9049: doc-spaces
9050: doc-emit
9051: doc-toupper
9052: doc-."
9053: doc-.(
1.98 anton 9054: doc-.\"
1.26 crook 9055: doc-type
1.44 crook 9056: doc-typewhite
1.26 crook 9057: doc-cr
1.27 crook 9058: @cindex cursor control
1.26 crook 9059: doc-s"
1.98 anton 9060: doc-s\"
1.26 crook 9061: doc-c"
9062: doc-char
9063: doc-[char]
9064:
1.44 crook 9065:
9066: @noindent
1.26 crook 9067: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9068:
9069: @example
1.26 crook 9070: .( text-1)
9071: : my-word
9072: ." text-2" cr
9073: .( text-3)
9074: ;
9075:
9076: ." text-4"
9077:
9078: : my-char
9079: [char] ALPHABET emit
9080: char emit
9081: ;
1.5 anton 9082: @end example
9083:
1.26 crook 9084: When you load this code into Gforth, the following output is generated:
1.5 anton 9085:
1.26 crook 9086: @example
1.30 anton 9087: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9088: @end example
1.5 anton 9089:
1.26 crook 9090: @itemize @bullet
9091: @item
9092: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9093: is an immediate word; it behaves in the same way whether it is used inside
9094: or outside a colon definition.
9095: @item
9096: Message @code{text-4} is displayed because of Gforth's added interpretation
9097: semantics for @code{."}.
9098: @item
1.29 crook 9099: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9100: performs the compilation semantics for @code{."} within the definition of
9101: @code{my-word}.
9102: @end itemize
1.5 anton 9103:
1.26 crook 9104: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9105:
1.26 crook 9106: @example
1.30 anton 9107: @kbd{my-word @key{RET}} text-2
1.26 crook 9108: ok
1.30 anton 9109: @kbd{my-char fred @key{RET}} Af ok
9110: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9111: @end example
1.5 anton 9112:
9113: @itemize @bullet
9114: @item
1.26 crook 9115: Message @code{text-2} is displayed because of the run-time behaviour of
9116: @code{."}.
9117: @item
9118: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9119: on the stack at run-time. @code{emit} always displays the character
9120: when @code{my-char} is executed.
9121: @item
9122: @code{char} parses a string at run-time and the second @code{emit} displays
9123: the first character of the string.
1.5 anton 9124: @item
1.26 crook 9125: If you type @code{see my-char} you can see that @code{[char]} discarded
9126: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9127: definition of @code{my-char}.
1.5 anton 9128: @end itemize
9129:
9130:
1.181 anton 9131: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9132: @subsection Terminal output
9133: @cindex output to terminal
9134: @cindex terminal output
9135:
9136: If you are outputting to a terminal, you may want to control the
9137: positioning of the cursor:
9138: @cindex cursor positioning
9139:
9140: doc-at-xy
9141:
9142: In order to know where to position the cursor, it is often helpful to
9143: know the size of the screen:
9144: @cindex terminal size
9145:
9146: doc-form
9147:
9148: And sometimes you want to use:
9149: @cindex clear screen
9150:
9151: doc-page
9152:
9153: Note that on non-terminals you should use @code{12 emit}, not
9154: @code{page}, to get a form feed.
9155:
1.5 anton 9156:
1.181 anton 9157: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9158: @subsection Single-key input
9159: @cindex single-key input
9160: @cindex input, single-key
9161:
9162: If you want to get a single printable character, you can use
9163: @code{key}; to check whether a character is available for @code{key},
9164: you can use @code{key?}.
1.5 anton 9165:
1.181 anton 9166: doc-key
9167: doc-key?
1.27 crook 9168:
1.181 anton 9169: If you want to process a mix of printable and non-printable
9170: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9171: produces a keyboard event that you have to convert into a character
9172: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9173:
9174: Typical code for using EKEY looks like this:
9175:
9176: @example
9177: ekey ekey>char if ( c )
9178: ... \ do something with the character
9179: else ekey>fkey if ( key-id )
9180: case
9181: k-up of ... endof
9182: k-f1 of ... endof
9183: k-left k-shift-mask or k-ctrl-mask or of ... endof
9184: ...
9185: endcase
9186: else ( keyboard-event )
9187: drop \ just ignore an unknown keyboard event type
9188: then then
9189: @end example
1.44 crook 9190:
1.45 crook 9191: doc-ekey
1.141 anton 9192: doc-ekey>char
1.181 anton 9193: doc-ekey>fkey
1.45 crook 9194: doc-ekey?
1.141 anton 9195:
1.181 anton 9196: The key identifiers for cursor keys are:
1.141 anton 9197:
9198: doc-k-left
9199: doc-k-right
1.185 anton 9200: doc-k-up
9201: doc-k-down
9202: doc-k-home
9203: doc-k-end
1.141 anton 9204: doc-k-prior
9205: doc-k-next
9206: doc-k-insert
9207: doc-k-delete
9208:
1.181 anton 9209: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9210:
1.181 anton 9211: doc-k-f1
9212: doc-k-f2
9213: doc-k-f3
9214: doc-k-f4
9215: doc-k-f5
9216: doc-k-f6
9217: doc-k-f7
9218: doc-k-f8
9219: doc-k-f9
9220: doc-k-f10
9221: doc-k-f11
9222: doc-k-f12
9223:
9224: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9225:
9226: You can combine these key identifiers with masks for various shift keys:
9227:
9228: doc-k-shift-mask
9229: doc-k-ctrl-mask
9230: doc-k-alt-mask
9231:
9232: Note that, even if a Forth system has @code{ekey>fkey} and the key
9233: identifier words, the keys are not necessarily available or it may not
9234: necessarily be able to report all the keys and all the possible
9235: combinations with shift masks. Therefore, write your programs in such
9236: a way that they are still useful even if the keys and key combinations
9237: cannot be pressed or are not recognized.
9238:
9239: Examples: Older keyboards often do not have an F11 and F12 key. If
9240: you run Gforth in an xterm, the xterm catches a number of combinations
9241: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9242: Gforth currently does not recognize and report combinations with
9243: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9244: above would never be entered).
9245:
9246: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9247: you need the ANSI.SYS driver to get that behaviour); it works by
9248: recognizing the escape sequences that ANSI terminals send when such a
9249: key is pressed. If you have a terminal that sends other escape
9250: sequences, you will not get useful results on Gforth. Other Forth
9251: systems may work in a different way.
9252:
1.200 anton 9253: Gforth also provides a few words for outputting names of function
9254: keys:
9255:
9256: doc-fkey.
9257: doc-simple-fkey-string
9258:
1.181 anton 9259:
9260: @node Line input and conversion, Pipes, Single-key input, Other I/O
9261: @subsection Line input and conversion
9262: @cindex line input from terminal
9263: @cindex input, linewise from terminal
9264: @cindex convertin strings to numbers
9265: @cindex I/O - see input
9266:
9267: For ways of storing character strings in memory see @ref{String Formats}.
9268:
9269: @comment TODO examples for >number >float accept key key? pad parse word refill
9270: @comment then index them
1.141 anton 9271:
9272: Words for inputting one line from the keyboard:
9273:
9274: doc-accept
9275: doc-edit-line
9276:
9277: Conversion words:
9278:
1.143 anton 9279: doc-s>number?
9280: doc-s>unumber?
1.26 crook 9281: doc->number
9282: doc->float
1.143 anton 9283:
1.141 anton 9284:
1.27 crook 9285: @comment obsolescent words..
1.141 anton 9286: Obsolescent input and conversion words:
9287:
1.27 crook 9288: doc-convert
1.26 crook 9289: doc-expect
1.27 crook 9290: doc-span
1.5 anton 9291:
9292:
1.181 anton 9293: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9294: @subsection Pipes
9295: @cindex pipes, creating your own
9296:
9297: In addition to using Gforth in pipes created by other processes
9298: (@pxref{Gforth in pipes}), you can create your own pipe with
9299: @code{open-pipe}, and read from or write to it.
9300:
9301: doc-open-pipe
9302: doc-close-pipe
9303:
9304: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9305: you don't catch this exception, Gforth will catch it and exit, usually
9306: silently (@pxref{Gforth in pipes}). Since you probably do not want
9307: this, you should wrap a @code{catch} or @code{try} block around the code
9308: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9309: problem yourself, and then return to regular processing.
9310:
9311: doc-broken-pipe-error
9312:
1.155 anton 9313: @node Xchars and Unicode, , Pipes, Other I/O
9314: @subsection Xchars and Unicode
1.149 pazsan 9315:
1.188 pazsan 9316: ASCII is only appropriate for the English language. Most western
9317: languages however fit somewhat into the Forth frame, since a byte is
9318: sufficient to encode the few special characters in each (though not
9319: always the same encoding can be used; latin-1 is most widely used,
9320: though). For other languages, different char-sets have to be used,
9321: several of them variable-width. Most prominent representant is
9322: UTF-8. Let's call these extended characters xchars. The primitive
9323: fixed-size characters stored as bytes are called pchars in this
9324: section.
9325:
9326: The xchar words add a few data types:
9327:
9328: @itemize
9329:
9330: @item
9331: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9332: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9333: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9334: character set can be used.
9335:
9336: @item
9337: @var{xc-addr} is the address of an xchar in memory. Alignment
9338: requirements are the same as @var{c-addr}. The memory representation of an
9339: xchar differs from the stack representation, and depends on the
9340: encoding used. An xchar may use a variable number of pchars in memory.
9341:
9342: @item
9343: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9344: @var{xc-addr}, @var{u} pchars long.
9345:
9346: @end itemize
9347:
9348: doc-xc-size
9349: doc-x-size
9350: doc-xc@+
9351: doc-xc!+?
9352: doc-xchar+
9353: doc-xchar-
9354: doc-+x/string
9355: doc-x\string-
9356: doc--trailing-garbage
9357: doc-x-width
9358: doc-xkey
9359: doc-xemit
9360:
9361: There's a new environment query
9362:
9363: doc-xchar-encoding
1.112 anton 9364:
1.121 anton 9365: @node OS command line arguments, Locals, Other I/O, Words
9366: @section OS command line arguments
9367: @cindex OS command line arguments
9368: @cindex command line arguments, OS
9369: @cindex arguments, OS command line
9370:
9371: The usual way to pass arguments to Gforth programs on the command line
9372: is via the @option{-e} option, e.g.
9373:
9374: @example
9375: gforth -e "123 456" foo.fs -e bye
9376: @end example
9377:
9378: However, you may want to interpret the command-line arguments directly.
9379: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9380: through @code{next-arg}:
1.121 anton 9381:
1.123 anton 9382: doc-next-arg
1.121 anton 9383:
1.123 anton 9384: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9385:
9386: @example
9387: : echo ( -- )
1.122 anton 9388: begin
1.123 anton 9389: next-arg 2dup 0 0 d<> while
9390: type space
9391: repeat
9392: 2drop ;
1.121 anton 9393:
9394: echo cr bye
9395: @end example
9396:
9397: This can be invoked with
9398:
9399: @example
9400: gforth echo.fs hello world
9401: @end example
1.123 anton 9402:
9403: and it will print
9404:
9405: @example
9406: hello world
9407: @end example
9408:
9409: The next lower level of dealing with the OS command line are the
9410: following words:
9411:
9412: doc-arg
9413: doc-shift-args
9414:
9415: Finally, at the lowest level Gforth provides the following words:
9416:
9417: doc-argc
9418: doc-argv
1.121 anton 9419:
1.78 anton 9420: @c -------------------------------------------------------------
1.126 pazsan 9421: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9422: @section Locals
9423: @cindex locals
9424:
9425: Local variables can make Forth programming more enjoyable and Forth
9426: programs easier to read. Unfortunately, the locals of ANS Forth are
9427: laden with restrictions. Therefore, we provide not only the ANS Forth
9428: locals wordset, but also our own, more powerful locals wordset (we
9429: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9430:
1.78 anton 9431: The ideas in this section have also been published in M. Anton Ertl,
9432: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9433: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9434:
9435: @menu
1.78 anton 9436: * Gforth locals::
9437: * ANS Forth locals::
1.5 anton 9438: @end menu
9439:
1.78 anton 9440: @node Gforth locals, ANS Forth locals, Locals, Locals
9441: @subsection Gforth locals
9442: @cindex Gforth locals
9443: @cindex locals, Gforth style
1.5 anton 9444:
1.78 anton 9445: Locals can be defined with
1.44 crook 9446:
1.78 anton 9447: @example
9448: @{ local1 local2 ... -- comment @}
9449: @end example
9450: or
9451: @example
9452: @{ local1 local2 ... @}
9453: @end example
1.5 anton 9454:
1.78 anton 9455: E.g.,
9456: @example
9457: : max @{ n1 n2 -- n3 @}
9458: n1 n2 > if
9459: n1
9460: else
9461: n2
9462: endif ;
9463: @end example
1.44 crook 9464:
1.78 anton 9465: The similarity of locals definitions with stack comments is intended. A
9466: locals definition often replaces the stack comment of a word. The order
9467: of the locals corresponds to the order in a stack comment and everything
9468: after the @code{--} is really a comment.
1.77 anton 9469:
1.78 anton 9470: This similarity has one disadvantage: It is too easy to confuse locals
9471: declarations with stack comments, causing bugs and making them hard to
9472: find. However, this problem can be avoided by appropriate coding
9473: conventions: Do not use both notations in the same program. If you do,
9474: they should be distinguished using additional means, e.g. by position.
1.77 anton 9475:
1.78 anton 9476: @cindex types of locals
9477: @cindex locals types
9478: The name of the local may be preceded by a type specifier, e.g.,
9479: @code{F:} for a floating point value:
1.5 anton 9480:
1.78 anton 9481: @example
9482: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9483: \ complex multiplication
9484: Ar Br f* Ai Bi f* f-
9485: Ar Bi f* Ai Br f* f+ ;
9486: @end example
1.44 crook 9487:
1.78 anton 9488: @cindex flavours of locals
9489: @cindex locals flavours
9490: @cindex value-flavoured locals
9491: @cindex variable-flavoured locals
9492: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9493: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9494: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9495: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9496: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9497: produces its address (which becomes invalid when the variable's scope is
9498: left). E.g., the standard word @code{emit} can be defined in terms of
9499: @code{type} like this:
1.5 anton 9500:
1.78 anton 9501: @example
9502: : emit @{ C^ char* -- @}
9503: char* 1 type ;
9504: @end example
1.5 anton 9505:
1.78 anton 9506: @cindex default type of locals
9507: @cindex locals, default type
9508: A local without type specifier is a @code{W:} local. Both flavours of
9509: locals are initialized with values from the data or FP stack.
1.44 crook 9510:
1.78 anton 9511: Currently there is no way to define locals with user-defined data
9512: structures, but we are working on it.
1.5 anton 9513:
1.78 anton 9514: Gforth allows defining locals everywhere in a colon definition. This
9515: poses the following questions:
1.5 anton 9516:
1.78 anton 9517: @menu
9518: * Where are locals visible by name?::
9519: * How long do locals live?::
9520: * Locals programming style::
9521: * Locals implementation::
9522: @end menu
1.44 crook 9523:
1.78 anton 9524: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9525: @subsubsection Where are locals visible by name?
9526: @cindex locals visibility
9527: @cindex visibility of locals
9528: @cindex scope of locals
1.5 anton 9529:
1.78 anton 9530: Basically, the answer is that locals are visible where you would expect
9531: it in block-structured languages, and sometimes a little longer. If you
9532: want to restrict the scope of a local, enclose its definition in
9533: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9534:
9535:
1.78 anton 9536: doc-scope
9537: doc-endscope
1.5 anton 9538:
9539:
1.78 anton 9540: These words behave like control structure words, so you can use them
9541: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9542: arbitrary ways.
1.77 anton 9543:
1.78 anton 9544: If you want a more exact answer to the visibility question, here's the
9545: basic principle: A local is visible in all places that can only be
9546: reached through the definition of the local@footnote{In compiler
9547: construction terminology, all places dominated by the definition of the
9548: local.}. In other words, it is not visible in places that can be reached
9549: without going through the definition of the local. E.g., locals defined
9550: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9551: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9552: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9553:
1.78 anton 9554: The reasoning behind this solution is: We want to have the locals
9555: visible as long as it is meaningful. The user can always make the
9556: visibility shorter by using explicit scoping. In a place that can
9557: only be reached through the definition of a local, the meaning of a
9558: local name is clear. In other places it is not: How is the local
9559: initialized at the control flow path that does not contain the
9560: definition? Which local is meant, if the same name is defined twice in
9561: two independent control flow paths?
1.77 anton 9562:
1.78 anton 9563: This should be enough detail for nearly all users, so you can skip the
9564: rest of this section. If you really must know all the gory details and
9565: options, read on.
1.77 anton 9566:
1.78 anton 9567: In order to implement this rule, the compiler has to know which places
9568: are unreachable. It knows this automatically after @code{AHEAD},
9569: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9570: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9571: compiler that the control flow never reaches that place. If
9572: @code{UNREACHABLE} is not used where it could, the only consequence is
9573: that the visibility of some locals is more limited than the rule above
9574: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9575: lie to the compiler), buggy code will be produced.
1.77 anton 9576:
1.5 anton 9577:
1.78 anton 9578: doc-unreachable
1.5 anton 9579:
1.23 crook 9580:
1.78 anton 9581: Another problem with this rule is that at @code{BEGIN}, the compiler
9582: does not know which locals will be visible on the incoming
9583: back-edge. All problems discussed in the following are due to this
9584: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9585: loops as examples; the discussion also applies to @code{?DO} and other
9586: loops). Perhaps the most insidious example is:
1.26 crook 9587: @example
1.78 anton 9588: AHEAD
9589: BEGIN
9590: x
9591: [ 1 CS-ROLL ] THEN
9592: @{ x @}
9593: ...
9594: UNTIL
1.26 crook 9595: @end example
1.23 crook 9596:
1.78 anton 9597: This should be legal according to the visibility rule. The use of
9598: @code{x} can only be reached through the definition; but that appears
9599: textually below the use.
9600:
9601: From this example it is clear that the visibility rules cannot be fully
9602: implemented without major headaches. Our implementation treats common
9603: cases as advertised and the exceptions are treated in a safe way: The
9604: compiler makes a reasonable guess about the locals visible after a
9605: @code{BEGIN}; if it is too pessimistic, the
9606: user will get a spurious error about the local not being defined; if the
9607: compiler is too optimistic, it will notice this later and issue a
9608: warning. In the case above the compiler would complain about @code{x}
9609: being undefined at its use. You can see from the obscure examples in
9610: this section that it takes quite unusual control structures to get the
9611: compiler into trouble, and even then it will often do fine.
1.23 crook 9612:
1.78 anton 9613: If the @code{BEGIN} is reachable from above, the most optimistic guess
9614: is that all locals visible before the @code{BEGIN} will also be
9615: visible after the @code{BEGIN}. This guess is valid for all loops that
9616: are entered only through the @code{BEGIN}, in particular, for normal
9617: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9618: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9619: compiler. When the branch to the @code{BEGIN} is finally generated by
9620: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9621: warns the user if it was too optimistic:
1.26 crook 9622: @example
1.78 anton 9623: IF
9624: @{ x @}
9625: BEGIN
9626: \ x ?
9627: [ 1 cs-roll ] THEN
9628: ...
9629: UNTIL
1.26 crook 9630: @end example
1.23 crook 9631:
1.78 anton 9632: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9633: optimistically assumes that it lives until the @code{THEN}. It notices
9634: this difference when it compiles the @code{UNTIL} and issues a
9635: warning. The user can avoid the warning, and make sure that @code{x}
9636: is not used in the wrong area by using explicit scoping:
9637: @example
9638: IF
9639: SCOPE
9640: @{ x @}
9641: ENDSCOPE
9642: BEGIN
9643: [ 1 cs-roll ] THEN
9644: ...
9645: UNTIL
9646: @end example
1.23 crook 9647:
1.78 anton 9648: Since the guess is optimistic, there will be no spurious error messages
9649: about undefined locals.
1.44 crook 9650:
1.78 anton 9651: If the @code{BEGIN} is not reachable from above (e.g., after
9652: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9653: optimistic guess, as the locals visible after the @code{BEGIN} may be
9654: defined later. Therefore, the compiler assumes that no locals are
9655: visible after the @code{BEGIN}. However, the user can use
9656: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9657: visible at the BEGIN as at the point where the top control-flow stack
9658: item was created.
1.23 crook 9659:
1.44 crook 9660:
1.78 anton 9661: doc-assume-live
1.26 crook 9662:
1.23 crook 9663:
1.78 anton 9664: @noindent
9665: E.g.,
9666: @example
9667: @{ x @}
9668: AHEAD
9669: ASSUME-LIVE
9670: BEGIN
9671: x
9672: [ 1 CS-ROLL ] THEN
9673: ...
9674: UNTIL
9675: @end example
1.44 crook 9676:
1.78 anton 9677: Other cases where the locals are defined before the @code{BEGIN} can be
9678: handled by inserting an appropriate @code{CS-ROLL} before the
9679: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9680: behind the @code{ASSUME-LIVE}).
1.23 crook 9681:
1.78 anton 9682: Cases where locals are defined after the @code{BEGIN} (but should be
9683: visible immediately after the @code{BEGIN}) can only be handled by
9684: rearranging the loop. E.g., the ``most insidious'' example above can be
9685: arranged into:
9686: @example
9687: BEGIN
9688: @{ x @}
9689: ... 0=
9690: WHILE
9691: x
9692: REPEAT
9693: @end example
1.44 crook 9694:
1.78 anton 9695: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9696: @subsubsection How long do locals live?
9697: @cindex locals lifetime
9698: @cindex lifetime of locals
1.23 crook 9699:
1.78 anton 9700: The right answer for the lifetime question would be: A local lives at
9701: least as long as it can be accessed. For a value-flavoured local this
9702: means: until the end of its visibility. However, a variable-flavoured
9703: local could be accessed through its address far beyond its visibility
9704: scope. Ultimately, this would mean that such locals would have to be
9705: garbage collected. Since this entails un-Forth-like implementation
9706: complexities, I adopted the same cowardly solution as some other
9707: languages (e.g., C): The local lives only as long as it is visible;
9708: afterwards its address is invalid (and programs that access it
9709: afterwards are erroneous).
1.23 crook 9710:
1.78 anton 9711: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9712: @subsubsection Locals programming style
9713: @cindex locals programming style
9714: @cindex programming style, locals
1.23 crook 9715:
1.78 anton 9716: The freedom to define locals anywhere has the potential to change
9717: programming styles dramatically. In particular, the need to use the
9718: return stack for intermediate storage vanishes. Moreover, all stack
9719: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9720: determined arguments) can be eliminated: If the stack items are in the
9721: wrong order, just write a locals definition for all of them; then
9722: write the items in the order you want.
1.23 crook 9723:
1.78 anton 9724: This seems a little far-fetched and eliminating stack manipulations is
9725: unlikely to become a conscious programming objective. Still, the number
9726: of stack manipulations will be reduced dramatically if local variables
9727: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9728: a traditional implementation of @code{max}).
1.23 crook 9729:
1.78 anton 9730: This shows one potential benefit of locals: making Forth programs more
9731: readable. Of course, this benefit will only be realized if the
9732: programmers continue to honour the principle of factoring instead of
9733: using the added latitude to make the words longer.
1.23 crook 9734:
1.78 anton 9735: @cindex single-assignment style for locals
9736: Using @code{TO} can and should be avoided. Without @code{TO},
9737: every value-flavoured local has only a single assignment and many
9738: advantages of functional languages apply to Forth. I.e., programs are
9739: easier to analyse, to optimize and to read: It is clear from the
9740: definition what the local stands for, it does not turn into something
9741: different later.
1.23 crook 9742:
1.78 anton 9743: E.g., a definition using @code{TO} might look like this:
9744: @example
9745: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9746: u1 u2 min 0
9747: ?do
9748: addr1 c@@ addr2 c@@ -
9749: ?dup-if
9750: unloop exit
9751: then
9752: addr1 char+ TO addr1
9753: addr2 char+ TO addr2
9754: loop
9755: u1 u2 - ;
1.26 crook 9756: @end example
1.78 anton 9757: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9758: every loop iteration. @code{strcmp} is a typical example of the
9759: readability problems of using @code{TO}. When you start reading
9760: @code{strcmp}, you think that @code{addr1} refers to the start of the
9761: string. Only near the end of the loop you realize that it is something
9762: else.
1.23 crook 9763:
1.78 anton 9764: This can be avoided by defining two locals at the start of the loop that
9765: are initialized with the right value for the current iteration.
9766: @example
9767: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9768: addr1 addr2
9769: u1 u2 min 0
9770: ?do @{ s1 s2 @}
9771: s1 c@@ s2 c@@ -
9772: ?dup-if
9773: unloop exit
9774: then
9775: s1 char+ s2 char+
9776: loop
9777: 2drop
9778: u1 u2 - ;
9779: @end example
9780: Here it is clear from the start that @code{s1} has a different value
9781: in every loop iteration.
1.23 crook 9782:
1.78 anton 9783: @node Locals implementation, , Locals programming style, Gforth locals
9784: @subsubsection Locals implementation
9785: @cindex locals implementation
9786: @cindex implementation of locals
1.23 crook 9787:
1.78 anton 9788: @cindex locals stack
9789: Gforth uses an extra locals stack. The most compelling reason for
9790: this is that the return stack is not float-aligned; using an extra stack
9791: also eliminates the problems and restrictions of using the return stack
9792: as locals stack. Like the other stacks, the locals stack grows toward
9793: lower addresses. A few primitives allow an efficient implementation:
9794:
9795:
9796: doc-@local#
9797: doc-f@local#
9798: doc-laddr#
9799: doc-lp+!#
9800: doc-lp!
9801: doc->l
9802: doc-f>l
9803:
9804:
9805: In addition to these primitives, some specializations of these
9806: primitives for commonly occurring inline arguments are provided for
9807: efficiency reasons, e.g., @code{@@local0} as specialization of
9808: @code{@@local#} for the inline argument 0. The following compiling words
9809: compile the right specialized version, or the general version, as
9810: appropriate:
1.23 crook 9811:
1.5 anton 9812:
1.107 dvdkhlng 9813: @c doc-compile-@local
9814: @c doc-compile-f@local
1.78 anton 9815: doc-compile-lp+!
1.5 anton 9816:
9817:
1.78 anton 9818: Combinations of conditional branches and @code{lp+!#} like
9819: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9820: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9821:
1.78 anton 9822: A special area in the dictionary space is reserved for keeping the
9823: local variable names. @code{@{} switches the dictionary pointer to this
9824: area and @code{@}} switches it back and generates the locals
9825: initializing code. @code{W:} etc.@ are normal defining words. This
9826: special area is cleared at the start of every colon definition.
1.5 anton 9827:
1.78 anton 9828: @cindex word list for defining locals
9829: A special feature of Gforth's dictionary is used to implement the
9830: definition of locals without type specifiers: every word list (aka
9831: vocabulary) has its own methods for searching
9832: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9833: with a special search method: When it is searched for a word, it
9834: actually creates that word using @code{W:}. @code{@{} changes the search
9835: order to first search the word list containing @code{@}}, @code{W:} etc.,
9836: and then the word list for defining locals without type specifiers.
1.5 anton 9837:
1.78 anton 9838: The lifetime rules support a stack discipline within a colon
9839: definition: The lifetime of a local is either nested with other locals
9840: lifetimes or it does not overlap them.
1.23 crook 9841:
1.78 anton 9842: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9843: pointer manipulation is generated. Between control structure words
9844: locals definitions can push locals onto the locals stack. @code{AGAIN}
9845: is the simplest of the other three control flow words. It has to
9846: restore the locals stack depth of the corresponding @code{BEGIN}
9847: before branching. The code looks like this:
9848: @format
9849: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9850: @code{branch} <begin>
9851: @end format
1.26 crook 9852:
1.78 anton 9853: @code{UNTIL} is a little more complicated: If it branches back, it
9854: must adjust the stack just like @code{AGAIN}. But if it falls through,
9855: the locals stack must not be changed. The compiler generates the
9856: following code:
9857: @format
9858: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9859: @end format
9860: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9861:
1.78 anton 9862: @code{THEN} can produce somewhat inefficient code:
9863: @format
9864: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9865: <orig target>:
9866: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9867: @end format
9868: The second @code{lp+!#} adjusts the locals stack pointer from the
9869: level at the @i{orig} point to the level after the @code{THEN}. The
9870: first @code{lp+!#} adjusts the locals stack pointer from the current
9871: level to the level at the orig point, so the complete effect is an
9872: adjustment from the current level to the right level after the
9873: @code{THEN}.
1.26 crook 9874:
1.78 anton 9875: @cindex locals information on the control-flow stack
9876: @cindex control-flow stack items, locals information
9877: In a conventional Forth implementation a dest control-flow stack entry
9878: is just the target address and an orig entry is just the address to be
9879: patched. Our locals implementation adds a word list to every orig or dest
9880: item. It is the list of locals visible (or assumed visible) at the point
9881: described by the entry. Our implementation also adds a tag to identify
9882: the kind of entry, in particular to differentiate between live and dead
9883: (reachable and unreachable) orig entries.
1.26 crook 9884:
1.78 anton 9885: A few unusual operations have to be performed on locals word lists:
1.44 crook 9886:
1.5 anton 9887:
1.78 anton 9888: doc-common-list
9889: doc-sub-list?
9890: doc-list-size
1.52 anton 9891:
9892:
1.78 anton 9893: Several features of our locals word list implementation make these
9894: operations easy to implement: The locals word lists are organised as
9895: linked lists; the tails of these lists are shared, if the lists
9896: contain some of the same locals; and the address of a name is greater
9897: than the address of the names behind it in the list.
1.5 anton 9898:
1.78 anton 9899: Another important implementation detail is the variable
9900: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9901: determine if they can be reached directly or only through the branch
9902: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9903: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9904: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9905:
1.78 anton 9906: Counted loops are similar to other loops in most respects, but
9907: @code{LEAVE} requires special attention: It performs basically the same
9908: service as @code{AHEAD}, but it does not create a control-flow stack
9909: entry. Therefore the information has to be stored elsewhere;
9910: traditionally, the information was stored in the target fields of the
9911: branches created by the @code{LEAVE}s, by organizing these fields into a
9912: linked list. Unfortunately, this clever trick does not provide enough
9913: space for storing our extended control flow information. Therefore, we
9914: introduce another stack, the leave stack. It contains the control-flow
9915: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9916:
1.78 anton 9917: Local names are kept until the end of the colon definition, even if
9918: they are no longer visible in any control-flow path. In a few cases
9919: this may lead to increased space needs for the locals name area, but
9920: usually less than reclaiming this space would cost in code size.
1.5 anton 9921:
1.44 crook 9922:
1.78 anton 9923: @node ANS Forth locals, , Gforth locals, Locals
9924: @subsection ANS Forth locals
9925: @cindex locals, ANS Forth style
1.5 anton 9926:
1.78 anton 9927: The ANS Forth locals wordset does not define a syntax for locals, but
9928: words that make it possible to define various syntaxes. One of the
9929: possible syntaxes is a subset of the syntax we used in the Gforth locals
9930: wordset, i.e.:
1.29 crook 9931:
9932: @example
1.78 anton 9933: @{ local1 local2 ... -- comment @}
9934: @end example
9935: @noindent
9936: or
9937: @example
9938: @{ local1 local2 ... @}
1.29 crook 9939: @end example
9940:
1.78 anton 9941: The order of the locals corresponds to the order in a stack comment. The
9942: restrictions are:
1.5 anton 9943:
1.78 anton 9944: @itemize @bullet
9945: @item
9946: Locals can only be cell-sized values (no type specifiers are allowed).
9947: @item
9948: Locals can be defined only outside control structures.
9949: @item
9950: Locals can interfere with explicit usage of the return stack. For the
9951: exact (and long) rules, see the standard. If you don't use return stack
9952: accessing words in a definition using locals, you will be all right. The
9953: purpose of this rule is to make locals implementation on the return
9954: stack easier.
9955: @item
9956: The whole definition must be in one line.
9957: @end itemize
1.5 anton 9958:
1.78 anton 9959: Locals defined in ANS Forth behave like @code{VALUE}s
9960: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9961: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9962:
1.78 anton 9963: Since the syntax above is supported by Gforth directly, you need not do
9964: anything to use it. If you want to port a program using this syntax to
9965: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9966: syntax on the other system.
1.5 anton 9967:
1.78 anton 9968: Note that a syntax shown in the standard, section A.13 looks
9969: similar, but is quite different in having the order of locals
9970: reversed. Beware!
1.5 anton 9971:
1.78 anton 9972: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9973:
1.78 anton 9974: doc-(local)
1.5 anton 9975:
1.78 anton 9976: The ANS Forth locals extension wordset defines a syntax using
9977: @code{locals|}, but it is so awful that we strongly recommend not to use
9978: it. We have implemented this syntax to make porting to Gforth easy, but
9979: do not document it here. The problem with this syntax is that the locals
9980: are defined in an order reversed with respect to the standard stack
9981: comment notation, making programs harder to read, and easier to misread
9982: and miswrite. The only merit of this syntax is that it is easy to
9983: implement using the ANS Forth locals wordset.
1.53 anton 9984:
9985:
1.78 anton 9986: @c ----------------------------------------------------------
9987: @node Structures, Object-oriented Forth, Locals, Words
9988: @section Structures
9989: @cindex structures
9990: @cindex records
1.53 anton 9991:
1.78 anton 9992: This section presents the structure package that comes with Gforth. A
9993: version of the package implemented in ANS Forth is available in
9994: @file{compat/struct.fs}. This package was inspired by a posting on
9995: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9996: possibly John Hayes). A version of this section has been published in
9997: M. Anton Ertl,
9998: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9999: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10000: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 10001:
1.78 anton 10002: @menu
10003: * Why explicit structure support?::
10004: * Structure Usage::
10005: * Structure Naming Convention::
10006: * Structure Implementation::
10007: * Structure Glossary::
1.183 anton 10008: * Forth200x Structures::
1.78 anton 10009: @end menu
1.55 anton 10010:
1.78 anton 10011: @node Why explicit structure support?, Structure Usage, Structures, Structures
10012: @subsection Why explicit structure support?
1.53 anton 10013:
1.78 anton 10014: @cindex address arithmetic for structures
10015: @cindex structures using address arithmetic
10016: If we want to use a structure containing several fields, we could simply
10017: reserve memory for it, and access the fields using address arithmetic
10018: (@pxref{Address arithmetic}). As an example, consider a structure with
10019: the following fields
1.57 anton 10020:
1.78 anton 10021: @table @code
10022: @item a
10023: is a float
10024: @item b
10025: is a cell
10026: @item c
10027: is a float
10028: @end table
1.57 anton 10029:
1.78 anton 10030: Given the (float-aligned) base address of the structure we get the
10031: address of the field
1.52 anton 10032:
1.78 anton 10033: @table @code
10034: @item a
10035: without doing anything further.
10036: @item b
10037: with @code{float+}
10038: @item c
10039: with @code{float+ cell+ faligned}
10040: @end table
1.52 anton 10041:
1.78 anton 10042: It is easy to see that this can become quite tiring.
1.52 anton 10043:
1.78 anton 10044: Moreover, it is not very readable, because seeing a
10045: @code{cell+} tells us neither which kind of structure is
10046: accessed nor what field is accessed; we have to somehow infer the kind
10047: of structure, and then look up in the documentation, which field of
10048: that structure corresponds to that offset.
1.53 anton 10049:
1.78 anton 10050: Finally, this kind of address arithmetic also causes maintenance
10051: troubles: If you add or delete a field somewhere in the middle of the
10052: structure, you have to find and change all computations for the fields
10053: afterwards.
1.52 anton 10054:
1.78 anton 10055: So, instead of using @code{cell+} and friends directly, how
10056: about storing the offsets in constants:
1.52 anton 10057:
1.78 anton 10058: @example
10059: 0 constant a-offset
10060: 0 float+ constant b-offset
10061: 0 float+ cell+ faligned c-offset
10062: @end example
1.64 pazsan 10063:
1.78 anton 10064: Now we can get the address of field @code{x} with @code{x-offset
10065: +}. This is much better in all respects. Of course, you still
10066: have to change all later offset definitions if you add a field. You can
10067: fix this by declaring the offsets in the following way:
1.57 anton 10068:
1.78 anton 10069: @example
10070: 0 constant a-offset
10071: a-offset float+ constant b-offset
10072: b-offset cell+ faligned constant c-offset
10073: @end example
1.57 anton 10074:
1.78 anton 10075: Since we always use the offsets with @code{+}, we could use a defining
10076: word @code{cfield} that includes the @code{+} in the action of the
10077: defined word:
1.64 pazsan 10078:
1.78 anton 10079: @example
10080: : cfield ( n "name" -- )
10081: create ,
10082: does> ( name execution: addr1 -- addr2 )
10083: @@ + ;
1.64 pazsan 10084:
1.78 anton 10085: 0 cfield a
10086: 0 a float+ cfield b
10087: 0 b cell+ faligned cfield c
10088: @end example
1.64 pazsan 10089:
1.78 anton 10090: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10091:
1.78 anton 10092: The structure field words now can be used quite nicely. However,
10093: their definition is still a bit cumbersome: We have to repeat the
10094: name, the information about size and alignment is distributed before
10095: and after the field definitions etc. The structure package presented
10096: here addresses these problems.
1.64 pazsan 10097:
1.78 anton 10098: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10099: @subsection Structure Usage
10100: @cindex structure usage
1.57 anton 10101:
1.78 anton 10102: @cindex @code{field} usage
10103: @cindex @code{struct} usage
10104: @cindex @code{end-struct} usage
10105: You can define a structure for a (data-less) linked list with:
1.57 anton 10106: @example
1.78 anton 10107: struct
10108: cell% field list-next
10109: end-struct list%
1.57 anton 10110: @end example
10111:
1.78 anton 10112: With the address of the list node on the stack, you can compute the
10113: address of the field that contains the address of the next node with
10114: @code{list-next}. E.g., you can determine the length of a list
10115: with:
1.57 anton 10116:
10117: @example
1.78 anton 10118: : list-length ( list -- n )
10119: \ "list" is a pointer to the first element of a linked list
10120: \ "n" is the length of the list
10121: 0 BEGIN ( list1 n1 )
10122: over
10123: WHILE ( list1 n1 )
10124: 1+ swap list-next @@ swap
10125: REPEAT
10126: nip ;
1.57 anton 10127: @end example
10128:
1.78 anton 10129: You can reserve memory for a list node in the dictionary with
10130: @code{list% %allot}, which leaves the address of the list node on the
10131: stack. For the equivalent allocation on the heap you can use @code{list%
10132: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10133: use @code{list% %allocate}). You can get the the size of a list
10134: node with @code{list% %size} and its alignment with @code{list%
10135: %alignment}.
10136:
10137: Note that in ANS Forth the body of a @code{create}d word is
10138: @code{aligned} but not necessarily @code{faligned};
10139: therefore, if you do a:
1.57 anton 10140:
10141: @example
1.78 anton 10142: create @emph{name} foo% %allot drop
1.57 anton 10143: @end example
10144:
1.78 anton 10145: @noindent
10146: then the memory alloted for @code{foo%} is guaranteed to start at the
10147: body of @code{@emph{name}} only if @code{foo%} contains only character,
10148: cell and double fields. Therefore, if your structure contains floats,
10149: better use
1.57 anton 10150:
10151: @example
1.78 anton 10152: foo% %allot constant @emph{name}
1.57 anton 10153: @end example
10154:
1.78 anton 10155: @cindex structures containing structures
10156: You can include a structure @code{foo%} as a field of
10157: another structure, like this:
1.65 anton 10158: @example
1.78 anton 10159: struct
10160: ...
10161: foo% field ...
10162: ...
10163: end-struct ...
1.65 anton 10164: @end example
1.52 anton 10165:
1.78 anton 10166: @cindex structure extension
10167: @cindex extended records
10168: Instead of starting with an empty structure, you can extend an
10169: existing structure. E.g., a plain linked list without data, as defined
10170: above, is hardly useful; You can extend it to a linked list of integers,
10171: like this:@footnote{This feature is also known as @emph{extended
10172: records}. It is the main innovation in the Oberon language; in other
10173: words, adding this feature to Modula-2 led Wirth to create a new
10174: language, write a new compiler etc. Adding this feature to Forth just
10175: required a few lines of code.}
1.52 anton 10176:
1.78 anton 10177: @example
10178: list%
10179: cell% field intlist-int
10180: end-struct intlist%
10181: @end example
1.55 anton 10182:
1.78 anton 10183: @code{intlist%} is a structure with two fields:
10184: @code{list-next} and @code{intlist-int}.
1.55 anton 10185:
1.78 anton 10186: @cindex structures containing arrays
10187: You can specify an array type containing @emph{n} elements of
10188: type @code{foo%} like this:
1.55 anton 10189:
10190: @example
1.78 anton 10191: foo% @emph{n} *
1.56 anton 10192: @end example
1.55 anton 10193:
1.78 anton 10194: You can use this array type in any place where you can use a normal
10195: type, e.g., when defining a @code{field}, or with
10196: @code{%allot}.
10197:
10198: @cindex first field optimization
10199: The first field is at the base address of a structure and the word for
10200: this field (e.g., @code{list-next}) actually does not change the address
10201: on the stack. You may be tempted to leave it away in the interest of
10202: run-time and space efficiency. This is not necessary, because the
10203: structure package optimizes this case: If you compile a first-field
10204: words, no code is generated. So, in the interest of readability and
10205: maintainability you should include the word for the field when accessing
10206: the field.
1.52 anton 10207:
10208:
1.78 anton 10209: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10210: @subsection Structure Naming Convention
10211: @cindex structure naming convention
1.52 anton 10212:
1.78 anton 10213: The field names that come to (my) mind are often quite generic, and,
10214: if used, would cause frequent name clashes. E.g., many structures
10215: probably contain a @code{counter} field. The structure names
10216: that come to (my) mind are often also the logical choice for the names
10217: of words that create such a structure.
1.52 anton 10218:
1.78 anton 10219: Therefore, I have adopted the following naming conventions:
1.52 anton 10220:
1.78 anton 10221: @itemize @bullet
10222: @cindex field naming convention
10223: @item
10224: The names of fields are of the form
10225: @code{@emph{struct}-@emph{field}}, where
10226: @code{@emph{struct}} is the basic name of the structure, and
10227: @code{@emph{field}} is the basic name of the field. You can
10228: think of field words as converting the (address of the)
10229: structure into the (address of the) field.
1.52 anton 10230:
1.78 anton 10231: @cindex structure naming convention
10232: @item
10233: The names of structures are of the form
10234: @code{@emph{struct}%}, where
10235: @code{@emph{struct}} is the basic name of the structure.
10236: @end itemize
1.52 anton 10237:
1.78 anton 10238: This naming convention does not work that well for fields of extended
10239: structures; e.g., the integer list structure has a field
10240: @code{intlist-int}, but has @code{list-next}, not
10241: @code{intlist-next}.
1.53 anton 10242:
1.78 anton 10243: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10244: @subsection Structure Implementation
10245: @cindex structure implementation
10246: @cindex implementation of structures
1.52 anton 10247:
1.78 anton 10248: The central idea in the implementation is to pass the data about the
10249: structure being built on the stack, not in some global
10250: variable. Everything else falls into place naturally once this design
10251: decision is made.
1.53 anton 10252:
1.78 anton 10253: The type description on the stack is of the form @emph{align
10254: size}. Keeping the size on the top-of-stack makes dealing with arrays
10255: very simple.
1.53 anton 10256:
1.78 anton 10257: @code{field} is a defining word that uses @code{Create}
10258: and @code{DOES>}. The body of the field contains the offset
10259: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10260:
10261: @example
1.78 anton 10262: @@ +
1.53 anton 10263: @end example
10264:
1.78 anton 10265: @noindent
10266: i.e., add the offset to the address, giving the stack effect
10267: @i{addr1 -- addr2} for a field.
10268:
10269: @cindex first field optimization, implementation
10270: This simple structure is slightly complicated by the optimization
10271: for fields with offset 0, which requires a different
10272: @code{DOES>}-part (because we cannot rely on there being
10273: something on the stack if such a field is invoked during
10274: compilation). Therefore, we put the different @code{DOES>}-parts
10275: in separate words, and decide which one to invoke based on the
10276: offset. For a zero offset, the field is basically a noop; it is
10277: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10278:
1.183 anton 10279: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10280: @subsection Structure Glossary
10281: @cindex structure glossary
1.53 anton 10282:
1.5 anton 10283:
1.78 anton 10284: doc-%align
10285: doc-%alignment
10286: doc-%alloc
10287: doc-%allocate
10288: doc-%allot
10289: doc-cell%
10290: doc-char%
10291: doc-dfloat%
10292: doc-double%
10293: doc-end-struct
10294: doc-field
10295: doc-float%
10296: doc-naligned
10297: doc-sfloat%
10298: doc-%size
10299: doc-struct
1.54 anton 10300:
10301:
1.183 anton 10302: @node Forth200x Structures, , Structure Glossary, Structures
10303: @subsection Forth200x Structures
10304: @cindex Structures in Forth200x
10305:
10306: The Forth 200x standard defines a slightly less convenient form of
10307: structures. In general (when using @code{field+}, you have to perform
10308: the alignment yourself, but there are a number of convenience words
10309: (e.g., @code{field:} that perform the alignment for you.
10310:
10311: A typical usage example is:
10312:
10313: @example
10314: 0
10315: field: s-a
10316: faligned 2 floats +field s-b
10317: constant s-struct
10318: @end example
10319:
10320: An alternative way of writing this structure is:
10321:
10322: @example
10323: begin-structure s-struct
10324: field: s-a
10325: faligned 2 floats +field s-b
10326: end-structure
10327: @end example
10328:
10329: doc-begin-structure
10330: doc-end-structure
10331: doc-+field
10332: doc-cfield:
10333: doc-field:
10334: doc-2field:
10335: doc-ffield:
10336: doc-sffield:
10337: doc-dffield:
10338:
1.26 crook 10339: @c -------------------------------------------------------------
1.78 anton 10340: @node Object-oriented Forth, Programming Tools, Structures, Words
10341: @section Object-oriented Forth
10342:
10343: Gforth comes with three packages for object-oriented programming:
10344: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10345: is preloaded, so you have to @code{include} them before use. The most
10346: important differences between these packages (and others) are discussed
10347: in @ref{Comparison with other object models}. All packages are written
10348: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10349:
1.78 anton 10350: @menu
10351: * Why object-oriented programming?::
10352: * Object-Oriented Terminology::
10353: * Objects::
10354: * OOF::
10355: * Mini-OOF::
10356: * Comparison with other object models::
10357: @end menu
1.5 anton 10358:
1.78 anton 10359: @c ----------------------------------------------------------------
10360: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10361: @subsection Why object-oriented programming?
10362: @cindex object-oriented programming motivation
10363: @cindex motivation for object-oriented programming
1.44 crook 10364:
1.78 anton 10365: Often we have to deal with several data structures (@emph{objects}),
10366: that have to be treated similarly in some respects, but differently in
10367: others. Graphical objects are the textbook example: circles, triangles,
10368: dinosaurs, icons, and others, and we may want to add more during program
10369: development. We want to apply some operations to any graphical object,
10370: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10371: has to do something different for every kind of object.
10372: @comment TODO add some other operations eg perimeter, area
10373: @comment and tie in to concrete examples later..
1.5 anton 10374:
1.78 anton 10375: We could implement @code{draw} as a big @code{CASE}
10376: control structure that executes the appropriate code depending on the
10377: kind of object to be drawn. This would be not be very elegant, and,
10378: moreover, we would have to change @code{draw} every time we add
10379: a new kind of graphical object (say, a spaceship).
1.44 crook 10380:
1.78 anton 10381: What we would rather do is: When defining spaceships, we would tell
10382: the system: ``Here's how you @code{draw} a spaceship; you figure
10383: out the rest''.
1.5 anton 10384:
1.78 anton 10385: This is the problem that all systems solve that (rightfully) call
10386: themselves object-oriented; the object-oriented packages presented here
10387: solve this problem (and not much else).
10388: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10389:
1.78 anton 10390: @c ------------------------------------------------------------------------
10391: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10392: @subsection Object-Oriented Terminology
10393: @cindex object-oriented terminology
10394: @cindex terminology for object-oriented programming
1.5 anton 10395:
1.78 anton 10396: This section is mainly for reference, so you don't have to understand
10397: all of it right away. The terminology is mainly Smalltalk-inspired. In
10398: short:
1.44 crook 10399:
1.78 anton 10400: @table @emph
10401: @cindex class
10402: @item class
10403: a data structure definition with some extras.
1.5 anton 10404:
1.78 anton 10405: @cindex object
10406: @item object
10407: an instance of the data structure described by the class definition.
1.5 anton 10408:
1.78 anton 10409: @cindex instance variables
10410: @item instance variables
10411: fields of the data structure.
1.5 anton 10412:
1.78 anton 10413: @cindex selector
10414: @cindex method selector
10415: @cindex virtual function
10416: @item selector
10417: (or @emph{method selector}) a word (e.g.,
10418: @code{draw}) that performs an operation on a variety of data
10419: structures (classes). A selector describes @emph{what} operation to
10420: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10421:
1.78 anton 10422: @cindex method
10423: @item method
10424: the concrete definition that performs the operation
10425: described by the selector for a specific class. A method specifies
10426: @emph{how} the operation is performed for a specific class.
1.5 anton 10427:
1.78 anton 10428: @cindex selector invocation
10429: @cindex message send
10430: @cindex invoking a selector
10431: @item selector invocation
10432: a call of a selector. One argument of the call (the TOS (top-of-stack))
10433: is used for determining which method is used. In Smalltalk terminology:
10434: a message (consisting of the selector and the other arguments) is sent
10435: to the object.
1.5 anton 10436:
1.78 anton 10437: @cindex receiving object
10438: @item receiving object
10439: the object used for determining the method executed by a selector
10440: invocation. In the @file{objects.fs} model, it is the object that is on
10441: the TOS when the selector is invoked. (@emph{Receiving} comes from
10442: the Smalltalk @emph{message} terminology.)
1.5 anton 10443:
1.78 anton 10444: @cindex child class
10445: @cindex parent class
10446: @cindex inheritance
10447: @item child class
10448: a class that has (@emph{inherits}) all properties (instance variables,
10449: selectors, methods) from a @emph{parent class}. In Smalltalk
10450: terminology: The subclass inherits from the superclass. In C++
10451: terminology: The derived class inherits from the base class.
1.5 anton 10452:
1.78 anton 10453: @end table
1.5 anton 10454:
1.78 anton 10455: @c If you wonder about the message sending terminology, it comes from
10456: @c a time when each object had it's own task and objects communicated via
10457: @c message passing; eventually the Smalltalk developers realized that
10458: @c they can do most things through simple (indirect) calls. They kept the
10459: @c terminology.
1.5 anton 10460:
1.78 anton 10461: @c --------------------------------------------------------------
10462: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10463: @subsection The @file{objects.fs} model
10464: @cindex objects
10465: @cindex object-oriented programming
1.26 crook 10466:
1.78 anton 10467: @cindex @file{objects.fs}
10468: @cindex @file{oof.fs}
1.26 crook 10469:
1.78 anton 10470: This section describes the @file{objects.fs} package. This material also
10471: has been published in M. Anton Ertl,
10472: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10473: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10474: 37--43.
10475: @c McKewan's and Zsoter's packages
1.26 crook 10476:
1.78 anton 10477: This section assumes that you have read @ref{Structures}.
1.5 anton 10478:
1.78 anton 10479: The techniques on which this model is based have been used to implement
10480: the parser generator, Gray, and have also been used in Gforth for
10481: implementing the various flavours of word lists (hashed or not,
10482: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10483:
10484:
1.26 crook 10485: @menu
1.78 anton 10486: * Properties of the Objects model::
10487: * Basic Objects Usage::
10488: * The Objects base class::
10489: * Creating objects::
10490: * Object-Oriented Programming Style::
10491: * Class Binding::
10492: * Method conveniences::
10493: * Classes and Scoping::
10494: * Dividing classes::
10495: * Object Interfaces::
10496: * Objects Implementation::
10497: * Objects Glossary::
1.26 crook 10498: @end menu
1.5 anton 10499:
1.78 anton 10500: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10501:
1.78 anton 10502: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10503: @subsubsection Properties of the @file{objects.fs} model
10504: @cindex @file{objects.fs} properties
1.5 anton 10505:
1.78 anton 10506: @itemize @bullet
10507: @item
10508: It is straightforward to pass objects on the stack. Passing
10509: selectors on the stack is a little less convenient, but possible.
1.44 crook 10510:
1.78 anton 10511: @item
10512: Objects are just data structures in memory, and are referenced by their
10513: address. You can create words for objects with normal defining words
10514: like @code{constant}. Likewise, there is no difference between instance
10515: variables that contain objects and those that contain other data.
1.5 anton 10516:
1.78 anton 10517: @item
10518: Late binding is efficient and easy to use.
1.44 crook 10519:
1.78 anton 10520: @item
10521: It avoids parsing, and thus avoids problems with state-smartness
10522: and reduced extensibility; for convenience there are a few parsing
10523: words, but they have non-parsing counterparts. There are also a few
10524: defining words that parse. This is hard to avoid, because all standard
10525: defining words parse (except @code{:noname}); however, such
10526: words are not as bad as many other parsing words, because they are not
10527: state-smart.
1.5 anton 10528:
1.78 anton 10529: @item
10530: It does not try to incorporate everything. It does a few things and does
10531: them well (IMO). In particular, this model was not designed to support
10532: information hiding (although it has features that may help); you can use
10533: a separate package for achieving this.
1.5 anton 10534:
1.78 anton 10535: @item
10536: It is layered; you don't have to learn and use all features to use this
10537: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10538: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10539: are optional and independent of each other.
1.5 anton 10540:
1.78 anton 10541: @item
10542: An implementation in ANS Forth is available.
1.5 anton 10543:
1.78 anton 10544: @end itemize
1.5 anton 10545:
1.44 crook 10546:
1.78 anton 10547: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10548: @subsubsection Basic @file{objects.fs} Usage
10549: @cindex basic objects usage
10550: @cindex objects, basic usage
1.5 anton 10551:
1.78 anton 10552: You can define a class for graphical objects like this:
1.44 crook 10553:
1.78 anton 10554: @cindex @code{class} usage
10555: @cindex @code{end-class} usage
10556: @cindex @code{selector} usage
1.5 anton 10557: @example
1.78 anton 10558: object class \ "object" is the parent class
10559: selector draw ( x y graphical -- )
10560: end-class graphical
10561: @end example
10562:
10563: This code defines a class @code{graphical} with an
10564: operation @code{draw}. We can perform the operation
10565: @code{draw} on any @code{graphical} object, e.g.:
10566:
10567: @example
10568: 100 100 t-rex draw
1.26 crook 10569: @end example
1.5 anton 10570:
1.78 anton 10571: @noindent
10572: where @code{t-rex} is a word (say, a constant) that produces a
10573: graphical object.
10574:
10575: @comment TODO add a 2nd operation eg perimeter.. and use for
10576: @comment a concrete example
1.5 anton 10577:
1.78 anton 10578: @cindex abstract class
10579: How do we create a graphical object? With the present definitions,
10580: we cannot create a useful graphical object. The class
10581: @code{graphical} describes graphical objects in general, but not
10582: any concrete graphical object type (C++ users would call it an
10583: @emph{abstract class}); e.g., there is no method for the selector
10584: @code{draw} in the class @code{graphical}.
1.5 anton 10585:
1.78 anton 10586: For concrete graphical objects, we define child classes of the
10587: class @code{graphical}, e.g.:
1.5 anton 10588:
1.78 anton 10589: @cindex @code{overrides} usage
10590: @cindex @code{field} usage in class definition
1.26 crook 10591: @example
1.78 anton 10592: graphical class \ "graphical" is the parent class
10593: cell% field circle-radius
1.5 anton 10594:
1.78 anton 10595: :noname ( x y circle -- )
10596: circle-radius @@ draw-circle ;
10597: overrides draw
1.5 anton 10598:
1.78 anton 10599: :noname ( n-radius circle -- )
10600: circle-radius ! ;
10601: overrides construct
1.5 anton 10602:
1.78 anton 10603: end-class circle
10604: @end example
1.44 crook 10605:
1.78 anton 10606: Here we define a class @code{circle} as a child of @code{graphical},
10607: with field @code{circle-radius} (which behaves just like a field
10608: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10609: for the selectors @code{draw} and @code{construct} (@code{construct} is
10610: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10611:
1.78 anton 10612: Now we can create a circle on the heap (i.e.,
10613: @code{allocate}d memory) with:
1.44 crook 10614:
1.78 anton 10615: @cindex @code{heap-new} usage
1.5 anton 10616: @example
1.78 anton 10617: 50 circle heap-new constant my-circle
1.5 anton 10618: @end example
10619:
1.78 anton 10620: @noindent
10621: @code{heap-new} invokes @code{construct}, thus
10622: initializing the field @code{circle-radius} with 50. We can draw
10623: this new circle at (100,100) with:
1.5 anton 10624:
10625: @example
1.78 anton 10626: 100 100 my-circle draw
1.5 anton 10627: @end example
10628:
1.78 anton 10629: @cindex selector invocation, restrictions
10630: @cindex class definition, restrictions
10631: Note: You can only invoke a selector if the object on the TOS
10632: (the receiving object) belongs to the class where the selector was
10633: defined or one of its descendents; e.g., you can invoke
10634: @code{draw} only for objects belonging to @code{graphical}
10635: or its descendents (e.g., @code{circle}). Immediately before
10636: @code{end-class}, the search order has to be the same as
10637: immediately after @code{class}.
10638:
10639: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10640: @subsubsection The @file{object.fs} base class
10641: @cindex @code{object} class
10642:
10643: When you define a class, you have to specify a parent class. So how do
10644: you start defining classes? There is one class available from the start:
10645: @code{object}. It is ancestor for all classes and so is the
10646: only class that has no parent. It has two selectors: @code{construct}
10647: and @code{print}.
10648:
10649: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10650: @subsubsection Creating objects
10651: @cindex creating objects
10652: @cindex object creation
10653: @cindex object allocation options
10654:
10655: @cindex @code{heap-new} discussion
10656: @cindex @code{dict-new} discussion
10657: @cindex @code{construct} discussion
10658: You can create and initialize an object of a class on the heap with
10659: @code{heap-new} ( ... class -- object ) and in the dictionary
10660: (allocation with @code{allot}) with @code{dict-new} (
10661: ... class -- object ). Both words invoke @code{construct}, which
10662: consumes the stack items indicated by "..." above.
10663:
10664: @cindex @code{init-object} discussion
10665: @cindex @code{class-inst-size} discussion
10666: If you want to allocate memory for an object yourself, you can get its
10667: alignment and size with @code{class-inst-size 2@@} ( class --
10668: align size ). Once you have memory for an object, you can initialize
10669: it with @code{init-object} ( ... class object -- );
10670: @code{construct} does only a part of the necessary work.
10671:
10672: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10673: @subsubsection Object-Oriented Programming Style
10674: @cindex object-oriented programming style
10675: @cindex programming style, object-oriented
1.5 anton 10676:
1.78 anton 10677: This section is not exhaustive.
1.5 anton 10678:
1.78 anton 10679: @cindex stack effects of selectors
10680: @cindex selectors and stack effects
10681: In general, it is a good idea to ensure that all methods for the
10682: same selector have the same stack effect: when you invoke a selector,
10683: you often have no idea which method will be invoked, so, unless all
10684: methods have the same stack effect, you will not know the stack effect
10685: of the selector invocation.
1.5 anton 10686:
1.78 anton 10687: One exception to this rule is methods for the selector
10688: @code{construct}. We know which method is invoked, because we
10689: specify the class to be constructed at the same place. Actually, I
10690: defined @code{construct} as a selector only to give the users a
10691: convenient way to specify initialization. The way it is used, a
10692: mechanism different from selector invocation would be more natural
10693: (but probably would take more code and more space to explain).
1.5 anton 10694:
1.78 anton 10695: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10696: @subsubsection Class Binding
10697: @cindex class binding
10698: @cindex early binding
1.5 anton 10699:
1.78 anton 10700: @cindex late binding
10701: Normal selector invocations determine the method at run-time depending
10702: on the class of the receiving object. This run-time selection is called
10703: @i{late binding}.
1.5 anton 10704:
1.78 anton 10705: Sometimes it's preferable to invoke a different method. For example,
10706: you might want to use the simple method for @code{print}ing
10707: @code{object}s instead of the possibly long-winded @code{print} method
10708: of the receiver class. You can achieve this by replacing the invocation
10709: of @code{print} with:
1.5 anton 10710:
1.78 anton 10711: @cindex @code{[bind]} usage
1.5 anton 10712: @example
1.78 anton 10713: [bind] object print
1.5 anton 10714: @end example
10715:
1.78 anton 10716: @noindent
10717: in compiled code or:
10718:
10719: @cindex @code{bind} usage
1.5 anton 10720: @example
1.78 anton 10721: bind object print
1.5 anton 10722: @end example
10723:
1.78 anton 10724: @cindex class binding, alternative to
10725: @noindent
10726: in interpreted code. Alternatively, you can define the method with a
10727: name (e.g., @code{print-object}), and then invoke it through the
10728: name. Class binding is just a (often more convenient) way to achieve
10729: the same effect; it avoids name clutter and allows you to invoke
10730: methods directly without naming them first.
1.5 anton 10731:
1.78 anton 10732: @cindex superclass binding
10733: @cindex parent class binding
10734: A frequent use of class binding is this: When we define a method
10735: for a selector, we often want the method to do what the selector does
10736: in the parent class, and a little more. There is a special word for
10737: this purpose: @code{[parent]}; @code{[parent]
10738: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10739: selector}}, where @code{@emph{parent}} is the parent
10740: class of the current class. E.g., a method definition might look like:
1.44 crook 10741:
1.78 anton 10742: @cindex @code{[parent]} usage
10743: @example
10744: :noname
10745: dup [parent] foo \ do parent's foo on the receiving object
10746: ... \ do some more
10747: ; overrides foo
10748: @end example
1.6 pazsan 10749:
1.78 anton 10750: @cindex class binding as optimization
10751: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10752: March 1997), Andrew McKewan presents class binding as an optimization
10753: technique. I recommend not using it for this purpose unless you are in
10754: an emergency. Late binding is pretty fast with this model anyway, so the
10755: benefit of using class binding is small; the cost of using class binding
10756: where it is not appropriate is reduced maintainability.
1.44 crook 10757:
1.78 anton 10758: While we are at programming style questions: You should bind
10759: selectors only to ancestor classes of the receiving object. E.g., say,
10760: you know that the receiving object is of class @code{foo} or its
10761: descendents; then you should bind only to @code{foo} and its
10762: ancestors.
1.12 anton 10763:
1.78 anton 10764: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10765: @subsubsection Method conveniences
10766: @cindex method conveniences
1.44 crook 10767:
1.78 anton 10768: In a method you usually access the receiving object pretty often. If
10769: you define the method as a plain colon definition (e.g., with
10770: @code{:noname}), you may have to do a lot of stack
10771: gymnastics. To avoid this, you can define the method with @code{m:
10772: ... ;m}. E.g., you could define the method for
10773: @code{draw}ing a @code{circle} with
1.6 pazsan 10774:
1.78 anton 10775: @cindex @code{this} usage
10776: @cindex @code{m:} usage
10777: @cindex @code{;m} usage
10778: @example
10779: m: ( x y circle -- )
10780: ( x y ) this circle-radius @@ draw-circle ;m
10781: @end example
1.6 pazsan 10782:
1.78 anton 10783: @cindex @code{exit} in @code{m: ... ;m}
10784: @cindex @code{exitm} discussion
10785: @cindex @code{catch} in @code{m: ... ;m}
10786: When this method is executed, the receiver object is removed from the
10787: stack; you can access it with @code{this} (admittedly, in this
10788: example the use of @code{m: ... ;m} offers no advantage). Note
10789: that I specify the stack effect for the whole method (i.e. including
10790: the receiver object), not just for the code between @code{m:}
10791: and @code{;m}. You cannot use @code{exit} in
10792: @code{m:...;m}; instead, use
10793: @code{exitm}.@footnote{Moreover, for any word that calls
10794: @code{catch} and was defined before loading
10795: @code{objects.fs}, you have to redefine it like I redefined
10796: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10797:
1.78 anton 10798: @cindex @code{inst-var} usage
10799: You will frequently use sequences of the form @code{this
10800: @emph{field}} (in the example above: @code{this
10801: circle-radius}). If you use the field only in this way, you can
10802: define it with @code{inst-var} and eliminate the
10803: @code{this} before the field name. E.g., the @code{circle}
10804: class above could also be defined with:
1.6 pazsan 10805:
1.78 anton 10806: @example
10807: graphical class
10808: cell% inst-var radius
1.6 pazsan 10809:
1.78 anton 10810: m: ( x y circle -- )
10811: radius @@ draw-circle ;m
10812: overrides draw
1.6 pazsan 10813:
1.78 anton 10814: m: ( n-radius circle -- )
10815: radius ! ;m
10816: overrides construct
1.6 pazsan 10817:
1.78 anton 10818: end-class circle
10819: @end example
1.6 pazsan 10820:
1.78 anton 10821: @code{radius} can only be used in @code{circle} and its
10822: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10823:
1.78 anton 10824: @cindex @code{inst-value} usage
10825: You can also define fields with @code{inst-value}, which is
10826: to @code{inst-var} what @code{value} is to
10827: @code{variable}. You can change the value of such a field with
10828: @code{[to-inst]}. E.g., we could also define the class
10829: @code{circle} like this:
1.44 crook 10830:
1.78 anton 10831: @example
10832: graphical class
10833: inst-value radius
1.6 pazsan 10834:
1.78 anton 10835: m: ( x y circle -- )
10836: radius draw-circle ;m
10837: overrides draw
1.44 crook 10838:
1.78 anton 10839: m: ( n-radius circle -- )
10840: [to-inst] radius ;m
10841: overrides construct
1.6 pazsan 10842:
1.78 anton 10843: end-class circle
10844: @end example
1.6 pazsan 10845:
1.78 anton 10846: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10847:
1.78 anton 10848: @c Finally, you can define named methods with @code{:m}. One use of this
10849: @c feature is the definition of words that occur only in one class and are
10850: @c not intended to be overridden, but which still need method context
10851: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10852: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10853:
10854:
1.78 anton 10855: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10856: @subsubsection Classes and Scoping
10857: @cindex classes and scoping
10858: @cindex scoping and classes
1.6 pazsan 10859:
1.78 anton 10860: Inheritance is frequent, unlike structure extension. This exacerbates
10861: the problem with the field name convention (@pxref{Structure Naming
10862: Convention}): One always has to remember in which class the field was
10863: originally defined; changing a part of the class structure would require
10864: changes for renaming in otherwise unaffected code.
1.6 pazsan 10865:
1.78 anton 10866: @cindex @code{inst-var} visibility
10867: @cindex @code{inst-value} visibility
10868: To solve this problem, I added a scoping mechanism (which was not in my
10869: original charter): A field defined with @code{inst-var} (or
10870: @code{inst-value}) is visible only in the class where it is defined and in
10871: the descendent classes of this class. Using such fields only makes
10872: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10873:
1.78 anton 10874: This scoping mechanism allows us to use the unadorned field name,
10875: because name clashes with unrelated words become much less likely.
1.6 pazsan 10876:
1.78 anton 10877: @cindex @code{protected} discussion
10878: @cindex @code{private} discussion
10879: Once we have this mechanism, we can also use it for controlling the
10880: visibility of other words: All words defined after
10881: @code{protected} are visible only in the current class and its
10882: descendents. @code{public} restores the compilation
10883: (i.e. @code{current}) word list that was in effect before. If you
10884: have several @code{protected}s without an intervening
10885: @code{public} or @code{set-current}, @code{public}
10886: will restore the compilation word list in effect before the first of
10887: these @code{protected}s.
1.6 pazsan 10888:
1.78 anton 10889: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10890: @subsubsection Dividing classes
10891: @cindex Dividing classes
10892: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10893:
1.78 anton 10894: You may want to do the definition of methods separate from the
10895: definition of the class, its selectors, fields, and instance variables,
10896: i.e., separate the implementation from the definition. You can do this
10897: in the following way:
1.6 pazsan 10898:
1.78 anton 10899: @example
10900: graphical class
10901: inst-value radius
10902: end-class circle
1.6 pazsan 10903:
1.78 anton 10904: ... \ do some other stuff
1.6 pazsan 10905:
1.78 anton 10906: circle methods \ now we are ready
1.44 crook 10907:
1.78 anton 10908: m: ( x y circle -- )
10909: radius draw-circle ;m
10910: overrides draw
1.6 pazsan 10911:
1.78 anton 10912: m: ( n-radius circle -- )
10913: [to-inst] radius ;m
10914: overrides construct
1.44 crook 10915:
1.78 anton 10916: end-methods
10917: @end example
1.7 pazsan 10918:
1.78 anton 10919: You can use several @code{methods}...@code{end-methods} sections. The
10920: only things you can do to the class in these sections are: defining
10921: methods, and overriding the class's selectors. You must not define new
10922: selectors or fields.
1.7 pazsan 10923:
1.78 anton 10924: Note that you often have to override a selector before using it. In
10925: particular, you usually have to override @code{construct} with a new
10926: method before you can invoke @code{heap-new} and friends. E.g., you
10927: must not create a circle before the @code{overrides construct} sequence
10928: in the example above.
1.7 pazsan 10929:
1.78 anton 10930: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10931: @subsubsection Object Interfaces
10932: @cindex object interfaces
10933: @cindex interfaces for objects
1.7 pazsan 10934:
1.78 anton 10935: In this model you can only call selectors defined in the class of the
10936: receiving objects or in one of its ancestors. If you call a selector
10937: with a receiving object that is not in one of these classes, the
10938: result is undefined; if you are lucky, the program crashes
10939: immediately.
1.7 pazsan 10940:
1.78 anton 10941: @cindex selectors common to hardly-related classes
10942: Now consider the case when you want to have a selector (or several)
10943: available in two classes: You would have to add the selector to a
10944: common ancestor class, in the worst case to @code{object}. You
10945: may not want to do this, e.g., because someone else is responsible for
10946: this ancestor class.
1.7 pazsan 10947:
1.78 anton 10948: The solution for this problem is interfaces. An interface is a
10949: collection of selectors. If a class implements an interface, the
10950: selectors become available to the class and its descendents. A class
10951: can implement an unlimited number of interfaces. For the problem
10952: discussed above, we would define an interface for the selector(s), and
10953: both classes would implement the interface.
1.7 pazsan 10954:
1.78 anton 10955: As an example, consider an interface @code{storage} for
10956: writing objects to disk and getting them back, and a class
10957: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10958:
1.78 anton 10959: @cindex @code{interface} usage
10960: @cindex @code{end-interface} usage
10961: @cindex @code{implementation} usage
10962: @example
10963: interface
10964: selector write ( file object -- )
10965: selector read1 ( file object -- )
10966: end-interface storage
1.13 pazsan 10967:
1.78 anton 10968: bar class
10969: storage implementation
1.13 pazsan 10970:
1.78 anton 10971: ... overrides write
10972: ... overrides read1
10973: ...
10974: end-class foo
10975: @end example
1.13 pazsan 10976:
1.78 anton 10977: @noindent
10978: (I would add a word @code{read} @i{( file -- object )} that uses
10979: @code{read1} internally, but that's beyond the point illustrated
10980: here.)
1.13 pazsan 10981:
1.78 anton 10982: Note that you cannot use @code{protected} in an interface; and
10983: of course you cannot define fields.
1.13 pazsan 10984:
1.78 anton 10985: In the Neon model, all selectors are available for all classes;
10986: therefore it does not need interfaces. The price you pay in this model
10987: is slower late binding, and therefore, added complexity to avoid late
10988: binding.
1.13 pazsan 10989:
1.78 anton 10990: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10991: @subsubsection @file{objects.fs} Implementation
10992: @cindex @file{objects.fs} implementation
1.13 pazsan 10993:
1.78 anton 10994: @cindex @code{object-map} discussion
10995: An object is a piece of memory, like one of the data structures
10996: described with @code{struct...end-struct}. It has a field
10997: @code{object-map} that points to the method map for the object's
10998: class.
1.13 pazsan 10999:
1.78 anton 11000: @cindex method map
11001: @cindex virtual function table
11002: The @emph{method map}@footnote{This is Self terminology; in C++
11003: terminology: virtual function table.} is an array that contains the
11004: execution tokens (@i{xt}s) of the methods for the object's class. Each
11005: selector contains an offset into a method map.
1.13 pazsan 11006:
1.78 anton 11007: @cindex @code{selector} implementation, class
11008: @code{selector} is a defining word that uses
11009: @code{CREATE} and @code{DOES>}. The body of the
11010: selector contains the offset; the @code{DOES>} action for a
11011: class selector is, basically:
1.8 pazsan 11012:
11013: @example
1.78 anton 11014: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 11015: @end example
11016:
1.78 anton 11017: Since @code{object-map} is the first field of the object, it
11018: does not generate any code. As you can see, calling a selector has a
11019: small, constant cost.
1.26 crook 11020:
1.78 anton 11021: @cindex @code{current-interface} discussion
11022: @cindex class implementation and representation
11023: A class is basically a @code{struct} combined with a method
11024: map. During the class definition the alignment and size of the class
11025: are passed on the stack, just as with @code{struct}s, so
11026: @code{field} can also be used for defining class
11027: fields. However, passing more items on the stack would be
11028: inconvenient, so @code{class} builds a data structure in memory,
11029: which is accessed through the variable
11030: @code{current-interface}. After its definition is complete, the
11031: class is represented on the stack by a pointer (e.g., as parameter for
11032: a child class definition).
1.26 crook 11033:
1.78 anton 11034: A new class starts off with the alignment and size of its parent,
11035: and a copy of the parent's method map. Defining new fields extends the
11036: size and alignment; likewise, defining new selectors extends the
11037: method map. @code{overrides} just stores a new @i{xt} in the method
11038: map at the offset given by the selector.
1.13 pazsan 11039:
1.78 anton 11040: @cindex class binding, implementation
11041: Class binding just gets the @i{xt} at the offset given by the selector
11042: from the class's method map and @code{compile,}s (in the case of
11043: @code{[bind]}) it.
1.13 pazsan 11044:
1.78 anton 11045: @cindex @code{this} implementation
11046: @cindex @code{catch} and @code{this}
11047: @cindex @code{this} and @code{catch}
11048: I implemented @code{this} as a @code{value}. At the
11049: start of an @code{m:...;m} method the old @code{this} is
11050: stored to the return stack and restored at the end; and the object on
11051: the TOS is stored @code{TO this}. This technique has one
11052: disadvantage: If the user does not leave the method via
11053: @code{;m}, but via @code{throw} or @code{exit},
11054: @code{this} is not restored (and @code{exit} may
11055: crash). To deal with the @code{throw} problem, I have redefined
11056: @code{catch} to save and restore @code{this}; the same
11057: should be done with any word that can catch an exception. As for
11058: @code{exit}, I simply forbid it (as a replacement, there is
11059: @code{exitm}).
1.13 pazsan 11060:
1.78 anton 11061: @cindex @code{inst-var} implementation
11062: @code{inst-var} is just the same as @code{field}, with
11063: a different @code{DOES>} action:
1.13 pazsan 11064: @example
1.78 anton 11065: @@ this +
1.8 pazsan 11066: @end example
1.78 anton 11067: Similar for @code{inst-value}.
1.8 pazsan 11068:
1.78 anton 11069: @cindex class scoping implementation
11070: Each class also has a word list that contains the words defined with
11071: @code{inst-var} and @code{inst-value}, and its protected
11072: words. It also has a pointer to its parent. @code{class} pushes
11073: the word lists of the class and all its ancestors onto the search order stack,
11074: and @code{end-class} drops them.
1.20 pazsan 11075:
1.78 anton 11076: @cindex interface implementation
11077: An interface is like a class without fields, parent and protected
11078: words; i.e., it just has a method map. If a class implements an
11079: interface, its method map contains a pointer to the method map of the
11080: interface. The positive offsets in the map are reserved for class
11081: methods, therefore interface map pointers have negative
11082: offsets. Interfaces have offsets that are unique throughout the
11083: system, unlike class selectors, whose offsets are only unique for the
11084: classes where the selector is available (invokable).
1.20 pazsan 11085:
1.78 anton 11086: This structure means that interface selectors have to perform one
11087: indirection more than class selectors to find their method. Their body
11088: contains the interface map pointer offset in the class method map, and
11089: the method offset in the interface method map. The
11090: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11091:
11092: @example
1.78 anton 11093: ( object selector-body )
11094: 2dup selector-interface @@ ( object selector-body object interface-offset )
11095: swap object-map @@ + @@ ( object selector-body map )
11096: swap selector-offset @@ + @@ execute
1.20 pazsan 11097: @end example
11098:
1.78 anton 11099: where @code{object-map} and @code{selector-offset} are
11100: first fields and generate no code.
1.20 pazsan 11101:
1.78 anton 11102: As a concrete example, consider the following code:
1.20 pazsan 11103:
11104: @example
1.78 anton 11105: interface
11106: selector if1sel1
11107: selector if1sel2
11108: end-interface if1
1.20 pazsan 11109:
1.78 anton 11110: object class
11111: if1 implementation
11112: selector cl1sel1
11113: cell% inst-var cl1iv1
1.20 pazsan 11114:
1.78 anton 11115: ' m1 overrides construct
11116: ' m2 overrides if1sel1
11117: ' m3 overrides if1sel2
11118: ' m4 overrides cl1sel2
11119: end-class cl1
1.20 pazsan 11120:
1.78 anton 11121: create obj1 object dict-new drop
11122: create obj2 cl1 dict-new drop
11123: @end example
1.20 pazsan 11124:
1.78 anton 11125: The data structure created by this code (including the data structure
11126: for @code{object}) is shown in the
11127: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11128: @comment TODO add this diagram..
1.20 pazsan 11129:
1.78 anton 11130: @node Objects Glossary, , Objects Implementation, Objects
11131: @subsubsection @file{objects.fs} Glossary
11132: @cindex @file{objects.fs} Glossary
1.20 pazsan 11133:
11134:
1.78 anton 11135: doc---objects-bind
11136: doc---objects-<bind>
11137: doc---objects-bind'
11138: doc---objects-[bind]
11139: doc---objects-class
11140: doc---objects-class->map
11141: doc---objects-class-inst-size
11142: doc---objects-class-override!
1.79 anton 11143: doc---objects-class-previous
11144: doc---objects-class>order
1.78 anton 11145: doc---objects-construct
11146: doc---objects-current'
11147: doc---objects-[current]
11148: doc---objects-current-interface
11149: doc---objects-dict-new
11150: doc---objects-end-class
11151: doc---objects-end-class-noname
11152: doc---objects-end-interface
11153: doc---objects-end-interface-noname
11154: doc---objects-end-methods
11155: doc---objects-exitm
11156: doc---objects-heap-new
11157: doc---objects-implementation
11158: doc---objects-init-object
11159: doc---objects-inst-value
11160: doc---objects-inst-var
11161: doc---objects-interface
11162: doc---objects-m:
11163: doc---objects-:m
11164: doc---objects-;m
11165: doc---objects-method
11166: doc---objects-methods
11167: doc---objects-object
11168: doc---objects-overrides
11169: doc---objects-[parent]
11170: doc---objects-print
11171: doc---objects-protected
11172: doc---objects-public
11173: doc---objects-selector
11174: doc---objects-this
11175: doc---objects-<to-inst>
11176: doc---objects-[to-inst]
11177: doc---objects-to-this
11178: doc---objects-xt-new
1.20 pazsan 11179:
11180:
1.78 anton 11181: @c -------------------------------------------------------------
11182: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11183: @subsection The @file{oof.fs} model
11184: @cindex oof
11185: @cindex object-oriented programming
1.20 pazsan 11186:
1.78 anton 11187: @cindex @file{objects.fs}
11188: @cindex @file{oof.fs}
1.20 pazsan 11189:
1.78 anton 11190: This section describes the @file{oof.fs} package.
1.20 pazsan 11191:
1.78 anton 11192: The package described in this section has been used in bigFORTH since 1991, and
11193: used for two large applications: a chromatographic system used to
11194: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11195:
1.78 anton 11196: You can find a description (in German) of @file{oof.fs} in @cite{Object
11197: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11198: 10(2), 1994.
1.20 pazsan 11199:
1.78 anton 11200: @menu
11201: * Properties of the OOF model::
11202: * Basic OOF Usage::
11203: * The OOF base class::
11204: * Class Declaration::
11205: * Class Implementation::
11206: @end menu
1.20 pazsan 11207:
1.78 anton 11208: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11209: @subsubsection Properties of the @file{oof.fs} model
11210: @cindex @file{oof.fs} properties
1.20 pazsan 11211:
1.78 anton 11212: @itemize @bullet
11213: @item
11214: This model combines object oriented programming with information
11215: hiding. It helps you writing large application, where scoping is
11216: necessary, because it provides class-oriented scoping.
1.20 pazsan 11217:
1.78 anton 11218: @item
11219: Named objects, object pointers, and object arrays can be created,
11220: selector invocation uses the ``object selector'' syntax. Selector invocation
11221: to objects and/or selectors on the stack is a bit less convenient, but
11222: possible.
1.44 crook 11223:
1.78 anton 11224: @item
11225: Selector invocation and instance variable usage of the active object is
11226: straightforward, since both make use of the active object.
1.44 crook 11227:
1.78 anton 11228: @item
11229: Late binding is efficient and easy to use.
1.20 pazsan 11230:
1.78 anton 11231: @item
11232: State-smart objects parse selectors. However, extensibility is provided
11233: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11234:
1.78 anton 11235: @item
11236: An implementation in ANS Forth is available.
1.20 pazsan 11237:
1.78 anton 11238: @end itemize
1.23 crook 11239:
11240:
1.78 anton 11241: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11242: @subsubsection Basic @file{oof.fs} Usage
11243: @cindex @file{oof.fs} usage
1.23 crook 11244:
1.78 anton 11245: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11246:
1.78 anton 11247: You can define a class for graphical objects like this:
1.23 crook 11248:
1.78 anton 11249: @cindex @code{class} usage
11250: @cindex @code{class;} usage
11251: @cindex @code{method} usage
11252: @example
11253: object class graphical \ "object" is the parent class
1.139 pazsan 11254: method draw ( x y -- )
1.78 anton 11255: class;
11256: @end example
1.23 crook 11257:
1.78 anton 11258: This code defines a class @code{graphical} with an
11259: operation @code{draw}. We can perform the operation
11260: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11261:
1.78 anton 11262: @example
11263: 100 100 t-rex draw
11264: @end example
1.23 crook 11265:
1.78 anton 11266: @noindent
11267: where @code{t-rex} is an object or object pointer, created with e.g.
11268: @code{graphical : t-rex}.
1.23 crook 11269:
1.78 anton 11270: @cindex abstract class
11271: How do we create a graphical object? With the present definitions,
11272: we cannot create a useful graphical object. The class
11273: @code{graphical} describes graphical objects in general, but not
11274: any concrete graphical object type (C++ users would call it an
11275: @emph{abstract class}); e.g., there is no method for the selector
11276: @code{draw} in the class @code{graphical}.
1.23 crook 11277:
1.78 anton 11278: For concrete graphical objects, we define child classes of the
11279: class @code{graphical}, e.g.:
1.23 crook 11280:
1.78 anton 11281: @example
11282: graphical class circle \ "graphical" is the parent class
11283: cell var circle-radius
11284: how:
11285: : draw ( x y -- )
11286: circle-radius @@ draw-circle ;
1.23 crook 11287:
1.139 pazsan 11288: : init ( n-radius -- )
1.78 anton 11289: circle-radius ! ;
11290: class;
11291: @end example
1.1 anton 11292:
1.78 anton 11293: Here we define a class @code{circle} as a child of @code{graphical},
11294: with a field @code{circle-radius}; it defines new methods for the
11295: selectors @code{draw} and @code{init} (@code{init} is defined in
11296: @code{object}, the parent class of @code{graphical}).
1.1 anton 11297:
1.78 anton 11298: Now we can create a circle in the dictionary with:
1.1 anton 11299:
1.78 anton 11300: @example
11301: 50 circle : my-circle
11302: @end example
1.21 crook 11303:
1.78 anton 11304: @noindent
11305: @code{:} invokes @code{init}, thus initializing the field
11306: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11307: with:
1.1 anton 11308:
1.78 anton 11309: @example
11310: 100 100 my-circle draw
11311: @end example
1.1 anton 11312:
1.78 anton 11313: @cindex selector invocation, restrictions
11314: @cindex class definition, restrictions
11315: Note: You can only invoke a selector if the receiving object belongs to
11316: the class where the selector was defined or one of its descendents;
11317: e.g., you can invoke @code{draw} only for objects belonging to
11318: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11319: mechanism will check if you try to invoke a selector that is not
11320: defined in this class hierarchy, so you'll get an error at compilation
11321: time.
1.1 anton 11322:
11323:
1.78 anton 11324: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11325: @subsubsection The @file{oof.fs} base class
11326: @cindex @file{oof.fs} base class
1.1 anton 11327:
1.78 anton 11328: When you define a class, you have to specify a parent class. So how do
11329: you start defining classes? There is one class available from the start:
11330: @code{object}. You have to use it as ancestor for all classes. It is the
11331: only class that has no parent. Classes are also objects, except that
11332: they don't have instance variables; class manipulation such as
11333: inheritance or changing definitions of a class is handled through
11334: selectors of the class @code{object}.
1.1 anton 11335:
1.78 anton 11336: @code{object} provides a number of selectors:
1.1 anton 11337:
1.78 anton 11338: @itemize @bullet
11339: @item
11340: @code{class} for subclassing, @code{definitions} to add definitions
11341: later on, and @code{class?} to get type informations (is the class a
11342: subclass of the class passed on the stack?).
1.1 anton 11343:
1.78 anton 11344: doc---object-class
11345: doc---object-definitions
11346: doc---object-class?
1.1 anton 11347:
11348:
1.26 crook 11349: @item
1.78 anton 11350: @code{init} and @code{dispose} as constructor and destructor of the
11351: object. @code{init} is invocated after the object's memory is allocated,
11352: while @code{dispose} also handles deallocation. Thus if you redefine
11353: @code{dispose}, you have to call the parent's dispose with @code{super
11354: dispose}, too.
11355:
11356: doc---object-init
11357: doc---object-dispose
11358:
1.1 anton 11359:
1.26 crook 11360: @item
1.78 anton 11361: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11362: @code{[]} to create named and unnamed objects and object arrays or
11363: object pointers.
11364:
11365: doc---object-new
11366: doc---object-new[]
11367: doc---object-:
11368: doc---object-ptr
11369: doc---object-asptr
11370: doc---object-[]
11371:
1.1 anton 11372:
1.26 crook 11373: @item
1.78 anton 11374: @code{::} and @code{super} for explicit scoping. You should use explicit
11375: scoping only for super classes or classes with the same set of instance
11376: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11377:
1.78 anton 11378: doc---object-::
11379: doc---object-super
1.21 crook 11380:
11381:
1.26 crook 11382: @item
1.78 anton 11383: @code{self} to get the address of the object
1.21 crook 11384:
1.78 anton 11385: doc---object-self
1.21 crook 11386:
11387:
1.78 anton 11388: @item
11389: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11390: pointers and instance defers.
1.21 crook 11391:
1.78 anton 11392: doc---object-bind
11393: doc---object-bound
11394: doc---object-link
11395: doc---object-is
1.21 crook 11396:
11397:
1.78 anton 11398: @item
11399: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11400: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11401:
1.78 anton 11402: doc---object-'
11403: doc---object-postpone
1.21 crook 11404:
11405:
1.78 anton 11406: @item
11407: @code{with} and @code{endwith} to select the active object from the
11408: stack, and enable its scope. Using @code{with} and @code{endwith}
11409: also allows you to create code using selector @code{postpone} without being
11410: trapped by the state-smart objects.
1.21 crook 11411:
1.78 anton 11412: doc---object-with
11413: doc---object-endwith
1.21 crook 11414:
11415:
1.78 anton 11416: @end itemize
1.21 crook 11417:
1.78 anton 11418: @node Class Declaration, Class Implementation, The OOF base class, OOF
11419: @subsubsection Class Declaration
11420: @cindex class declaration
1.21 crook 11421:
1.78 anton 11422: @itemize @bullet
11423: @item
11424: Instance variables
1.21 crook 11425:
1.78 anton 11426: doc---oof-var
1.21 crook 11427:
11428:
1.78 anton 11429: @item
11430: Object pointers
1.21 crook 11431:
1.78 anton 11432: doc---oof-ptr
11433: doc---oof-asptr
1.21 crook 11434:
11435:
1.78 anton 11436: @item
11437: Instance defers
1.21 crook 11438:
1.78 anton 11439: doc---oof-defer
1.21 crook 11440:
11441:
1.78 anton 11442: @item
11443: Method selectors
1.21 crook 11444:
1.78 anton 11445: doc---oof-early
11446: doc---oof-method
1.21 crook 11447:
11448:
1.78 anton 11449: @item
11450: Class-wide variables
1.21 crook 11451:
1.78 anton 11452: doc---oof-static
1.21 crook 11453:
11454:
1.78 anton 11455: @item
11456: End declaration
1.1 anton 11457:
1.78 anton 11458: doc---oof-how:
11459: doc---oof-class;
1.21 crook 11460:
11461:
1.78 anton 11462: @end itemize
1.21 crook 11463:
1.78 anton 11464: @c -------------------------------------------------------------
11465: @node Class Implementation, , Class Declaration, OOF
11466: @subsubsection Class Implementation
11467: @cindex class implementation
1.21 crook 11468:
1.78 anton 11469: @c -------------------------------------------------------------
11470: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11471: @subsection The @file{mini-oof.fs} model
11472: @cindex mini-oof
1.21 crook 11473:
1.78 anton 11474: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11475: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11476: and reduces to the bare minimum of features. This is based on a posting
11477: of Bernd Paysan in comp.lang.forth.
1.21 crook 11478:
1.78 anton 11479: @menu
11480: * Basic Mini-OOF Usage::
11481: * Mini-OOF Example::
11482: * Mini-OOF Implementation::
11483: @end menu
1.21 crook 11484:
1.78 anton 11485: @c -------------------------------------------------------------
11486: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11487: @subsubsection Basic @file{mini-oof.fs} Usage
11488: @cindex mini-oof usage
1.21 crook 11489:
1.78 anton 11490: There is a base class (@code{class}, which allocates one cell for the
11491: object pointer) plus seven other words: to define a method, a variable,
11492: a class; to end a class, to resolve binding, to allocate an object and
11493: to compile a class method.
11494: @comment TODO better description of the last one
1.26 crook 11495:
1.21 crook 11496:
1.78 anton 11497: doc-object
11498: doc-method
11499: doc-var
11500: doc-class
11501: doc-end-class
11502: doc-defines
11503: doc-new
11504: doc-::
1.21 crook 11505:
11506:
11507:
1.78 anton 11508: @c -------------------------------------------------------------
11509: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11510: @subsubsection Mini-OOF Example
11511: @cindex mini-oof example
1.1 anton 11512:
1.78 anton 11513: A short example shows how to use this package. This example, in slightly
11514: extended form, is supplied as @file{moof-exm.fs}
11515: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11516:
1.26 crook 11517: @example
1.78 anton 11518: object class
11519: method init
11520: method draw
11521: end-class graphical
1.26 crook 11522: @end example
1.20 pazsan 11523:
1.78 anton 11524: This code defines a class @code{graphical} with an
11525: operation @code{draw}. We can perform the operation
11526: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11527:
1.26 crook 11528: @example
1.78 anton 11529: 100 100 t-rex draw
1.26 crook 11530: @end example
1.12 anton 11531:
1.78 anton 11532: where @code{t-rex} is an object or object pointer, created with e.g.
11533: @code{graphical new Constant t-rex}.
1.12 anton 11534:
1.78 anton 11535: For concrete graphical objects, we define child classes of the
11536: class @code{graphical}, e.g.:
1.12 anton 11537:
1.26 crook 11538: @example
11539: graphical class
1.78 anton 11540: cell var circle-radius
11541: end-class circle \ "graphical" is the parent class
1.12 anton 11542:
1.78 anton 11543: :noname ( x y -- )
11544: circle-radius @@ draw-circle ; circle defines draw
11545: :noname ( r -- )
11546: circle-radius ! ; circle defines init
11547: @end example
1.12 anton 11548:
1.78 anton 11549: There is no implicit init method, so we have to define one. The creation
11550: code of the object now has to call init explicitely.
1.21 crook 11551:
1.78 anton 11552: @example
11553: circle new Constant my-circle
11554: 50 my-circle init
1.12 anton 11555: @end example
11556:
1.78 anton 11557: It is also possible to add a function to create named objects with
11558: automatic call of @code{init}, given that all objects have @code{init}
11559: on the same place:
1.38 anton 11560:
1.78 anton 11561: @example
11562: : new: ( .. o "name" -- )
11563: new dup Constant init ;
11564: 80 circle new: large-circle
11565: @end example
1.12 anton 11566:
1.78 anton 11567: We can draw this new circle at (100,100) with:
1.12 anton 11568:
1.78 anton 11569: @example
11570: 100 100 my-circle draw
11571: @end example
1.12 anton 11572:
1.78 anton 11573: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11574: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11575:
1.78 anton 11576: Object-oriented systems with late binding typically use a
11577: ``vtable''-approach: the first variable in each object is a pointer to a
11578: table, which contains the methods as function pointers. The vtable
11579: may also contain other information.
1.12 anton 11580:
1.79 anton 11581: So first, let's declare selectors:
1.37 anton 11582:
11583: @example
1.79 anton 11584: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11585: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11586: @end example
1.37 anton 11587:
1.79 anton 11588: During selector declaration, the number of selectors and instance
11589: variables is on the stack (in address units). @code{method} creates one
11590: selector and increments the selector number. To execute a selector, it
1.78 anton 11591: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11592: executes the method @i{xt} stored there. Each selector takes the object
11593: it is invoked with as top of stack parameter; it passes the parameters
11594: (including the object) unchanged to the appropriate method which should
1.78 anton 11595: consume that object.
1.37 anton 11596:
1.78 anton 11597: Now, we also have to declare instance variables
1.37 anton 11598:
1.78 anton 11599: @example
1.79 anton 11600: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11601: DOES> ( o -- addr ) @@ + ;
1.37 anton 11602: @end example
11603:
1.78 anton 11604: As before, a word is created with the current offset. Instance
11605: variables can have different sizes (cells, floats, doubles, chars), so
11606: all we do is take the size and add it to the offset. If your machine
11607: has alignment restrictions, put the proper @code{aligned} or
11608: @code{faligned} before the variable, to adjust the variable
11609: offset. That's why it is on the top of stack.
1.37 anton 11610:
1.78 anton 11611: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11612:
1.78 anton 11613: @example
11614: Create object 1 cells , 2 cells ,
1.79 anton 11615: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11616: @end example
1.12 anton 11617:
1.78 anton 11618: For inheritance, the vtable of the parent object has to be
11619: copied when a new, derived class is declared. This gives all the
11620: methods of the parent class, which can be overridden, though.
1.12 anton 11621:
1.78 anton 11622: @example
1.79 anton 11623: : end-class ( class selectors vars "name" -- )
1.78 anton 11624: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11625: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11626: @end example
1.12 anton 11627:
1.78 anton 11628: The first line creates the vtable, initialized with
11629: @code{noop}s. The second line is the inheritance mechanism, it
11630: copies the xts from the parent vtable.
1.12 anton 11631:
1.78 anton 11632: We still have no way to define new methods, let's do that now:
1.12 anton 11633:
1.26 crook 11634: @example
1.79 anton 11635: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11636: @end example
1.12 anton 11637:
1.78 anton 11638: To allocate a new object, we need a word, too:
1.12 anton 11639:
1.78 anton 11640: @example
11641: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11642: @end example
11643:
1.78 anton 11644: Sometimes derived classes want to access the method of the
11645: parent object. There are two ways to achieve this with Mini-OOF:
11646: first, you could use named words, and second, you could look up the
11647: vtable of the parent object.
1.12 anton 11648:
1.78 anton 11649: @example
11650: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11651: @end example
1.12 anton 11652:
11653:
1.78 anton 11654: Nothing can be more confusing than a good example, so here is
11655: one. First let's declare a text object (called
11656: @code{button}), that stores text and position:
1.12 anton 11657:
1.78 anton 11658: @example
11659: object class
11660: cell var text
11661: cell var len
11662: cell var x
11663: cell var y
11664: method init
11665: method draw
11666: end-class button
11667: @end example
1.12 anton 11668:
1.78 anton 11669: @noindent
11670: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11671:
1.26 crook 11672: @example
1.78 anton 11673: :noname ( o -- )
11674: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11675: button defines draw
11676: :noname ( addr u o -- )
11677: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11678: button defines init
1.26 crook 11679: @end example
1.12 anton 11680:
1.78 anton 11681: @noindent
11682: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11683: new data and no new selectors:
1.78 anton 11684:
11685: @example
11686: button class
11687: end-class bold-button
1.12 anton 11688:
1.78 anton 11689: : bold 27 emit ." [1m" ;
11690: : normal 27 emit ." [0m" ;
11691: @end example
1.1 anton 11692:
1.78 anton 11693: @noindent
11694: The class @code{bold-button} has a different draw method to
11695: @code{button}, but the new method is defined in terms of the draw method
11696: for @code{button}:
1.20 pazsan 11697:
1.78 anton 11698: @example
11699: :noname bold [ button :: draw ] normal ; bold-button defines draw
11700: @end example
1.21 crook 11701:
1.78 anton 11702: @noindent
1.79 anton 11703: Finally, create two objects and apply selectors:
1.21 crook 11704:
1.26 crook 11705: @example
1.78 anton 11706: button new Constant foo
11707: s" thin foo" foo init
11708: page
11709: foo draw
11710: bold-button new Constant bar
11711: s" fat bar" bar init
11712: 1 bar y !
11713: bar draw
1.26 crook 11714: @end example
1.21 crook 11715:
11716:
1.78 anton 11717: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11718: @subsection Comparison with other object models
11719: @cindex comparison of object models
11720: @cindex object models, comparison
11721:
11722: Many object-oriented Forth extensions have been proposed (@cite{A survey
11723: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11724: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11725: relation of the object models described here to two well-known and two
11726: closely-related (by the use of method maps) models. Andras Zsoter
11727: helped us with this section.
11728:
11729: @cindex Neon model
11730: The most popular model currently seems to be the Neon model (see
11731: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11732: 1997) by Andrew McKewan) but this model has a number of limitations
11733: @footnote{A longer version of this critique can be
11734: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11735: Dimensions, May 1997) by Anton Ertl.}:
11736:
11737: @itemize @bullet
11738: @item
11739: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11740: to pass objects on the stack.
1.21 crook 11741:
1.78 anton 11742: @item
11743: It requires that the selector parses the input stream (at
1.79 anton 11744: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11745: hard to find.
1.21 crook 11746:
1.78 anton 11747: @item
1.79 anton 11748: It allows using every selector on every object; this eliminates the
11749: need for interfaces, but makes it harder to create efficient
11750: implementations.
1.78 anton 11751: @end itemize
1.21 crook 11752:
1.78 anton 11753: @cindex Pountain's object-oriented model
11754: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11755: Press, London, 1987) by Dick Pountain. However, it is not really about
11756: object-oriented programming, because it hardly deals with late
11757: binding. Instead, it focuses on features like information hiding and
11758: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11759:
1.78 anton 11760: @cindex Zsoter's object-oriented model
1.79 anton 11761: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11762: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11763: describes a model that makes heavy use of an active object (like
11764: @code{this} in @file{objects.fs}): The active object is not only used
11765: for accessing all fields, but also specifies the receiving object of
11766: every selector invocation; you have to change the active object
11767: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11768: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11769: the method entry point is unnecessary with Zsoter's model, because the
11770: receiving object is the active object already. On the other hand, the
11771: explicit change is absolutely necessary in that model, because otherwise
11772: no one could ever change the active object. An ANS Forth implementation
11773: of this model is available through
11774: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11775:
1.78 anton 11776: @cindex @file{oof.fs}, differences to other models
11777: The @file{oof.fs} model combines information hiding and overloading
11778: resolution (by keeping names in various word lists) with object-oriented
11779: programming. It sets the active object implicitly on method entry, but
11780: also allows explicit changing (with @code{>o...o>} or with
11781: @code{with...endwith}). It uses parsing and state-smart objects and
11782: classes for resolving overloading and for early binding: the object or
11783: class parses the selector and determines the method from this. If the
11784: selector is not parsed by an object or class, it performs a call to the
11785: selector for the active object (late binding), like Zsoter's model.
11786: Fields are always accessed through the active object. The big
11787: disadvantage of this model is the parsing and the state-smartness, which
11788: reduces extensibility and increases the opportunities for subtle bugs;
11789: essentially, you are only safe if you never tick or @code{postpone} an
11790: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11791:
1.78 anton 11792: @cindex @file{mini-oof.fs}, differences to other models
11793: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11794: version of the @file{objects.fs} model, but syntactically it is a
11795: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11796:
11797:
1.78 anton 11798: @c -------------------------------------------------------------
1.150 anton 11799: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11800: @section Programming Tools
11801: @cindex programming tools
1.21 crook 11802:
1.78 anton 11803: @c !! move this and assembler down below OO stuff.
1.21 crook 11804:
1.78 anton 11805: @menu
1.150 anton 11806: * Examining:: Data and Code.
11807: * Forgetting words:: Usually before reloading.
1.78 anton 11808: * Debugging:: Simple and quick.
11809: * Assertions:: Making your programs self-checking.
11810: * Singlestep Debugger:: Executing your program word by word.
11811: @end menu
1.21 crook 11812:
1.78 anton 11813: @node Examining, Forgetting words, Programming Tools, Programming Tools
11814: @subsection Examining data and code
11815: @cindex examining data and code
11816: @cindex data examination
11817: @cindex code examination
1.44 crook 11818:
1.78 anton 11819: The following words inspect the stack non-destructively:
1.21 crook 11820:
1.78 anton 11821: doc-.s
11822: doc-f.s
1.158 anton 11823: doc-maxdepth-.s
1.44 crook 11824:
1.78 anton 11825: There is a word @code{.r} but it does @i{not} display the return stack!
11826: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11827:
1.78 anton 11828: doc-depth
11829: doc-fdepth
11830: doc-clearstack
1.124 anton 11831: doc-clearstacks
1.21 crook 11832:
1.78 anton 11833: The following words inspect memory.
1.21 crook 11834:
1.78 anton 11835: doc-?
11836: doc-dump
1.21 crook 11837:
1.78 anton 11838: And finally, @code{see} allows to inspect code:
1.21 crook 11839:
1.78 anton 11840: doc-see
11841: doc-xt-see
1.111 anton 11842: doc-simple-see
11843: doc-simple-see-range
1.182 anton 11844: doc-see-code
11845: doc-see-code-range
1.21 crook 11846:
1.78 anton 11847: @node Forgetting words, Debugging, Examining, Programming Tools
11848: @subsection Forgetting words
11849: @cindex words, forgetting
11850: @cindex forgeting words
1.21 crook 11851:
1.78 anton 11852: @c anton: other, maybe better places for this subsection: Defining Words;
11853: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11854:
1.78 anton 11855: Forth allows you to forget words (and everything that was alloted in the
11856: dictonary after them) in a LIFO manner.
1.21 crook 11857:
1.78 anton 11858: doc-marker
1.21 crook 11859:
1.78 anton 11860: The most common use of this feature is during progam development: when
11861: you change a source file, forget all the words it defined and load it
11862: again (since you also forget everything defined after the source file
11863: was loaded, you have to reload that, too). Note that effects like
11864: storing to variables and destroyed system words are not undone when you
11865: forget words. With a system like Gforth, that is fast enough at
11866: starting up and compiling, I find it more convenient to exit and restart
11867: Gforth, as this gives me a clean slate.
1.21 crook 11868:
1.78 anton 11869: Here's an example of using @code{marker} at the start of a source file
11870: that you are debugging; it ensures that you only ever have one copy of
11871: the file's definitions compiled at any time:
1.21 crook 11872:
1.78 anton 11873: @example
11874: [IFDEF] my-code
11875: my-code
11876: [ENDIF]
1.26 crook 11877:
1.78 anton 11878: marker my-code
11879: init-included-files
1.21 crook 11880:
1.78 anton 11881: \ .. definitions start here
11882: \ .
11883: \ .
11884: \ end
11885: @end example
1.21 crook 11886:
1.26 crook 11887:
1.78 anton 11888: @node Debugging, Assertions, Forgetting words, Programming Tools
11889: @subsection Debugging
11890: @cindex debugging
1.21 crook 11891:
1.78 anton 11892: Languages with a slow edit/compile/link/test development loop tend to
11893: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11894:
1.78 anton 11895: A much better (faster) way in fast-compiling languages is to add
11896: printing code at well-selected places, let the program run, look at
11897: the output, see where things went wrong, add more printing code, etc.,
11898: until the bug is found.
1.21 crook 11899:
1.78 anton 11900: The simple debugging aids provided in @file{debugs.fs}
11901: are meant to support this style of debugging.
1.21 crook 11902:
1.78 anton 11903: The word @code{~~} prints debugging information (by default the source
11904: location and the stack contents). It is easy to insert. If you use Emacs
11905: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11906: query-replace them with nothing). The deferred words
1.101 anton 11907: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11908: @code{~~}. The default source location output format works well with
11909: Emacs' compilation mode, so you can step through the program at the
11910: source level using @kbd{C-x `} (the advantage over a stepping debugger
11911: is that you can step in any direction and you know where the crash has
11912: happened or where the strange data has occurred).
1.21 crook 11913:
1.78 anton 11914: doc-~~
11915: doc-printdebugdata
1.101 anton 11916: doc-.debugline
1.203 anton 11917: doc-debug-fid
1.21 crook 11918:
1.106 anton 11919: @cindex filenames in @code{~~} output
11920: @code{~~} (and assertions) will usually print the wrong file name if a
11921: marker is executed in the same file after their occurance. They will
11922: print @samp{*somewhere*} as file name if a marker is executed in the
11923: same file before their occurance.
11924:
11925:
1.78 anton 11926: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11927: @subsection Assertions
11928: @cindex assertions
1.21 crook 11929:
1.78 anton 11930: It is a good idea to make your programs self-checking, especially if you
11931: make an assumption that may become invalid during maintenance (for
11932: example, that a certain field of a data structure is never zero). Gforth
11933: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11934:
11935: @example
1.78 anton 11936: assert( @i{flag} )
1.26 crook 11937: @end example
11938:
1.78 anton 11939: The code between @code{assert(} and @code{)} should compute a flag, that
11940: should be true if everything is alright and false otherwise. It should
11941: not change anything else on the stack. The overall stack effect of the
11942: assertion is @code{( -- )}. E.g.
1.21 crook 11943:
1.26 crook 11944: @example
1.78 anton 11945: assert( 1 1 + 2 = ) \ what we learn in school
11946: assert( dup 0<> ) \ assert that the top of stack is not zero
11947: assert( false ) \ this code should not be reached
1.21 crook 11948: @end example
11949:
1.78 anton 11950: The need for assertions is different at different times. During
11951: debugging, we want more checking, in production we sometimes care more
11952: for speed. Therefore, assertions can be turned off, i.e., the assertion
11953: becomes a comment. Depending on the importance of an assertion and the
11954: time it takes to check it, you may want to turn off some assertions and
11955: keep others turned on. Gforth provides several levels of assertions for
11956: this purpose:
11957:
11958:
11959: doc-assert0(
11960: doc-assert1(
11961: doc-assert2(
11962: doc-assert3(
11963: doc-assert(
11964: doc-)
1.21 crook 11965:
11966:
1.78 anton 11967: The variable @code{assert-level} specifies the highest assertions that
11968: are turned on. I.e., at the default @code{assert-level} of one,
11969: @code{assert0(} and @code{assert1(} assertions perform checking, while
11970: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11971:
1.78 anton 11972: The value of @code{assert-level} is evaluated at compile-time, not at
11973: run-time. Therefore you cannot turn assertions on or off at run-time;
11974: you have to set the @code{assert-level} appropriately before compiling a
11975: piece of code. You can compile different pieces of code at different
11976: @code{assert-level}s (e.g., a trusted library at level 1 and
11977: newly-written code at level 3).
1.26 crook 11978:
11979:
1.78 anton 11980: doc-assert-level
1.26 crook 11981:
11982:
1.78 anton 11983: If an assertion fails, a message compatible with Emacs' compilation mode
11984: is produced and the execution is aborted (currently with @code{ABORT"}.
11985: If there is interest, we will introduce a special throw code. But if you
11986: intend to @code{catch} a specific condition, using @code{throw} is
11987: probably more appropriate than an assertion).
1.106 anton 11988:
11989: @cindex filenames in assertion output
11990: Assertions (and @code{~~}) will usually print the wrong file name if a
11991: marker is executed in the same file after their occurance. They will
11992: print @samp{*somewhere*} as file name if a marker is executed in the
11993: same file before their occurance.
1.44 crook 11994:
1.78 anton 11995: Definitions in ANS Forth for these assertion words are provided
11996: in @file{compat/assert.fs}.
1.26 crook 11997:
1.44 crook 11998:
1.78 anton 11999: @node Singlestep Debugger, , Assertions, Programming Tools
12000: @subsection Singlestep Debugger
12001: @cindex singlestep Debugger
12002: @cindex debugging Singlestep
1.44 crook 12003:
1.189 anton 12004: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 12005:
1.78 anton 12006: When you create a new word there's often the need to check whether it
12007: behaves correctly or not. You can do this by typing @code{dbg
12008: badword}. A debug session might look like this:
1.26 crook 12009:
1.78 anton 12010: @example
12011: : badword 0 DO i . LOOP ; ok
12012: 2 dbg badword
12013: : badword
12014: Scanning code...
1.44 crook 12015:
1.78 anton 12016: Nesting debugger ready!
1.44 crook 12017:
1.78 anton 12018: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
12019: 400D4740 8049F68 DO -> [ 0 ]
12020: 400D4744 804A0C8 i -> [ 1 ] 00000
12021: 400D4748 400C5E60 . -> 0 [ 0 ]
12022: 400D474C 8049D0C LOOP -> [ 0 ]
12023: 400D4744 804A0C8 i -> [ 1 ] 00001
12024: 400D4748 400C5E60 . -> 1 [ 0 ]
12025: 400D474C 8049D0C LOOP -> [ 0 ]
12026: 400D4758 804B384 ; -> ok
12027: @end example
1.21 crook 12028:
1.78 anton 12029: Each line displayed is one step. You always have to hit return to
12030: execute the next word that is displayed. If you don't want to execute
12031: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12032: an overview what keys are available:
1.44 crook 12033:
1.78 anton 12034: @table @i
1.44 crook 12035:
1.78 anton 12036: @item @key{RET}
12037: Next; Execute the next word.
1.21 crook 12038:
1.78 anton 12039: @item n
12040: Nest; Single step through next word.
1.44 crook 12041:
1.78 anton 12042: @item u
12043: Unnest; Stop debugging and execute rest of word. If we got to this word
12044: with nest, continue debugging with the calling word.
1.44 crook 12045:
1.78 anton 12046: @item d
12047: Done; Stop debugging and execute rest.
1.21 crook 12048:
1.78 anton 12049: @item s
12050: Stop; Abort immediately.
1.44 crook 12051:
1.78 anton 12052: @end table
1.44 crook 12053:
1.78 anton 12054: Debugging large application with this mechanism is very difficult, because
12055: you have to nest very deeply into the program before the interesting part
12056: begins. This takes a lot of time.
1.26 crook 12057:
1.78 anton 12058: To do it more directly put a @code{BREAK:} command into your source code.
12059: When program execution reaches @code{BREAK:} the single step debugger is
12060: invoked and you have all the features described above.
1.44 crook 12061:
1.78 anton 12062: If you have more than one part to debug it is useful to know where the
12063: program has stopped at the moment. You can do this by the
12064: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12065: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12066:
1.26 crook 12067:
1.78 anton 12068: doc-dbg
12069: doc-break:
12070: doc-break"
1.44 crook 12071:
1.150 anton 12072: @c ------------------------------------------------------------
12073: @node C Interface, Assembler and Code Words, Programming Tools, Words
12074: @section C Interface
12075: @cindex C interface
12076: @cindex foreign language interface
12077: @cindex interface to C functions
12078:
1.178 anton 12079: Note that the C interface is not yet complete; callbacks are missing,
12080: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12081:
12082: @menu
12083: * Calling C Functions::
12084: * Declaring C Functions::
1.180 anton 12085: * Calling C function pointers::
1.196 anton 12086: * Defining library interfaces::
12087: * Declaring OS-level libraries::
1.150 anton 12088: * Callbacks::
1.178 anton 12089: * C interface internals::
1.155 anton 12090: * Low-Level C Interface Words::
1.150 anton 12091: @end menu
12092:
1.151 pazsan 12093: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12094: @subsection Calling C functions
1.155 anton 12095: @cindex C functions, calls to
12096: @cindex calling C functions
1.150 anton 12097:
1.151 pazsan 12098: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12099: can call it as follows: You push the arguments on the stack(s), and
12100: then call the word for the C function. The arguments have to be
12101: pushed in the same order as the arguments appear in the C
12102: documentation (i.e., the first argument is deepest on the stack).
12103: Integer and pointer arguments have to be pushed on the data stack,
12104: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12105: by the called C function.
1.150 anton 12106:
1.155 anton 12107: On returning from the C function, the return value, if any, resides on
12108: the appropriate stack: an integer return value is pushed on the data
12109: stack, an FP return value on the FP stack, and a void return value
12110: results in not pushing anything. Note that most C functions have a
12111: return value, even if that is often not used in C; in Forth, you have
12112: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12113:
1.177 anton 12114: The C interface automatically converts between the C type and the
12115: Forth type as necessary, on a best-effort basis (in some cases, there
12116: may be some loss).
1.150 anton 12117:
12118: As an example, consider the POSIX function @code{lseek()}:
12119:
12120: @example
12121: off_t lseek(int fd, off_t offset, int whence);
12122: @end example
12123:
12124: This function takes three integer arguments, and returns an integer
12125: argument, so a Forth call for setting the current file offset to the
12126: start of the file could look like this:
12127:
12128: @example
12129: fd @@ 0 SEEK_SET lseek -1 = if
12130: ... \ error handling
12131: then
12132: @end example
12133:
12134: You might be worried that an @code{off_t} does not fit into a cell, so
12135: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12136: of the return values. In that case, in your declaration of the
12137: function (@pxref{Declaring C Functions}) you should declare it to use
12138: double-cells for the off_t argument and return value, and maybe give
12139: the resulting Forth word a different name, like @code{dlseek}; the
12140: result could be called like this:
1.150 anton 12141:
12142: @example
12143: fd @@ 0. SEEK_SET dlseek -1. d= if
12144: ... \ error handling
12145: then
12146: @end example
12147:
12148: Passing and returning structs or unions is currently not supported by
12149: our interface@footnote{If you know the calling convention of your C
12150: compiler, you usually can call such functions in some way, but that
12151: way is usually not portable between platforms, and sometimes not even
12152: between C compilers.}.
12153:
1.177 anton 12154: Calling functions with a variable number of arguments (@emph{variadic}
12155: functions, e.g., @code{printf()}) is only supported by having you
12156: declare one function-calling word for each argument pattern, and
12157: calling the appropriate word for the desired pattern.
12158:
1.150 anton 12159:
1.155 anton 12160:
1.180 anton 12161: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12162: @subsection Declaring C Functions
1.155 anton 12163: @cindex C functions, declarations
12164: @cindex declaring C functions
1.150 anton 12165:
12166: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12167: it. The declaration consists of two parts:
12168:
12169: @table @b
12170:
12171: @item The C part
1.179 anton 12172: is the C declaration of the function, or more typically and portably,
12173: a C-style @code{#include} of a file that contains the declaration of
12174: the C function.
1.177 anton 12175:
12176: @item The Forth part
12177: declares the Forth types of the parameters and the Forth word name
12178: corresponding to the C function.
12179:
12180: @end table
12181:
12182: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12183: declarations are:
12184:
12185: @example
12186: \c #define _FILE_OFFSET_BITS 64
12187: \c #include <sys/types.h>
12188: \c #include <unistd.h>
12189: c-function lseek lseek n n n -- n
12190: c-function dlseek lseek n d n -- d
12191: @end example
12192:
1.178 anton 12193: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12194: of the line is ordinary C code. You can use as many lines of C
12195: declarations as you like, and they are visible for all further
12196: function declarations.
12197:
12198: The Forth part declares each interface word with @code{c-function},
12199: followed by the Forth name of the word, the C name of the called
12200: function, and the stack effect of the word. The stack effect contains
1.178 anton 12201: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12202: exactly one type for the return value. The possible types are:
12203:
12204: @table @code
12205:
12206: @item n
12207: single-cell integer
12208:
12209: @item a
12210: address (single-cell)
12211:
12212: @item d
12213: double-cell integer
12214:
12215: @item r
12216: floating-point value
12217:
12218: @item func
12219: C function pointer
12220:
12221: @item void
12222: no value (used as return type for void functions)
12223:
12224: @end table
12225:
12226: @cindex variadic C functions
12227:
12228: To deal with variadic C functions, you can declare one Forth word for
12229: every pattern you want to use, e.g.:
12230:
12231: @example
12232: \c #include <stdio.h>
12233: c-function printf-nr printf a n r -- n
12234: c-function printf-rn printf a r n -- n
12235: @end example
12236:
12237: Note that with C functions declared as variadic (or if you don't
12238: provide a prototype), the C interface has no C type to convert to, so
12239: no automatic conversion happens, which may lead to portability
12240: problems in some cases. In such cases you can perform the conversion
12241: explicitly on the C level, e.g., as follows:
12242:
12243: @example
1.178 anton 12244: \c #define printfll(s,ll) printf(s,(long long)ll)
12245: c-function printfll printfll a n -- n
1.177 anton 12246: @end example
12247:
12248: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12249: that casts (converts) the Forth single-cell integer into a
12250: C @code{long long} before calling @code{printf()}.
1.177 anton 12251:
12252: doc-\c
12253: doc-c-function
12254:
12255: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12256: dynamic linking. If these features are not available, there are
12257: other, less convenient and less portable C interfaces in @file{lib.fs}
12258: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12259: mostly incompatible with each other and with the documented C
12260: interface; you can find some examples for the @file{lib.fs} interface
12261: in @file{lib.fs}.
1.177 anton 12262:
12263:
1.196 anton 12264: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180 anton 12265: @subsection Calling C function pointers from Forth
12266: @cindex C function pointers, calling from Forth
1.177 anton 12267:
1.180 anton 12268: If you come across a C function pointer (e.g., in some C-constructed
12269: structure) and want to call it from your Forth program, you can also
12270: use the features explained until now to achieve that, as follows:
1.150 anton 12271:
1.180 anton 12272: Let us assume that there is a C function pointer type @code{func1}
12273: defined in some header file @file{func1.h}, and you know that these
12274: functions take one integer argument and return an integer result; and
12275: you want to call functions through such pointers. Just define
1.155 anton 12276:
1.180 anton 12277: @example
12278: \c #include <func1.h>
12279: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12280: c-function call-func1 call_func1 n func -- n
12281: @end example
12282:
12283: and then you can call a function pointed to by, say @code{func1a} as
12284: follows:
12285:
12286: @example
12287: -5 func1a call-func1 .
12288: @end example
12289:
12290: In the C part, @code{call_func} is defined as a macro to avoid having
12291: to declare the exact parameter and return types, so the C compiler
12292: knows them from the declaration of @code{func1}.
12293:
12294: The Forth word @code{call-func1} is similar to @code{execute}, except
12295: that it takes a C @code{func1} pointer instead of a Forth execution
12296: token, and it is specific to @code{func1} pointers. For each type of
12297: function pointer you want to call from Forth, you have to define
12298: a separate calling word.
12299:
12300:
1.196 anton 12301: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12302: @subsection Defining library interfaces
12303: @cindex giving a name to a library interface
12304: @cindex library interface names
12305:
12306: You can give a name to a bunch of C function declarations (a library
12307: interface), as follows:
12308:
12309: @example
12310: c-library lseek-lib
12311: \c #define _FILE_OFFSET_BITS 64
12312: ...
12313: end-c-library
12314: @end example
12315:
1.202 anton 12316: The effect of giving such a name to the interface is that the names of
12317: the generated files will contain that name, and when you use the
12318: interface a second time, it will use the existing files instead of
12319: generating and compiling them again, saving you time. Note that even
12320: if you change the declarations, the old (stale) files will be used,
12321: probably leading to errors. So, during development of the
12322: declarations we recommend not using @code{c-library}. Normally these
12323: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12324: that directory you can get rid of stale files.
12325:
12326: Note that you should use @code{c-library} before everything else
12327: having anything to do with that library, as it resets some setup
12328: stuff. The idea is that the typical use is to put each
12329: @code{c-library}...@code{end-library} unit in its own file, and to be
12330: able to include these files in any order.
1.196 anton 12331:
12332: Note that the library name is not allocated in the dictionary and
12333: therefore does not shadow dictionary names. It is used in the file
12334: system, so you have to use naming conventions appropriate for file
12335: systems. Also, you must not call a function you declare after
12336: @code{c-library} before you perform @code{end-c-library}.
12337:
12338: A major benefit of these named library interfaces is that, once they
12339: are generated, the tools used to generated them (in particular, the C
12340: compiler and libtool) are no longer needed, so the interface can be
12341: used even on machines that do not have the tools installed.
12342:
12343: doc-c-library-name
12344: doc-c-library
12345: doc-end-c-library
12346:
12347:
12348: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12349: @subsection Declaring OS-level libraries
1.195 anton 12350: @cindex Shared libraries in C interface
12351: @cindex Dynamically linked libraries in C interface
12352: @cindex Libraries in C interface
12353:
1.196 anton 12354: For calling some C functions, you need to link with a specific
12355: OS-level library that contains that function. E.g., the @code{sin}
12356: function requires linking a special library by using the command line
12357: switch @code{-lm}. In our C iterface you do the equivalent thing by
12358: calling @code{add-lib} as follows:
1.195 anton 12359:
12360: @example
12361: clear-libs
12362: s" m" add-lib
12363: \c #include <math.h>
12364: c-function sin sin r -- r
12365: @end example
12366:
12367: First, you clear any libraries that may have been declared earlier
12368: (you don't need them for @code{sin}); then you add the @code{m}
12369: library (actually @code{libm.so} or somesuch) to the currently
12370: declared libraries; you can add as many as you need. Finally you
12371: declare the function as shown above. Typically you will use the same
12372: set of library declarations for many function declarations; you need
12373: to write only one set for that, right at the beginning.
12374:
1.196 anton 12375: Note that you must not call @code{clear-libs} inside
12376: @code{c-library...end-c-library}; however, @code{c-library} performs
12377: the function of @code{clear-libs}, so @code{clear-libs} is not
12378: necessary, and you usually want to put @code{add-lib} calls inside
12379: @code{c-library...end-c-library}.
12380:
1.195 anton 12381: doc-clear-libs
12382: doc-add-lib
12383:
12384:
1.196 anton 12385: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150 anton 12386: @subsection Callbacks
1.155 anton 12387: @cindex Callback functions written in Forth
12388: @cindex C function pointers to Forth words
12389:
1.177 anton 12390: Callbacks are not yet supported by the documented C interface. You
12391: can use the undocumented @file{lib.fs} interface for callbacks.
12392:
1.155 anton 12393: In some cases you have to pass a function pointer to a C function,
12394: i.e., the library wants to call back to your application (and the
12395: pointed-to function is called a callback function). You can pass the
12396: address of an existing C function (that you get with @code{lib-sym},
12397: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12398: function, you probably want to define the function as a Forth word.
12399:
12400: @c I don't understand the existing callback interface from the example - anton
12401:
1.165 anton 12402:
12403: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12404: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12405: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12406: @c > > C-Funktionsadresse auf dem TOS).
12407: @c >
12408: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12409: @c > gesehen habe, wozu das gut ist.
12410: @c
12411: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12412: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12413: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12414: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12415: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12416: @c demselben Prototyp.
12417:
12418:
1.178 anton 12419: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12420: @subsection How the C interface works
12421:
12422: The documented C interface works by generating a C code out of the
12423: declarations.
12424:
12425: In particular, for every Forth word declared with @code{c-function},
12426: it generates a wrapper function in C that takes the Forth data from
12427: the Forth stacks, and calls the target C function with these data as
12428: arguments. The C compiler then performs an implicit conversion
12429: between the Forth type from the stack, and the C type for the
12430: parameter, which is given by the C function prototype. After the C
12431: function returns, the return value is likewise implicitly converted to
12432: a Forth type and written back on the stack.
12433:
12434: The @code{\c} lines are literally included in the C code (but without
12435: the @code{\c}), and provide the necessary declarations so that the C
12436: compiler knows the C types and has enough information to perform the
12437: conversion.
12438:
12439: These wrapper functions are eventually compiled and dynamically linked
12440: into Gforth, and then they can be called.
12441:
1.195 anton 12442: The libraries added with @code{add-lib} are used in the compile
12443: command line to specify dependent libraries with @code{-l@var{lib}},
12444: causing these libraries to be dynamically linked when the wrapper
12445: function is linked.
12446:
1.177 anton 12447:
1.178 anton 12448: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12449: @subsection Low-Level C Interface Words
1.44 crook 12450:
1.155 anton 12451: doc-open-lib
12452: doc-lib-sym
1.196 anton 12453: doc-lib-error
1.177 anton 12454: doc-call-c
1.26 crook 12455:
1.78 anton 12456: @c -------------------------------------------------------------
1.150 anton 12457: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12458: @section Assembler and Code Words
12459: @cindex assembler
12460: @cindex code words
1.44 crook 12461:
1.78 anton 12462: @menu
12463: * Code and ;code::
12464: * Common Assembler:: Assembler Syntax
12465: * Common Disassembler::
12466: * 386 Assembler:: Deviations and special cases
12467: * Alpha Assembler:: Deviations and special cases
12468: * MIPS assembler:: Deviations and special cases
1.161 anton 12469: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 12470: * ARM Assembler:: Deviations and special cases
1.78 anton 12471: * Other assemblers:: How to write them
12472: @end menu
1.21 crook 12473:
1.78 anton 12474: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12475: @subsection @code{Code} and @code{;code}
1.26 crook 12476:
1.78 anton 12477: Gforth provides some words for defining primitives (words written in
12478: machine code), and for defining the machine-code equivalent of
12479: @code{DOES>}-based defining words. However, the machine-independent
12480: nature of Gforth poses a few problems: First of all, Gforth runs on
12481: several architectures, so it can provide no standard assembler. What's
12482: worse is that the register allocation not only depends on the processor,
12483: but also on the @code{gcc} version and options used.
1.44 crook 12484:
1.78 anton 12485: The words that Gforth offers encapsulate some system dependences (e.g.,
12486: the header structure), so a system-independent assembler may be used in
12487: Gforth. If you do not have an assembler, you can compile machine code
12488: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12489: because these words emit stuff in @i{data} space; it works because
12490: Gforth has unified code/data spaces. Assembler isn't likely to be
12491: portable anyway.}.
1.21 crook 12492:
1.44 crook 12493:
1.78 anton 12494: doc-assembler
12495: doc-init-asm
12496: doc-code
12497: doc-end-code
12498: doc-;code
12499: doc-flush-icache
1.44 crook 12500:
1.21 crook 12501:
1.78 anton 12502: If @code{flush-icache} does not work correctly, @code{code} words
12503: etc. will not work (reliably), either.
1.44 crook 12504:
1.78 anton 12505: The typical usage of these @code{code} words can be shown most easily by
12506: analogy to the equivalent high-level defining words:
1.44 crook 12507:
1.78 anton 12508: @example
12509: : foo code foo
12510: <high-level Forth words> <assembler>
12511: ; end-code
12512:
12513: : bar : bar
12514: <high-level Forth words> <high-level Forth words>
12515: CREATE CREATE
12516: <high-level Forth words> <high-level Forth words>
12517: DOES> ;code
12518: <high-level Forth words> <assembler>
12519: ; end-code
12520: @end example
1.21 crook 12521:
1.78 anton 12522: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12523:
1.78 anton 12524: @cindex registers of the inner interpreter
12525: In the assembly code you will want to refer to the inner interpreter's
12526: registers (e.g., the data stack pointer) and you may want to use other
12527: registers for temporary storage. Unfortunately, the register allocation
12528: is installation-dependent.
1.44 crook 12529:
1.78 anton 12530: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12531: (return stack pointer) may be in different places in @code{gforth} and
12532: @code{gforth-fast}, or different installations. This means that you
12533: cannot write a @code{NEXT} routine that works reliably on both versions
12534: or different installations; so for doing @code{NEXT}, I recommend
12535: jumping to @code{' noop >code-address}, which contains nothing but a
12536: @code{NEXT}.
1.21 crook 12537:
1.78 anton 12538: For general accesses to the inner interpreter's registers, the easiest
12539: solution is to use explicit register declarations (@pxref{Explicit Reg
12540: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12541: all of the inner interpreter's registers: You have to compile Gforth
12542: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12543: the appropriate declarations must be present in the @code{machine.h}
12544: file (see @code{mips.h} for an example; you can find a full list of all
12545: declarable register symbols with @code{grep register engine.c}). If you
12546: give explicit registers to all variables that are declared at the
12547: beginning of @code{engine()}, you should be able to use the other
12548: caller-saved registers for temporary storage. Alternatively, you can use
12549: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12550: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12551: reserve a register (however, this restriction on register allocation may
12552: slow Gforth significantly).
1.44 crook 12553:
1.78 anton 12554: If this solution is not viable (e.g., because @code{gcc} does not allow
12555: you to explicitly declare all the registers you need), you have to find
12556: out by looking at the code where the inner interpreter's registers
12557: reside and which registers can be used for temporary storage. You can
12558: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12559:
1.78 anton 12560: In any case, it is good practice to abstract your assembly code from the
12561: actual register allocation. E.g., if the data stack pointer resides in
12562: register @code{$17}, create an alias for this register called @code{sp},
12563: and use that in your assembly code.
1.21 crook 12564:
1.78 anton 12565: @cindex code words, portable
12566: Another option for implementing normal and defining words efficiently
12567: is to add the desired functionality to the source of Gforth. For normal
12568: words you just have to edit @file{primitives} (@pxref{Automatic
12569: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12570: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12571: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12572:
1.78 anton 12573: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12574: @subsection Common Assembler
1.44 crook 12575:
1.78 anton 12576: The assemblers in Gforth generally use a postfix syntax, i.e., the
12577: instruction name follows the operands.
1.21 crook 12578:
1.78 anton 12579: The operands are passed in the usual order (the same that is used in the
12580: manual of the architecture). Since they all are Forth words, they have
12581: to be separated by spaces; you can also use Forth words to compute the
12582: operands.
1.44 crook 12583:
1.78 anton 12584: The instruction names usually end with a @code{,}. This makes it easier
12585: to visually separate instructions if you put several of them on one
12586: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12587:
1.78 anton 12588: Registers are usually specified by number; e.g., (decimal) @code{11}
12589: specifies registers R11 and F11 on the Alpha architecture (which one,
12590: depends on the instruction). The usual names are also available, e.g.,
12591: @code{s2} for R11 on Alpha.
1.21 crook 12592:
1.78 anton 12593: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12594: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12595: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12596: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12597: conditions are specified in a way specific to each assembler.
1.1 anton 12598:
1.78 anton 12599: Note that the register assignments of the Gforth engine can change
12600: between Gforth versions, or even between different compilations of the
12601: same Gforth version (e.g., if you use a different GCC version). So if
12602: you want to refer to Gforth's registers (e.g., the stack pointer or
12603: TOS), I recommend defining your own words for refering to these
12604: registers, and using them later on; then you can easily adapt to a
12605: changed register assignment. The stability of the register assignment
12606: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12607:
1.100 anton 12608: The most common use of these registers is to dispatch to the next word
12609: (the @code{next} routine). A portable way to do this is to jump to
12610: @code{' noop >code-address} (of course, this is less efficient than
12611: integrating the @code{next} code and scheduling it well).
1.1 anton 12612:
1.96 anton 12613: Another difference between Gforth version is that the top of stack is
12614: kept in memory in @code{gforth} and, on most platforms, in a register in
12615: @code{gforth-fast}.
12616:
1.78 anton 12617: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12618: @subsection Common Disassembler
1.127 anton 12619: @cindex disassembler, general
12620: @cindex gdb disassembler
1.1 anton 12621:
1.78 anton 12622: You can disassemble a @code{code} word with @code{see}
12623: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12624:
1.127 anton 12625: doc-discode
1.44 crook 12626:
1.127 anton 12627: There are two kinds of disassembler for Gforth: The Forth disassembler
12628: (available on some CPUs) and the gdb disassembler (available on
12629: platforms with @command{gdb} and @command{mktemp}). If both are
12630: available, the Forth disassembler is used by default. If you prefer
12631: the gdb disassembler, say
12632:
12633: @example
12634: ' disasm-gdb is discode
12635: @end example
12636:
12637: If neither is available, @code{discode} performs @code{dump}.
12638:
12639: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12640: assembler (i.e., same syntax, etc.). It also includes additional
12641: information in comments. In particular, the address of the instruction
12642: is given in a comment before the instruction.
1.1 anton 12643:
1.127 anton 12644: The gdb disassembler produces output in the same format as the gdb
12645: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12646: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12647: the 386 and AMD64 architectures).
12648:
1.78 anton 12649: @code{See} may display more or less than the actual code of the word,
12650: because the recognition of the end of the code is unreliable. You can
1.127 anton 12651: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12652: the code word is not immediately followed by a named word. If you have
1.116 anton 12653: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12654: to ensure that the end is recognized.
1.21 crook 12655:
1.78 anton 12656: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12657: @subsection 386 Assembler
1.44 crook 12658:
1.78 anton 12659: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12660: available under GPL, and originally part of bigFORTH.
1.21 crook 12661:
1.78 anton 12662: The 386 disassembler included in Gforth was written by Andrew McKewan
12663: and is in the public domain.
1.21 crook 12664:
1.91 anton 12665: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12666:
1.78 anton 12667: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12668:
1.78 anton 12669: The assembler includes all instruction of the Athlon, i.e. 486 core
12670: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12671: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12672: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12673:
1.78 anton 12674: There are several prefixes to switch between different operation sizes,
12675: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12676: double-word accesses. Addressing modes can be switched with @code{.wa}
12677: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12678: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12679:
1.78 anton 12680: For floating point operations, the prefixes are @code{.fs} (IEEE
12681: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12682: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12683:
1.78 anton 12684: The MMX opcodes don't have size prefixes, they are spelled out like in
12685: the Intel assembler. Instead of move from and to memory, there are
12686: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12687:
1.78 anton 12688: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12689: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12690: e.g., @code{3 #}. Here are some examples of addressing modes in various
12691: syntaxes:
1.21 crook 12692:
1.26 crook 12693: @example
1.91 anton 12694: Gforth Intel (NASM) AT&T (gas) Name
12695: .w ax ax %ax register (16 bit)
12696: ax eax %eax register (32 bit)
12697: 3 # offset 3 $3 immediate
12698: 1000 #) byte ptr 1000 1000 displacement
12699: bx ) [ebx] (%ebx) base
12700: 100 di d) 100[edi] 100(%edi) base+displacement
12701: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12702: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12703: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12704: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12705: @end example
12706:
12707: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12708: @code{DI)} to enforce 32-bit displacement fields (useful for
12709: later patching).
1.21 crook 12710:
1.78 anton 12711: Some example of instructions are:
1.1 anton 12712:
12713: @example
1.78 anton 12714: ax bx mov \ move ebx,eax
12715: 3 # ax mov \ mov eax,3
1.137 pazsan 12716: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12717: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12718: .w ax bx mov \ mov bx,ax
1.1 anton 12719: @end example
12720:
1.78 anton 12721: The following forms are supported for binary instructions:
1.1 anton 12722:
12723: @example
1.78 anton 12724: <reg> <reg> <inst>
12725: <n> # <reg> <inst>
12726: <mem> <reg> <inst>
12727: <reg> <mem> <inst>
1.136 pazsan 12728: <n> # <mem> <inst>
1.1 anton 12729: @end example
12730:
1.136 pazsan 12731: The shift/rotate syntax is:
1.1 anton 12732:
1.26 crook 12733: @example
1.78 anton 12734: <reg/mem> 1 # shl \ shortens to shift without immediate
12735: <reg/mem> 4 # shl
12736: <reg/mem> cl shl
1.26 crook 12737: @end example
1.1 anton 12738:
1.78 anton 12739: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12740: the byte version.
1.1 anton 12741:
1.78 anton 12742: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12743: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12744: pc < >= <= >}. (Note that most of these words shadow some Forth words
12745: when @code{assembler} is in front of @code{forth} in the search path,
12746: e.g., in @code{code} words). Currently the control structure words use
12747: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12748: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12749:
1.78 anton 12750: Here is an example of a @code{code} word (assumes that the stack pointer
12751: is in esi and the TOS is in ebx):
1.21 crook 12752:
1.26 crook 12753: @example
1.78 anton 12754: code my+ ( n1 n2 -- n )
12755: 4 si D) bx add
12756: 4 # si add
12757: Next
12758: end-code
1.26 crook 12759: @end example
1.21 crook 12760:
1.161 anton 12761:
1.78 anton 12762: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12763: @subsection Alpha Assembler
1.21 crook 12764:
1.78 anton 12765: The Alpha assembler and disassembler were originally written by Bernd
12766: Thallner.
1.26 crook 12767:
1.78 anton 12768: The register names @code{a0}--@code{a5} are not available to avoid
12769: shadowing hex numbers.
1.2 jwilke 12770:
1.78 anton 12771: Immediate forms of arithmetic instructions are distinguished by a
12772: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12773: does not count as arithmetic instruction).
1.2 jwilke 12774:
1.78 anton 12775: You have to specify all operands to an instruction, even those that
12776: other assemblers consider optional, e.g., the destination register for
12777: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12778:
1.78 anton 12779: You can specify conditions for @code{if,} by removing the first @code{b}
12780: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12781:
1.26 crook 12782: @example
1.78 anton 12783: 11 fgt if, \ if F11>0e
12784: ...
12785: endif,
1.26 crook 12786: @end example
1.2 jwilke 12787:
1.78 anton 12788: @code{fbgt,} gives @code{fgt}.
12789:
1.161 anton 12790: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12791: @subsection MIPS assembler
1.2 jwilke 12792:
1.78 anton 12793: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12794:
1.78 anton 12795: Currently the assembler and disassembler only cover the MIPS-I
12796: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12797:
1.78 anton 12798: The register names @code{$a0}--@code{$a3} are not available to avoid
12799: shadowing hex numbers.
1.2 jwilke 12800:
1.78 anton 12801: Because there is no way to distinguish registers from immediate values,
12802: you have to explicitly use the immediate forms of instructions, i.e.,
12803: @code{addiu,}, not just @code{addu,} (@command{as} does this
12804: implicitly).
1.2 jwilke 12805:
1.78 anton 12806: If the architecture manual specifies several formats for the instruction
12807: (e.g., for @code{jalr,}), you usually have to use the one with more
12808: arguments (i.e., two for @code{jalr,}). When in doubt, see
12809: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12810:
1.78 anton 12811: Branches and jumps in the MIPS architecture have a delay slot. You have
12812: to fill it yourself (the simplest way is to use @code{nop,}), the
12813: assembler does not do it for you (unlike @command{as}). Even
12814: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12815: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12816: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12817:
1.78 anton 12818: Note that you must not put branches, jumps, or @code{li,} into the delay
12819: slot: @code{li,} may expand to several instructions, and control flow
12820: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12821:
1.78 anton 12822: For branches the argument specifying the target is a relative address;
12823: You have to add the address of the delay slot to get the absolute
12824: address.
1.1 anton 12825:
1.78 anton 12826: The MIPS architecture also has load delay slots and restrictions on
12827: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12828: yourself to satisfy these restrictions, the assembler does not do it for
12829: you.
1.1 anton 12830:
1.78 anton 12831: You can specify the conditions for @code{if,} etc. by taking a
12832: conditional branch and leaving away the @code{b} at the start and the
12833: @code{,} at the end. E.g.,
1.1 anton 12834:
1.26 crook 12835: @example
1.78 anton 12836: 4 5 eq if,
12837: ... \ do something if $4 equals $5
12838: then,
1.26 crook 12839: @end example
1.1 anton 12840:
1.161 anton 12841:
1.193 dvdkhlng 12842: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161 anton 12843: @subsection PowerPC assembler
12844:
1.162 anton 12845: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12846: Revucky.
12847:
1.162 anton 12848: This assembler does not follow the convention of ending mnemonic names
12849: with a ``,'', so some mnemonic names shadow regular Forth words (in
12850: particular: @code{and or xor fabs}); so if you want to use the Forth
12851: words, you have to make them visible first, e.g., with @code{also
12852: forth}.
12853:
1.161 anton 12854: Registers are referred to by their number, e.g., @code{9} means the
12855: integer register 9 or the FP register 9 (depending on the
12856: instruction).
12857:
12858: Because there is no way to distinguish registers from immediate values,
12859: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12860: @code{addi,}, not just @code{add,}.
1.161 anton 12861:
1.162 anton 12862: The assembler and disassembler usually support the most general form
1.161 anton 12863: of an instruction, but usually not the shorter forms (especially for
12864: branches).
12865:
12866:
1.193 dvdkhlng 12867: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12868: @subsection ARM Assembler
1.161 anton 12869:
1.193 dvdkhlng 12870: The ARM assembler included in Gforth was written from scratch by David
12871: Kuehling.
12872:
12873: The assembler includes all instruction of ARM architecture version 4,
12874: but does not (yet) have support for Thumb instructions. It also lacks
12875: support for any co-processors.
12876:
12877: The assembler uses a postfix syntax with the target operand specified
12878: last. For load/store instructions the last operand will be the
12879: register(s) to be loaded from/stored to.
12880:
12881: Registers are specified by their names @code{r0} through @code{r15},
12882: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12883: @code{fp} provided for convenience. Note that @code{ip} means intra
12884: procedure call scratch register (@code{r12}) and does not refer to the
12885: instruction pointer.
12886:
12887: Condition codes can be specified anywhere in the instruction, but will
12888: be most readable if specified just in front of the mnemonic. The 'S'
12889: flag is not a separate word, but encoded into instruction mnemonics,
12890: ie. just use @code{adds,} instead of @code{add,} if you want the
12891: status register to be updated.
12892:
12893: The following table lists the syntax of operands for general
12894: instructions:
12895:
12896: @example
12897: Gforth normal assembler description
12898: 123 # #123 immediate
12899: r12 r12 register
12900: r12 4 #LSL r12, LSL #4 shift left by immediate
12901: r12 r1 #LSL r12, LSL r1 shift left by register
12902: r12 4 #LSR r12, LSR #4 shift right by immediate
12903: r12 r1 #LSR r12, LSR r1 shift right by register
12904: r12 4 #ASR r12, ASR #4 arithmetic shift right
12905: r12 r1 #ASR r12, ASR r1 ... by register
12906: r12 4 #ROR r12, ROR #4 rotate right by immediate
12907: r12 r1 #ROR r12, ROR r1 ... by register
12908: r12 RRX r12, RRX rotate right with extend by 1
12909: @end example
12910:
12911: Memory operand syntax is listed in this table:
12912:
12913: @example
12914: Gforth normal assembler description
12915: r4 ] [r4] register
12916: r4 4 #] [r4, #+4] register with immediate offset
12917: r4 -4 #] [r4, #-4] with negative offset
12918: r4 r1 +] [r4, +r1] register with register offset
12919: r4 r1 -] [r4, -r1] with negated register offset
12920: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
12921: r4 4 #]! [r4, #+4]! immediate preincrement
12922: r4 r1 +]! [r4, +r1]! register preincrement
12923: r4 r1 -]! [r4, +r1]! register predecrement
12924: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
12925: r4 -4 ]# [r4], #-4 immediate postdecrement
12926: r4 r1 ]+ [r4], r1 register postincrement
12927: r4 r1 ]- [r4], -r1 register postdecrement
12928: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
12929: ' xyz >body [#] xyz PC-relative addressing
12930: @end example
12931:
12932: Register lists for load/store multiple instructions are started and
12933: terminated by using the words @code{@{} and @code{@}}
12934: respectivly. Between braces, register names can be listed one by one,
12935: or register ranges can be formed by using the postfix operator
12936: @code{r-r}. The @code{^} flag is not encoded in the register list
12937: operand, but instead directly encoded into the instruction mnemonic,
12938: ie. use @code{^ldm,} and @code{^stm,}.
12939:
12940: Addressing modes for load/store multiple are not encoded as
12941: instruction suffixes, but instead specified after the register that
12942: supplies the address. Use one of @code{DA}, @code{IA}, @code{DB},
12943: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
12944:
12945: The following table gives some examples:
12946:
12947: @example
12948: Gforth normal assembler
12949: @{ r0 r7 r8 @} r4 ia stm, stmia @{r0,r7,r8@}, r4
12950: @{ r0 r7 r8 @} r4 db! ldm, ldmdb @{r0,r7,r8@}, r4!
12951: @{ r0 r15 r-r @} sp ia! ^ldm, ldmfd @{r0-r15@}^, sp!
12952: @end example
12953:
12954: Conditions for control structure words are specified in front of a
12955: word:
12956:
12957: @example
12958: r1 r2 cmp, \ compare r1 and r2
12959: eq if, \ equal?
12960: ... \ code executed if r1 == r2
12961: then,
12962: @end example
12963:
12964: Here is an example of a @code{code} word (assumes that the stack
12965: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
12966: clobbered):
12967:
12968: @example
12969: code my+ ( n1 n2 -- n3 )
12970: r9 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
12971: r2 r3 r3 add, \ r3 = n2+n1
12972: r9 -4 #]! r3 str, \ push r3
12973: next,
12974: end-code
12975: @end example
12976:
12977: Look at @file{arch/arm/asm-example.fs} for more examples.
12978:
12979: @node Other assemblers, , ARM Assembler, Assembler and Code Words
1.78 anton 12980: @subsection Other assemblers
12981:
12982: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12983: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12984: an assembler already. If you are writing them from scratch, please use
12985: a similar syntax style as the one we use (i.e., postfix, commas at the
12986: end of the instruction names, @pxref{Common Assembler}); make the output
12987: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12988: similar to the style we used.
12989:
12990: Hints on implementation: The most important part is to have a good test
12991: suite that contains all instructions. Once you have that, the rest is
12992: easy. For actual coding you can take a look at
12993: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12994: the assembler and disassembler, avoiding redundancy and some potential
12995: bugs. You can also look at that file (and @pxref{Advanced does> usage
12996: example}) to get ideas how to factor a disassembler.
12997:
12998: Start with the disassembler, because it's easier to reuse data from the
12999: disassembler for the assembler than the other way round.
1.1 anton 13000:
1.78 anton 13001: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13002: how simple it can be.
1.1 anton 13003:
1.161 anton 13004:
13005:
13006:
1.78 anton 13007: @c -------------------------------------------------------------
13008: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13009: @section Threading Words
13010: @cindex threading words
1.1 anton 13011:
1.78 anton 13012: @cindex code address
13013: These words provide access to code addresses and other threading stuff
13014: in Gforth (and, possibly, other interpretive Forths). It more or less
13015: abstracts away the differences between direct and indirect threading
13016: (and, for direct threading, the machine dependences). However, at
13017: present this wordset is still incomplete. It is also pretty low-level;
13018: some day it will hopefully be made unnecessary by an internals wordset
13019: that abstracts implementation details away completely.
1.1 anton 13020:
1.78 anton 13021: The terminology used here stems from indirect threaded Forth systems; in
13022: such a system, the XT of a word is represented by the CFA (code field
13023: address) of a word; the CFA points to a cell that contains the code
13024: address. The code address is the address of some machine code that
13025: performs the run-time action of invoking the word (e.g., the
13026: @code{dovar:} routine pushes the address of the body of the word (a
13027: variable) on the stack
13028: ).
1.1 anton 13029:
1.78 anton 13030: @cindex code address
13031: @cindex code field address
13032: In an indirect threaded Forth, you can get the code address of @i{name}
13033: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13034: >code-address}, independent of the threading method.
1.1 anton 13035:
1.78 anton 13036: doc-threading-method
13037: doc->code-address
13038: doc-code-address!
1.1 anton 13039:
1.78 anton 13040: @cindex @code{does>}-handler
13041: @cindex @code{does>}-code
13042: For a word defined with @code{DOES>}, the code address usually points to
13043: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13044: routine (in Gforth on some platforms, it can also point to the dodoes
13045: routine itself). What you are typically interested in, though, is
13046: whether a word is a @code{DOES>}-defined word, and what Forth code it
13047: executes; @code{>does-code} tells you that.
1.1 anton 13048:
1.78 anton 13049: doc->does-code
1.1 anton 13050:
1.78 anton 13051: To create a @code{DOES>}-defined word with the following basic words,
13052: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13053: @code{/does-handler} aus behind you have to place your executable Forth
13054: code. Finally you have to create a word and modify its behaviour with
13055: @code{does-handler!}.
1.1 anton 13056:
1.78 anton 13057: doc-does-code!
13058: doc-does-handler!
13059: doc-/does-handler
1.1 anton 13060:
1.78 anton 13061: The code addresses produced by various defining words are produced by
13062: the following words:
1.1 anton 13063:
1.78 anton 13064: doc-docol:
13065: doc-docon:
13066: doc-dovar:
13067: doc-douser:
13068: doc-dodefer:
13069: doc-dofield:
1.1 anton 13070:
1.99 anton 13071: @cindex definer
13072: The following two words generalize @code{>code-address},
13073: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13074:
13075: doc->definer
13076: doc-definer!
13077:
1.26 crook 13078: @c -------------------------------------------------------------
1.78 anton 13079: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 13080: @section Passing Commands to the Operating System
13081: @cindex operating system - passing commands
13082: @cindex shell commands
13083:
13084: Gforth allows you to pass an arbitrary string to the host operating
13085: system shell (if such a thing exists) for execution.
13086:
13087: doc-sh
13088: doc-system
13089: doc-$?
1.23 crook 13090: doc-getenv
1.44 crook 13091:
1.26 crook 13092: @c -------------------------------------------------------------
1.47 crook 13093: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13094: @section Keeping track of Time
13095: @cindex time-related words
13096:
13097: doc-ms
13098: doc-time&date
1.79 anton 13099: doc-utime
13100: doc-cputime
1.47 crook 13101:
13102:
13103: @c -------------------------------------------------------------
13104: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 13105: @section Miscellaneous Words
13106: @cindex miscellaneous words
13107:
1.29 crook 13108: @comment TODO find homes for these
13109:
1.26 crook 13110: These section lists the ANS Forth words that are not documented
1.21 crook 13111: elsewhere in this manual. Ultimately, they all need proper homes.
13112:
1.68 anton 13113: doc-quit
1.44 crook 13114:
1.26 crook 13115: The following ANS Forth words are not currently supported by Gforth
1.27 crook 13116: (@pxref{ANS conformance}):
1.21 crook 13117:
13118: @code{EDITOR}
13119: @code{EMIT?}
13120: @code{FORGET}
13121:
1.24 anton 13122: @c ******************************************************************
13123: @node Error messages, Tools, Words, Top
13124: @chapter Error messages
13125: @cindex error messages
13126: @cindex backtrace
13127:
13128: A typical Gforth error message looks like this:
13129:
13130: @example
1.86 anton 13131: in file included from \evaluated string/:-1
1.24 anton 13132: in file included from ./yyy.fs:1
13133: ./xxx.fs:4: Invalid memory address
1.134 anton 13134: >>>bar<<<
1.79 anton 13135: Backtrace:
1.25 anton 13136: $400E664C @@
13137: $400E6664 foo
1.24 anton 13138: @end example
13139:
13140: The message identifying the error is @code{Invalid memory address}. The
13141: error happened when text-interpreting line 4 of the file
13142: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13143: word on the line where the error happened, is pointed out (with
1.134 anton 13144: @code{>>>} and @code{<<<}).
1.24 anton 13145:
13146: The file containing the error was included in line 1 of @file{./yyy.fs},
13147: and @file{yyy.fs} was included from a non-file (in this case, by giving
13148: @file{yyy.fs} as command-line parameter to Gforth).
13149:
13150: At the end of the error message you find a return stack dump that can be
13151: interpreted as a backtrace (possibly empty). On top you find the top of
13152: the return stack when the @code{throw} happened, and at the bottom you
13153: find the return stack entry just above the return stack of the topmost
13154: text interpreter.
13155:
13156: To the right of most return stack entries you see a guess for the word
13157: that pushed that return stack entry as its return address. This gives a
13158: backtrace. In our case we see that @code{bar} called @code{foo}, and
13159: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13160: address} exception).
13161:
13162: Note that the backtrace is not perfect: We don't know which return stack
13163: entries are return addresses (so we may get false positives); and in
13164: some cases (e.g., for @code{abort"}) we cannot determine from the return
13165: address the word that pushed the return address, so for some return
13166: addresses you see no names in the return stack dump.
1.25 anton 13167:
13168: @cindex @code{catch} and backtraces
13169: The return stack dump represents the return stack at the time when a
13170: specific @code{throw} was executed. In programs that make use of
13171: @code{catch}, it is not necessarily clear which @code{throw} should be
13172: used for the return stack dump (e.g., consider one @code{throw} that
13173: indicates an error, which is caught, and during recovery another error
1.160 anton 13174: happens; which @code{throw} should be used for the stack dump?).
13175: Gforth presents the return stack dump for the first @code{throw} after
13176: the last executed (not returned-to) @code{catch} or @code{nothrow};
13177: this works well in the usual case. To get the right backtrace, you
13178: usually want to insert @code{nothrow} or @code{['] false catch drop}
13179: after a @code{catch} if the error is not rethrown.
1.25 anton 13180:
13181: @cindex @code{gforth-fast} and backtraces
13182: @cindex @code{gforth-fast}, difference from @code{gforth}
13183: @cindex backtraces with @code{gforth-fast}
13184: @cindex return stack dump with @code{gforth-fast}
1.79 anton 13185: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 13186: from primitives (e.g., invalid memory address, stack empty etc.);
13187: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 13188: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 13189: exception caused by a primitive in @code{gforth-fast}, you will
13190: typically see no return stack dump at all; however, if the exception is
13191: caught by @code{catch} (e.g., for restoring some state), and then
13192: @code{throw}n again, the return stack dump will be for the first such
13193: @code{throw}.
1.2 jwilke 13194:
1.5 anton 13195: @c ******************************************************************
1.24 anton 13196: @node Tools, ANS conformance, Error messages, Top
1.1 anton 13197: @chapter Tools
13198:
13199: @menu
13200: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 13201: * Stack depth changes:: Where does this stack item come from?
1.1 anton 13202: @end menu
13203:
13204: See also @ref{Emacs and Gforth}.
13205:
1.126 pazsan 13206: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 13207: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13208: @cindex @file{ans-report.fs}
13209: @cindex report the words used in your program
13210: @cindex words used in your program
13211:
13212: If you want to label a Forth program as ANS Forth Program, you must
13213: document which wordsets the program uses; for extension wordsets, it is
13214: helpful to list the words the program requires from these wordsets
13215: (because Forth systems are allowed to provide only some words of them).
13216:
13217: The @file{ans-report.fs} tool makes it easy for you to determine which
13218: words from which wordset and which non-ANS words your application
13219: uses. You simply have to include @file{ans-report.fs} before loading the
13220: program you want to check. After loading your program, you can get the
13221: report with @code{print-ans-report}. A typical use is to run this as
13222: batch job like this:
13223: @example
13224: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13225: @end example
13226:
13227: The output looks like this (for @file{compat/control.fs}):
13228: @example
13229: The program uses the following words
13230: from CORE :
13231: : POSTPONE THEN ; immediate ?dup IF 0=
13232: from BLOCK-EXT :
13233: \
13234: from FILE :
13235: (
13236: @end example
13237:
13238: @subsection Caveats
13239:
13240: Note that @file{ans-report.fs} just checks which words are used, not whether
13241: they are used in an ANS Forth conforming way!
13242:
13243: Some words are defined in several wordsets in the
13244: standard. @file{ans-report.fs} reports them for only one of the
13245: wordsets, and not necessarily the one you expect. It depends on usage
13246: which wordset is the right one to specify. E.g., if you only use the
13247: compilation semantics of @code{S"}, it is a Core word; if you also use
13248: its interpretation semantics, it is a File word.
1.124 anton 13249:
13250:
1.127 anton 13251: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13252: @section Stack depth changes during interpretation
13253: @cindex @file{depth-changes.fs}
13254: @cindex depth changes during interpretation
13255: @cindex stack depth changes during interpretation
13256: @cindex items on the stack after interpretation
13257:
13258: Sometimes you notice that, after loading a file, there are items left
13259: on the stack. The tool @file{depth-changes.fs} helps you find out
13260: quickly where in the file these stack items are coming from.
13261:
13262: The simplest way of using @file{depth-changes.fs} is to include it
13263: before the file(s) you want to check, e.g.:
13264:
13265: @example
13266: gforth depth-changes.fs my-file.fs
13267: @end example
13268:
13269: This will compare the stack depths of the data and FP stack at every
13270: empty line (in interpretation state) against these depths at the last
13271: empty line (in interpretation state). If the depths are not equal,
13272: the position in the file and the stack contents are printed with
13273: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13274: change has occured in the paragraph of non-empty lines before the
13275: indicated line. It is a good idea to leave an empty line at the end
13276: of the file, so the last paragraph is checked, too.
13277:
13278: Checking only at empty lines usually works well, but sometimes you
13279: have big blocks of non-empty lines (e.g., when building a big table),
13280: and you want to know where in this block the stack depth changed. You
13281: can check all interpreted lines with
13282:
13283: @example
13284: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13285: @end example
13286:
13287: This checks the stack depth at every end-of-line. So the depth change
13288: occured in the line reported by the @code{~~} (not in the line
13289: before).
13290:
13291: Note that, while this offers better accuracy in indicating where the
13292: stack depth changes, it will often report many intentional stack depth
13293: changes (e.g., when an interpreted computation stretches across
13294: several lines). You can suppress the checking of some lines by
13295: putting backslashes at the end of these lines (not followed by white
13296: space), and using
13297:
13298: @example
13299: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13300: @end example
1.1 anton 13301:
13302: @c ******************************************************************
1.65 anton 13303: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13304: @chapter ANS conformance
13305: @cindex ANS conformance of Gforth
13306:
13307: To the best of our knowledge, Gforth is an
13308:
13309: ANS Forth System
13310: @itemize @bullet
13311: @item providing the Core Extensions word set
13312: @item providing the Block word set
13313: @item providing the Block Extensions word set
13314: @item providing the Double-Number word set
13315: @item providing the Double-Number Extensions word set
13316: @item providing the Exception word set
13317: @item providing the Exception Extensions word set
13318: @item providing the Facility word set
1.40 anton 13319: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13320: @item providing the File Access word set
13321: @item providing the File Access Extensions word set
13322: @item providing the Floating-Point word set
13323: @item providing the Floating-Point Extensions word set
13324: @item providing the Locals word set
13325: @item providing the Locals Extensions word set
13326: @item providing the Memory-Allocation word set
13327: @item providing the Memory-Allocation Extensions word set (that one's easy)
13328: @item providing the Programming-Tools word set
13329: @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
13330: @item providing the Search-Order word set
13331: @item providing the Search-Order Extensions word set
13332: @item providing the String word set
13333: @item providing the String Extensions word set (another easy one)
13334: @end itemize
13335:
1.118 anton 13336: Gforth has the following environmental restrictions:
13337:
13338: @cindex environmental restrictions
13339: @itemize @bullet
13340: @item
13341: While processing the OS command line, if an exception is not caught,
13342: Gforth exits with a non-zero exit code instyead of performing QUIT.
13343:
13344: @item
13345: When an @code{throw} is performed after a @code{query}, Gforth does not
13346: allways restore the input source specification in effect at the
13347: corresponding catch.
13348:
13349: @end itemize
13350:
13351:
1.1 anton 13352: @cindex system documentation
13353: In addition, ANS Forth systems are required to document certain
13354: implementation choices. This chapter tries to meet these
13355: requirements. In many cases it gives a way to ask the system for the
13356: information instead of providing the information directly, in
13357: particular, if the information depends on the processor, the operating
13358: system or the installation options chosen, or if they are likely to
13359: change during the maintenance of Gforth.
13360:
13361: @comment The framework for the rest has been taken from pfe.
13362:
13363: @menu
13364: * The Core Words::
13365: * The optional Block word set::
13366: * The optional Double Number word set::
13367: * The optional Exception word set::
13368: * The optional Facility word set::
13369: * The optional File-Access word set::
13370: * The optional Floating-Point word set::
13371: * The optional Locals word set::
13372: * The optional Memory-Allocation word set::
13373: * The optional Programming-Tools word set::
13374: * The optional Search-Order word set::
13375: @end menu
13376:
13377:
13378: @c =====================================================================
13379: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13380: @comment node-name, next, previous, up
13381: @section The Core Words
13382: @c =====================================================================
13383: @cindex core words, system documentation
13384: @cindex system documentation, core words
13385:
13386: @menu
13387: * core-idef:: Implementation Defined Options
13388: * core-ambcond:: Ambiguous Conditions
13389: * core-other:: Other System Documentation
13390: @end menu
13391:
13392: @c ---------------------------------------------------------------------
13393: @node core-idef, core-ambcond, The Core Words, The Core Words
13394: @subsection Implementation Defined Options
13395: @c ---------------------------------------------------------------------
13396: @cindex core words, implementation-defined options
13397: @cindex implementation-defined options, core words
13398:
13399:
13400: @table @i
13401: @item (Cell) aligned addresses:
13402: @cindex cell-aligned addresses
13403: @cindex aligned addresses
13404: processor-dependent. Gforth's alignment words perform natural alignment
13405: (e.g., an address aligned for a datum of size 8 is divisible by
13406: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13407:
13408: @item @code{EMIT} and non-graphic characters:
13409: @cindex @code{EMIT} and non-graphic characters
13410: @cindex non-graphic characters and @code{EMIT}
13411: The character is output using the C library function (actually, macro)
13412: @code{putc}.
13413:
13414: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13415: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13416: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13417: @cindex @code{ACCEPT}, editing
13418: @cindex @code{EXPECT}, editing
13419: This is modeled on the GNU readline library (@pxref{Readline
13420: Interaction, , Command Line Editing, readline, The GNU Readline
13421: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13422: producing a full word completion every time you type it (instead of
1.28 crook 13423: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13424:
13425: @item character set:
13426: @cindex character set
13427: The character set of your computer and display device. Gforth is
13428: 8-bit-clean (but some other component in your system may make trouble).
13429:
13430: @item Character-aligned address requirements:
13431: @cindex character-aligned address requirements
13432: installation-dependent. Currently a character is represented by a C
13433: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13434: (Comments on that requested).
13435:
13436: @item character-set extensions and matching of names:
13437: @cindex character-set extensions and matching of names
1.26 crook 13438: @cindex case-sensitivity for name lookup
13439: @cindex name lookup, case-sensitivity
13440: @cindex locale and case-sensitivity
1.21 crook 13441: Any character except the ASCII NUL character can be used in a
1.1 anton 13442: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13443: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13444: function is probably influenced by the locale. E.g., the @code{C} locale
13445: does not know about accents and umlauts, so they are matched
13446: case-sensitively in that locale. For portability reasons it is best to
13447: write programs such that they work in the @code{C} locale. Then one can
13448: use libraries written by a Polish programmer (who might use words
13449: containing ISO Latin-2 encoded characters) and by a French programmer
13450: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13451: funny results for some of the words (which ones, depends on the font you
13452: are using)). Also, the locale you prefer may not be available in other
13453: operating systems. Hopefully, Unicode will solve these problems one day.
13454:
13455: @item conditions under which control characters match a space delimiter:
13456: @cindex space delimiters
13457: @cindex control characters as delimiters
1.117 anton 13458: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13459: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13460: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13461: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13462: interpreter (aka text interpreter) by default, treats all white-space
13463: characters as delimiters.
13464:
1.26 crook 13465: @item format of the control-flow stack:
13466: @cindex control-flow stack, format
13467: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13468: stack item in cells is given by the constant @code{cs-item-size}. At the
13469: time of this writing, an item consists of a (pointer to a) locals list
13470: (third), an address in the code (second), and a tag for identifying the
13471: item (TOS). The following tags are used: @code{defstart},
13472: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13473: @code{scopestart}.
13474:
13475: @item conversion of digits > 35
13476: @cindex digits > 35
13477: The characters @code{[\]^_'} are the digits with the decimal value
13478: 36@minus{}41. There is no way to input many of the larger digits.
13479:
13480: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13481: @cindex @code{EXPECT}, display after end of input
13482: @cindex @code{ACCEPT}, display after end of input
13483: The cursor is moved to the end of the entered string. If the input is
13484: terminated using the @kbd{Return} key, a space is typed.
13485:
13486: @item exception abort sequence of @code{ABORT"}:
13487: @cindex exception abort sequence of @code{ABORT"}
13488: @cindex @code{ABORT"}, exception abort sequence
13489: The error string is stored into the variable @code{"error} and a
13490: @code{-2 throw} is performed.
13491:
13492: @item input line terminator:
13493: @cindex input line terminator
13494: @cindex line terminator on input
1.26 crook 13495: @cindex newline character on input
1.1 anton 13496: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13497: lines. One of these characters is typically produced when you type the
13498: @kbd{Enter} or @kbd{Return} key.
13499:
13500: @item maximum size of a counted string:
13501: @cindex maximum size of a counted string
13502: @cindex counted string, maximum size
13503: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13504: on all platforms, but this may change.
1.1 anton 13505:
13506: @item maximum size of a parsed string:
13507: @cindex maximum size of a parsed string
13508: @cindex parsed string, maximum size
13509: Given by the constant @code{/line}. Currently 255 characters.
13510:
13511: @item maximum size of a definition name, in characters:
13512: @cindex maximum size of a definition name, in characters
13513: @cindex name, maximum length
1.113 anton 13514: MAXU/8
1.1 anton 13515:
13516: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13517: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13518: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13519: MAXU/8
1.1 anton 13520:
13521: @item method of selecting the user input device:
13522: @cindex user input device, method of selecting
13523: The user input device is the standard input. There is currently no way to
13524: change it from within Gforth. However, the input can typically be
13525: redirected in the command line that starts Gforth.
13526:
13527: @item method of selecting the user output device:
13528: @cindex user output device, method of selecting
13529: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13530: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13531: output when the user output device is a terminal, otherwise the output
13532: is buffered.
1.1 anton 13533:
13534: @item methods of dictionary compilation:
13535: What are we expected to document here?
13536:
13537: @item number of bits in one address unit:
13538: @cindex number of bits in one address unit
13539: @cindex address unit, size in bits
13540: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13541: platforms.
1.1 anton 13542:
13543: @item number representation and arithmetic:
13544: @cindex number representation and arithmetic
1.79 anton 13545: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13546:
13547: @item ranges for integer types:
13548: @cindex ranges for integer types
13549: @cindex integer types, ranges
13550: Installation-dependent. Make environmental queries for @code{MAX-N},
13551: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13552: unsigned (and positive) types is 0. The lower bound for signed types on
13553: two's complement and one's complement machines machines can be computed
13554: by adding 1 to the upper bound.
13555:
13556: @item read-only data space regions:
13557: @cindex read-only data space regions
13558: @cindex data-space, read-only regions
13559: The whole Forth data space is writable.
13560:
13561: @item size of buffer at @code{WORD}:
13562: @cindex size of buffer at @code{WORD}
13563: @cindex @code{WORD} buffer size
13564: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13565: shared with the pictured numeric output string. If overwriting
13566: @code{PAD} is acceptable, it is as large as the remaining dictionary
13567: space, although only as much can be sensibly used as fits in a counted
13568: string.
13569:
13570: @item size of one cell in address units:
13571: @cindex cell size
13572: @code{1 cells .}.
13573:
13574: @item size of one character in address units:
13575: @cindex char size
1.79 anton 13576: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13577:
13578: @item size of the keyboard terminal buffer:
13579: @cindex size of the keyboard terminal buffer
13580: @cindex terminal buffer, size
13581: Varies. You can determine the size at a specific time using @code{lp@@
13582: tib - .}. It is shared with the locals stack and TIBs of files that
13583: include the current file. You can change the amount of space for TIBs
13584: and locals stack at Gforth startup with the command line option
13585: @code{-l}.
13586:
13587: @item size of the pictured numeric output buffer:
13588: @cindex size of the pictured numeric output buffer
13589: @cindex pictured numeric output buffer, size
13590: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13591: shared with @code{WORD}.
13592:
13593: @item size of the scratch area returned by @code{PAD}:
13594: @cindex size of the scratch area returned by @code{PAD}
13595: @cindex @code{PAD} size
13596: The remainder of dictionary space. @code{unused pad here - - .}.
13597:
13598: @item system case-sensitivity characteristics:
13599: @cindex case-sensitivity characteristics
1.26 crook 13600: Dictionary searches are case-insensitive (except in
1.1 anton 13601: @code{TABLE}s). However, as explained above under @i{character-set
13602: extensions}, the matching for non-ASCII characters is determined by the
13603: locale you are using. In the default @code{C} locale all non-ASCII
13604: characters are matched case-sensitively.
13605:
13606: @item system prompt:
13607: @cindex system prompt
13608: @cindex prompt
13609: @code{ ok} in interpret state, @code{ compiled} in compile state.
13610:
13611: @item division rounding:
13612: @cindex division rounding
1.166 anton 13613: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13614: division (with the default installation of Gforth). You can check
13615: this with @code{s" floored" environment? drop .}. If you write
13616: programs that need a specific division rounding, best use
13617: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13618:
13619: @item values of @code{STATE} when true:
13620: @cindex @code{STATE} values
13621: -1.
13622:
13623: @item values returned after arithmetic overflow:
13624: On two's complement machines, arithmetic is performed modulo
13625: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13626: arithmetic (with appropriate mapping for signed types). Division by
13627: zero typically results in a @code{-55 throw} (Floating-point
13628: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13629: division overflow can result in these throws, or in @code{-11 throw};
13630: in @code{gforth-fast} division overflow and divide by zero may also
13631: result in returning bogus results without producing an exception.
1.1 anton 13632:
13633: @item whether the current definition can be found after @t{DOES>}:
13634: @cindex @t{DOES>}, visibility of current definition
13635: No.
13636:
13637: @end table
13638:
13639: @c ---------------------------------------------------------------------
13640: @node core-ambcond, core-other, core-idef, The Core Words
13641: @subsection Ambiguous conditions
13642: @c ---------------------------------------------------------------------
13643: @cindex core words, ambiguous conditions
13644: @cindex ambiguous conditions, core words
13645:
13646: @table @i
13647:
13648: @item a name is neither a word nor a number:
13649: @cindex name not found
1.26 crook 13650: @cindex undefined word
1.80 anton 13651: @code{-13 throw} (Undefined word).
1.1 anton 13652:
13653: @item a definition name exceeds the maximum length allowed:
1.26 crook 13654: @cindex word name too long
1.1 anton 13655: @code{-19 throw} (Word name too long)
13656:
13657: @item addressing a region not inside the various data spaces of the forth system:
13658: @cindex Invalid memory address
1.32 anton 13659: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13660: typically readable. Accessing other addresses gives results dependent on
13661: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13662: address).
13663:
13664: @item argument type incompatible with parameter:
1.26 crook 13665: @cindex argument type mismatch
1.1 anton 13666: This is usually not caught. Some words perform checks, e.g., the control
13667: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13668: mismatch).
13669:
13670: @item attempting to obtain the execution token of a word with undefined execution semantics:
13671: @cindex Interpreting a compile-only word, for @code{'} etc.
13672: @cindex execution token of words with undefined execution semantics
13673: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13674: get an execution token for @code{compile-only-error} (which performs a
13675: @code{-14 throw} when executed).
13676:
13677: @item dividing by zero:
13678: @cindex dividing by zero
13679: @cindex floating point unidentified fault, integer division
1.80 anton 13680: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13681: zero); on other systems, this typically results in a @code{-55 throw}
13682: (Floating-point unidentified fault).
1.1 anton 13683:
13684: @item insufficient data stack or return stack space:
13685: @cindex insufficient data stack or return stack space
13686: @cindex stack overflow
1.26 crook 13687: @cindex address alignment exception, stack overflow
1.1 anton 13688: @cindex Invalid memory address, stack overflow
13689: Depending on the operating system, the installation, and the invocation
13690: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13691: it is not checked. If it is checked, you typically get a @code{-3 throw}
13692: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13693: throw} (Invalid memory address) (depending on the platform and how you
13694: achieved the overflow) as soon as the overflow happens. If it is not
13695: checked, overflows typically result in mysterious illegal memory
13696: accesses, producing @code{-9 throw} (Invalid memory address) or
13697: @code{-23 throw} (Address alignment exception); they might also destroy
13698: the internal data structure of @code{ALLOCATE} and friends, resulting in
13699: various errors in these words.
1.1 anton 13700:
13701: @item insufficient space for loop control parameters:
13702: @cindex insufficient space for loop control parameters
1.80 anton 13703: Like other return stack overflows.
1.1 anton 13704:
13705: @item insufficient space in the dictionary:
13706: @cindex insufficient space in the dictionary
13707: @cindex dictionary overflow
1.12 anton 13708: If you try to allot (either directly with @code{allot}, or indirectly
13709: with @code{,}, @code{create} etc.) more memory than available in the
13710: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13711: to access memory beyond the end of the dictionary, the results are
13712: similar to stack overflows.
1.1 anton 13713:
13714: @item interpreting a word with undefined interpretation semantics:
13715: @cindex interpreting a word with undefined interpretation semantics
13716: @cindex Interpreting a compile-only word
13717: For some words, we have defined interpretation semantics. For the
13718: others: @code{-14 throw} (Interpreting a compile-only word).
13719:
13720: @item modifying the contents of the input buffer or a string literal:
13721: @cindex modifying the contents of the input buffer or a string literal
13722: These are located in writable memory and can be modified.
13723:
13724: @item overflow of the pictured numeric output string:
13725: @cindex overflow of the pictured numeric output string
13726: @cindex pictured numeric output string, overflow
1.24 anton 13727: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13728:
13729: @item parsed string overflow:
13730: @cindex parsed string overflow
13731: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13732:
13733: @item producing a result out of range:
13734: @cindex result out of range
13735: On two's complement machines, arithmetic is performed modulo
13736: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13737: arithmetic (with appropriate mapping for signed types). Division by
13738: zero typically results in a @code{-10 throw} (divide by zero) or
13739: @code{-55 throw} (floating point unidentified fault). Overflow on
13740: division may result in these errors or in @code{-11 throw} (result out
13741: of range). @code{Gforth-fast} may silently produce bogus results on
13742: division overflow or division by zero. @code{Convert} and
1.24 anton 13743: @code{>number} currently overflow silently.
1.1 anton 13744:
13745: @item reading from an empty data or return stack:
13746: @cindex stack empty
13747: @cindex stack underflow
1.24 anton 13748: @cindex return stack underflow
1.1 anton 13749: The data stack is checked by the outer (aka text) interpreter after
13750: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13751: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13752: depending on operating system, installation, and invocation. If they are
13753: caught by a check, they typically result in @code{-4 throw} (Stack
13754: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13755: (Invalid memory address), depending on the platform and which stack
13756: underflows and by how much. Note that even if the system uses checking
13757: (through the MMU), your program may have to underflow by a significant
13758: number of stack items to trigger the reaction (the reason for this is
13759: that the MMU, and therefore the checking, works with a page-size
13760: granularity). If there is no checking, the symptoms resulting from an
13761: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13762: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13763: (Invalid memory address) and Illegal Instruction (typically @code{-260
13764: throw}).
1.1 anton 13765:
13766: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13767: @cindex unexpected end of the input buffer
13768: @cindex zero-length string as a name
13769: @cindex Attempt to use zero-length string as a name
13770: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13771: use zero-length string as a name). Words like @code{'} probably will not
13772: find what they search. Note that it is possible to create zero-length
13773: names with @code{nextname} (should it not?).
13774:
13775: @item @code{>IN} greater than input buffer:
13776: @cindex @code{>IN} greater than input buffer
13777: The next invocation of a parsing word returns a string with length 0.
13778:
13779: @item @code{RECURSE} appears after @code{DOES>}:
13780: @cindex @code{RECURSE} appears after @code{DOES>}
13781: Compiles a recursive call to the defining word, not to the defined word.
13782:
13783: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13784: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13785: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13786: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13787: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13788: the end of the file was reached), its source-id may be
13789: reused. Therefore, restoring an input source specification referencing a
13790: closed file may lead to unpredictable results instead of a @code{-12
13791: THROW}.
13792:
13793: In the future, Gforth may be able to restore input source specifications
13794: from other than the current input source.
13795:
13796: @item data space containing definitions gets de-allocated:
13797: @cindex data space containing definitions gets de-allocated
13798: Deallocation with @code{allot} is not checked. This typically results in
13799: memory access faults or execution of illegal instructions.
13800:
13801: @item data space read/write with incorrect alignment:
13802: @cindex data space read/write with incorrect alignment
13803: @cindex alignment faults
1.26 crook 13804: @cindex address alignment exception
1.1 anton 13805: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13806: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13807: alignment turned on, incorrect alignment results in a @code{-9 throw}
13808: (Invalid memory address). There are reportedly some processors with
1.12 anton 13809: alignment restrictions that do not report violations.
1.1 anton 13810:
13811: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13812: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13813: Like other alignment errors.
13814:
13815: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13816: Like other stack underflows.
13817:
13818: @item loop control parameters not available:
13819: @cindex loop control parameters not available
13820: Not checked. The counted loop words simply assume that the top of return
13821: stack items are loop control parameters and behave accordingly.
13822:
13823: @item most recent definition does not have a name (@code{IMMEDIATE}):
13824: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13825: @cindex last word was headerless
13826: @code{abort" last word was headerless"}.
13827:
13828: @item name not defined by @code{VALUE} used by @code{TO}:
13829: @cindex name not defined by @code{VALUE} used by @code{TO}
13830: @cindex @code{TO} on non-@code{VALUE}s
13831: @cindex Invalid name argument, @code{TO}
13832: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13833: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13834:
13835: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13836: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13837: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13838: @code{-13 throw} (Undefined word)
13839:
13840: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13841: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13842: Gforth behaves as if they were of the same type. I.e., you can predict
13843: the behaviour by interpreting all parameters as, e.g., signed.
13844:
13845: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13846: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13847: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13848: compilation semantics of @code{TO}.
13849:
13850: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13851: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13852: @cindex @code{WORD}, string overflow
13853: Not checked. The string will be ok, but the count will, of course,
13854: contain only the least significant bits of the length.
13855:
13856: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13857: @cindex @code{LSHIFT}, large shift counts
13858: @cindex @code{RSHIFT}, large shift counts
13859: Processor-dependent. Typical behaviours are returning 0 and using only
13860: the low bits of the shift count.
13861:
13862: @item word not defined via @code{CREATE}:
13863: @cindex @code{>BODY} of non-@code{CREATE}d words
13864: @code{>BODY} produces the PFA of the word no matter how it was defined.
13865:
13866: @cindex @code{DOES>} of non-@code{CREATE}d words
13867: @code{DOES>} changes the execution semantics of the last defined word no
13868: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13869: @code{CREATE , DOES>}.
13870:
13871: @item words improperly used outside @code{<#} and @code{#>}:
13872: Not checked. As usual, you can expect memory faults.
13873:
13874: @end table
13875:
13876:
13877: @c ---------------------------------------------------------------------
13878: @node core-other, , core-ambcond, The Core Words
13879: @subsection Other system documentation
13880: @c ---------------------------------------------------------------------
13881: @cindex other system documentation, core words
13882: @cindex core words, other system documentation
13883:
13884: @table @i
13885: @item nonstandard words using @code{PAD}:
13886: @cindex @code{PAD} use by nonstandard words
13887: None.
13888:
13889: @item operator's terminal facilities available:
13890: @cindex operator's terminal facilities available
1.80 anton 13891: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13892: and you can give commands to Gforth interactively. The actual facilities
13893: available depend on how you invoke Gforth.
13894:
13895: @item program data space available:
13896: @cindex program data space available
13897: @cindex data space available
13898: @code{UNUSED .} gives the remaining dictionary space. The total
13899: dictionary space can be specified with the @code{-m} switch
13900: (@pxref{Invoking Gforth}) when Gforth starts up.
13901:
13902: @item return stack space available:
13903: @cindex return stack space available
13904: You can compute the total return stack space in cells with
13905: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13906: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13907:
13908: @item stack space available:
13909: @cindex stack space available
13910: You can compute the total data stack space in cells with
13911: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13912: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13913:
13914: @item system dictionary space required, in address units:
13915: @cindex system dictionary space required, in address units
13916: Type @code{here forthstart - .} after startup. At the time of this
13917: writing, this gives 80080 (bytes) on a 32-bit system.
13918: @end table
13919:
13920:
13921: @c =====================================================================
13922: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13923: @section The optional Block word set
13924: @c =====================================================================
13925: @cindex system documentation, block words
13926: @cindex block words, system documentation
13927:
13928: @menu
13929: * block-idef:: Implementation Defined Options
13930: * block-ambcond:: Ambiguous Conditions
13931: * block-other:: Other System Documentation
13932: @end menu
13933:
13934:
13935: @c ---------------------------------------------------------------------
13936: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13937: @subsection Implementation Defined Options
13938: @c ---------------------------------------------------------------------
13939: @cindex implementation-defined options, block words
13940: @cindex block words, implementation-defined options
13941:
13942: @table @i
13943: @item the format for display by @code{LIST}:
13944: @cindex @code{LIST} display format
13945: First the screen number is displayed, then 16 lines of 64 characters,
13946: each line preceded by the line number.
13947:
13948: @item the length of a line affected by @code{\}:
13949: @cindex length of a line affected by @code{\}
13950: @cindex @code{\}, line length in blocks
13951: 64 characters.
13952: @end table
13953:
13954:
13955: @c ---------------------------------------------------------------------
13956: @node block-ambcond, block-other, block-idef, The optional Block word set
13957: @subsection Ambiguous conditions
13958: @c ---------------------------------------------------------------------
13959: @cindex block words, ambiguous conditions
13960: @cindex ambiguous conditions, block words
13961:
13962: @table @i
13963: @item correct block read was not possible:
13964: @cindex block read not possible
13965: Typically results in a @code{throw} of some OS-derived value (between
13966: -512 and -2048). If the blocks file was just not long enough, blanks are
13967: supplied for the missing portion.
13968:
13969: @item I/O exception in block transfer:
13970: @cindex I/O exception in block transfer
13971: @cindex block transfer, I/O exception
13972: Typically results in a @code{throw} of some OS-derived value (between
13973: -512 and -2048).
13974:
13975: @item invalid block number:
13976: @cindex invalid block number
13977: @cindex block number invalid
13978: @code{-35 throw} (Invalid block number)
13979:
13980: @item a program directly alters the contents of @code{BLK}:
13981: @cindex @code{BLK}, altering @code{BLK}
13982: The input stream is switched to that other block, at the same
13983: position. If the storing to @code{BLK} happens when interpreting
13984: non-block input, the system will get quite confused when the block ends.
13985:
13986: @item no current block buffer for @code{UPDATE}:
13987: @cindex @code{UPDATE}, no current block buffer
13988: @code{UPDATE} has no effect.
13989:
13990: @end table
13991:
13992: @c ---------------------------------------------------------------------
13993: @node block-other, , block-ambcond, The optional Block word set
13994: @subsection Other system documentation
13995: @c ---------------------------------------------------------------------
13996: @cindex other system documentation, block words
13997: @cindex block words, other system documentation
13998:
13999: @table @i
14000: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14001: No restrictions (yet).
14002:
14003: @item the number of blocks available for source and data:
14004: depends on your disk space.
14005:
14006: @end table
14007:
14008:
14009: @c =====================================================================
14010: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14011: @section The optional Double Number word set
14012: @c =====================================================================
14013: @cindex system documentation, double words
14014: @cindex double words, system documentation
14015:
14016: @menu
14017: * double-ambcond:: Ambiguous Conditions
14018: @end menu
14019:
14020:
14021: @c ---------------------------------------------------------------------
14022: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
14023: @subsection Ambiguous conditions
14024: @c ---------------------------------------------------------------------
14025: @cindex double words, ambiguous conditions
14026: @cindex ambiguous conditions, double words
14027:
14028: @table @i
1.29 crook 14029: @item @i{d} outside of range of @i{n} in @code{D>S}:
14030: @cindex @code{D>S}, @i{d} out of range of @i{n}
14031: The least significant cell of @i{d} is produced.
1.1 anton 14032:
14033: @end table
14034:
14035:
14036: @c =====================================================================
14037: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14038: @section The optional Exception word set
14039: @c =====================================================================
14040: @cindex system documentation, exception words
14041: @cindex exception words, system documentation
14042:
14043: @menu
14044: * exception-idef:: Implementation Defined Options
14045: @end menu
14046:
14047:
14048: @c ---------------------------------------------------------------------
14049: @node exception-idef, , The optional Exception word set, The optional Exception word set
14050: @subsection Implementation Defined Options
14051: @c ---------------------------------------------------------------------
14052: @cindex implementation-defined options, exception words
14053: @cindex exception words, implementation-defined options
14054:
14055: @table @i
14056: @item @code{THROW}-codes used in the system:
14057: @cindex @code{THROW}-codes used in the system
14058: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 14059: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 14060: codes -512@minus{}-2047 are used for OS errors (for file and memory
14061: allocation operations). The mapping from OS error numbers to throw codes
14062: is -512@minus{}@code{errno}. One side effect of this mapping is that
14063: undefined OS errors produce a message with a strange number; e.g.,
14064: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14065: @end table
14066:
14067: @c =====================================================================
14068: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14069: @section The optional Facility word set
14070: @c =====================================================================
14071: @cindex system documentation, facility words
14072: @cindex facility words, system documentation
14073:
14074: @menu
14075: * facility-idef:: Implementation Defined Options
14076: * facility-ambcond:: Ambiguous Conditions
14077: @end menu
14078:
14079:
14080: @c ---------------------------------------------------------------------
14081: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14082: @subsection Implementation Defined Options
14083: @c ---------------------------------------------------------------------
14084: @cindex implementation-defined options, facility words
14085: @cindex facility words, implementation-defined options
14086:
14087: @table @i
14088: @item encoding of keyboard events (@code{EKEY}):
14089: @cindex keyboard events, encoding in @code{EKEY}
14090: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 14091: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 14092: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14093: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14094: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14095: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 14096:
1.1 anton 14097:
14098: @item duration of a system clock tick:
14099: @cindex duration of a system clock tick
14100: @cindex clock tick duration
14101: System dependent. With respect to @code{MS}, the time is specified in
14102: microseconds. How well the OS and the hardware implement this, is
14103: another question.
14104:
14105: @item repeatability to be expected from the execution of @code{MS}:
14106: @cindex repeatability to be expected from the execution of @code{MS}
14107: @cindex @code{MS}, repeatability to be expected
14108: System dependent. On Unix, a lot depends on load. If the system is
14109: lightly loaded, and the delay is short enough that Gforth does not get
14110: swapped out, the performance should be acceptable. Under MS-DOS and
14111: other single-tasking systems, it should be good.
14112:
14113: @end table
14114:
14115:
14116: @c ---------------------------------------------------------------------
14117: @node facility-ambcond, , facility-idef, The optional Facility word set
14118: @subsection Ambiguous conditions
14119: @c ---------------------------------------------------------------------
14120: @cindex facility words, ambiguous conditions
14121: @cindex ambiguous conditions, facility words
14122:
14123: @table @i
14124: @item @code{AT-XY} can't be performed on user output device:
14125: @cindex @code{AT-XY} can't be performed on user output device
14126: Largely terminal dependent. No range checks are done on the arguments.
14127: No errors are reported. You may see some garbage appearing, you may see
14128: simply nothing happen.
14129:
14130: @end table
14131:
14132:
14133: @c =====================================================================
14134: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14135: @section The optional File-Access word set
14136: @c =====================================================================
14137: @cindex system documentation, file words
14138: @cindex file words, system documentation
14139:
14140: @menu
14141: * file-idef:: Implementation Defined Options
14142: * file-ambcond:: Ambiguous Conditions
14143: @end menu
14144:
14145: @c ---------------------------------------------------------------------
14146: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14147: @subsection Implementation Defined Options
14148: @c ---------------------------------------------------------------------
14149: @cindex implementation-defined options, file words
14150: @cindex file words, implementation-defined options
14151:
14152: @table @i
14153: @item file access methods used:
14154: @cindex file access methods used
14155: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14156: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14157: @code{wb}): The file is cleared, if it exists, and created, if it does
14158: not (with both @code{open-file} and @code{create-file}). Under Unix
14159: @code{create-file} creates a file with 666 permissions modified by your
14160: umask.
14161:
14162: @item file exceptions:
14163: @cindex file exceptions
14164: The file words do not raise exceptions (except, perhaps, memory access
14165: faults when you pass illegal addresses or file-ids).
14166:
14167: @item file line terminator:
14168: @cindex file line terminator
14169: System-dependent. Gforth uses C's newline character as line
14170: terminator. What the actual character code(s) of this are is
14171: system-dependent.
14172:
14173: @item file name format:
14174: @cindex file name format
14175: System dependent. Gforth just uses the file name format of your OS.
14176:
14177: @item information returned by @code{FILE-STATUS}:
14178: @cindex @code{FILE-STATUS}, returned information
14179: @code{FILE-STATUS} returns the most powerful file access mode allowed
14180: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14181: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14182: along with the returned mode.
14183:
14184: @item input file state after an exception when including source:
14185: @cindex exception when including source
14186: All files that are left via the exception are closed.
14187:
1.29 crook 14188: @item @i{ior} values and meaning:
14189: @cindex @i{ior} values and meaning
1.68 anton 14190: @cindex @i{wior} values and meaning
1.29 crook 14191: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14192: intended as throw codes. They typically are in the range
14193: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14194: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14195:
14196: @item maximum depth of file input nesting:
14197: @cindex maximum depth of file input nesting
14198: @cindex file input nesting, maximum depth
14199: limited by the amount of return stack, locals/TIB stack, and the number
14200: of open files available. This should not give you troubles.
14201:
14202: @item maximum size of input line:
14203: @cindex maximum size of input line
14204: @cindex input line size, maximum
14205: @code{/line}. Currently 255.
14206:
14207: @item methods of mapping block ranges to files:
14208: @cindex mapping block ranges to files
14209: @cindex files containing blocks
14210: @cindex blocks in files
14211: By default, blocks are accessed in the file @file{blocks.fb} in the
14212: current working directory. The file can be switched with @code{USE}.
14213:
14214: @item number of string buffers provided by @code{S"}:
14215: @cindex @code{S"}, number of string buffers
14216: 1
14217:
14218: @item size of string buffer used by @code{S"}:
14219: @cindex @code{S"}, size of string buffer
14220: @code{/line}. currently 255.
14221:
14222: @end table
14223:
14224: @c ---------------------------------------------------------------------
14225: @node file-ambcond, , file-idef, The optional File-Access word set
14226: @subsection Ambiguous conditions
14227: @c ---------------------------------------------------------------------
14228: @cindex file words, ambiguous conditions
14229: @cindex ambiguous conditions, file words
14230:
14231: @table @i
14232: @item attempting to position a file outside its boundaries:
14233: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14234: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14235: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14236:
14237: @item attempting to read from file positions not yet written:
14238: @cindex reading from file positions not yet written
14239: End-of-file, i.e., zero characters are read and no error is reported.
14240:
1.29 crook 14241: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14242: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14243: An appropriate exception may be thrown, but a memory fault or other
14244: problem is more probable.
14245:
1.29 crook 14246: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14247: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14248: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14249: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14250: thrown.
14251:
14252: @item named file cannot be opened (@code{INCLUDED}):
14253: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14254: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14255:
14256: @item requesting an unmapped block number:
14257: @cindex unmapped block numbers
14258: There are no unmapped legal block numbers. On some operating systems,
14259: writing a block with a large number may overflow the file system and
14260: have an error message as consequence.
14261:
14262: @item using @code{source-id} when @code{blk} is non-zero:
14263: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14264: @code{source-id} performs its function. Typically it will give the id of
14265: the source which loaded the block. (Better ideas?)
14266:
14267: @end table
14268:
14269:
14270: @c =====================================================================
14271: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14272: @section The optional Floating-Point word set
14273: @c =====================================================================
14274: @cindex system documentation, floating-point words
14275: @cindex floating-point words, system documentation
14276:
14277: @menu
14278: * floating-idef:: Implementation Defined Options
14279: * floating-ambcond:: Ambiguous Conditions
14280: @end menu
14281:
14282:
14283: @c ---------------------------------------------------------------------
14284: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14285: @subsection Implementation Defined Options
14286: @c ---------------------------------------------------------------------
14287: @cindex implementation-defined options, floating-point words
14288: @cindex floating-point words, implementation-defined options
14289:
14290: @table @i
14291: @item format and range of floating point numbers:
14292: @cindex format and range of floating point numbers
14293: @cindex floating point numbers, format and range
14294: System-dependent; the @code{double} type of C.
14295:
1.29 crook 14296: @item results of @code{REPRESENT} when @i{float} is out of range:
14297: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14298: System dependent; @code{REPRESENT} is implemented using the C library
14299: function @code{ecvt()} and inherits its behaviour in this respect.
14300:
14301: @item rounding or truncation of floating-point numbers:
14302: @cindex rounding of floating-point numbers
14303: @cindex truncation of floating-point numbers
14304: @cindex floating-point numbers, rounding or truncation
14305: System dependent; the rounding behaviour is inherited from the hosting C
14306: compiler. IEEE-FP-based (i.e., most) systems by default round to
14307: nearest, and break ties by rounding to even (i.e., such that the last
14308: bit of the mantissa is 0).
14309:
14310: @item size of floating-point stack:
14311: @cindex floating-point stack size
14312: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14313: the floating-point stack (in floats). You can specify this on startup
14314: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14315:
14316: @item width of floating-point stack:
14317: @cindex floating-point stack width
14318: @code{1 floats}.
14319:
14320: @end table
14321:
14322:
14323: @c ---------------------------------------------------------------------
14324: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14325: @subsection Ambiguous conditions
14326: @c ---------------------------------------------------------------------
14327: @cindex floating-point words, ambiguous conditions
14328: @cindex ambiguous conditions, floating-point words
14329:
14330: @table @i
14331: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14332: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14333: System-dependent. Typically results in a @code{-23 THROW} like other
14334: alignment violations.
14335:
14336: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14337: @cindex @code{f@@} used with an address that is not float aligned
14338: @cindex @code{f!} used with an address that is not float aligned
14339: System-dependent. Typically results in a @code{-23 THROW} like other
14340: alignment violations.
14341:
14342: @item floating-point result out of range:
14343: @cindex floating-point result out of range
1.80 anton 14344: System-dependent. Can result in a @code{-43 throw} (floating point
14345: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14346: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14347: unidentified fault), or can produce a special value representing, e.g.,
14348: Infinity.
14349:
14350: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14351: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14352: System-dependent. Typically results in an alignment fault like other
14353: alignment violations.
14354:
1.35 anton 14355: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14356: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14357: The floating-point number is converted into decimal nonetheless.
14358:
14359: @item Both arguments are equal to zero (@code{FATAN2}):
14360: @cindex @code{FATAN2}, both arguments are equal to zero
14361: System-dependent. @code{FATAN2} is implemented using the C library
14362: function @code{atan2()}.
14363:
1.29 crook 14364: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14365: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14366: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14367: because of small errors and the tan will be a very large (or very small)
14368: but finite number.
14369:
1.29 crook 14370: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14371: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14372: The result is rounded to the nearest float.
14373:
14374: @item dividing by zero:
14375: @cindex dividing by zero, floating-point
14376: @cindex floating-point dividing by zero
14377: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14378: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14379: (floating point divide by zero) or @code{-55 throw} (Floating-point
14380: unidentified fault).
1.1 anton 14381:
14382: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14383: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14384: System dependent. On IEEE-FP based systems the number is converted into
14385: an infinity.
14386:
1.29 crook 14387: @item @i{float}<1 (@code{FACOSH}):
14388: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14389: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14390: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14391:
1.29 crook 14392: @item @i{float}=<-1 (@code{FLNP1}):
14393: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14394: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14395: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14396: negative infinity for @i{float}=-1).
1.1 anton 14397:
1.29 crook 14398: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14399: @cindex @code{FLN}, @i{float}=<0
14400: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14401: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14402: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14403: negative infinity for @i{float}=0).
1.1 anton 14404:
1.29 crook 14405: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14406: @cindex @code{FASINH}, @i{float}<0
14407: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14408: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14409: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14410: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14411: C library?).
1.1 anton 14412:
1.29 crook 14413: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14414: @cindex @code{FACOS}, |@i{float}|>1
14415: @cindex @code{FASIN}, |@i{float}|>1
14416: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14417: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14418: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14419:
1.29 crook 14420: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14421: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14422: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14423: Platform-dependent; typically, some double number is produced and no
14424: error is reported.
1.1 anton 14425:
14426: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14427: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14428: @code{Precision} characters of the numeric output area are used. If
14429: @code{precision} is too high, these words will smash the data or code
14430: close to @code{here}.
1.1 anton 14431: @end table
14432:
14433: @c =====================================================================
14434: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14435: @section The optional Locals word set
14436: @c =====================================================================
14437: @cindex system documentation, locals words
14438: @cindex locals words, system documentation
14439:
14440: @menu
14441: * locals-idef:: Implementation Defined Options
14442: * locals-ambcond:: Ambiguous Conditions
14443: @end menu
14444:
14445:
14446: @c ---------------------------------------------------------------------
14447: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14448: @subsection Implementation Defined Options
14449: @c ---------------------------------------------------------------------
14450: @cindex implementation-defined options, locals words
14451: @cindex locals words, implementation-defined options
14452:
14453: @table @i
14454: @item maximum number of locals in a definition:
14455: @cindex maximum number of locals in a definition
14456: @cindex locals, maximum number in a definition
14457: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14458: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14459: characters. The number of locals in a definition is bounded by the size
14460: of locals-buffer, which contains the names of the locals.
14461:
14462: @end table
14463:
14464:
14465: @c ---------------------------------------------------------------------
14466: @node locals-ambcond, , locals-idef, The optional Locals word set
14467: @subsection Ambiguous conditions
14468: @c ---------------------------------------------------------------------
14469: @cindex locals words, ambiguous conditions
14470: @cindex ambiguous conditions, locals words
14471:
14472: @table @i
14473: @item executing a named local in interpretation state:
14474: @cindex local in interpretation state
14475: @cindex Interpreting a compile-only word, for a local
14476: Locals have no interpretation semantics. If you try to perform the
14477: interpretation semantics, you will get a @code{-14 throw} somewhere
14478: (Interpreting a compile-only word). If you perform the compilation
14479: semantics, the locals access will be compiled (irrespective of state).
14480:
1.29 crook 14481: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14482: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14483: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14484: @cindex Invalid name argument, @code{TO}
14485: @code{-32 throw} (Invalid name argument)
14486:
14487: @end table
14488:
14489:
14490: @c =====================================================================
14491: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14492: @section The optional Memory-Allocation word set
14493: @c =====================================================================
14494: @cindex system documentation, memory-allocation words
14495: @cindex memory-allocation words, system documentation
14496:
14497: @menu
14498: * memory-idef:: Implementation Defined Options
14499: @end menu
14500:
14501:
14502: @c ---------------------------------------------------------------------
14503: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14504: @subsection Implementation Defined Options
14505: @c ---------------------------------------------------------------------
14506: @cindex implementation-defined options, memory-allocation words
14507: @cindex memory-allocation words, implementation-defined options
14508:
14509: @table @i
1.29 crook 14510: @item values and meaning of @i{ior}:
14511: @cindex @i{ior} values and meaning
14512: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14513: intended as throw codes. They typically are in the range
14514: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14515: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14516:
14517: @end table
14518:
14519: @c =====================================================================
14520: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14521: @section The optional Programming-Tools word set
14522: @c =====================================================================
14523: @cindex system documentation, programming-tools words
14524: @cindex programming-tools words, system documentation
14525:
14526: @menu
14527: * programming-idef:: Implementation Defined Options
14528: * programming-ambcond:: Ambiguous Conditions
14529: @end menu
14530:
14531:
14532: @c ---------------------------------------------------------------------
14533: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14534: @subsection Implementation Defined Options
14535: @c ---------------------------------------------------------------------
14536: @cindex implementation-defined options, programming-tools words
14537: @cindex programming-tools words, implementation-defined options
14538:
14539: @table @i
14540: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14541: @cindex @code{;CODE} ending sequence
14542: @cindex @code{CODE} ending sequence
14543: @code{END-CODE}
14544:
14545: @item manner of processing input following @code{;CODE} and @code{CODE}:
14546: @cindex @code{;CODE}, processing input
14547: @cindex @code{CODE}, processing input
14548: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14549: the input is processed by the text interpreter, (starting) in interpret
14550: state.
14551:
14552: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14553: @cindex @code{ASSEMBLER}, search order capability
14554: The ANS Forth search order word set.
14555:
14556: @item source and format of display by @code{SEE}:
14557: @cindex @code{SEE}, source and format of output
1.80 anton 14558: The source for @code{see} is the executable code used by the inner
1.1 anton 14559: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14560: (and on some platforms, assembly code for primitives) as well as
14561: possible.
1.1 anton 14562:
14563: @end table
14564:
14565: @c ---------------------------------------------------------------------
14566: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14567: @subsection Ambiguous conditions
14568: @c ---------------------------------------------------------------------
14569: @cindex programming-tools words, ambiguous conditions
14570: @cindex ambiguous conditions, programming-tools words
14571:
14572: @table @i
14573:
1.21 crook 14574: @item deleting the compilation word list (@code{FORGET}):
14575: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14576: Not implemented (yet).
14577:
1.29 crook 14578: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14579: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14580: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14581: @cindex control-flow stack underflow
14582: This typically results in an @code{abort"} with a descriptive error
14583: message (may change into a @code{-22 throw} (Control structure mismatch)
14584: in the future). You may also get a memory access error. If you are
14585: unlucky, this ambiguous condition is not caught.
14586:
1.29 crook 14587: @item @i{name} can't be found (@code{FORGET}):
14588: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14589: Not implemented (yet).
14590:
1.29 crook 14591: @item @i{name} not defined via @code{CREATE}:
14592: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14593: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14594: the execution semantics of the last defined word no matter how it was
14595: defined.
14596:
14597: @item @code{POSTPONE} applied to @code{[IF]}:
14598: @cindex @code{POSTPONE} applied to @code{[IF]}
14599: @cindex @code{[IF]} and @code{POSTPONE}
14600: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14601: equivalent to @code{[IF]}.
14602:
14603: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14604: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14605: Continue in the same state of conditional compilation in the next outer
14606: input source. Currently there is no warning to the user about this.
14607:
14608: @item removing a needed definition (@code{FORGET}):
14609: @cindex @code{FORGET}, removing a needed definition
14610: Not implemented (yet).
14611:
14612: @end table
14613:
14614:
14615: @c =====================================================================
14616: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14617: @section The optional Search-Order word set
14618: @c =====================================================================
14619: @cindex system documentation, search-order words
14620: @cindex search-order words, system documentation
14621:
14622: @menu
14623: * search-idef:: Implementation Defined Options
14624: * search-ambcond:: Ambiguous Conditions
14625: @end menu
14626:
14627:
14628: @c ---------------------------------------------------------------------
14629: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14630: @subsection Implementation Defined Options
14631: @c ---------------------------------------------------------------------
14632: @cindex implementation-defined options, search-order words
14633: @cindex search-order words, implementation-defined options
14634:
14635: @table @i
14636: @item maximum number of word lists in search order:
14637: @cindex maximum number of word lists in search order
14638: @cindex search order, maximum depth
14639: @code{s" wordlists" environment? drop .}. Currently 16.
14640:
14641: @item minimum search order:
14642: @cindex minimum search order
14643: @cindex search order, minimum
14644: @code{root root}.
14645:
14646: @end table
14647:
14648: @c ---------------------------------------------------------------------
14649: @node search-ambcond, , search-idef, The optional Search-Order word set
14650: @subsection Ambiguous conditions
14651: @c ---------------------------------------------------------------------
14652: @cindex search-order words, ambiguous conditions
14653: @cindex ambiguous conditions, search-order words
14654:
14655: @table @i
1.21 crook 14656: @item changing the compilation word list (during compilation):
14657: @cindex changing the compilation word list (during compilation)
14658: @cindex compilation word list, change before definition ends
14659: The word is entered into the word list that was the compilation word list
1.1 anton 14660: at the start of the definition. Any changes to the name field (e.g.,
14661: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14662: are applied to the latest defined word (as reported by @code{latest} or
14663: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14664:
14665: @item search order empty (@code{previous}):
14666: @cindex @code{previous}, search order empty
1.26 crook 14667: @cindex vocstack empty, @code{previous}
1.1 anton 14668: @code{abort" Vocstack empty"}.
14669:
14670: @item too many word lists in search order (@code{also}):
14671: @cindex @code{also}, too many word lists in search order
1.26 crook 14672: @cindex vocstack full, @code{also}
1.1 anton 14673: @code{abort" Vocstack full"}.
14674:
14675: @end table
14676:
14677: @c ***************************************************************
1.65 anton 14678: @node Standard vs Extensions, Model, ANS conformance, Top
14679: @chapter Should I use Gforth extensions?
14680: @cindex Gforth extensions
14681:
14682: As you read through the rest of this manual, you will see documentation
14683: for @i{Standard} words, and documentation for some appealing Gforth
14684: @i{extensions}. You might ask yourself the question: @i{``Should I
14685: restrict myself to the standard, or should I use the extensions?''}
14686:
14687: The answer depends on the goals you have for the program you are working
14688: on:
14689:
14690: @itemize @bullet
14691:
14692: @item Is it just for yourself or do you want to share it with others?
14693:
14694: @item
14695: If you want to share it, do the others all use Gforth?
14696:
14697: @item
14698: If it is just for yourself, do you want to restrict yourself to Gforth?
14699:
14700: @end itemize
14701:
14702: If restricting the program to Gforth is ok, then there is no reason not
14703: to use extensions. It is still a good idea to keep to the standard
14704: where it is easy, in case you want to reuse these parts in another
14705: program that you want to be portable.
14706:
14707: If you want to be able to port the program to other Forth systems, there
14708: are the following points to consider:
14709:
14710: @itemize @bullet
14711:
14712: @item
14713: Most Forth systems that are being maintained support the ANS Forth
14714: standard. So if your program complies with the standard, it will be
14715: portable among many systems.
14716:
14717: @item
14718: A number of the Gforth extensions can be implemented in ANS Forth using
14719: public-domain files provided in the @file{compat/} directory. These are
14720: mentioned in the text in passing. There is no reason not to use these
14721: extensions, your program will still be ANS Forth compliant; just include
14722: the appropriate compat files with your program.
14723:
14724: @item
14725: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14726: analyse your program and determine what non-Standard words it relies
14727: upon. However, it does not check whether you use standard words in a
14728: non-standard way.
14729:
14730: @item
14731: Some techniques are not standardized by ANS Forth, and are hard or
14732: impossible to implement in a standard way, but can be implemented in
14733: most Forth systems easily, and usually in similar ways (e.g., accessing
14734: word headers). Forth has a rich historical precedent for programmers
14735: taking advantage of implementation-dependent features of their tools
14736: (for example, relying on a knowledge of the dictionary
14737: structure). Sometimes these techniques are necessary to extract every
14738: last bit of performance from the hardware, sometimes they are just a
14739: programming shorthand.
14740:
14741: @item
14742: Does using a Gforth extension save more work than the porting this part
14743: to other Forth systems (if any) will cost?
14744:
14745: @item
14746: Is the additional functionality worth the reduction in portability and
14747: the additional porting problems?
14748:
14749: @end itemize
14750:
14751: In order to perform these consideratios, you need to know what's
14752: standard and what's not. This manual generally states if something is
1.81 anton 14753: non-standard, but the authoritative source is the
14754: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14755: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14756: into the thought processes of the technical committee.
14757:
14758: Note also that portability between Forth systems is not the only
14759: portability issue; there is also the issue of portability between
14760: different platforms (processor/OS combinations).
14761:
14762: @c ***************************************************************
14763: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14764: @chapter Model
14765:
14766: This chapter has yet to be written. It will contain information, on
14767: which internal structures you can rely.
14768:
14769: @c ***************************************************************
14770: @node Integrating Gforth, Emacs and Gforth, Model, Top
14771: @chapter Integrating Gforth into C programs
14772:
14773: This is not yet implemented.
14774:
14775: Several people like to use Forth as scripting language for applications
14776: that are otherwise written in C, C++, or some other language.
14777:
14778: The Forth system ATLAST provides facilities for embedding it into
14779: applications; unfortunately it has several disadvantages: most
14780: importantly, it is not based on ANS Forth, and it is apparently dead
14781: (i.e., not developed further and not supported). The facilities
1.21 crook 14782: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14783: making the switch should not be hard.
14784:
14785: We also tried to design the interface such that it can easily be
14786: implemented by other Forth systems, so that we may one day arrive at a
14787: standardized interface. Such a standard interface would allow you to
14788: replace the Forth system without having to rewrite C code.
14789:
14790: You embed the Gforth interpreter by linking with the library
14791: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14792: global symbols in this library that belong to the interface, have the
14793: prefix @code{forth_}. (Global symbols that are used internally have the
14794: prefix @code{gforth_}).
14795:
14796: You can include the declarations of Forth types and the functions and
14797: variables of the interface with @code{#include <forth.h>}.
14798:
14799: Types.
14800:
14801: Variables.
14802:
14803: Data and FP Stack pointer. Area sizes.
14804:
14805: functions.
14806:
14807: forth_init(imagefile)
14808: forth_evaluate(string) exceptions?
14809: forth_goto(address) (or forth_execute(xt)?)
14810: forth_continue() (a corountining mechanism)
14811:
14812: Adding primitives.
14813:
14814: No checking.
14815:
14816: Signals?
14817:
14818: Accessing the Stacks
14819:
1.26 crook 14820: @c ******************************************************************
1.1 anton 14821: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14822: @chapter Emacs and Gforth
14823: @cindex Emacs and Gforth
14824:
14825: @cindex @file{gforth.el}
14826: @cindex @file{forth.el}
14827: @cindex Rydqvist, Goran
1.107 dvdkhlng 14828: @cindex Kuehling, David
1.1 anton 14829: @cindex comment editing commands
14830: @cindex @code{\}, editing with Emacs
14831: @cindex debug tracer editing commands
14832: @cindex @code{~~}, removal with Emacs
14833: @cindex Forth mode in Emacs
1.107 dvdkhlng 14834:
1.1 anton 14835: Gforth comes with @file{gforth.el}, an improved version of
14836: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14837: improvements are:
14838:
14839: @itemize @bullet
14840: @item
1.107 dvdkhlng 14841: A better handling of indentation.
14842: @item
14843: A custom hilighting engine for Forth-code.
1.26 crook 14844: @item
14845: Comment paragraph filling (@kbd{M-q})
14846: @item
14847: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14848: @item
14849: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14850: @item
14851: Support of the @code{info-lookup} feature for looking up the
14852: documentation of a word.
1.107 dvdkhlng 14853: @item
14854: Support for reading and writing blocks files.
1.26 crook 14855: @end itemize
14856:
1.107 dvdkhlng 14857: To get a basic description of these features, enter Forth mode and
14858: type @kbd{C-h m}.
1.1 anton 14859:
14860: @cindex source location of error or debugging output in Emacs
14861: @cindex error output, finding the source location in Emacs
14862: @cindex debugging output, finding the source location in Emacs
14863: In addition, Gforth supports Emacs quite well: The source code locations
14864: given in error messages, debugging output (from @code{~~}) and failed
14865: assertion messages are in the right format for Emacs' compilation mode
14866: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14867: Manual}) so the source location corresponding to an error or other
14868: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14869: @kbd{C-c C-c} for the error under the cursor).
14870:
1.107 dvdkhlng 14871: @cindex viewing the documentation of a word in Emacs
14872: @cindex context-sensitive help
14873: Moreover, for words documented in this manual, you can look up the
14874: glossary entry quickly by using @kbd{C-h TAB}
14875: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14876: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14877: later and does not work for words containing @code{:}.
14878:
14879: @menu
14880: * Installing gforth.el:: Making Emacs aware of Forth.
14881: * Emacs Tags:: Viewing the source of a word in Emacs.
14882: * Hilighting:: Making Forth code look prettier.
14883: * Auto-Indentation:: Customizing auto-indentation.
14884: * Blocks Files:: Reading and writing blocks files.
14885: @end menu
14886:
14887: @c ----------------------------------
1.109 anton 14888: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14889: @section Installing gforth.el
14890: @cindex @file{.emacs}
14891: @cindex @file{gforth.el}, installation
14892: To make the features from @file{gforth.el} available in Emacs, add
14893: the following lines to your @file{.emacs} file:
14894:
14895: @example
14896: (autoload 'forth-mode "gforth.el")
14897: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14898: auto-mode-alist))
14899: (autoload 'forth-block-mode "gforth.el")
14900: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14901: auto-mode-alist))
14902: (add-hook 'forth-mode-hook (function (lambda ()
14903: ;; customize variables here:
14904: (setq forth-indent-level 4)
14905: (setq forth-minor-indent-level 2)
14906: (setq forth-hilight-level 3)
14907: ;;; ...
14908: )))
14909: @end example
14910:
14911: @c ----------------------------------
14912: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14913: @section Emacs Tags
1.1 anton 14914: @cindex @file{TAGS} file
14915: @cindex @file{etags.fs}
14916: @cindex viewing the source of a word in Emacs
1.43 anton 14917: @cindex @code{require}, placement in files
14918: @cindex @code{include}, placement in files
1.107 dvdkhlng 14919: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14920: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14921: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14922: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14923: several tags files at the same time (e.g., one for the Gforth sources
14924: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14925: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14926: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14927: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14928: with @file{etags.fs}, you should avoid putting definitions both before
14929: and after @code{require} etc., otherwise you will see the same file
14930: visited several times by commands like @code{tags-search}.
1.1 anton 14931:
1.107 dvdkhlng 14932: @c ----------------------------------
14933: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14934: @section Hilighting
14935: @cindex hilighting Forth code in Emacs
14936: @cindex highlighting Forth code in Emacs
14937: @file{gforth.el} comes with a custom source hilighting engine. When
14938: you open a file in @code{forth-mode}, it will be completely parsed,
14939: assigning faces to keywords, comments, strings etc. While you edit
14940: the file, modified regions get parsed and updated on-the-fly.
14941:
14942: Use the variable `forth-hilight-level' to change the level of
14943: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14944: you set the hilighting level to 0, the parser will still work in the
14945: background, collecting information about whether regions of text are
14946: ``compiled'' or ``interpreted''. Those information are required for
14947: auto-indentation to work properly. Set `forth-disable-parser' to
14948: non-nil if your computer is too slow to handle parsing. This will
14949: have an impact on the smartness of the auto-indentation engine,
14950: though.
14951:
14952: Sometimes Forth sources define new features that should be hilighted,
14953: new control structures, defining-words etc. You can use the variable
14954: `forth-custom-words' to make @code{forth-mode} hilight additional
14955: words and constructs. See the docstring of `forth-words' for details
14956: (in Emacs, type @kbd{C-h v forth-words}).
14957:
14958: `forth-custom-words' is meant to be customized in your
14959: @file{.emacs} file. To customize hilighing in a file-specific manner,
14960: set `forth-local-words' in a local-variables section at the end of
14961: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14962:
14963: Example:
14964: @example
14965: 0 [IF]
14966: Local Variables:
14967: forth-local-words:
14968: ((("t:") definition-starter (font-lock-keyword-face . 1)
14969: "[ \t\n]" t name (font-lock-function-name-face . 3))
14970: ((";t") definition-ender (font-lock-keyword-face . 1)))
14971: End:
14972: [THEN]
14973: @end example
14974:
14975: @c ----------------------------------
14976: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14977: @section Auto-Indentation
14978: @cindex auto-indentation of Forth code in Emacs
14979: @cindex indentation of Forth code in Emacs
14980: @code{forth-mode} automatically tries to indent lines in a smart way,
14981: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14982:
14983: Simple customization can be achieved by setting
14984: `forth-indent-level' and `forth-minor-indent-level' in your
14985: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14986: per default by multiples of 4 columns. To use the more traditional
14987: 3-column indentation, add the following lines to your @file{.emacs}:
14988:
14989: @example
14990: (add-hook 'forth-mode-hook (function (lambda ()
14991: ;; customize variables here:
14992: (setq forth-indent-level 3)
14993: (setq forth-minor-indent-level 1)
14994: )))
14995: @end example
14996:
14997: If you want indentation to recognize non-default words, customize it
14998: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14999: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15000: v forth-indent-words}).
15001:
15002: To customize indentation in a file-specific manner, set
15003: `forth-local-indent-words' in a local-variables section at the end of
15004: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15005: Emacs Manual}).
15006:
15007: Example:
15008: @example
15009: 0 [IF]
15010: Local Variables:
15011: forth-local-indent-words:
15012: ((("t:") (0 . 2) (0 . 2))
15013: ((";t") (-2 . 0) (0 . -2)))
15014: End:
15015: [THEN]
15016: @end example
15017:
15018: @c ----------------------------------
1.109 anton 15019: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 15020: @section Blocks Files
15021: @cindex blocks files, use with Emacs
15022: @code{forth-mode} Autodetects blocks files by checking whether the
15023: length of the first line exceeds 1023 characters. It then tries to
15024: convert the file into normal text format. When you save the file, it
15025: will be written to disk as normal stream-source file.
15026:
15027: If you want to write blocks files, use @code{forth-blocks-mode}. It
15028: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 15029:
1.107 dvdkhlng 15030: @itemize @bullet
15031: @item
15032: Files are written to disk in blocks file format.
15033: @item
15034: Screen numbers are displayed in the mode line (enumerated beginning
15035: with the value of `forth-block-base')
15036: @item
15037: Warnings are displayed when lines exceed 64 characters.
15038: @item
15039: The beginning of the currently edited block is marked with an
15040: overlay-arrow.
15041: @end itemize
1.41 anton 15042:
1.107 dvdkhlng 15043: There are some restrictions you should be aware of. When you open a
15044: blocks file that contains tabulator or newline characters, these
15045: characters will be translated into spaces when the file is written
15046: back to disk. If tabs or newlines are encountered during blocks file
15047: reading, an error is output to the echo area. So have a look at the
15048: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 15049:
1.107 dvdkhlng 15050: Please consult the docstring of @code{forth-blocks-mode} for more
15051: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 15052:
1.26 crook 15053: @c ******************************************************************
1.1 anton 15054: @node Image Files, Engine, Emacs and Gforth, Top
15055: @chapter Image Files
1.26 crook 15056: @cindex image file
15057: @cindex @file{.fi} files
1.1 anton 15058: @cindex precompiled Forth code
15059: @cindex dictionary in persistent form
15060: @cindex persistent form of dictionary
15061:
15062: An image file is a file containing an image of the Forth dictionary,
15063: i.e., compiled Forth code and data residing in the dictionary. By
15064: convention, we use the extension @code{.fi} for image files.
15065:
15066: @menu
1.18 anton 15067: * Image Licensing Issues:: Distribution terms for images.
15068: * Image File Background:: Why have image files?
1.67 anton 15069: * Non-Relocatable Image Files:: don't always work.
1.18 anton 15070: * Data-Relocatable Image Files:: are better.
1.67 anton 15071: * Fully Relocatable Image Files:: better yet.
1.18 anton 15072: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 15073: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 15074: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 15075: @end menu
15076:
1.18 anton 15077: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15078: @section Image Licensing Issues
15079: @cindex license for images
15080: @cindex image license
15081:
15082: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15083: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15084: original image; i.e., according to copyright law it is a derived work of
15085: the original image.
15086:
15087: Since Gforth is distributed under the GNU GPL, the newly created image
15088: falls under the GNU GPL, too. In particular, this means that if you
15089: distribute the image, you have to make all of the sources for the image
1.113 anton 15090: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 15091: GNU General Public License (Section 3)}.
15092:
15093: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15094: contains only code compiled from the sources you gave it; if none of
15095: these sources is under the GPL, the terms discussed above do not apply
15096: to the image. However, if your image needs an engine (a gforth binary)
15097: that is under the GPL, you should make sure that you distribute both in
15098: a way that is at most a @emph{mere aggregation}, if you don't want the
15099: terms of the GPL to apply to the image.
15100:
15101: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 15102: @section Image File Background
15103: @cindex image file background
15104:
1.80 anton 15105: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 15106: definitions written in Forth. Since the Forth compiler itself belongs to
15107: those definitions, it is not possible to start the system with the
1.80 anton 15108: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 15109: code as an image file in nearly executable form. When Gforth starts up,
15110: a C routine loads the image file into memory, optionally relocates the
15111: addresses, then sets up the memory (stacks etc.) according to
15112: information in the image file, and (finally) starts executing Forth
15113: code.
1.1 anton 15114:
1.204 anton 15115: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15116: You can use a different image by using the @code{-i},
15117: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15118: Gforth}), e.g.:
15119:
15120: @example
15121: gforth-fast -i myimage.fi
15122: @end example
15123:
15124: There are different variants of image files, and they represent
15125: different compromises between the goals of making it easy to generate
15126: image files and making them portable.
1.1 anton 15127:
15128: @cindex relocation at run-time
1.26 crook 15129: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 15130: run-time. This avoids many of the complications discussed below (image
15131: files are data relocatable without further ado), but costs performance
1.204 anton 15132: (one addition per memory access) and makes it difficult to pass
15133: addresses between Forth and library calls or other programs.
1.1 anton 15134:
15135: @cindex relocation at load-time
1.26 crook 15136: By contrast, the Gforth loader performs relocation at image load time. The
15137: loader also has to replace tokens that represent primitive calls with the
1.1 anton 15138: appropriate code-field addresses (or code addresses in the case of
15139: direct threading).
15140:
15141: There are three kinds of image files, with different degrees of
15142: relocatability: non-relocatable, data-relocatable, and fully relocatable
15143: image files.
15144:
15145: @cindex image file loader
15146: @cindex relocating loader
15147: @cindex loader for image files
15148: These image file variants have several restrictions in common; they are
15149: caused by the design of the image file loader:
15150:
15151: @itemize @bullet
15152: @item
15153: There is only one segment; in particular, this means, that an image file
15154: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 15155: them). The contents of the stacks are not represented, either.
1.1 anton 15156:
15157: @item
15158: The only kinds of relocation supported are: adding the same offset to
15159: all cells that represent data addresses; and replacing special tokens
15160: with code addresses or with pieces of machine code.
15161:
15162: If any complex computations involving addresses are performed, the
15163: results cannot be represented in the image file. Several applications that
15164: use such computations come to mind:
1.204 anton 15165:
1.1 anton 15166: @itemize @minus
15167: @item
15168: Hashing addresses (or data structures which contain addresses) for table
15169: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15170: purpose, you will have no problem, because the hash tables are
15171: recomputed automatically when the system is started. If you use your own
15172: hash tables, you will have to do something similar.
15173:
15174: @item
15175: There's a cute implementation of doubly-linked lists that uses
15176: @code{XOR}ed addresses. You could represent such lists as singly-linked
15177: in the image file, and restore the doubly-linked representation on
15178: startup.@footnote{In my opinion, though, you should think thrice before
15179: using a doubly-linked list (whatever implementation).}
15180:
15181: @item
15182: The code addresses of run-time routines like @code{docol:} cannot be
15183: represented in the image file (because their tokens would be replaced by
15184: machine code in direct threaded implementations). As a workaround,
15185: compute these addresses at run-time with @code{>code-address} from the
15186: executions tokens of appropriate words (see the definitions of
1.80 anton 15187: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 15188:
15189: @item
15190: On many architectures addresses are represented in machine code in some
15191: shifted or mangled form. You cannot put @code{CODE} words that contain
15192: absolute addresses in this form in a relocatable image file. Workarounds
15193: are representing the address in some relative form (e.g., relative to
15194: the CFA, which is present in some register), or loading the address from
15195: a place where it is stored in a non-mangled form.
15196: @end itemize
15197: @end itemize
15198:
15199: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15200: @section Non-Relocatable Image Files
15201: @cindex non-relocatable image files
1.26 crook 15202: @cindex image file, non-relocatable
1.1 anton 15203:
1.204 anton 15204: These files are simple memory dumps of the dictionary. They are
15205: specific to the executable (i.e., @file{gforth} file) they were
15206: created with. What's worse, they are specific to the place on which
15207: the dictionary resided when the image was created. Now, there is no
1.1 anton 15208: guarantee that the dictionary will reside at the same place the next
15209: time you start Gforth, so there's no guarantee that a non-relocatable
1.204 anton 15210: image will work the next time (Gforth will complain instead of
15211: crashing, though). Indeed, on OSs with (enabled) address-space
15212: randomization non-relocatable images are unlikely to work.
1.1 anton 15213:
1.204 anton 15214: You can create a non-relocatable image file with @code{savesystem}, e.g.:
1.1 anton 15215:
1.204 anton 15216: @example
15217: gforth app.fs -e "savesystem app.fi bye"
15218: @end example
1.44 crook 15219:
1.1 anton 15220: doc-savesystem
15221:
1.44 crook 15222:
1.1 anton 15223: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15224: @section Data-Relocatable Image Files
15225: @cindex data-relocatable image files
1.26 crook 15226: @cindex image file, data-relocatable
1.1 anton 15227:
1.204 anton 15228: These files contain relocatable data addresses, but fixed code
15229: addresses (instead of tokens). They are specific to the executable
15230: (i.e., @file{gforth} file) they were created with. Also, they disable
15231: dynamic native code generation (typically a factor of 2 in speed).
15232: You get a data-relocatable image, if you pass the engine you want to
15233: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15234: (@pxref{gforthmi}), e.g.
15235:
15236: @example
15237: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15238: @end example
15239:
15240: Note that the @code{--no-dynamic} is required here for the image to
15241: work (otherwise it will contain references to dynamically generated
15242: code that is not saved in the image).
15243:
1.1 anton 15244:
15245: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15246: @section Fully Relocatable Image Files
15247: @cindex fully relocatable image files
1.26 crook 15248: @cindex image file, fully relocatable
1.1 anton 15249:
15250: @cindex @file{kern*.fi}, relocatability
15251: @cindex @file{gforth.fi}, relocatability
15252: These image files have relocatable data addresses, and tokens for code
15253: addresses. They can be used with different binaries (e.g., with and
15254: without debugging) on the same machine, and even across machines with
1.204 anton 15255: the same data formats (byte order, cell size, floating point format),
15256: and they work with dynamic native code generation. However, they are
15257: usually specific to the version of Gforth they were created with. The
15258: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
1.1 anton 15259:
15260: There are two ways to create a fully relocatable image file:
15261:
15262: @menu
1.29 crook 15263: * gforthmi:: The normal way
1.1 anton 15264: * cross.fs:: The hard way
15265: @end menu
15266:
15267: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15268: @subsection @file{gforthmi}
15269: @cindex @file{comp-i.fs}
15270: @cindex @file{gforthmi}
15271:
15272: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15273: image @i{file} that contains everything you would load by invoking
15274: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15275: @example
1.29 crook 15276: gforthmi @i{file} @i{options}
1.1 anton 15277: @end example
15278:
15279: E.g., if you want to create an image @file{asm.fi} that has the file
15280: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15281: like this:
15282:
15283: @example
15284: gforthmi asm.fi asm.fs
15285: @end example
15286:
1.27 crook 15287: @file{gforthmi} is implemented as a sh script and works like this: It
15288: produces two non-relocatable images for different addresses and then
15289: compares them. Its output reflects this: first you see the output (if
1.62 crook 15290: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15291: files, then you see the output of the comparing program: It displays the
15292: offset used for data addresses and the offset used for code addresses;
1.1 anton 15293: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15294: image files, it displays a line like this:
1.1 anton 15295:
15296: @example
15297: 78DC BFFFFA50 BFFFFA40
15298: @end example
15299:
15300: This means that at offset $78dc from @code{forthstart}, one input image
15301: contains $bffffa50, and the other contains $bffffa40. Since these cells
15302: cannot be represented correctly in the output image, you should examine
15303: these places in the dictionary and verify that these cells are dead
15304: (i.e., not read before they are written).
1.39 anton 15305:
15306: @cindex --application, @code{gforthmi} option
15307: If you insert the option @code{--application} in front of the image file
15308: name, you will get an image that uses the @code{--appl-image} option
15309: instead of the @code{--image-file} option (@pxref{Invoking
15310: Gforth}). When you execute such an image on Unix (by typing the image
15311: name as command), the Gforth engine will pass all options to the image
15312: instead of trying to interpret them as engine options.
1.1 anton 15313:
1.27 crook 15314: If you type @file{gforthmi} with no arguments, it prints some usage
15315: instructions.
15316:
1.1 anton 15317: @cindex @code{savesystem} during @file{gforthmi}
15318: @cindex @code{bye} during @file{gforthmi}
15319: @cindex doubly indirect threaded code
1.44 crook 15320: @cindex environment variables
15321: @cindex @code{GFORTHD} -- environment variable
15322: @cindex @code{GFORTH} -- environment variable
1.1 anton 15323: @cindex @code{gforth-ditc}
1.29 crook 15324: There are a few wrinkles: After processing the passed @i{options}, the
1.204 anton 15325: words @code{savesystem} and @code{bye} must be visible. A special
15326: doubly indirect threaded version of the @file{gforth} executable is
15327: used for creating the non-relocatable images; you can pass the exact
15328: filename of this executable through the environment variable
15329: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15330: that is not doubly indirect threaded, you will not get a fully
15331: relocatable image, but a data-relocatable image
15332: (@pxref{Data-Relocatable Image Files}), because there is no code
15333: address offset). The normal @file{gforth} executable is used for
15334: creating the relocatable image; you can pass the exact filename of
15335: this executable through the environment variable @code{GFORTH}.
1.1 anton 15336:
15337: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15338: @subsection @file{cross.fs}
15339: @cindex @file{cross.fs}
15340: @cindex cross-compiler
15341: @cindex metacompiler
1.47 crook 15342: @cindex target compiler
1.1 anton 15343:
15344: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15345: programming language (@pxref{Cross Compiler}).
1.1 anton 15346:
1.47 crook 15347: @code{cross} allows you to create image files for machines with
1.1 anton 15348: different data sizes and data formats than the one used for generating
15349: the image file. You can also use it to create an application image that
15350: does not contain a Forth compiler. These features are bought with
15351: restrictions and inconveniences in programming. E.g., addresses have to
15352: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15353: order to make the code relocatable.
15354:
15355:
15356: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15357: @section Stack and Dictionary Sizes
15358: @cindex image file, stack and dictionary sizes
15359: @cindex dictionary size default
15360: @cindex stack size default
15361:
15362: If you invoke Gforth with a command line flag for the size
15363: (@pxref{Invoking Gforth}), the size you specify is stored in the
15364: dictionary. If you save the dictionary with @code{savesystem} or create
15365: an image with @file{gforthmi}, this size will become the default
15366: for the resulting image file. E.g., the following will create a
1.21 crook 15367: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15368:
15369: @example
15370: gforthmi gforth.fi -m 1M
15371: @end example
15372:
15373: In other words, if you want to set the default size for the dictionary
15374: and the stacks of an image, just invoke @file{gforthmi} with the
15375: appropriate options when creating the image.
15376:
15377: @cindex stack size, cache-friendly
15378: Note: For cache-friendly behaviour (i.e., good performance), you should
15379: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15380: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15381: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15382:
15383: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15384: @section Running Image Files
15385: @cindex running image files
15386: @cindex invoking image files
15387: @cindex image file invocation
15388:
15389: @cindex -i, invoke image file
15390: @cindex --image file, invoke image file
1.29 crook 15391: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15392: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15393: @example
1.29 crook 15394: gforth -i @i{image}
1.1 anton 15395: @end example
15396:
15397: @cindex executable image file
1.26 crook 15398: @cindex image file, executable
1.1 anton 15399: If your operating system supports starting scripts with a line of the
15400: form @code{#! ...}, you just have to type the image file name to start
15401: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15402: just a convention). I.e., to run Gforth with the image file @i{image},
15403: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15404: This works because every @code{.fi} file starts with a line of this
15405: format:
15406:
15407: @example
15408: #! /usr/local/bin/gforth-0.4.0 -i
15409: @end example
15410:
15411: The file and pathname for the Gforth engine specified on this line is
15412: the specific Gforth executable that it was built against; i.e. the value
15413: of the environment variable @code{GFORTH} at the time that
15414: @file{gforthmi} was executed.
1.1 anton 15415:
1.27 crook 15416: You can make use of the same shell capability to make a Forth source
15417: file into an executable. For example, if you place this text in a file:
1.26 crook 15418:
15419: @example
15420: #! /usr/local/bin/gforth
15421:
15422: ." Hello, world" CR
15423: bye
15424: @end example
15425:
15426: @noindent
1.27 crook 15427: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15428: directly from the command line. The sequence @code{#!} is used in two
15429: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15430: system@footnote{The Unix kernel actually recognises two types of files:
15431: executable files and files of data, where the data is processed by an
15432: interpreter that is specified on the ``interpreter line'' -- the first
15433: line of the file, starting with the sequence #!. There may be a small
15434: limit (e.g., 32) on the number of characters that may be specified on
15435: the interpreter line.} secondly it is treated as a comment character by
15436: Gforth. Because of the second usage, a space is required between
1.80 anton 15437: @code{#!} and the path to the executable (moreover, some Unixes
15438: require the sequence @code{#! /}).
1.27 crook 15439:
15440: The disadvantage of this latter technique, compared with using
1.80 anton 15441: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15442: compiled on-the-fly, each time the program is invoked.
1.26 crook 15443:
1.1 anton 15444: doc-#!
15445:
1.44 crook 15446:
1.1 anton 15447: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15448: @section Modifying the Startup Sequence
15449: @cindex startup sequence for image file
15450: @cindex image file initialization sequence
15451: @cindex initialization sequence of image file
15452:
1.120 anton 15453: You can add your own initialization to the startup sequence of an image
15454: through the deferred word @code{'cold}. @code{'cold} is invoked just
15455: before the image-specific command line processing (i.e., loading files
15456: and evaluating (@code{-e}) strings) starts.
1.1 anton 15457:
15458: A sequence for adding your initialization usually looks like this:
15459:
15460: @example
15461: :noname
15462: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15463: ... \ your stuff
15464: ; IS 'cold
15465: @end example
15466:
1.157 anton 15467: After @code{'cold}, Gforth processes the image options
15468: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15469: another deferred word. This normally prints Gforth's startup message
15470: and does nothing else.
15471:
1.1 anton 15472: @cindex turnkey image files
1.26 crook 15473: @cindex image file, turnkey applications
1.157 anton 15474: So, if you want to make a turnkey image (i.e., an image for an
15475: application instead of an extended Forth system), you can do this in
15476: two ways:
15477:
15478: @itemize @bullet
15479:
15480: @item
15481: If you want to do your interpretation of the OS command-line
15482: arguments, hook into @code{'cold}. In that case you probably also
15483: want to build the image with @code{gforthmi --application}
15484: (@pxref{gforthmi}) to keep the engine from processing OS command line
15485: options. You can then do your own command-line processing with
15486: @code{next-arg}
15487:
15488: @item
15489: If you want to have the normal Gforth processing of OS command-line
15490: arguments, hook into @code{bootmessage}.
15491:
15492: @end itemize
15493:
15494: In either case, you probably do not want the word that you execute in
15495: these hooks to exit normally, but use @code{bye} or @code{throw}.
15496: Otherwise the Gforth startup process would continue and eventually
15497: present the Forth command line to the user.
1.26 crook 15498:
15499: doc-'cold
1.157 anton 15500: doc-bootmessage
1.44 crook 15501:
1.1 anton 15502: @c ******************************************************************
1.113 anton 15503: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15504: @chapter Engine
15505: @cindex engine
15506: @cindex virtual machine
15507:
1.26 crook 15508: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15509: may be helpful for finding your way in the Gforth sources.
15510:
1.109 anton 15511: The ideas in this section have also been published in the following
15512: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15513: Forth-Tagung '93; M. Anton Ertl,
15514: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15515: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15516: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15517: Threaded code variations and optimizations (extended version)}},
15518: Forth-Tagung '02.
1.1 anton 15519:
15520: @menu
15521: * Portability::
15522: * Threading::
15523: * Primitives::
15524: * Performance::
15525: @end menu
15526:
15527: @node Portability, Threading, Engine, Engine
15528: @section Portability
15529: @cindex engine portability
15530:
1.26 crook 15531: An important goal of the Gforth Project is availability across a wide
15532: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15533: achieved this goal by manually coding the engine in assembly language
15534: for several then-popular processors. This approach is very
15535: labor-intensive and the results are short-lived due to progress in
15536: computer architecture.
1.1 anton 15537:
15538: @cindex C, using C for the engine
15539: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15540: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15541: particularly popular for UNIX-based Forths due to the large variety of
15542: architectures of UNIX machines. Unfortunately an implementation in C
15543: does not mix well with the goals of efficiency and with using
15544: traditional techniques: Indirect or direct threading cannot be expressed
15545: in C, and switch threading, the fastest technique available in C, is
15546: significantly slower. Another problem with C is that it is very
15547: cumbersome to express double integer arithmetic.
15548:
15549: @cindex GNU C for the engine
15550: @cindex long long
15551: Fortunately, there is a portable language that does not have these
15552: limitations: GNU C, the version of C processed by the GNU C compiler
15553: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15554: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15555: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15556: threading possible, its @code{long long} type (@pxref{Long Long, ,
15557: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15558: double numbers on many systems. GNU C is freely available on all
1.1 anton 15559: important (and many unimportant) UNIX machines, VMS, 80386s running
15560: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15561: on all these machines.
15562:
15563: Writing in a portable language has the reputation of producing code that
15564: is slower than assembly. For our Forth engine we repeatedly looked at
15565: the code produced by the compiler and eliminated most compiler-induced
15566: inefficiencies by appropriate changes in the source code.
15567:
15568: @cindex explicit register declarations
15569: @cindex --enable-force-reg, configuration flag
15570: @cindex -DFORCE_REG
15571: However, register allocation cannot be portably influenced by the
15572: programmer, leading to some inefficiencies on register-starved
15573: machines. We use explicit register declarations (@pxref{Explicit Reg
15574: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15575: improve the speed on some machines. They are turned on by using the
15576: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15577: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15578: machine, but also on the compiler version: On some machines some
15579: compiler versions produce incorrect code when certain explicit register
15580: declarations are used. So by default @code{-DFORCE_REG} is not used.
15581:
15582: @node Threading, Primitives, Portability, Engine
15583: @section Threading
15584: @cindex inner interpreter implementation
15585: @cindex threaded code implementation
15586:
15587: @cindex labels as values
15588: GNU C's labels as values extension (available since @code{gcc-2.0},
15589: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15590: makes it possible to take the address of @i{label} by writing
15591: @code{&&@i{label}}. This address can then be used in a statement like
15592: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15593: @code{goto x}.
15594:
1.26 crook 15595: @cindex @code{NEXT}, indirect threaded
1.1 anton 15596: @cindex indirect threaded inner interpreter
15597: @cindex inner interpreter, indirect threaded
1.26 crook 15598: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15599: @example
15600: cfa = *ip++;
15601: ca = *cfa;
15602: goto *ca;
15603: @end example
15604: @cindex instruction pointer
15605: For those unfamiliar with the names: @code{ip} is the Forth instruction
15606: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15607: execution token and points to the code field of the next word to be
15608: executed; The @code{ca} (code address) fetched from there points to some
15609: executable code, e.g., a primitive or the colon definition handler
15610: @code{docol}.
15611:
1.26 crook 15612: @cindex @code{NEXT}, direct threaded
1.1 anton 15613: @cindex direct threaded inner interpreter
15614: @cindex inner interpreter, direct threaded
15615: Direct threading is even simpler:
15616: @example
15617: ca = *ip++;
15618: goto *ca;
15619: @end example
15620:
15621: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15622: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15623:
15624: @menu
15625: * Scheduling::
15626: * Direct or Indirect Threaded?::
1.109 anton 15627: * Dynamic Superinstructions::
1.1 anton 15628: * DOES>::
15629: @end menu
15630:
15631: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15632: @subsection Scheduling
15633: @cindex inner interpreter optimization
15634:
15635: There is a little complication: Pipelined and superscalar processors,
15636: i.e., RISC and some modern CISC machines can process independent
15637: instructions while waiting for the results of an instruction. The
15638: compiler usually reorders (schedules) the instructions in a way that
15639: achieves good usage of these delay slots. However, on our first tries
15640: the compiler did not do well on scheduling primitives. E.g., for
15641: @code{+} implemented as
15642: @example
15643: n=sp[0]+sp[1];
15644: sp++;
15645: sp[0]=n;
15646: NEXT;
15647: @end example
1.81 anton 15648: the @code{NEXT} comes strictly after the other code, i.e., there is
15649: nearly no scheduling. After a little thought the problem becomes clear:
15650: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15651: addresses (and the version of @code{gcc} we used would not know it even
15652: if it was possible), so it could not move the load of the cfa above the
15653: store to the TOS. Indeed the pointers could be the same, if code on or
15654: very near the top of stack were executed. In the interest of speed we
15655: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15656: in scheduling: @code{NEXT} is divided into several parts:
15657: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15658: like:
1.1 anton 15659: @example
1.81 anton 15660: NEXT_P0;
1.1 anton 15661: n=sp[0]+sp[1];
15662: sp++;
15663: NEXT_P1;
15664: sp[0]=n;
15665: NEXT_P2;
15666: @end example
15667:
1.81 anton 15668: There are various schemes that distribute the different operations of
15669: NEXT between these parts in several ways; in general, different schemes
15670: perform best on different processors. We use a scheme for most
15671: architectures that performs well for most processors of this
1.109 anton 15672: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15673: the scheme on installation time.
15674:
1.1 anton 15675:
1.109 anton 15676: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15677: @subsection Direct or Indirect Threaded?
15678: @cindex threading, direct or indirect?
15679:
1.109 anton 15680: Threaded forth code consists of references to primitives (simple machine
15681: code routines like @code{+}) and to non-primitives (e.g., colon
15682: definitions, variables, constants); for a specific class of
15683: non-primitives (e.g., variables) there is one code routine (e.g.,
15684: @code{dovar}), but each variable needs a separate reference to its data.
15685:
15686: Traditionally Forth has been implemented as indirect threaded code,
15687: because this allows to use only one cell to reference a non-primitive
15688: (basically you point to the data, and find the code address there).
15689:
15690: @cindex primitive-centric threaded code
15691: However, threaded code in Gforth (since 0.6.0) uses two cells for
15692: non-primitives, one for the code address, and one for the data address;
15693: the data pointer is an immediate argument for the virtual machine
15694: instruction represented by the code address. We call this
15695: @emph{primitive-centric} threaded code, because all code addresses point
15696: to simple primitives. E.g., for a variable, the code address is for
15697: @code{lit} (also used for integer literals like @code{99}).
15698:
15699: Primitive-centric threaded code allows us to use (faster) direct
15700: threading as dispatch method, completely portably (direct threaded code
15701: in Gforth before 0.6.0 required architecture-specific code). It also
15702: eliminates the performance problems related to I-cache consistency that
15703: 386 implementations have with direct threaded code, and allows
15704: additional optimizations.
15705:
15706: @cindex hybrid direct/indirect threaded code
15707: There is a catch, however: the @var{xt} parameter of @code{execute} can
15708: occupy only one cell, so how do we pass non-primitives with their code
15709: @emph{and} data addresses to them? Our answer is to use indirect
15710: threaded dispatch for @code{execute} and other words that use a
15711: single-cell xt. So, normal threaded code in colon definitions uses
15712: direct threading, and @code{execute} and similar words, which dispatch
15713: to xts on the data stack, use indirect threaded code. We call this
15714: @emph{hybrid direct/indirect} threaded code.
15715:
15716: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15717: @cindex gforth engine
15718: @cindex gforth-fast engine
15719: The engines @command{gforth} and @command{gforth-fast} use hybrid
15720: direct/indirect threaded code. This means that with these engines you
15721: cannot use @code{,} to compile an xt. Instead, you have to use
15722: @code{compile,}.
15723:
15724: @cindex gforth-itc engine
1.115 anton 15725: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15726: This engine uses plain old indirect threaded code. It still compiles in
15727: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15728: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15729: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15730: and execute @code{' , is compile,}. Your program can check if it is
15731: running on a hybrid direct/indirect threaded engine or a pure indirect
15732: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15733:
15734:
15735: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15736: @subsection Dynamic Superinstructions
15737: @cindex Dynamic superinstructions with replication
15738: @cindex Superinstructions
15739: @cindex Replication
15740:
15741: The engines @command{gforth} and @command{gforth-fast} use another
15742: optimization: Dynamic superinstructions with replication. As an
15743: example, consider the following colon definition:
15744:
15745: @example
15746: : squared ( n1 -- n2 )
15747: dup * ;
15748: @end example
15749:
15750: Gforth compiles this into the threaded code sequence
15751:
15752: @example
15753: dup
15754: *
15755: ;s
15756: @end example
15757:
15758: In normal direct threaded code there is a code address occupying one
15759: cell for each of these primitives. Each code address points to a
15760: machine code routine, and the interpreter jumps to this machine code in
15761: order to execute the primitive. The routines for these three
15762: primitives are (in @command{gforth-fast} on the 386):
15763:
15764: @example
15765: Code dup
15766: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15767: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15768: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15769: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15770: end-code
15771: Code *
15772: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15773: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15774: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15775: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15776: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15777: end-code
15778: Code ;s
15779: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15780: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15781: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15782: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15783: end-code
15784: @end example
15785:
15786: With dynamic superinstructions and replication the compiler does not
15787: just lay down the threaded code, but also copies the machine code
15788: fragments, usually without the jump at the end.
15789:
15790: @example
15791: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15792: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15793: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15794: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15795: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15796: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15797: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15798: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15799: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15800: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15801: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15802: @end example
15803:
15804: Only when a threaded-code control-flow change happens (e.g., in
15805: @code{;s}), the jump is appended. This optimization eliminates many of
15806: these jumps and makes the rest much more predictable. The speedup
15807: depends on the processor and the application; on the Athlon and Pentium
15808: III this optimization typically produces a speedup by a factor of 2.
15809:
15810: The code addresses in the direct-threaded code are set to point to the
15811: appropriate points in the copied machine code, in this example like
15812: this:
1.1 anton 15813:
1.109 anton 15814: @example
15815: primitive code address
15816: dup $4057D27D
15817: * $4057D286
15818: ;s $4057D292
15819: @end example
15820:
15821: Thus there can be threaded-code jumps to any place in this piece of
15822: code. This also simplifies decompilation quite a bit.
15823:
15824: @cindex --no-dynamic command-line option
15825: @cindex --no-super command-line option
15826: You can disable this optimization with @option{--no-dynamic}. You can
15827: use the copying without eliminating the jumps (i.e., dynamic
15828: replication, but without superinstructions) with @option{--no-super};
15829: this gives the branch prediction benefit alone; the effect on
1.110 anton 15830: performance depends on the CPU; on the Athlon and Pentium III the
15831: speedup is a little less than for dynamic superinstructions with
15832: replication.
15833:
15834: @cindex patching threaded code
15835: One use of these options is if you want to patch the threaded code.
15836: With superinstructions, many of the dispatch jumps are eliminated, so
15837: patching often has no effect. These options preserve all the dispatch
15838: jumps.
1.109 anton 15839:
15840: @cindex --dynamic command-line option
1.110 anton 15841: On some machines dynamic superinstructions are disabled by default,
15842: because it is unsafe on these machines. However, if you feel
15843: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15844:
15845: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15846: @subsection DOES>
15847: @cindex @code{DOES>} implementation
15848:
1.26 crook 15849: @cindex @code{dodoes} routine
15850: @cindex @code{DOES>}-code
1.1 anton 15851: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15852: the chunk of code executed by every word defined by a
1.109 anton 15853: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15854: this is only needed if the xt of the word is @code{execute}d. The main
15855: problem here is: How to find the Forth code to be executed, i.e. the
15856: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15857: solutions:
1.1 anton 15858:
1.21 crook 15859: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15860: @code{DOES>}-code address is stored in the cell after the code address
15861: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15862: illegal in the Forth-79 and all later standards, because in fig-Forth
15863: this address lies in the body (which is illegal in these
15864: standards). However, by making the code field larger for all words this
15865: solution becomes legal again. We use this approach. Leaving a cell
15866: unused in most words is a bit wasteful, but on the machines we are
15867: targeting this is hardly a problem.
15868:
1.1 anton 15869:
15870: @node Primitives, Performance, Threading, Engine
15871: @section Primitives
15872: @cindex primitives, implementation
15873: @cindex virtual machine instructions, implementation
15874:
15875: @menu
15876: * Automatic Generation::
15877: * TOS Optimization::
15878: * Produced code::
15879: @end menu
15880:
15881: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15882: @subsection Automatic Generation
15883: @cindex primitives, automatic generation
15884:
15885: @cindex @file{prims2x.fs}
1.109 anton 15886:
1.1 anton 15887: Since the primitives are implemented in a portable language, there is no
15888: longer any need to minimize the number of primitives. On the contrary,
15889: having many primitives has an advantage: speed. In order to reduce the
15890: number of errors in primitives and to make programming them easier, we
1.109 anton 15891: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15892: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15893: generates most (and sometimes all) of the C code for a primitive from
15894: the stack effect notation. The source for a primitive has the following
15895: form:
1.1 anton 15896:
15897: @cindex primitive source format
15898: @format
1.58 anton 15899: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15900: [@code{""}@i{glossary entry}@code{""}]
15901: @i{C code}
1.1 anton 15902: [@code{:}
1.29 crook 15903: @i{Forth code}]
1.1 anton 15904: @end format
15905:
15906: The items in brackets are optional. The category and glossary fields
15907: are there for generating the documentation, the Forth code is there
15908: for manual implementations on machines without GNU C. E.g., the source
15909: for the primitive @code{+} is:
15910: @example
1.58 anton 15911: + ( n1 n2 -- n ) core plus
1.1 anton 15912: n = n1+n2;
15913: @end example
15914:
15915: This looks like a specification, but in fact @code{n = n1+n2} is C
15916: code. Our primitive generation tool extracts a lot of information from
15917: the stack effect notations@footnote{We use a one-stack notation, even
15918: though we have separate data and floating-point stacks; The separate
15919: notation can be generated easily from the unified notation.}: The number
15920: of items popped from and pushed on the stack, their type, and by what
15921: name they are referred to in the C code. It then generates a C code
15922: prelude and postlude for each primitive. The final C code for @code{+}
15923: looks like this:
15924:
15925: @example
1.46 pazsan 15926: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15927: /* */ /* documentation */
1.81 anton 15928: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15929: @{
15930: DEF_CA /* definition of variable ca (indirect threading) */
15931: Cell n1; /* definitions of variables */
15932: Cell n2;
15933: Cell n;
1.81 anton 15934: NEXT_P0; /* NEXT part 0 */
1.1 anton 15935: n1 = (Cell) sp[1]; /* input */
15936: n2 = (Cell) TOS;
15937: sp += 1; /* stack adjustment */
15938: @{
15939: n = n1+n2; /* C code taken from the source */
15940: @}
15941: NEXT_P1; /* NEXT part 1 */
15942: TOS = (Cell)n; /* output */
15943: NEXT_P2; /* NEXT part 2 */
15944: @}
15945: @end example
15946:
15947: This looks long and inefficient, but the GNU C compiler optimizes quite
15948: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15949: HP RISC machines: Defining the @code{n}s does not produce any code, and
15950: using them as intermediate storage also adds no cost.
15951:
1.26 crook 15952: There are also other optimizations that are not illustrated by this
15953: example: assignments between simple variables are usually for free (copy
1.1 anton 15954: propagation). If one of the stack items is not used by the primitive
15955: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15956: (dead code elimination). On the other hand, there are some things that
15957: the compiler does not do, therefore they are performed by
15958: @file{prims2x.fs}: The compiler does not optimize code away that stores
15959: a stack item to the place where it just came from (e.g., @code{over}).
15960:
15961: While programming a primitive is usually easy, there are a few cases
15962: where the programmer has to take the actions of the generator into
15963: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15964: fall through to @code{NEXT}.
1.109 anton 15965:
15966: For more information
1.1 anton 15967:
15968: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15969: @subsection TOS Optimization
15970: @cindex TOS optimization for primitives
15971: @cindex primitives, keeping the TOS in a register
15972:
15973: An important optimization for stack machine emulators, e.g., Forth
15974: engines, is keeping one or more of the top stack items in
1.29 crook 15975: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15976: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15977: @itemize @bullet
15978: @item
1.29 crook 15979: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15980: due to fewer loads from and stores to the stack.
1.29 crook 15981: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15982: @i{y<n}, due to additional moves between registers.
1.1 anton 15983: @end itemize
15984:
15985: @cindex -DUSE_TOS
15986: @cindex -DUSE_NO_TOS
15987: In particular, keeping one item in a register is never a disadvantage,
15988: if there are enough registers. Keeping two items in registers is a
15989: disadvantage for frequent words like @code{?branch}, constants,
15990: variables, literals and @code{i}. Therefore our generator only produces
15991: code that keeps zero or one items in registers. The generated C code
15992: covers both cases; the selection between these alternatives is made at
15993: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15994: code for @code{+} is just a simple variable name in the one-item case,
15995: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15996: GNU C compiler tries to keep simple variables like @code{TOS} in
15997: registers, and it usually succeeds, if there are enough registers.
15998:
15999: @cindex -DUSE_FTOS
16000: @cindex -DUSE_NO_FTOS
16001: The primitive generator performs the TOS optimization for the
16002: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16003: operations the benefit of this optimization is even larger:
16004: floating-point operations take quite long on most processors, but can be
16005: performed in parallel with other operations as long as their results are
16006: not used. If the FP-TOS is kept in a register, this works. If
16007: it is kept on the stack, i.e., in memory, the store into memory has to
16008: wait for the result of the floating-point operation, lengthening the
16009: execution time of the primitive considerably.
16010:
16011: The TOS optimization makes the automatic generation of primitives a
16012: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16013: @code{TOS} is not sufficient. There are some special cases to
16014: consider:
16015: @itemize @bullet
16016: @item In the case of @code{dup ( w -- w w )} the generator must not
16017: eliminate the store to the original location of the item on the stack,
16018: if the TOS optimization is turned on.
16019: @item Primitives with stack effects of the form @code{--}
1.29 crook 16020: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16021: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 16022: must load the TOS from the stack at the end. But for the null stack
16023: effect @code{--} no stores or loads should be generated.
16024: @end itemize
16025:
16026: @node Produced code, , TOS Optimization, Primitives
16027: @subsection Produced code
16028: @cindex primitives, assembly code listing
16029:
16030: @cindex @file{engine.s}
16031: To see what assembly code is produced for the primitives on your machine
16032: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 16033: look at the resulting file @file{engine.s}. Alternatively, you can also
16034: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 16035:
16036: @node Performance, , Primitives, Engine
16037: @section Performance
16038: @cindex performance of some Forth interpreters
16039: @cindex engine performance
16040: @cindex benchmarking Forth systems
16041: @cindex Gforth performance
16042:
16043: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 16044: impossible to write a significantly faster threaded-code engine.
1.1 anton 16045:
16046: On register-starved machines like the 386 architecture processors
16047: improvements are possible, because @code{gcc} does not utilize the
16048: registers as well as a human, even with explicit register declarations;
16049: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16050: and hand-tuned it for the 486; this system is 1.19 times faster on the
16051: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 16052: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
16053: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16054: registers fit in real registers (and we can even afford to use the TOS
16055: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 16056: earlier results. And dynamic superinstructions provide another speedup
16057: (but only around a factor 1.2 on the 486).
1.1 anton 16058:
16059: @cindex Win32Forth performance
16060: @cindex NT Forth performance
16061: @cindex eforth performance
16062: @cindex ThisForth performance
16063: @cindex PFE performance
16064: @cindex TILE performance
1.81 anton 16065: The potential advantage of assembly language implementations is not
1.112 anton 16066: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 16067: (direct threaded, compiled with @code{gcc-2.95.1} and
16068: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16069: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16070: (with and without peephole (aka pinhole) optimization of the threaded
16071: code); all these systems were written in assembly language. We also
16072: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16073: with @code{gcc-2.6.3} with the default configuration for Linux:
16074: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16075: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16076: employs peephole optimization of the threaded code) and TILE (compiled
16077: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16078: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16079: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16080: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16081: then extended it to run the benchmarks, added the peephole optimizer,
16082: ran the benchmarks and reported the results.
1.40 anton 16083:
1.1 anton 16084: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16085: matrix multiplication come from the Stanford integer benchmarks and have
16086: been translated into Forth by Martin Fraeman; we used the versions
16087: included in the TILE Forth package, but with bigger data set sizes; and
16088: a recursive Fibonacci number computation for benchmarking calling
16089: performance. The following table shows the time taken for the benchmarks
16090: scaled by the time taken by Gforth (in other words, it shows the speedup
16091: factor that Gforth achieved over the other systems).
16092:
16093: @example
1.112 anton 16094: relative Win32- NT eforth This-
16095: time Gforth Forth Forth eforth +opt PFE Forth TILE
16096: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
16097: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
16098: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
16099: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 16100: @end example
16101:
1.26 crook 16102: You may be quite surprised by the good performance of Gforth when
16103: compared with systems written in assembly language. One important reason
16104: for the disappointing performance of these other systems is probably
16105: that they are not written optimally for the 486 (e.g., they use the
16106: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16107: but costly method for relocating the Forth image: like @code{cforth}, it
16108: computes the actual addresses at run time, resulting in two address
16109: computations per @code{NEXT} (@pxref{Image File Background}).
16110:
1.1 anton 16111: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16112: explained with the self-imposed restriction of the latter systems to
16113: standard C, which makes efficient threading impossible (however, the
1.4 anton 16114: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 16115: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16116: Moreover, current C compilers have a hard time optimizing other aspects
16117: of the ThisForth and the TILE source.
16118:
1.26 crook 16119: The performance of Gforth on 386 architecture processors varies widely
16120: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16121: allocate any of the virtual machine registers into real machine
16122: registers by itself and would not work correctly with explicit register
1.112 anton 16123: declarations, giving a significantly slower engine (on a 486DX2/66
16124: running the Sieve) than the one measured above.
1.1 anton 16125:
1.26 crook 16126: Note that there have been several releases of Win32Forth since the
16127: release presented here, so the results presented above may have little
1.40 anton 16128: predictive value for the performance of Win32Forth today (results for
16129: the current release on an i486DX2/66 are welcome).
1.1 anton 16130:
16131: @cindex @file{Benchres}
1.66 anton 16132: In
16133: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16134: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 16135: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 16136: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16137: several native code systems; that version of Gforth is slower on a 486
1.112 anton 16138: than the version used here. You can find a newer version of these
16139: measurements at
1.47 crook 16140: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 16141: find numbers for Gforth on various machines in @file{Benchres}.
16142:
1.26 crook 16143: @c ******************************************************************
1.113 anton 16144: @c @node Binding to System Library, Cross Compiler, Engine, Top
16145: @c @chapter Binding to System Library
1.13 pazsan 16146:
1.113 anton 16147: @c ****************************************************************
16148: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 16149: @chapter Cross Compiler
1.47 crook 16150: @cindex @file{cross.fs}
16151: @cindex cross-compiler
16152: @cindex metacompiler
16153: @cindex target compiler
1.13 pazsan 16154:
1.46 pazsan 16155: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16156: mostly written in Forth, including crucial parts like the outer
16157: interpreter and compiler, it needs compiled Forth code to get
16158: started. The cross compiler allows to create new images for other
16159: architectures, even running under another Forth system.
1.13 pazsan 16160:
16161: @menu
1.67 anton 16162: * Using the Cross Compiler::
16163: * How the Cross Compiler Works::
1.13 pazsan 16164: @end menu
16165:
1.21 crook 16166: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 16167: @section Using the Cross Compiler
1.46 pazsan 16168:
16169: The cross compiler uses a language that resembles Forth, but isn't. The
16170: main difference is that you can execute Forth code after definition,
16171: while you usually can't execute the code compiled by cross, because the
16172: code you are compiling is typically for a different computer than the
16173: one you are compiling on.
16174:
1.81 anton 16175: @c anton: This chapter is somewhat different from waht I would expect: I
16176: @c would expect an explanation of the cross language and how to create an
16177: @c application image with it. The section explains some aspects of
16178: @c creating a Gforth kernel.
16179:
1.46 pazsan 16180: The Makefile is already set up to allow you to create kernels for new
16181: architectures with a simple make command. The generic kernels using the
16182: GCC compiled virtual machine are created in the normal build process
16183: with @code{make}. To create a embedded Gforth executable for e.g. the
16184: 8086 processor (running on a DOS machine), type
16185:
16186: @example
16187: make kernl-8086.fi
16188: @end example
16189:
16190: This will use the machine description from the @file{arch/8086}
16191: directory to create a new kernel. A machine file may look like that:
16192:
16193: @example
16194: \ Parameter for target systems 06oct92py
16195:
16196: 4 Constant cell \ cell size in bytes
16197: 2 Constant cell<< \ cell shift to bytes
16198: 5 Constant cell>bit \ cell shift to bits
16199: 8 Constant bits/char \ bits per character
16200: 8 Constant bits/byte \ bits per byte [default: 8]
16201: 8 Constant float \ bytes per float
16202: 8 Constant /maxalign \ maximum alignment in bytes
16203: false Constant bigendian \ byte order
16204: ( true=big, false=little )
16205:
16206: include machpc.fs \ feature list
16207: @end example
16208:
16209: This part is obligatory for the cross compiler itself, the feature list
16210: is used by the kernel to conditionally compile some features in and out,
16211: depending on whether the target supports these features.
16212:
16213: There are some optional features, if you define your own primitives,
16214: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 16215: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 16216: @code{prims-include} includes primitives, and @code{>boot} prepares for
16217: booting.
16218:
16219: @example
16220: : asm-include ." Include assembler" cr
16221: s" arch/8086/asm.fs" included ;
16222:
16223: : prims-include ." Include primitives" cr
16224: s" arch/8086/prim.fs" included ;
16225:
16226: : >boot ." Prepare booting" cr
16227: s" ' boot >body into-forth 1+ !" evaluate ;
16228: @end example
16229:
16230: These words are used as sort of macro during the cross compilation in
1.81 anton 16231: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 16232: be possible --- but more complicated --- to write a new kernel project
16233: file, too.
16234:
16235: @file{kernel/main.fs} expects the machine description file name on the
16236: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16237: @code{mach-file} leaves a counted string on the stack, or
16238: @code{machine-file} leaves an address, count pair of the filename on the
16239: stack.
16240:
16241: The feature list is typically controlled using @code{SetValue}, generic
16242: files that are used by several projects can use @code{DefaultValue}
16243: instead. Both functions work like @code{Value}, when the value isn't
16244: defined, but @code{SetValue} works like @code{to} if the value is
16245: defined, and @code{DefaultValue} doesn't set anything, if the value is
16246: defined.
16247:
16248: @example
16249: \ generic mach file for pc gforth 03sep97jaw
16250:
16251: true DefaultValue NIL \ relocating
16252:
16253: >ENVIRON
16254:
16255: true DefaultValue file \ controls the presence of the
16256: \ file access wordset
16257: true DefaultValue OS \ flag to indicate a operating system
16258:
16259: true DefaultValue prims \ true: primitives are c-code
16260:
16261: true DefaultValue floating \ floating point wordset is present
16262:
16263: true DefaultValue glocals \ gforth locals are present
16264: \ will be loaded
16265: true DefaultValue dcomps \ double number comparisons
16266:
16267: true DefaultValue hash \ hashing primitives are loaded/present
16268:
16269: true DefaultValue xconds \ used together with glocals,
16270: \ special conditionals supporting gforths'
16271: \ local variables
16272: true DefaultValue header \ save a header information
16273:
16274: true DefaultValue backtrace \ enables backtrace code
16275:
16276: false DefaultValue ec
16277: false DefaultValue crlf
16278:
16279: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16280:
16281: &16 KB DefaultValue stack-size
16282: &15 KB &512 + DefaultValue fstack-size
16283: &15 KB DefaultValue rstack-size
16284: &14 KB &512 + DefaultValue lstack-size
16285: @end example
1.13 pazsan 16286:
1.48 anton 16287: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16288: @section How the Cross Compiler Works
1.13 pazsan 16289:
16290: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16291: @appendix Bugs
1.1 anton 16292: @cindex bug reporting
16293:
1.21 crook 16294: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16295:
1.103 anton 16296: If you find a bug, please submit a bug report through
16297: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16298:
16299: @itemize @bullet
16300: @item
1.81 anton 16301: A program (or a sequence of keyboard commands) that reproduces the bug.
16302: @item
16303: A description of what you think constitutes the buggy behaviour.
16304: @item
1.21 crook 16305: The Gforth version used (it is announced at the start of an
16306: interactive Gforth session).
16307: @item
16308: The machine and operating system (on Unix
16309: systems @code{uname -a} will report this information).
16310: @item
1.81 anton 16311: The installation options (you can find the configure options at the
16312: start of @file{config.status}) and configuration (@code{configure}
16313: output or @file{config.cache}).
1.21 crook 16314: @item
16315: A complete list of changes (if any) you (or your installer) have made to the
16316: Gforth sources.
16317: @end itemize
1.1 anton 16318:
16319: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16320: to Report Bugs, gcc.info, GNU C Manual}.
16321:
16322:
1.21 crook 16323: @node Origin, Forth-related information, Bugs, Top
16324: @appendix Authors and Ancestors of Gforth
1.1 anton 16325:
16326: @section Authors and Contributors
16327: @cindex authors of Gforth
16328: @cindex contributors to Gforth
16329:
16330: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16331: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16332: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16333: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16334: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16335: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16336: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16337: working on automatic support for calling C libraries. Helpful comments
16338: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16339: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16340: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16341: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16342: comments from many others; thank you all, sorry for not listing you
16343: here (but digging through my mailbox to extract your names is on my
16344: to-do list).
1.1 anton 16345:
16346: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16347: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16348: was developed across the Internet, and its authors did not meet
1.20 pazsan 16349: physically for the first 4 years of development.
1.1 anton 16350:
16351: @section Pedigree
1.26 crook 16352: @cindex pedigree of Gforth
1.1 anton 16353:
1.81 anton 16354: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16355: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16356:
1.20 pazsan 16357: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16358: 32 bit native code version of VolksForth for the Atari ST, written
16359: mostly by Dietrich Weineck.
16360:
1.81 anton 16361: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16362: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16363: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16364:
1.147 anton 16365: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16366: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16367:
16368: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16369: 1979. Robert Selzer and Bill Ragsdale developed the original
16370: implementation of fig-Forth for the 6502 based on microForth.
16371:
16372: The principal architect of microForth was Dean Sanderson. microForth was
16373: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16374: the 1802, and subsequently implemented on the 8080, the 6800 and the
16375: Z80.
16376:
16377: All earlier Forth systems were custom-made, usually by Charles Moore,
16378: who discovered (as he puts it) Forth during the late 60s. The first full
16379: Forth existed in 1971.
16380:
1.81 anton 16381: A part of the information in this section comes from
16382: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16383: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16384: Charles H. Moore, presented at the HOPL-II conference and preprinted
16385: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16386: genealogical information about Forth there. For a more general (and
16387: graphical) Forth family tree look see
16388: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16389: Forth Family Tree and Timeline}.
1.1 anton 16390:
1.81 anton 16391: @c ------------------------------------------------------------------
1.113 anton 16392: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16393: @appendix Other Forth-related information
16394: @cindex Forth-related information
16395:
1.81 anton 16396: @c anton: I threw most of this stuff out, because it can be found through
16397: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16398:
16399: @cindex comp.lang.forth
16400: @cindex frequently asked questions
1.81 anton 16401: There is an active news group (comp.lang.forth) discussing Forth
16402: (including Gforth) and Forth-related issues. Its
16403: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16404: (frequently asked questions and their answers) contains a lot of
16405: information on Forth. You should read it before posting to
16406: comp.lang.forth.
1.21 crook 16407:
1.81 anton 16408: The ANS Forth standard is most usable in its
16409: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16410:
1.113 anton 16411: @c ---------------------------------------------------
16412: @node Licenses, Word Index, Forth-related information, Top
16413: @appendix Licenses
16414:
16415: @menu
16416: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 16417: * Copying:: GPL (for copying this software).
1.113 anton 16418: @end menu
16419:
1.192 anton 16420: @node GNU Free Documentation License, Copying, Licenses, Licenses
16421: @appendixsec GNU Free Documentation License
1.113 anton 16422: @include fdl.texi
16423:
1.192 anton 16424: @node Copying, , GNU Free Documentation License, Licenses
16425: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16426: @include gpl.texi
16427:
16428:
16429:
1.81 anton 16430: @c ------------------------------------------------------------------
1.113 anton 16431: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16432: @unnumbered Word Index
16433:
1.26 crook 16434: This index is a list of Forth words that have ``glossary'' entries
16435: within this manual. Each word is listed with its stack effect and
16436: wordset.
1.1 anton 16437:
16438: @printindex fn
16439:
1.81 anton 16440: @c anton: the name index seems superfluous given the word and concept indices.
16441:
16442: @c @node Name Index, Concept Index, Word Index, Top
16443: @c @unnumbered Name Index
1.41 anton 16444:
1.81 anton 16445: @c This index is a list of Forth words that have ``glossary'' entries
16446: @c within this manual.
1.41 anton 16447:
1.81 anton 16448: @c @printindex ky
1.41 anton 16449:
1.113 anton 16450: @c -------------------------------------------------------
1.81 anton 16451: @node Concept Index, , Word Index, Top
1.1 anton 16452: @unnumbered Concept and Word Index
16453:
1.26 crook 16454: Not all entries listed in this index are present verbatim in the
16455: text. This index also duplicates, in abbreviated form, all of the words
16456: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16457:
16458: @printindex cp
16459:
16460: @bye
1.81 anton 16461:
16462:
1.1 anton 16463:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>