Annotation of gforth/doc/gforth.ds, revision 1.200
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.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.190 anton 177: * Floating Point Tutorial::
1.87 anton 178: * Files Tutorial::
1.48 anton 179: * Interpretation and Compilation Semantics and Immediacy Tutorial::
180: * Execution Tokens Tutorial::
181: * Exceptions Tutorial::
182: * Defining Words Tutorial::
183: * Arrays and Records Tutorial::
184: * POSTPONE Tutorial::
185: * Literal Tutorial::
186: * Advanced macros Tutorial::
187: * Compilation Tokens Tutorial::
188: * Wordlists and Search Order Tutorial::
1.29 crook 189:
1.24 anton 190: An Introduction to ANS Forth
191:
1.67 anton 192: * Introducing the Text Interpreter::
193: * Stacks and Postfix notation::
194: * Your first definition::
195: * How does that work?::
196: * Forth is written in Forth::
197: * Review - elements of a Forth system::
198: * Where to go next::
199: * Exercises::
1.24 anton 200:
1.12 anton 201: Forth Words
202:
203: * Notation::
1.65 anton 204: * Case insensitivity::
205: * Comments::
206: * Boolean Flags::
1.12 anton 207: * Arithmetic::
208: * Stack Manipulation::
209: * Memory::
210: * Control Structures::
211: * Defining Words::
1.65 anton 212: * Interpretation and Compilation Semantics::
1.47 crook 213: * Tokens for Words::
1.81 anton 214: * Compiling words::
1.65 anton 215: * The Text Interpreter::
1.111 anton 216: * The Input Stream::
1.65 anton 217: * Word Lists::
218: * Environmental Queries::
1.12 anton 219: * Files::
220: * Blocks::
221: * Other I/O::
1.121 anton 222: * OS command line arguments::
1.78 anton 223: * Locals::
224: * Structures::
225: * Object-oriented Forth::
1.12 anton 226: * Programming Tools::
1.150 anton 227: * C Interface::
1.12 anton 228: * Assembler and Code Words::
229: * Threading Words::
1.65 anton 230: * Passing Commands to the OS::
231: * Keeping track of Time::
232: * Miscellaneous Words::
1.12 anton 233:
234: Arithmetic
235:
236: * Single precision::
1.67 anton 237: * Double precision:: Double-cell integer arithmetic
1.12 anton 238: * Bitwise operations::
1.67 anton 239: * Numeric comparison::
1.32 anton 240: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 241: * Floating Point::
242:
243: Stack Manipulation
244:
245: * Data stack::
246: * Floating point stack::
247: * Return stack::
248: * Locals stack::
249: * Stack pointer manipulation::
250:
251: Memory
252:
1.32 anton 253: * Memory model::
254: * Dictionary allocation::
255: * Heap Allocation::
256: * Memory Access::
257: * Address arithmetic::
258: * Memory Blocks::
1.12 anton 259:
260: Control Structures
261:
1.41 anton 262: * Selection:: IF ... ELSE ... ENDIF
263: * Simple Loops:: BEGIN ...
1.32 anton 264: * Counted Loops:: DO
1.67 anton 265: * Arbitrary control structures::
266: * Calls and returns::
1.12 anton 267: * Exception Handling::
268:
269: Defining Words
270:
1.67 anton 271: * CREATE::
1.44 crook 272: * Variables:: Variables and user variables
1.67 anton 273: * Constants::
1.44 crook 274: * Values:: Initialised variables
1.67 anton 275: * Colon Definitions::
1.44 crook 276: * Anonymous Definitions:: Definitions without names
1.71 anton 277: * Supplying names:: Passing definition names as strings
1.67 anton 278: * User-defined Defining Words::
1.170 pazsan 279: * Deferred Words:: Allow forward references
1.67 anton 280: * Aliases::
1.47 crook 281:
1.63 anton 282: User-defined Defining Words
283:
284: * CREATE..DOES> applications::
285: * CREATE..DOES> details::
286: * Advanced does> usage example::
1.155 anton 287: * Const-does>::
1.63 anton 288:
1.47 crook 289: Interpretation and Compilation Semantics
290:
1.67 anton 291: * Combined words::
1.12 anton 292:
1.71 anton 293: Tokens for Words
294:
295: * Execution token:: represents execution/interpretation semantics
296: * Compilation token:: represents compilation semantics
297: * Name token:: represents named words
298:
1.82 anton 299: Compiling words
300:
301: * Literals:: Compiling data values
302: * Macros:: Compiling words
303:
1.21 crook 304: The Text Interpreter
305:
1.67 anton 306: * Input Sources::
307: * Number Conversion::
308: * Interpret/Compile states::
309: * Interpreter Directives::
1.21 crook 310:
1.26 crook 311: Word Lists
312:
1.75 anton 313: * Vocabularies::
1.67 anton 314: * Why use word lists?::
1.75 anton 315: * Word list example::
1.26 crook 316:
317: Files
318:
1.48 anton 319: * Forth source files::
320: * General files::
1.167 anton 321: * Redirection::
1.48 anton 322: * Search Paths::
323:
324: Search Paths
325:
1.75 anton 326: * Source Search Paths::
1.26 crook 327: * General Search Paths::
328:
329: Other I/O
330:
1.32 anton 331: * Simple numeric output:: Predefined formats
332: * Formatted numeric output:: Formatted (pictured) output
333: * String Formats:: How Forth stores strings in memory
1.67 anton 334: * Displaying characters and strings:: Other stuff
1.178 anton 335: * Terminal output:: Cursor positioning etc.
1.181 anton 336: * Single-key input::
337: * Line input and conversion::
1.112 anton 338: * Pipes:: How to create your own pipes
1.149 pazsan 339: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 340:
341: Locals
342:
343: * Gforth locals::
344: * ANS Forth locals::
345:
346: Gforth locals
347:
348: * Where are locals visible by name?::
349: * How long do locals live?::
1.78 anton 350: * Locals programming style::
351: * Locals implementation::
1.26 crook 352:
1.12 anton 353: Structures
354:
355: * Why explicit structure support?::
356: * Structure Usage::
357: * Structure Naming Convention::
358: * Structure Implementation::
359: * Structure Glossary::
1.183 anton 360: * Forth200x Structures::
1.12 anton 361:
362: Object-oriented Forth
363:
1.48 anton 364: * Why object-oriented programming?::
365: * Object-Oriented Terminology::
366: * Objects::
367: * OOF::
368: * Mini-OOF::
1.23 crook 369: * Comparison with other object models::
1.12 anton 370:
1.24 anton 371: The @file{objects.fs} model
1.12 anton 372:
373: * Properties of the Objects model::
374: * Basic Objects Usage::
1.41 anton 375: * The Objects base class::
1.12 anton 376: * Creating objects::
377: * Object-Oriented Programming Style::
378: * Class Binding::
379: * Method conveniences::
380: * Classes and Scoping::
1.41 anton 381: * Dividing classes::
1.12 anton 382: * Object Interfaces::
383: * Objects Implementation::
384: * Objects Glossary::
385:
1.24 anton 386: The @file{oof.fs} model
1.12 anton 387:
1.67 anton 388: * Properties of the OOF model::
389: * Basic OOF Usage::
390: * The OOF base class::
391: * Class Declaration::
392: * Class Implementation::
1.12 anton 393:
1.24 anton 394: The @file{mini-oof.fs} model
1.23 crook 395:
1.48 anton 396: * Basic Mini-OOF Usage::
397: * Mini-OOF Example::
398: * Mini-OOF Implementation::
1.23 crook 399:
1.78 anton 400: Programming Tools
401:
1.150 anton 402: * Examining:: Data and Code.
403: * Forgetting words:: Usually before reloading.
1.78 anton 404: * Debugging:: Simple and quick.
405: * Assertions:: Making your programs self-checking.
406: * Singlestep Debugger:: Executing your program word by word.
407:
1.155 anton 408: C Interface
409:
410: * Calling C Functions::
411: * Declaring C Functions::
1.180 anton 412: * Calling C function pointers::
1.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.48 anton 634: * Startup speed:: When 35ms 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
1142: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1143: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1144: system time.
1145:
1146: If startup speed is a problem, you may consider the following ways to
1147: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1148: (for example, by using Fast-CGI).
1.48 anton 1149:
1.112 anton 1150: An easy step that influences Gforth startup speed is the use of the
1151: @option{--no-dynamic} option; this decreases image loading speed, but
1152: increases compile-time and run-time.
1153:
1154: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1155: building it with @code{XLDFLAGS=-static}. This requires more memory for
1156: the code and will therefore slow down the first invocation, but
1157: subsequent invocations avoid the dynamic linking overhead. Another
1158: disadvantage is that Gforth won't profit from library upgrades. As a
1159: result, @code{gforth-static -e bye} takes about 17.1ms user and
1160: 8.2ms system time.
1161:
1162: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1163: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1164: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1165: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1166: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1167: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1168: address for the dictionary, for whatever reason; so you better provide a
1169: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1170: bye} takes about 15.3ms user and 7.5ms system time.
1171:
1172: The final step is to disable dictionary hashing in Gforth. Gforth
1173: builds the hash table on startup, which takes much of the startup
1174: overhead. You can do this by commenting out the @code{include hash.fs}
1175: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1176: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1177: The disadvantages are that functionality like @code{table} and
1178: @code{ekey} is missing and that text interpretation (e.g., compiling)
1179: now takes much longer. So, you should only use this method if there is
1180: no significant text interpretation to perform (the script should be
1.62 crook 1181: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1182: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1183:
1184: @c ******************************************************************
1185: @node Tutorial, Introduction, Gforth Environment, Top
1186: @chapter Forth Tutorial
1187: @cindex Tutorial
1188: @cindex Forth Tutorial
1189:
1.67 anton 1190: @c Topics from nac's Introduction that could be mentioned:
1191: @c press <ret> after each line
1192: @c Prompt
1193: @c numbers vs. words in dictionary on text interpretation
1194: @c what happens on redefinition
1195: @c parsing words (in particular, defining words)
1196:
1.83 anton 1197: The difference of this chapter from the Introduction
1198: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1199: be used while sitting in front of a computer, and covers much more
1200: material, but does not explain how the Forth system works.
1201:
1.62 crook 1202: This tutorial can be used with any ANS-compliant Forth; any
1203: Gforth-specific features are marked as such and you can skip them if you
1204: work with another Forth. This tutorial does not explain all features of
1205: Forth, just enough to get you started and give you some ideas about the
1206: facilities available in Forth. Read the rest of the manual and the
1207: standard when you are through this.
1.48 anton 1208:
1209: The intended way to use this tutorial is that you work through it while
1210: sitting in front of the console, take a look at the examples and predict
1211: what they will do, then try them out; if the outcome is not as expected,
1212: find out why (e.g., by trying out variations of the example), so you
1213: understand what's going on. There are also some assignments that you
1214: should solve.
1215:
1216: This tutorial assumes that you have programmed before and know what,
1217: e.g., a loop is.
1218:
1219: @c !! explain compat library
1220:
1221: @menu
1222: * Starting Gforth Tutorial::
1223: * Syntax Tutorial::
1224: * Crash Course Tutorial::
1225: * Stack Tutorial::
1226: * Arithmetics Tutorial::
1227: * Stack Manipulation Tutorial::
1228: * Using files for Forth code Tutorial::
1229: * Comments Tutorial::
1230: * Colon Definitions Tutorial::
1231: * Decompilation Tutorial::
1232: * Stack-Effect Comments Tutorial::
1233: * Types Tutorial::
1234: * Factoring Tutorial::
1235: * Designing the stack effect Tutorial::
1236: * Local Variables Tutorial::
1237: * Conditional execution Tutorial::
1238: * Flags and Comparisons Tutorial::
1239: * General Loops Tutorial::
1240: * Counted loops Tutorial::
1241: * Recursion Tutorial::
1242: * Leaving definitions or loops Tutorial::
1243: * Return Stack Tutorial::
1244: * Memory Tutorial::
1245: * Characters and Strings Tutorial::
1246: * Alignment Tutorial::
1.190 anton 1247: * Floating Point Tutorial::
1.87 anton 1248: * Files Tutorial::
1.48 anton 1249: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1250: * Execution Tokens Tutorial::
1251: * Exceptions Tutorial::
1252: * Defining Words Tutorial::
1253: * Arrays and Records Tutorial::
1254: * POSTPONE Tutorial::
1255: * Literal Tutorial::
1256: * Advanced macros Tutorial::
1257: * Compilation Tokens Tutorial::
1258: * Wordlists and Search Order Tutorial::
1259: @end menu
1260:
1261: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1262: @section Starting Gforth
1.66 anton 1263: @cindex starting Gforth tutorial
1.48 anton 1264: You can start Gforth by typing its name:
1265:
1266: @example
1267: gforth
1268: @end example
1269:
1270: That puts you into interactive mode; you can leave Gforth by typing
1271: @code{bye}. While in Gforth, you can edit the command line and access
1272: the command line history with cursor keys, similar to bash.
1273:
1274:
1275: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1276: @section Syntax
1.66 anton 1277: @cindex syntax tutorial
1.48 anton 1278:
1.171 anton 1279: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1280: space). Words are separated by white space. E.g., each of the
1281: following lines contains exactly one word:
1282:
1283: @example
1284: word
1285: !@@#$%^&*()
1286: 1234567890
1287: 5!a
1288: @end example
1289:
1290: A frequent beginner's error is to leave away necessary white space,
1291: resulting in an error like @samp{Undefined word}; so if you see such an
1292: error, check if you have put spaces wherever necessary.
1293:
1294: @example
1295: ." hello, world" \ correct
1296: ."hello, world" \ gives an "Undefined word" error
1297: @end example
1298:
1.65 anton 1299: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1300: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1301: your system is case-sensitive, you may have to type all the examples
1302: given here in upper case.
1303:
1304:
1305: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1306: @section Crash Course
1307:
1308: Type
1309:
1310: @example
1311: 0 0 !
1312: here execute
1313: ' catch >body 20 erase abort
1314: ' (quit) >body 20 erase
1315: @end example
1316:
1317: The last two examples are guaranteed to destroy parts of Gforth (and
1318: most other systems), so you better leave Gforth afterwards (if it has
1319: not finished by itself). On some systems you may have to kill gforth
1320: from outside (e.g., in Unix with @code{kill}).
1321:
1322: Now that you know how to produce crashes (and that there's not much to
1323: them), let's learn how to produce meaningful programs.
1324:
1325:
1326: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1327: @section Stack
1.66 anton 1328: @cindex stack tutorial
1.48 anton 1329:
1330: The most obvious feature of Forth is the stack. When you type in a
1331: number, it is pushed on the stack. You can display the content of the
1332: stack with @code{.s}.
1333:
1334: @example
1335: 1 2 .s
1336: 3 .s
1337: @end example
1338:
1339: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1340: appear in @code{.s} output as they appeared in the input.
1341:
1342: You can print the top of stack element with @code{.}.
1343:
1344: @example
1345: 1 2 3 . . .
1346: @end example
1347:
1348: In general, words consume their stack arguments (@code{.s} is an
1349: exception).
1350:
1.141 anton 1351: @quotation Assignment
1.48 anton 1352: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1353: @end quotation
1.48 anton 1354:
1355:
1356: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1357: @section Arithmetics
1.66 anton 1358: @cindex arithmetics tutorial
1.48 anton 1359:
1360: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1361: operate on the top two stack items:
1362:
1363: @example
1.67 anton 1364: 2 2 .s
1365: + .s
1366: .
1.48 anton 1367: 2 1 - .
1368: 7 3 mod .
1369: @end example
1370:
1371: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1372: as in the corresponding infix expression (this is generally the case in
1373: Forth).
1374:
1375: Parentheses are superfluous (and not available), because the order of
1376: the words unambiguously determines the order of evaluation and the
1377: operands:
1378:
1379: @example
1380: 3 4 + 5 * .
1381: 3 4 5 * + .
1382: @end example
1383:
1.141 anton 1384: @quotation Assignment
1.48 anton 1385: What are the infix expressions corresponding to the Forth code above?
1386: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1387: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1388: @end quotation
1.48 anton 1389:
1390: To change the sign, use @code{negate}:
1391:
1392: @example
1393: 2 negate .
1394: @end example
1395:
1.141 anton 1396: @quotation Assignment
1.48 anton 1397: Convert -(-3)*4-5 to Forth.
1.141 anton 1398: @end quotation
1.48 anton 1399:
1400: @code{/mod} performs both @code{/} and @code{mod}.
1401:
1402: @example
1403: 7 3 /mod . .
1404: @end example
1405:
1.66 anton 1406: Reference: @ref{Arithmetic}.
1407:
1408:
1.48 anton 1409: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1410: @section Stack Manipulation
1.66 anton 1411: @cindex stack manipulation tutorial
1.48 anton 1412:
1413: Stack manipulation words rearrange the data on the stack.
1414:
1415: @example
1416: 1 .s drop .s
1417: 1 .s dup .s drop drop .s
1418: 1 2 .s over .s drop drop drop
1419: 1 2 .s swap .s drop drop
1420: 1 2 3 .s rot .s drop drop drop
1421: @end example
1422:
1423: These are the most important stack manipulation words. There are also
1424: variants that manipulate twice as many stack items:
1425:
1426: @example
1427: 1 2 3 4 .s 2swap .s 2drop 2drop
1428: @end example
1429:
1430: Two more stack manipulation words are:
1431:
1432: @example
1433: 1 2 .s nip .s drop
1434: 1 2 .s tuck .s 2drop drop
1435: @end example
1436:
1.141 anton 1437: @quotation Assignment
1.48 anton 1438: Replace @code{nip} and @code{tuck} with combinations of other stack
1439: manipulation words.
1440:
1441: @example
1442: Given: How do you get:
1443: 1 2 3 3 2 1
1444: 1 2 3 1 2 3 2
1445: 1 2 3 1 2 3 3
1446: 1 2 3 1 3 3
1447: 1 2 3 2 1 3
1448: 1 2 3 4 4 3 2 1
1449: 1 2 3 1 2 3 1 2 3
1450: 1 2 3 4 1 2 3 4 1 2
1451: 1 2 3
1452: 1 2 3 1 2 3 4
1453: 1 2 3 1 3
1454: @end example
1.141 anton 1455: @end quotation
1.48 anton 1456:
1457: @example
1458: 5 dup * .
1459: @end example
1460:
1.141 anton 1461: @quotation Assignment
1.48 anton 1462: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1463: Write a piece of Forth code that expects two numbers on the stack
1464: (@var{a} and @var{b}, with @var{b} on top) and computes
1465: @code{(a-b)(a+1)}.
1.141 anton 1466: @end quotation
1.48 anton 1467:
1.66 anton 1468: Reference: @ref{Stack Manipulation}.
1469:
1470:
1.48 anton 1471: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1472: @section Using files for Forth code
1.66 anton 1473: @cindex loading Forth code, tutorial
1474: @cindex files containing Forth code, tutorial
1.48 anton 1475:
1476: While working at the Forth command line is convenient for one-line
1477: examples and short one-off code, you probably want to store your source
1478: code in files for convenient editing and persistence. You can use your
1479: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1480: Gforth}) to create @var{file.fs} and use
1.48 anton 1481:
1482: @example
1.102 anton 1483: s" @var{file.fs}" included
1.48 anton 1484: @end example
1485:
1486: to load it into your Forth system. The file name extension I use for
1487: Forth files is @samp{.fs}.
1488:
1489: You can easily start Gforth with some files loaded like this:
1490:
1491: @example
1.102 anton 1492: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1493: @end example
1494:
1495: If an error occurs during loading these files, Gforth terminates,
1496: whereas an error during @code{INCLUDED} within Gforth usually gives you
1497: a Gforth command line. Starting the Forth system every time gives you a
1498: clean start every time, without interference from the results of earlier
1499: tries.
1500:
1501: I often put all the tests in a file, then load the code and run the
1502: tests with
1503:
1504: @example
1.102 anton 1505: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1506: @end example
1507:
1508: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1509: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1510: restart this command without ado.
1511:
1512: The advantage of this approach is that the tests can be repeated easily
1513: every time the program ist changed, making it easy to catch bugs
1514: introduced by the change.
1515:
1.66 anton 1516: Reference: @ref{Forth source files}.
1517:
1.48 anton 1518:
1519: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1520: @section Comments
1.66 anton 1521: @cindex comments tutorial
1.48 anton 1522:
1523: @example
1524: \ That's a comment; it ends at the end of the line
1525: ( Another comment; it ends here: ) .s
1526: @end example
1527:
1528: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1529: separated with white space from the following text.
1530:
1531: @example
1532: \This gives an "Undefined word" error
1533: @end example
1534:
1535: The first @code{)} ends a comment started with @code{(}, so you cannot
1536: nest @code{(}-comments; and you cannot comment out text containing a
1537: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1538: avoid @code{)} in word names.}.
1539:
1540: I use @code{\}-comments for descriptive text and for commenting out code
1541: of one or more line; I use @code{(}-comments for describing the stack
1542: effect, the stack contents, or for commenting out sub-line pieces of
1543: code.
1544:
1545: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1546: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1547: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1548: with @kbd{M-q}.
1549:
1.66 anton 1550: Reference: @ref{Comments}.
1551:
1.48 anton 1552:
1553: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1554: @section Colon Definitions
1.66 anton 1555: @cindex colon definitions, tutorial
1556: @cindex definitions, tutorial
1557: @cindex procedures, tutorial
1558: @cindex functions, tutorial
1.48 anton 1559:
1560: are similar to procedures and functions in other programming languages.
1561:
1562: @example
1563: : squared ( n -- n^2 )
1564: dup * ;
1565: 5 squared .
1566: 7 squared .
1567: @end example
1568:
1569: @code{:} starts the colon definition; its name is @code{squared}. The
1570: following comment describes its stack effect. The words @code{dup *}
1571: are not executed, but compiled into the definition. @code{;} ends the
1572: colon definition.
1573:
1574: The newly-defined word can be used like any other word, including using
1575: it in other definitions:
1576:
1577: @example
1578: : cubed ( n -- n^3 )
1579: dup squared * ;
1580: -5 cubed .
1581: : fourth-power ( n -- n^4 )
1582: squared squared ;
1583: 3 fourth-power .
1584: @end example
1585:
1.141 anton 1586: @quotation Assignment
1.48 anton 1587: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1588: @code{/mod} in terms of other Forth words, and check if they work (hint:
1589: test your tests on the originals first). Don't let the
1590: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1591: @end quotation
1.48 anton 1592:
1.66 anton 1593: Reference: @ref{Colon Definitions}.
1594:
1.48 anton 1595:
1596: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1597: @section Decompilation
1.66 anton 1598: @cindex decompilation tutorial
1599: @cindex see tutorial
1.48 anton 1600:
1601: You can decompile colon definitions with @code{see}:
1602:
1603: @example
1604: see squared
1605: see cubed
1606: @end example
1607:
1608: In Gforth @code{see} shows you a reconstruction of the source code from
1609: the executable code. Informations that were present in the source, but
1610: not in the executable code, are lost (e.g., comments).
1611:
1.65 anton 1612: You can also decompile the predefined words:
1613:
1614: @example
1615: see .
1616: see +
1617: @end example
1618:
1619:
1.48 anton 1620: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1621: @section Stack-Effect Comments
1.66 anton 1622: @cindex stack-effect comments, tutorial
1623: @cindex --, tutorial
1.48 anton 1624: By convention the comment after the name of a definition describes the
1.171 anton 1625: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1626: the stack before the execution of the definition, i.e., the parameters
1627: that are passed into the colon definition; the part behind the @samp{--}
1628: is the state of the stack after the execution of the definition, i.e.,
1629: the results of the definition. The stack comment only shows the top
1630: stack items that the definition accesses and/or changes.
1631:
1632: You should put a correct stack effect on every definition, even if it is
1633: just @code{( -- )}. You should also add some descriptive comment to
1634: more complicated words (I usually do this in the lines following
1635: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1636: you have to work through every definition before you can understand
1.48 anton 1637: any).
1638:
1.141 anton 1639: @quotation Assignment
1.48 anton 1640: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1641: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1642: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1643: are done, you can compare your stack effects to those in this manual
1.48 anton 1644: (@pxref{Word Index}).
1.141 anton 1645: @end quotation
1.48 anton 1646:
1647: Sometimes programmers put comments at various places in colon
1648: definitions that describe the contents of the stack at that place (stack
1649: comments); i.e., they are like the first part of a stack-effect
1650: comment. E.g.,
1651:
1652: @example
1653: : cubed ( n -- n^3 )
1654: dup squared ( n n^2 ) * ;
1655: @end example
1656:
1657: In this case the stack comment is pretty superfluous, because the word
1658: is simple enough. If you think it would be a good idea to add such a
1659: comment to increase readability, you should also consider factoring the
1660: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1661: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1662: however, if you decide not to refactor it, then having such a comment is
1663: better than not having it.
1664:
1665: The names of the stack items in stack-effect and stack comments in the
1666: standard, in this manual, and in many programs specify the type through
1667: a type prefix, similar to Fortran and Hungarian notation. The most
1668: frequent prefixes are:
1669:
1670: @table @code
1671: @item n
1672: signed integer
1673: @item u
1674: unsigned integer
1675: @item c
1676: character
1677: @item f
1678: Boolean flags, i.e. @code{false} or @code{true}.
1679: @item a-addr,a-
1680: Cell-aligned address
1681: @item c-addr,c-
1682: Char-aligned address (note that a Char may have two bytes in Windows NT)
1683: @item xt
1684: Execution token, same size as Cell
1685: @item w,x
1686: Cell, can contain an integer or an address. It usually takes 32, 64 or
1687: 16 bits (depending on your platform and Forth system). A cell is more
1688: commonly known as machine word, but the term @emph{word} already means
1689: something different in Forth.
1690: @item d
1691: signed double-cell integer
1692: @item ud
1693: unsigned double-cell integer
1694: @item r
1695: Float (on the FP stack)
1696: @end table
1697:
1698: You can find a more complete list in @ref{Notation}.
1699:
1.141 anton 1700: @quotation Assignment
1.48 anton 1701: Write stack-effect comments for all definitions you have written up to
1702: now.
1.141 anton 1703: @end quotation
1.48 anton 1704:
1705:
1706: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1707: @section Types
1.66 anton 1708: @cindex types tutorial
1.48 anton 1709:
1710: In Forth the names of the operations are not overloaded; so similar
1711: operations on different types need different names; e.g., @code{+} adds
1712: integers, and you have to use @code{f+} to add floating-point numbers.
1713: The following prefixes are often used for related operations on
1714: different types:
1715:
1716: @table @code
1717: @item (none)
1718: signed integer
1719: @item u
1720: unsigned integer
1721: @item c
1722: character
1723: @item d
1724: signed double-cell integer
1725: @item ud, du
1726: unsigned double-cell integer
1727: @item 2
1728: two cells (not-necessarily double-cell numbers)
1729: @item m, um
1730: mixed single-cell and double-cell operations
1731: @item f
1732: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1733: and @samp{r} represents FP numbers).
1.48 anton 1734: @end table
1735:
1736: If there are no differences between the signed and the unsigned variant
1737: (e.g., for @code{+}), there is only the prefix-less variant.
1738:
1739: Forth does not perform type checking, neither at compile time, nor at
1740: run time. If you use the wrong oeration, the data are interpreted
1741: incorrectly:
1742:
1743: @example
1744: -1 u.
1745: @end example
1746:
1747: If you have only experience with type-checked languages until now, and
1748: have heard how important type-checking is, don't panic! In my
1749: experience (and that of other Forthers), type errors in Forth code are
1750: usually easy to find (once you get used to it), the increased vigilance
1751: of the programmer tends to catch some harder errors in addition to most
1752: type errors, and you never have to work around the type system, so in
1753: most situations the lack of type-checking seems to be a win (projects to
1754: add type checking to Forth have not caught on).
1755:
1756:
1757: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1758: @section Factoring
1.66 anton 1759: @cindex factoring tutorial
1.48 anton 1760:
1761: If you try to write longer definitions, you will soon find it hard to
1762: keep track of the stack contents. Therefore, good Forth programmers
1763: tend to write only short definitions (e.g., three lines). The art of
1764: finding meaningful short definitions is known as factoring (as in
1765: factoring polynomials).
1766:
1767: Well-factored programs offer additional advantages: smaller, more
1768: general words, are easier to test and debug and can be reused more and
1769: better than larger, specialized words.
1770:
1771: So, if you run into difficulties with stack management, when writing
1772: code, try to define meaningful factors for the word, and define the word
1773: in terms of those. Even if a factor contains only two words, it is
1774: often helpful.
1775:
1.65 anton 1776: Good factoring is not easy, and it takes some practice to get the knack
1777: for it; but even experienced Forth programmers often don't find the
1778: right solution right away, but only when rewriting the program. So, if
1779: you don't come up with a good solution immediately, keep trying, don't
1780: despair.
1.48 anton 1781:
1782: @c example !!
1783:
1784:
1785: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1786: @section Designing the stack effect
1.66 anton 1787: @cindex Stack effect design, tutorial
1788: @cindex design of stack effects, tutorial
1.48 anton 1789:
1790: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1791: function; and since there is only one result, you don't have to deal with
1.48 anton 1792: the order of results, either.
1793:
1.117 anton 1794: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1795: parameter and result order of a definition is important and should be
1796: designed well. The general guideline is to design the stack effect such
1797: that the word is simple to use in most cases, even if that complicates
1798: the implementation of the word. Some concrete rules are:
1799:
1800: @itemize @bullet
1801:
1802: @item
1803: Words consume all of their parameters (e.g., @code{.}).
1804:
1805: @item
1806: If there is a convention on the order of parameters (e.g., from
1807: mathematics or another programming language), stick with it (e.g.,
1808: @code{-}).
1809:
1810: @item
1811: If one parameter usually requires only a short computation (e.g., it is
1812: a constant), pass it on the top of the stack. Conversely, parameters
1813: that usually require a long sequence of code to compute should be passed
1814: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1815: read, because the reader does not need to keep track of the bottom item
1.48 anton 1816: through a long sequence of code (or, alternatively, through stack
1.49 anton 1817: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1818: address on top of the stack because it is usually simpler to compute
1819: than the stored value (often the address is just a variable).
1820:
1821: @item
1822: Similarly, results that are usually consumed quickly should be returned
1823: on the top of stack, whereas a result that is often used in long
1824: computations should be passed as bottom result. E.g., the file words
1825: like @code{open-file} return the error code on the top of stack, because
1826: it is usually consumed quickly by @code{throw}; moreover, the error code
1827: has to be checked before doing anything with the other results.
1828:
1829: @end itemize
1830:
1831: These rules are just general guidelines, don't lose sight of the overall
1832: goal to make the words easy to use. E.g., if the convention rule
1833: conflicts with the computation-length rule, you might decide in favour
1834: of the convention if the word will be used rarely, and in favour of the
1835: computation-length rule if the word will be used frequently (because
1836: with frequent use the cost of breaking the computation-length rule would
1837: be quite high, and frequent use makes it easier to remember an
1838: unconventional order).
1839:
1840: @c example !! structure package
1841:
1.65 anton 1842:
1.48 anton 1843: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1844: @section Local Variables
1.66 anton 1845: @cindex local variables, tutorial
1.48 anton 1846:
1847: You can define local variables (@emph{locals}) in a colon definition:
1848:
1849: @example
1850: : swap @{ a b -- b a @}
1851: b a ;
1852: 1 2 swap .s 2drop
1853: @end example
1854:
1855: (If your Forth system does not support this syntax, include
1.187 anton 1856: @file{compat/anslocal.fs} first).
1.48 anton 1857:
1858: In this example @code{@{ a b -- b a @}} is the locals definition; it
1859: takes two cells from the stack, puts the top of stack in @code{b} and
1860: the next stack element in @code{a}. @code{--} starts a comment ending
1861: with @code{@}}. After the locals definition, using the name of the
1862: local will push its value on the stack. You can leave the comment
1863: part (@code{-- b a}) away:
1864:
1865: @example
1866: : swap ( x1 x2 -- x2 x1 )
1867: @{ a b @} b a ;
1868: @end example
1869:
1870: In Gforth you can have several locals definitions, anywhere in a colon
1871: definition; in contrast, in a standard program you can have only one
1872: locals definition per colon definition, and that locals definition must
1.163 anton 1873: be outside any control structure.
1.48 anton 1874:
1875: With locals you can write slightly longer definitions without running
1876: into stack trouble. However, I recommend trying to write colon
1877: definitions without locals for exercise purposes to help you gain the
1878: essential factoring skills.
1879:
1.141 anton 1880: @quotation Assignment
1.48 anton 1881: Rewrite your definitions until now with locals
1.141 anton 1882: @end quotation
1.48 anton 1883:
1.66 anton 1884: Reference: @ref{Locals}.
1885:
1.48 anton 1886:
1887: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1888: @section Conditional execution
1.66 anton 1889: @cindex conditionals, tutorial
1890: @cindex if, tutorial
1.48 anton 1891:
1892: In Forth you can use control structures only inside colon definitions.
1893: An @code{if}-structure looks like this:
1894:
1895: @example
1896: : abs ( n1 -- +n2 )
1897: dup 0 < if
1898: negate
1899: endif ;
1900: 5 abs .
1901: -5 abs .
1902: @end example
1903:
1904: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1905: the following code is performed, otherwise execution continues after the
1.51 pazsan 1906: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1907: elements and produces a flag:
1.48 anton 1908:
1909: @example
1910: 1 2 < .
1911: 2 1 < .
1912: 1 1 < .
1913: @end example
1914:
1915: Actually the standard name for @code{endif} is @code{then}. This
1916: tutorial presents the examples using @code{endif}, because this is often
1917: less confusing for people familiar with other programming languages
1918: where @code{then} has a different meaning. If your system does not have
1919: @code{endif}, define it with
1920:
1921: @example
1922: : endif postpone then ; immediate
1923: @end example
1924:
1925: You can optionally use an @code{else}-part:
1926:
1927: @example
1928: : min ( n1 n2 -- n )
1929: 2dup < if
1930: drop
1931: else
1932: nip
1933: endif ;
1934: 2 3 min .
1935: 3 2 min .
1936: @end example
1937:
1.141 anton 1938: @quotation Assignment
1.48 anton 1939: Write @code{min} without @code{else}-part (hint: what's the definition
1940: of @code{nip}?).
1.141 anton 1941: @end quotation
1.48 anton 1942:
1.66 anton 1943: Reference: @ref{Selection}.
1944:
1.48 anton 1945:
1946: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1947: @section Flags and Comparisons
1.66 anton 1948: @cindex flags tutorial
1949: @cindex comparison tutorial
1.48 anton 1950:
1951: In a false-flag all bits are clear (0 when interpreted as integer). In
1952: a canonical true-flag all bits are set (-1 as a twos-complement signed
1953: integer); in many contexts (e.g., @code{if}) any non-zero value is
1954: treated as true flag.
1955:
1956: @example
1957: false .
1958: true .
1959: true hex u. decimal
1960: @end example
1961:
1962: Comparison words produce canonical flags:
1963:
1964: @example
1965: 1 1 = .
1966: 1 0= .
1967: 0 1 < .
1968: 0 0 < .
1969: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1970: -1 1 < .
1971: @end example
1972:
1.66 anton 1973: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1974: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1975: these combinations are standard (for details see the standard,
1976: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1977:
1.171 anton 1978: You can use @code{and or xor invert} as operations on canonical flags.
1979: Actually they are bitwise operations:
1.48 anton 1980:
1981: @example
1982: 1 2 and .
1983: 1 2 or .
1984: 1 3 xor .
1985: 1 invert .
1986: @end example
1987:
1988: You can convert a zero/non-zero flag into a canonical flag with
1989: @code{0<>} (and complement it on the way with @code{0=}).
1990:
1991: @example
1992: 1 0= .
1993: 1 0<> .
1994: @end example
1995:
1.65 anton 1996: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1997: operation of the Boolean operations to avoid @code{if}s:
1998:
1999: @example
2000: : foo ( n1 -- n2 )
2001: 0= if
2002: 14
2003: else
2004: 0
2005: endif ;
2006: 0 foo .
2007: 1 foo .
2008:
2009: : foo ( n1 -- n2 )
2010: 0= 14 and ;
2011: 0 foo .
2012: 1 foo .
2013: @end example
2014:
1.141 anton 2015: @quotation Assignment
1.48 anton 2016: Write @code{min} without @code{if}.
1.141 anton 2017: @end quotation
1.48 anton 2018:
1.66 anton 2019: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2020: @ref{Bitwise operations}.
2021:
1.48 anton 2022:
2023: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2024: @section General Loops
1.66 anton 2025: @cindex loops, indefinite, tutorial
1.48 anton 2026:
2027: The endless loop is the most simple one:
2028:
2029: @example
2030: : endless ( -- )
2031: 0 begin
2032: dup . 1+
2033: again ;
2034: endless
2035: @end example
2036:
2037: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2038: does nothing at run-time, @code{again} jumps back to @code{begin}.
2039:
2040: A loop with one exit at any place looks like this:
2041:
2042: @example
2043: : log2 ( +n1 -- n2 )
2044: \ logarithmus dualis of n1>0, rounded down to the next integer
2045: assert( dup 0> )
2046: 2/ 0 begin
2047: over 0> while
2048: 1+ swap 2/ swap
2049: repeat
2050: nip ;
2051: 7 log2 .
2052: 8 log2 .
2053: @end example
2054:
2055: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2056: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2057: continues behind the @code{while}. @code{Repeat} jumps back to
2058: @code{begin}, just like @code{again}.
2059:
2060: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2061: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2062: one bit (arithmetic shift right):
2063:
2064: @example
2065: -5 2 / .
2066: -5 2/ .
2067: @end example
2068:
2069: @code{assert(} is no standard word, but you can get it on systems other
1.198 anton 2070: than Gforth by including @file{compat/assert.fs}. You can see what it
1.48 anton 2071: does by trying
2072:
2073: @example
2074: 0 log2 .
2075: @end example
2076:
2077: Here's a loop with an exit at the end:
2078:
2079: @example
2080: : log2 ( +n1 -- n2 )
2081: \ logarithmus dualis of n1>0, rounded down to the next integer
2082: assert( dup 0 > )
2083: -1 begin
2084: 1+ swap 2/ swap
2085: over 0 <=
2086: until
2087: nip ;
2088: @end example
2089:
2090: @code{Until} consumes a flag; if it is non-zero, execution continues at
2091: the @code{begin}, otherwise after the @code{until}.
2092:
1.141 anton 2093: @quotation Assignment
1.48 anton 2094: Write a definition for computing the greatest common divisor.
1.141 anton 2095: @end quotation
1.48 anton 2096:
1.66 anton 2097: Reference: @ref{Simple Loops}.
2098:
1.48 anton 2099:
2100: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2101: @section Counted loops
1.66 anton 2102: @cindex loops, counted, tutorial
1.48 anton 2103:
2104: @example
2105: : ^ ( n1 u -- n )
1.171 anton 2106: \ n = the uth power of n1
1.48 anton 2107: 1 swap 0 u+do
2108: over *
2109: loop
2110: nip ;
2111: 3 2 ^ .
2112: 4 3 ^ .
2113: @end example
2114:
2115: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2116: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2117: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2118: times (or not at all, if @code{u3-u4<0}).
2119:
2120: You can see the stack effect design rules at work in the stack effect of
2121: the loop start words: Since the start value of the loop is more
2122: frequently constant than the end value, the start value is passed on
2123: the top-of-stack.
2124:
2125: You can access the counter of a counted loop with @code{i}:
2126:
2127: @example
2128: : fac ( u -- u! )
2129: 1 swap 1+ 1 u+do
2130: i *
2131: loop ;
2132: 5 fac .
2133: 7 fac .
2134: @end example
2135:
2136: There is also @code{+do}, which expects signed numbers (important for
2137: deciding whether to enter the loop).
2138:
1.141 anton 2139: @quotation Assignment
1.48 anton 2140: Write a definition for computing the nth Fibonacci number.
1.141 anton 2141: @end quotation
1.48 anton 2142:
1.65 anton 2143: You can also use increments other than 1:
2144:
2145: @example
2146: : up2 ( n1 n2 -- )
2147: +do
2148: i .
2149: 2 +loop ;
2150: 10 0 up2
2151:
2152: : down2 ( n1 n2 -- )
2153: -do
2154: i .
2155: 2 -loop ;
2156: 0 10 down2
2157: @end example
1.48 anton 2158:
1.66 anton 2159: Reference: @ref{Counted Loops}.
2160:
1.48 anton 2161:
2162: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2163: @section Recursion
1.66 anton 2164: @cindex recursion tutorial
1.48 anton 2165:
2166: Usually the name of a definition is not visible in the definition; but
2167: earlier definitions are usually visible:
2168:
2169: @example
1.166 anton 2170: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2171: : / ( n1 n2 -- n )
2172: dup 0= if
2173: -10 throw \ report division by zero
2174: endif
2175: / \ old version
2176: ;
2177: 1 0 /
2178: @end example
2179:
2180: For recursive definitions you can use @code{recursive} (non-standard) or
2181: @code{recurse}:
2182:
2183: @example
2184: : fac1 ( n -- n! ) recursive
2185: dup 0> if
2186: dup 1- fac1 *
2187: else
2188: drop 1
2189: endif ;
2190: 7 fac1 .
2191:
2192: : fac2 ( n -- n! )
2193: dup 0> if
2194: dup 1- recurse *
2195: else
2196: drop 1
2197: endif ;
2198: 8 fac2 .
2199: @end example
2200:
1.141 anton 2201: @quotation Assignment
1.48 anton 2202: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2203: @end quotation
1.48 anton 2204:
1.66 anton 2205: Reference (including indirect recursion): @xref{Calls and returns}.
2206:
1.48 anton 2207:
2208: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2209: @section Leaving definitions or loops
1.66 anton 2210: @cindex leaving definitions, tutorial
2211: @cindex leaving loops, tutorial
1.48 anton 2212:
2213: @code{EXIT} exits the current definition right away. For every counted
2214: loop that is left in this way, an @code{UNLOOP} has to be performed
2215: before the @code{EXIT}:
2216:
2217: @c !! real examples
2218: @example
2219: : ...
2220: ... u+do
2221: ... if
2222: ... unloop exit
2223: endif
2224: ...
2225: loop
2226: ... ;
2227: @end example
2228:
2229: @code{LEAVE} leaves the innermost counted loop right away:
2230:
2231: @example
2232: : ...
2233: ... u+do
2234: ... if
2235: ... leave
2236: endif
2237: ...
2238: loop
2239: ... ;
2240: @end example
2241:
1.65 anton 2242: @c !! example
1.48 anton 2243:
1.66 anton 2244: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2245:
2246:
1.48 anton 2247: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2248: @section Return Stack
1.66 anton 2249: @cindex return stack tutorial
1.48 anton 2250:
2251: In addition to the data stack Forth also has a second stack, the return
2252: stack; most Forth systems store the return addresses of procedure calls
2253: there (thus its name). Programmers can also use this stack:
2254:
2255: @example
2256: : foo ( n1 n2 -- )
2257: .s
2258: >r .s
1.50 anton 2259: r@@ .
1.48 anton 2260: >r .s
1.50 anton 2261: r@@ .
1.48 anton 2262: r> .
1.50 anton 2263: r@@ .
1.48 anton 2264: r> . ;
2265: 1 2 foo
2266: @end example
2267:
2268: @code{>r} takes an element from the data stack and pushes it onto the
2269: return stack; conversely, @code{r>} moves an elementm from the return to
2270: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2271: on the data stack.
1.48 anton 2272:
2273: Forth programmers usually use the return stack for storing data
2274: temporarily, if using the data stack alone would be too complex, and
2275: factoring and locals are not an option:
2276:
2277: @example
2278: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2279: rot >r rot r> ;
2280: @end example
2281:
2282: The return address of the definition and the loop control parameters of
2283: counted loops usually reside on the return stack, so you have to take
2284: all items, that you have pushed on the return stack in a colon
2285: definition or counted loop, from the return stack before the definition
2286: or loop ends. You cannot access items that you pushed on the return
2287: stack outside some definition or loop within the definition of loop.
2288:
2289: If you miscount the return stack items, this usually ends in a crash:
2290:
2291: @example
2292: : crash ( n -- )
2293: >r ;
2294: 5 crash
2295: @end example
2296:
2297: You cannot mix using locals and using the return stack (according to the
2298: standard; Gforth has no problem). However, they solve the same
2299: problems, so this shouldn't be an issue.
2300:
1.141 anton 2301: @quotation Assignment
1.48 anton 2302: Can you rewrite any of the definitions you wrote until now in a better
2303: way using the return stack?
1.141 anton 2304: @end quotation
1.48 anton 2305:
1.66 anton 2306: Reference: @ref{Return stack}.
2307:
1.48 anton 2308:
2309: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2310: @section Memory
1.66 anton 2311: @cindex memory access/allocation tutorial
1.48 anton 2312:
2313: You can create a global variable @code{v} with
2314:
2315: @example
2316: variable v ( -- addr )
2317: @end example
2318:
2319: @code{v} pushes the address of a cell in memory on the stack. This cell
2320: was reserved by @code{variable}. You can use @code{!} (store) to store
2321: values into this cell and @code{@@} (fetch) to load the value from the
2322: stack into memory:
2323:
2324: @example
2325: v .
2326: 5 v ! .s
1.50 anton 2327: v @@ .
1.48 anton 2328: @end example
2329:
1.65 anton 2330: You can see a raw dump of memory with @code{dump}:
2331:
2332: @example
2333: v 1 cells .s dump
2334: @end example
2335:
2336: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2337: generally, address units (aus)) that @code{n1 cells} occupy. You can
2338: also reserve more memory:
1.48 anton 2339:
2340: @example
2341: create v2 20 cells allot
1.65 anton 2342: v2 20 cells dump
1.48 anton 2343: @end example
2344:
1.65 anton 2345: creates a word @code{v2} and reserves 20 uninitialized cells; the
2346: address pushed by @code{v2} points to the start of these 20 cells. You
2347: can use address arithmetic to access these cells:
1.48 anton 2348:
2349: @example
2350: 3 v2 5 cells + !
1.65 anton 2351: v2 20 cells dump
1.48 anton 2352: @end example
2353:
2354: You can reserve and initialize memory with @code{,}:
2355:
2356: @example
2357: create v3
2358: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2359: v3 @@ .
2360: v3 cell+ @@ .
2361: v3 2 cells + @@ .
1.65 anton 2362: v3 5 cells dump
1.48 anton 2363: @end example
2364:
1.141 anton 2365: @quotation Assignment
1.48 anton 2366: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2367: @code{u} cells, with the first of these cells at @code{addr}, the next
2368: one at @code{addr cell+} etc.
1.141 anton 2369: @end quotation
1.48 anton 2370:
2371: You can also reserve memory without creating a new word:
2372:
2373: @example
1.60 anton 2374: here 10 cells allot .
2375: here .
1.48 anton 2376: @end example
2377:
2378: @code{Here} pushes the start address of the memory area. You should
2379: store it somewhere, or you will have a hard time finding the memory area
2380: again.
2381:
2382: @code{Allot} manages dictionary memory. The dictionary memory contains
2383: the system's data structures for words etc. on Gforth and most other
2384: Forth systems. It is managed like a stack: You can free the memory that
2385: you have just @code{allot}ed with
2386:
2387: @example
2388: -10 cells allot
1.60 anton 2389: here .
1.48 anton 2390: @end example
2391:
2392: Note that you cannot do this if you have created a new word in the
2393: meantime (because then your @code{allot}ed memory is no longer on the
2394: top of the dictionary ``stack'').
2395:
2396: Alternatively, you can use @code{allocate} and @code{free} which allow
2397: freeing memory in any order:
2398:
2399: @example
2400: 10 cells allocate throw .s
2401: 20 cells allocate throw .s
2402: swap
2403: free throw
2404: free throw
2405: @end example
2406:
2407: The @code{throw}s deal with errors (e.g., out of memory).
2408:
1.65 anton 2409: And there is also a
2410: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2411: garbage collector}, which eliminates the need to @code{free} memory
2412: explicitly.
1.48 anton 2413:
1.66 anton 2414: Reference: @ref{Memory}.
2415:
1.48 anton 2416:
2417: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2418: @section Characters and Strings
1.66 anton 2419: @cindex strings tutorial
2420: @cindex characters tutorial
1.48 anton 2421:
2422: On the stack characters take up a cell, like numbers. In memory they
2423: have their own size (one 8-bit byte on most systems), and therefore
2424: require their own words for memory access:
2425:
2426: @example
2427: create v4
2428: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2429: v4 4 chars + c@@ .
1.65 anton 2430: v4 5 chars dump
1.48 anton 2431: @end example
2432:
2433: The preferred representation of strings on the stack is @code{addr
2434: u-count}, where @code{addr} is the address of the first character and
2435: @code{u-count} is the number of characters in the string.
2436:
2437: @example
2438: v4 5 type
2439: @end example
2440:
2441: You get a string constant with
2442:
2443: @example
2444: s" hello, world" .s
2445: type
2446: @end example
2447:
2448: Make sure you have a space between @code{s"} and the string; @code{s"}
2449: is a normal Forth word and must be delimited with white space (try what
2450: happens when you remove the space).
2451:
2452: However, this interpretive use of @code{s"} is quite restricted: the
2453: string exists only until the next call of @code{s"} (some Forth systems
2454: keep more than one of these strings, but usually they still have a
1.62 crook 2455: limited lifetime).
1.48 anton 2456:
2457: @example
2458: s" hello," s" world" .s
2459: type
2460: type
2461: @end example
2462:
1.62 crook 2463: You can also use @code{s"} in a definition, and the resulting
2464: strings then live forever (well, for as long as the definition):
1.48 anton 2465:
2466: @example
2467: : foo s" hello," s" world" ;
2468: foo .s
2469: type
2470: type
2471: @end example
2472:
1.141 anton 2473: @quotation Assignment
1.48 anton 2474: @code{Emit ( c -- )} types @code{c} as character (not a number).
2475: Implement @code{type ( addr u -- )}.
1.141 anton 2476: @end quotation
1.48 anton 2477:
1.66 anton 2478: Reference: @ref{Memory Blocks}.
2479:
2480:
1.190 anton 2481: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2482: @section Alignment
1.66 anton 2483: @cindex alignment tutorial
2484: @cindex memory alignment tutorial
1.48 anton 2485:
2486: On many processors cells have to be aligned in memory, if you want to
2487: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2488: not require alignment, access to aligned cells is faster).
1.48 anton 2489:
2490: @code{Create} aligns @code{here} (i.e., the place where the next
2491: allocation will occur, and that the @code{create}d word points to).
2492: Likewise, the memory produced by @code{allocate} starts at an aligned
2493: address. Adding a number of @code{cells} to an aligned address produces
2494: another aligned address.
2495:
2496: However, address arithmetic involving @code{char+} and @code{chars} can
2497: create an address that is not cell-aligned. @code{Aligned ( addr --
2498: a-addr )} produces the next aligned address:
2499:
2500: @example
1.50 anton 2501: v3 char+ aligned .s @@ .
2502: v3 char+ .s @@ .
1.48 anton 2503: @end example
2504:
2505: Similarly, @code{align} advances @code{here} to the next aligned
2506: address:
2507:
2508: @example
2509: create v5 97 c,
2510: here .
2511: align here .
2512: 1000 ,
2513: @end example
2514:
2515: Note that you should use aligned addresses even if your processor does
2516: not require them, if you want your program to be portable.
2517:
1.66 anton 2518: Reference: @ref{Address arithmetic}.
2519:
1.190 anton 2520: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2521: @section Floating Point
2522: @cindex floating point tutorial
2523: @cindex FP tutorial
2524:
2525: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2526: might expect, but there are a few things worth noting:
2527:
2528: The first point is not specific to Forth, but so important and yet not
2529: universally known that I mention it here: FP numbers are not reals.
2530: Many properties (e.g., arithmetic laws) that reals have and that one
2531: expects of all kinds of numbers do not hold for FP numbers. If you
2532: want to use FP computations, you should learn about their problems and
2533: how to avoid them; a good starting point is @cite{David Goldberg,
2534: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2535: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2536: Computing Surveys 23(1):5@minus{}48, March 1991}.
2537:
2538: In Forth source code literal FP numbers need an exponent, e.g.,
2539: @code{1e0}; this can also be written shorter as @code{1e},
2540: @code{+1.0e+0}, and many variations in between. The reason for this
2541: is that, for historical reasons, Forth interprets a decimal point
2542: alone (e.g., @code{1.}) as indicating a double-cell integer. Another
2543: requirement for literal FP numbers is that the current base is
2544: decimal; with a hex base @code{1e} is interpreted as an integer.
2545:
2546: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2547: ANS Forth system may implement the FP stack on the data stack, but
2548: virtually all systems implement a separate FP stack; and programming
2549: in a way that accommodates all models is so cumbersome that nobody
2550: does it.} One advantage of this model is that cells are not in the
2551: way when accessing FP values, and vice versa. Forth has a set of
2552: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2553: frot} and (non-standard) @code{fnip ftuck fpick}.
2554:
2555: FP arithmetic words are prefixed with @code{F}. There is the usual
2556: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2557: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2558: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2559: computation results are usually inaccurate, so exact comparison is
2560: usually a mistake, and one should use approximate comparison.
2561: Unfortunately, @code{f~}, the standard word for that purpose, is not
2562: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2563: well.
2564:
2565: And of course there are words for accessing FP numbers in memory
2566: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2567: faligned}). There are also variants of these words with an @code{sf}
2568: and @code{df} prefix for accessing IEEE format single-precision and
2569: double-precision numbers in memory; their main purpose is for
2570: accessing external FP data (e.g., that has been read from or will be
2571: written to a file).
2572:
2573: Here is an example of a dot-product word and its use:
2574:
2575: @example
2576: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2577: >r swap 2swap swap 0e r> 0 ?DO
2578: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2579: LOOP
2580: 2drop 2drop ;
1.48 anton 2581:
1.190 anton 2582: create v 1.23e f, 4.56e f, 7.89e f,
2583:
2584: v 1 floats v 1 floats 3 v* f.
2585: @end example
2586:
2587: @quotation Assignment
2588: Write a program to solve a quadratic equation. Then read @cite{Henry
2589: G. Baker,
2590: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2591: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2592: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2593: program. Finally, find a test case where the original and the
2594: improved version produce different results.
2595: @end quotation
2596:
2597: Reference: @ref{Floating Point}; @ref{Floating point stack};
2598: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2599: arithmetic}.
2600:
2601: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84 pazsan 2602: @section Files
2603: @cindex files tutorial
2604:
2605: This section gives a short introduction into how to use files inside
2606: Forth. It's broken up into five easy steps:
2607:
2608: @enumerate 1
2609: @item Opened an ASCII text file for input
2610: @item Opened a file for output
2611: @item Read input file until string matched (or some other condition matched)
2612: @item Wrote some lines from input ( modified or not) to output
2613: @item Closed the files.
2614: @end enumerate
2615:
1.153 anton 2616: Reference: @ref{General files}.
2617:
1.84 pazsan 2618: @subsection Open file for input
2619:
2620: @example
2621: s" foo.in" r/o open-file throw Value fd-in
2622: @end example
2623:
2624: @subsection Create file for output
2625:
2626: @example
2627: s" foo.out" w/o create-file throw Value fd-out
2628: @end example
2629:
2630: The available file modes are r/o for read-only access, r/w for
2631: read-write access, and w/o for write-only access. You could open both
2632: files with r/w, too, if you like. All file words return error codes; for
2633: most applications, it's best to pass there error codes with @code{throw}
2634: to the outer error handler.
2635:
2636: If you want words for opening and assigning, define them as follows:
2637:
2638: @example
2639: 0 Value fd-in
2640: 0 Value fd-out
2641: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2642: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2643: @end example
2644:
2645: Usage example:
2646:
2647: @example
2648: s" foo.in" open-input
2649: s" foo.out" open-output
2650: @end example
2651:
2652: @subsection Scan file for a particular line
2653:
2654: @example
2655: 256 Constant max-line
2656: Create line-buffer max-line 2 + allot
2657:
2658: : scan-file ( addr u -- )
2659: begin
2660: line-buffer max-line fd-in read-line throw
2661: while
2662: >r 2dup line-buffer r> compare 0=
2663: until
2664: else
2665: drop
2666: then
2667: 2drop ;
2668: @end example
2669:
2670: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2671: the buffer at addr, and returns the number of bytes read, a flag that is
2672: false when the end of file is reached, and an error code.
1.84 pazsan 2673:
2674: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2675: returns zero if both strings are equal. It returns a positive number if
2676: the first string is lexically greater, a negative if the second string
2677: is lexically greater.
2678:
2679: We haven't seen this loop here; it has two exits. Since the @code{while}
2680: exits with the number of bytes read on the stack, we have to clean up
2681: that separately; that's after the @code{else}.
2682:
2683: Usage example:
2684:
2685: @example
2686: s" The text I search is here" scan-file
2687: @end example
2688:
2689: @subsection Copy input to output
2690:
2691: @example
2692: : copy-file ( -- )
2693: begin
2694: line-buffer max-line fd-in read-line throw
2695: while
1.194 anton 2696: line-buffer swap fd-out write-line throw
1.84 pazsan 2697: repeat ;
2698: @end example
1.194 anton 2699: @c !! does not handle long lines, no newline at end of file
1.84 pazsan 2700:
2701: @subsection Close files
2702:
2703: @example
2704: fd-in close-file throw
2705: fd-out close-file throw
2706: @end example
2707:
2708: Likewise, you can put that into definitions, too:
2709:
2710: @example
2711: : close-input ( -- ) fd-in close-file throw ;
2712: : close-output ( -- ) fd-out close-file throw ;
2713: @end example
2714:
1.141 anton 2715: @quotation Assignment
1.84 pazsan 2716: How could you modify @code{copy-file} so that it copies until a second line is
2717: matched? Can you write a program that extracts a section of a text file,
2718: given the line that starts and the line that terminates that section?
1.141 anton 2719: @end quotation
1.84 pazsan 2720:
2721: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2722: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2723: @cindex semantics tutorial
2724: @cindex interpretation semantics tutorial
2725: @cindex compilation semantics tutorial
2726: @cindex immediate, tutorial
1.48 anton 2727:
2728: When a word is compiled, it behaves differently from being interpreted.
2729: E.g., consider @code{+}:
2730:
2731: @example
2732: 1 2 + .
2733: : foo + ;
2734: @end example
2735:
2736: These two behaviours are known as compilation and interpretation
2737: semantics. For normal words (e.g., @code{+}), the compilation semantics
2738: is to append the interpretation semantics to the currently defined word
2739: (@code{foo} in the example above). I.e., when @code{foo} is executed
2740: later, the interpretation semantics of @code{+} (i.e., adding two
2741: numbers) will be performed.
2742:
2743: However, there are words with non-default compilation semantics, e.g.,
2744: the control-flow words like @code{if}. You can use @code{immediate} to
2745: change the compilation semantics of the last defined word to be equal to
2746: the interpretation semantics:
2747:
2748: @example
2749: : [FOO] ( -- )
2750: 5 . ; immediate
2751:
2752: [FOO]
2753: : bar ( -- )
2754: [FOO] ;
2755: bar
2756: see bar
2757: @end example
2758:
1.198 anton 2759: Two conventions to mark words with non-default compilation semantics are
1.48 anton 2760: names with brackets (more frequently used) and to write them all in
2761: upper case (less frequently used).
2762:
2763: In Gforth (and many other systems) you can also remove the
2764: interpretation semantics with @code{compile-only} (the compilation
2765: semantics is derived from the original interpretation semantics):
2766:
2767: @example
2768: : flip ( -- )
2769: 6 . ; compile-only \ but not immediate
2770: flip
2771:
2772: : flop ( -- )
2773: flip ;
2774: flop
2775: @end example
2776:
2777: In this example the interpretation semantics of @code{flop} is equal to
2778: the original interpretation semantics of @code{flip}.
2779:
2780: The text interpreter has two states: in interpret state, it performs the
2781: interpretation semantics of words it encounters; in compile state, it
2782: performs the compilation semantics of these words.
2783:
2784: Among other things, @code{:} switches into compile state, and @code{;}
2785: switches back to interpret state. They contain the factors @code{]}
2786: (switch to compile state) and @code{[} (switch to interpret state), that
2787: do nothing but switch the state.
2788:
2789: @example
2790: : xxx ( -- )
2791: [ 5 . ]
2792: ;
2793:
2794: xxx
2795: see xxx
2796: @end example
2797:
2798: These brackets are also the source of the naming convention mentioned
2799: above.
2800:
1.66 anton 2801: Reference: @ref{Interpretation and Compilation Semantics}.
2802:
1.48 anton 2803:
2804: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2805: @section Execution Tokens
1.66 anton 2806: @cindex execution tokens tutorial
2807: @cindex XT tutorial
1.48 anton 2808:
2809: @code{' word} gives you the execution token (XT) of a word. The XT is a
2810: cell representing the interpretation semantics of a word. You can
2811: execute this semantics with @code{execute}:
2812:
2813: @example
2814: ' + .s
2815: 1 2 rot execute .
2816: @end example
2817:
2818: The XT is similar to a function pointer in C. However, parameter
2819: passing through the stack makes it a little more flexible:
2820:
2821: @example
2822: : map-array ( ... addr u xt -- ... )
1.50 anton 2823: \ executes xt ( ... x -- ... ) for every element of the array starting
2824: \ at addr and containing u elements
1.48 anton 2825: @{ xt @}
2826: cells over + swap ?do
1.50 anton 2827: i @@ xt execute
1.48 anton 2828: 1 cells +loop ;
2829:
2830: create a 3 , 4 , 2 , -1 , 4 ,
2831: a 5 ' . map-array .s
2832: 0 a 5 ' + map-array .
2833: s" max-n" environment? drop .s
2834: a 5 ' min map-array .
2835: @end example
2836:
2837: You can use map-array with the XTs of words that consume one element
2838: more than they produce. In theory you can also use it with other XTs,
2839: but the stack effect then depends on the size of the array, which is
2840: hard to understand.
2841:
1.51 pazsan 2842: Since XTs are cell-sized, you can store them in memory and manipulate
2843: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2844: word with @code{compile,}:
2845:
2846: @example
2847: : foo1 ( n1 n2 -- n )
2848: [ ' + compile, ] ;
2849: see foo
2850: @end example
2851:
2852: This is non-standard, because @code{compile,} has no compilation
2853: semantics in the standard, but it works in good Forth systems. For the
2854: broken ones, use
2855:
2856: @example
2857: : [compile,] compile, ; immediate
2858:
2859: : foo1 ( n1 n2 -- n )
2860: [ ' + ] [compile,] ;
2861: see foo
2862: @end example
2863:
2864: @code{'} is a word with default compilation semantics; it parses the
2865: next word when its interpretation semantics are executed, not during
2866: compilation:
2867:
2868: @example
2869: : foo ( -- xt )
2870: ' ;
2871: see foo
2872: : bar ( ... "word" -- ... )
2873: ' execute ;
2874: see bar
1.60 anton 2875: 1 2 bar + .
1.48 anton 2876: @end example
2877:
2878: You often want to parse a word during compilation and compile its XT so
2879: it will be pushed on the stack at run-time. @code{[']} does this:
2880:
2881: @example
2882: : xt-+ ( -- xt )
2883: ['] + ;
2884: see xt-+
2885: 1 2 xt-+ execute .
2886: @end example
2887:
2888: Many programmers tend to see @code{'} and the word it parses as one
2889: unit, and expect it to behave like @code{[']} when compiled, and are
2890: confused by the actual behaviour. If you are, just remember that the
2891: Forth system just takes @code{'} as one unit and has no idea that it is
2892: a parsing word (attempts to convenience programmers in this issue have
2893: usually resulted in even worse pitfalls, see
1.66 anton 2894: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2895: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2896:
2897: Note that the state of the interpreter does not come into play when
1.51 pazsan 2898: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2899: compile state, it still gives you the interpretation semantics. And
2900: whatever that state is, @code{execute} performs the semantics
1.66 anton 2901: represented by the XT (i.e., for XTs produced with @code{'} the
2902: interpretation semantics).
2903:
2904: Reference: @ref{Tokens for Words}.
1.48 anton 2905:
2906:
2907: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2908: @section Exceptions
1.66 anton 2909: @cindex exceptions tutorial
1.48 anton 2910:
2911: @code{throw ( n -- )} causes an exception unless n is zero.
2912:
2913: @example
2914: 100 throw .s
2915: 0 throw .s
2916: @end example
2917:
2918: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2919: it catches exceptions and pushes the number of the exception on the
2920: stack (or 0, if the xt executed without exception). If there was an
2921: exception, the stacks have the same depth as when entering @code{catch}:
2922:
2923: @example
2924: .s
2925: 3 0 ' / catch .s
2926: 3 2 ' / catch .s
2927: @end example
2928:
1.141 anton 2929: @quotation Assignment
1.48 anton 2930: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2931: @end quotation
1.48 anton 2932:
2933: @code{Throw} always jumps to the dynamically next enclosing
2934: @code{catch}, even if it has to leave several call levels to achieve
2935: this:
2936:
2937: @example
2938: : foo 100 throw ;
2939: : foo1 foo ." after foo" ;
1.51 pazsan 2940: : bar ['] foo1 catch ;
1.60 anton 2941: bar .
1.48 anton 2942: @end example
2943:
2944: It is often important to restore a value upon leaving a definition, even
2945: if the definition is left through an exception. You can ensure this
2946: like this:
2947:
2948: @example
2949: : ...
2950: save-x
1.51 pazsan 2951: ['] word-changing-x catch ( ... n )
1.48 anton 2952: restore-x
2953: ( ... n ) throw ;
2954: @end example
2955:
1.172 anton 2956: However, this is still not safe against, e.g., the user pressing
2957: @kbd{Ctrl-C} when execution is between the @code{catch} and
2958: @code{restore-x}.
2959:
2960: Gforth provides an alternative exception handling syntax that is safe
2961: against such cases: @code{try ... restore ... endtry}. If the code
2962: between @code{try} and @code{endtry} has an exception, the stack
2963: depths are restored, the exception number is pushed on the stack, and
2964: the execution continues right after @code{restore}.
1.48 anton 2965:
1.172 anton 2966: The safer equivalent to the restoration code above is
1.48 anton 2967:
2968: @example
2969: : ...
2970: save-x
2971: try
1.92 anton 2972: word-changing-x 0
1.172 anton 2973: restore
2974: restore-x
2975: endtry
1.48 anton 2976: throw ;
2977: @end example
2978:
1.66 anton 2979: Reference: @ref{Exception Handling}.
2980:
1.48 anton 2981:
2982: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2983: @section Defining Words
1.66 anton 2984: @cindex defining words tutorial
2985: @cindex does> tutorial
2986: @cindex create...does> tutorial
2987:
2988: @c before semantics?
1.48 anton 2989:
2990: @code{:}, @code{create}, and @code{variable} are definition words: They
2991: define other words. @code{Constant} is another definition word:
2992:
2993: @example
2994: 5 constant foo
2995: foo .
2996: @end example
2997:
2998: You can also use the prefixes @code{2} (double-cell) and @code{f}
2999: (floating point) with @code{variable} and @code{constant}.
3000:
3001: You can also define your own defining words. E.g.:
3002:
3003: @example
3004: : variable ( "name" -- )
3005: create 0 , ;
3006: @end example
3007:
3008: You can also define defining words that create words that do something
3009: other than just producing their address:
3010:
3011: @example
3012: : constant ( n "name" -- )
3013: create ,
3014: does> ( -- n )
1.50 anton 3015: ( addr ) @@ ;
1.48 anton 3016:
3017: 5 constant foo
3018: foo .
3019: @end example
3020:
3021: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3022: @code{does>} replaces @code{;}, but it also does something else: It
3023: changes the last defined word such that it pushes the address of the
3024: body of the word and then performs the code after the @code{does>}
3025: whenever it is called.
3026:
3027: In the example above, @code{constant} uses @code{,} to store 5 into the
3028: body of @code{foo}. When @code{foo} executes, it pushes the address of
3029: the body onto the stack, then (in the code after the @code{does>})
3030: fetches the 5 from there.
3031:
3032: The stack comment near the @code{does>} reflects the stack effect of the
3033: defined word, not the stack effect of the code after the @code{does>}
3034: (the difference is that the code expects the address of the body that
3035: the stack comment does not show).
3036:
3037: You can use these definition words to do factoring in cases that involve
3038: (other) definition words. E.g., a field offset is always added to an
3039: address. Instead of defining
3040:
3041: @example
3042: 2 cells constant offset-field1
3043: @end example
3044:
3045: and using this like
3046:
3047: @example
3048: ( addr ) offset-field1 +
3049: @end example
3050:
3051: you can define a definition word
3052:
3053: @example
3054: : simple-field ( n "name" -- )
3055: create ,
3056: does> ( n1 -- n1+n )
1.50 anton 3057: ( addr ) @@ + ;
1.48 anton 3058: @end example
1.21 crook 3059:
1.48 anton 3060: Definition and use of field offsets now look like this:
1.21 crook 3061:
1.48 anton 3062: @example
3063: 2 cells simple-field field1
1.60 anton 3064: create mystruct 4 cells allot
3065: mystruct .s field1 .s drop
1.48 anton 3066: @end example
1.21 crook 3067:
1.48 anton 3068: If you want to do something with the word without performing the code
3069: after the @code{does>}, you can access the body of a @code{create}d word
3070: with @code{>body ( xt -- addr )}:
1.21 crook 3071:
1.48 anton 3072: @example
3073: : value ( n "name" -- )
3074: create ,
3075: does> ( -- n1 )
1.50 anton 3076: @@ ;
1.48 anton 3077: : to ( n "name" -- )
3078: ' >body ! ;
1.21 crook 3079:
1.48 anton 3080: 5 value foo
3081: foo .
3082: 7 to foo
3083: foo .
3084: @end example
1.21 crook 3085:
1.141 anton 3086: @quotation Assignment
1.48 anton 3087: Define @code{defer ( "name" -- )}, which creates a word that stores an
3088: XT (at the start the XT of @code{abort}), and upon execution
3089: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3090: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3091: recursion is one application of @code{defer}.
1.141 anton 3092: @end quotation
1.29 crook 3093:
1.66 anton 3094: Reference: @ref{User-defined Defining Words}.
3095:
3096:
1.48 anton 3097: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3098: @section Arrays and Records
1.66 anton 3099: @cindex arrays tutorial
3100: @cindex records tutorial
3101: @cindex structs tutorial
1.29 crook 3102:
1.48 anton 3103: Forth has no standard words for defining data structures such as arrays
3104: and records (structs in C terminology), but you can build them yourself
3105: based on address arithmetic. You can also define words for defining
3106: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3107:
1.48 anton 3108: One of the first projects a Forth newcomer sets out upon when learning
3109: about defining words is an array defining word (possibly for
3110: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3111: learn something from it. However, don't be disappointed when you later
3112: learn that you have little use for these words (inappropriate use would
1.198 anton 3113: be even worse). I have not found a set of useful array words yet;
1.48 anton 3114: the needs are just too diverse, and named, global arrays (the result of
3115: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3116: consider how to pass them as parameters). Another such project is a set
3117: of words to help dealing with strings.
1.29 crook 3118:
1.48 anton 3119: On the other hand, there is a useful set of record words, and it has
3120: been defined in @file{compat/struct.fs}; these words are predefined in
3121: Gforth. They are explained in depth elsewhere in this manual (see
3122: @pxref{Structures}). The @code{simple-field} example above is
3123: simplified variant of fields in this package.
1.21 crook 3124:
3125:
1.48 anton 3126: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3127: @section @code{POSTPONE}
1.66 anton 3128: @cindex postpone tutorial
1.21 crook 3129:
1.48 anton 3130: You can compile the compilation semantics (instead of compiling the
3131: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3132:
1.48 anton 3133: @example
3134: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3135: POSTPONE + ; immediate
1.48 anton 3136: : foo ( n1 n2 -- n )
3137: MY-+ ;
3138: 1 2 foo .
3139: see foo
3140: @end example
1.21 crook 3141:
1.48 anton 3142: During the definition of @code{foo} the text interpreter performs the
3143: compilation semantics of @code{MY-+}, which performs the compilation
3144: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3145:
3146: This example also displays separate stack comments for the compilation
3147: semantics and for the stack effect of the compiled code. For words with
3148: default compilation semantics these stack effects are usually not
3149: displayed; the stack effect of the compilation semantics is always
3150: @code{( -- )} for these words, the stack effect for the compiled code is
3151: the stack effect of the interpretation semantics.
3152:
3153: Note that the state of the interpreter does not come into play when
3154: performing the compilation semantics in this way. You can also perform
3155: it interpretively, e.g.:
3156:
3157: @example
3158: : foo2 ( n1 n2 -- n )
3159: [ MY-+ ] ;
3160: 1 2 foo .
3161: see foo
3162: @end example
1.21 crook 3163:
1.48 anton 3164: However, there are some broken Forth systems where this does not always
1.62 crook 3165: work, and therefore this practice was been declared non-standard in
1.48 anton 3166: 1999.
3167: @c !! repair.fs
3168:
3169: Here is another example for using @code{POSTPONE}:
1.44 crook 3170:
1.48 anton 3171: @example
3172: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3173: POSTPONE negate POSTPONE + ; immediate compile-only
3174: : bar ( n1 n2 -- n )
3175: MY-- ;
3176: 2 1 bar .
3177: see bar
3178: @end example
1.21 crook 3179:
1.48 anton 3180: You can define @code{ENDIF} in this way:
1.21 crook 3181:
1.48 anton 3182: @example
3183: : ENDIF ( Compilation: orig -- )
3184: POSTPONE then ; immediate
3185: @end example
1.21 crook 3186:
1.141 anton 3187: @quotation Assignment
1.48 anton 3188: Write @code{MY-2DUP} that has compilation semantics equivalent to
3189: @code{2dup}, but compiles @code{over over}.
1.141 anton 3190: @end quotation
1.29 crook 3191:
1.66 anton 3192: @c !! @xref{Macros} for reference
3193:
3194:
1.48 anton 3195: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3196: @section @code{Literal}
1.66 anton 3197: @cindex literal tutorial
1.29 crook 3198:
1.48 anton 3199: You cannot @code{POSTPONE} numbers:
1.21 crook 3200:
1.48 anton 3201: @example
3202: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3203: @end example
3204:
1.48 anton 3205: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3206:
1.48 anton 3207: @example
3208: : [FOO] ( compilation: --; run-time: -- n )
3209: 500 POSTPONE literal ; immediate
1.29 crook 3210:
1.60 anton 3211: : flip [FOO] ;
1.48 anton 3212: flip .
3213: see flip
3214: @end example
1.29 crook 3215:
1.48 anton 3216: @code{LITERAL} consumes a number at compile-time (when it's compilation
3217: semantics are executed) and pushes it at run-time (when the code it
3218: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3219: number computed at compile time into the current word:
1.29 crook 3220:
1.48 anton 3221: @example
3222: : bar ( -- n )
3223: [ 2 2 + ] literal ;
3224: see bar
3225: @end example
1.29 crook 3226:
1.141 anton 3227: @quotation Assignment
1.48 anton 3228: Write @code{]L} which allows writing the example above as @code{: bar (
3229: -- n ) [ 2 2 + ]L ;}
1.141 anton 3230: @end quotation
1.48 anton 3231:
1.66 anton 3232: @c !! @xref{Macros} for reference
3233:
1.48 anton 3234:
3235: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3236: @section Advanced macros
1.66 anton 3237: @cindex macros, advanced tutorial
3238: @cindex run-time code generation, tutorial
1.48 anton 3239:
1.66 anton 3240: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3241: Execution Tokens}. It frequently performs @code{execute}, a relatively
3242: expensive operation in some Forth implementations. You can use
1.48 anton 3243: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3244: and produce a word that contains the word to be performed directly:
3245:
3246: @c use ]] ... [[
3247: @example
3248: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3249: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3250: \ array beginning at addr and containing u elements
3251: @{ xt @}
3252: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3253: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3254: 1 cells POSTPONE literal POSTPONE +loop ;
3255:
3256: : sum-array ( addr u -- n )
3257: 0 rot rot [ ' + compile-map-array ] ;
3258: see sum-array
3259: a 5 sum-array .
3260: @end example
3261:
3262: You can use the full power of Forth for generating the code; here's an
3263: example where the code is generated in a loop:
3264:
3265: @example
3266: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3267: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3268: POSTPONE tuck POSTPONE @@
1.48 anton 3269: POSTPONE literal POSTPONE * POSTPONE +
3270: POSTPONE swap POSTPONE cell+ ;
3271:
3272: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3273: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3274: 0 postpone literal postpone swap
3275: [ ' compile-vmul-step compile-map-array ]
3276: postpone drop ;
3277: see compile-vmul
3278:
3279: : a-vmul ( addr -- n )
1.51 pazsan 3280: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3281: [ a 5 compile-vmul ] ;
3282: see a-vmul
3283: a a-vmul .
3284: @end example
3285:
3286: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3287: also use @code{map-array} instead (try it now!).
1.48 anton 3288:
3289: You can use this technique for efficient multiplication of large
3290: matrices. In matrix multiplication, you multiply every line of one
3291: matrix with every column of the other matrix. You can generate the code
3292: for one line once, and use it for every column. The only downside of
3293: this technique is that it is cumbersome to recover the memory consumed
3294: by the generated code when you are done (and in more complicated cases
3295: it is not possible portably).
3296:
1.66 anton 3297: @c !! @xref{Macros} for reference
3298:
3299:
1.48 anton 3300: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3301: @section Compilation Tokens
1.66 anton 3302: @cindex compilation tokens, tutorial
3303: @cindex CT, tutorial
1.48 anton 3304:
3305: This section is Gforth-specific. You can skip it.
3306:
3307: @code{' word compile,} compiles the interpretation semantics. For words
3308: with default compilation semantics this is the same as performing the
3309: compilation semantics. To represent the compilation semantics of other
3310: words (e.g., words like @code{if} that have no interpretation
3311: semantics), Gforth has the concept of a compilation token (CT,
3312: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3313: You can perform the compilation semantics represented by a CT with
3314: @code{execute}:
1.29 crook 3315:
1.48 anton 3316: @example
3317: : foo2 ( n1 n2 -- n )
3318: [ comp' + execute ] ;
3319: see foo
3320: @end example
1.29 crook 3321:
1.48 anton 3322: You can compile the compilation semantics represented by a CT with
3323: @code{postpone,}:
1.30 anton 3324:
1.48 anton 3325: @example
3326: : foo3 ( -- )
3327: [ comp' + postpone, ] ;
3328: see foo3
3329: @end example
1.30 anton 3330:
1.51 pazsan 3331: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3332: @code{comp'} is particularly useful for words that have no
3333: interpretation semantics:
1.29 crook 3334:
1.30 anton 3335: @example
1.48 anton 3336: ' if
1.60 anton 3337: comp' if .s 2drop
1.30 anton 3338: @end example
3339:
1.66 anton 3340: Reference: @ref{Tokens for Words}.
3341:
1.29 crook 3342:
1.48 anton 3343: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3344: @section Wordlists and Search Order
1.66 anton 3345: @cindex wordlists tutorial
3346: @cindex search order, tutorial
1.48 anton 3347:
3348: The dictionary is not just a memory area that allows you to allocate
3349: memory with @code{allot}, it also contains the Forth words, arranged in
3350: several wordlists. When searching for a word in a wordlist,
3351: conceptually you start searching at the youngest and proceed towards
3352: older words (in reality most systems nowadays use hash-tables); i.e., if
3353: you define a word with the same name as an older word, the new word
3354: shadows the older word.
3355:
3356: Which wordlists are searched in which order is determined by the search
3357: order. You can display the search order with @code{order}. It displays
3358: first the search order, starting with the wordlist searched first, then
3359: it displays the wordlist that will contain newly defined words.
1.21 crook 3360:
1.48 anton 3361: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3362:
1.48 anton 3363: @example
3364: wordlist constant mywords
3365: @end example
1.21 crook 3366:
1.48 anton 3367: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3368: defined words (the @emph{current} wordlist):
1.21 crook 3369:
1.48 anton 3370: @example
3371: mywords set-current
3372: order
3373: @end example
1.26 crook 3374:
1.48 anton 3375: Gforth does not display a name for the wordlist in @code{mywords}
3376: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3377:
1.48 anton 3378: You can get the current wordlist with @code{get-current ( -- wid)}. If
3379: you want to put something into a specific wordlist without overall
3380: effect on the current wordlist, this typically looks like this:
1.21 crook 3381:
1.48 anton 3382: @example
3383: get-current mywords set-current ( wid )
3384: create someword
3385: ( wid ) set-current
3386: @end example
1.21 crook 3387:
1.48 anton 3388: You can write the search order with @code{set-order ( wid1 .. widn n --
3389: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3390: searched wordlist is topmost.
1.21 crook 3391:
1.48 anton 3392: @example
3393: get-order mywords swap 1+ set-order
3394: order
3395: @end example
1.21 crook 3396:
1.48 anton 3397: Yes, the order of wordlists in the output of @code{order} is reversed
3398: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3399:
1.141 anton 3400: @quotation Assignment
1.48 anton 3401: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3402: wordlist to the search order. Define @code{previous ( -- )}, which
3403: removes the first searched wordlist from the search order. Experiment
3404: with boundary conditions (you will see some crashes or situations that
3405: are hard or impossible to leave).
1.141 anton 3406: @end quotation
1.21 crook 3407:
1.48 anton 3408: The search order is a powerful foundation for providing features similar
3409: to Modula-2 modules and C++ namespaces. However, trying to modularize
3410: programs in this way has disadvantages for debugging and reuse/factoring
3411: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3412: though). These disadvantages are not so clear in other
1.82 anton 3413: languages/programming environments, because these languages are not so
1.48 anton 3414: strong in debugging and reuse.
1.21 crook 3415:
1.66 anton 3416: @c !! example
3417:
3418: Reference: @ref{Word Lists}.
1.21 crook 3419:
1.29 crook 3420: @c ******************************************************************
1.48 anton 3421: @node Introduction, Words, Tutorial, Top
1.29 crook 3422: @comment node-name, next, previous, up
3423: @chapter An Introduction to ANS Forth
3424: @cindex Forth - an introduction
1.21 crook 3425:
1.83 anton 3426: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3427: that it is slower-paced in its examples, but uses them to dive deep into
3428: explaining Forth internals (not covered by the Tutorial). Apart from
3429: that, this chapter covers far less material. It is suitable for reading
3430: without using a computer.
3431:
1.29 crook 3432: The primary purpose of this manual is to document Gforth. However, since
3433: Forth is not a widely-known language and there is a lack of up-to-date
3434: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3435: material. For other sources of Forth-related
3436: information, see @ref{Forth-related information}.
1.21 crook 3437:
1.29 crook 3438: The examples in this section should work on any ANS Forth; the
3439: output shown was produced using Gforth. Each example attempts to
3440: reproduce the exact output that Gforth produces. If you try out the
3441: examples (and you should), what you should type is shown @kbd{like this}
3442: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3443: that, where the example shows @key{RET} it means that you should
1.29 crook 3444: press the ``carriage return'' key. Unfortunately, some output formats for
3445: this manual cannot show the difference between @kbd{this} and
3446: @code{this} which will make trying out the examples harder (but not
3447: impossible).
1.21 crook 3448:
1.29 crook 3449: Forth is an unusual language. It provides an interactive development
3450: environment which includes both an interpreter and compiler. Forth
3451: programming style encourages you to break a problem down into many
3452: @cindex factoring
3453: small fragments (@dfn{factoring}), and then to develop and test each
3454: fragment interactively. Forth advocates assert that breaking the
3455: edit-compile-test cycle used by conventional programming languages can
3456: lead to great productivity improvements.
1.21 crook 3457:
1.29 crook 3458: @menu
1.67 anton 3459: * Introducing the Text Interpreter::
3460: * Stacks and Postfix notation::
3461: * Your first definition::
3462: * How does that work?::
3463: * Forth is written in Forth::
3464: * Review - elements of a Forth system::
3465: * Where to go next::
3466: * Exercises::
1.29 crook 3467: @end menu
1.21 crook 3468:
1.29 crook 3469: @comment ----------------------------------------------
3470: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3471: @section Introducing the Text Interpreter
3472: @cindex text interpreter
3473: @cindex outer interpreter
1.21 crook 3474:
1.30 anton 3475: @c IMO this is too detailed and the pace is too slow for
3476: @c an introduction. If you know German, take a look at
3477: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3478: @c to see how I do it - anton
3479:
1.44 crook 3480: @c nac-> Where I have accepted your comments 100% and modified the text
3481: @c accordingly, I have deleted your comments. Elsewhere I have added a
3482: @c response like this to attempt to rationalise what I have done. Of
3483: @c course, this is a very clumsy mechanism for something that would be
3484: @c done far more efficiently over a beer. Please delete any dialogue
3485: @c you consider closed.
3486:
1.29 crook 3487: When you invoke the Forth image, you will see a startup banner printed
3488: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3489: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3490: its command line interpreter, which is called the @dfn{Text Interpreter}
3491: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3492: about the text interpreter as you read through this chapter, for more
3493: detail @pxref{The Text Interpreter}).
1.21 crook 3494:
1.29 crook 3495: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3496: input. Type a number and press the @key{RET} key:
1.21 crook 3497:
1.26 crook 3498: @example
1.30 anton 3499: @kbd{45@key{RET}} ok
1.26 crook 3500: @end example
1.21 crook 3501:
1.29 crook 3502: Rather than give you a prompt to invite you to input something, the text
3503: interpreter prints a status message @i{after} it has processed a line
3504: of input. The status message in this case (``@code{ ok}'' followed by
3505: carriage-return) indicates that the text interpreter was able to process
3506: all of your input successfully. Now type something illegal:
3507:
3508: @example
1.30 anton 3509: @kbd{qwer341@key{RET}}
1.134 anton 3510: *the terminal*:2: Undefined word
3511: >>>qwer341<<<
3512: Backtrace:
3513: $2A95B42A20 throw
3514: $2A95B57FB8 no.extensions
1.29 crook 3515: @end example
1.23 crook 3516:
1.134 anton 3517: The exact text, other than the ``Undefined word'' may differ slightly
3518: on your system, but the effect is the same; when the text interpreter
1.29 crook 3519: detects an error, it discards any remaining text on a line, resets
1.134 anton 3520: certain internal state and prints an error message. For a detailed
3521: description of error messages see @ref{Error messages}.
1.23 crook 3522:
1.29 crook 3523: The text interpreter waits for you to press carriage-return, and then
3524: processes your input line. Starting at the beginning of the line, it
3525: breaks the line into groups of characters separated by spaces. For each
3526: group of characters in turn, it makes two attempts to do something:
1.23 crook 3527:
1.29 crook 3528: @itemize @bullet
3529: @item
1.44 crook 3530: @cindex name dictionary
1.29 crook 3531: It tries to treat it as a command. It does this by searching a @dfn{name
3532: dictionary}. If the group of characters matches an entry in the name
3533: dictionary, the name dictionary provides the text interpreter with
3534: information that allows the text interpreter perform some actions. In
3535: Forth jargon, we say that the group
3536: @cindex word
3537: @cindex definition
3538: @cindex execution token
3539: @cindex xt
3540: of characters names a @dfn{word}, that the dictionary search returns an
3541: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3542: word, and that the text interpreter executes the xt. Often, the terms
3543: @dfn{word} and @dfn{definition} are used interchangeably.
3544: @item
3545: If the text interpreter fails to find a match in the name dictionary, it
3546: tries to treat the group of characters as a number in the current number
3547: base (when you start up Forth, the current number base is base 10). If
3548: the group of characters legitimately represents a number, the text
3549: interpreter pushes the number onto a stack (we'll learn more about that
3550: in the next section).
3551: @end itemize
1.23 crook 3552:
1.29 crook 3553: If the text interpreter is unable to do either of these things with any
3554: group of characters, it discards the group of characters and the rest of
3555: the line, then prints an error message. If the text interpreter reaches
3556: the end of the line without error, it prints the status message ``@code{ ok}''
3557: followed by carriage-return.
1.21 crook 3558:
1.29 crook 3559: This is the simplest command we can give to the text interpreter:
1.23 crook 3560:
3561: @example
1.30 anton 3562: @key{RET} ok
1.23 crook 3563: @end example
1.21 crook 3564:
1.29 crook 3565: The text interpreter did everything we asked it to do (nothing) without
3566: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3567: command:
1.21 crook 3568:
1.23 crook 3569: @example
1.30 anton 3570: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3571: *the terminal*:3: Undefined word
3572: 12 dup >>>fred<<< dup
3573: Backtrace:
3574: $2A95B42A20 throw
3575: $2A95B57FB8 no.extensions
1.23 crook 3576: @end example
1.21 crook 3577:
1.29 crook 3578: When you press the carriage-return key, the text interpreter starts to
3579: work its way along the line:
1.21 crook 3580:
1.29 crook 3581: @itemize @bullet
3582: @item
3583: When it gets to the space after the @code{2}, it takes the group of
3584: characters @code{12} and looks them up in the name
3585: dictionary@footnote{We can't tell if it found them or not, but assume
3586: for now that it did not}. There is no match for this group of characters
3587: in the name dictionary, so it tries to treat them as a number. It is
3588: able to do this successfully, so it puts the number, 12, ``on the stack''
3589: (whatever that means).
3590: @item
3591: The text interpreter resumes scanning the line and gets the next group
3592: of characters, @code{dup}. It looks it up in the name dictionary and
3593: (you'll have to take my word for this) finds it, and executes the word
3594: @code{dup} (whatever that means).
3595: @item
3596: Once again, the text interpreter resumes scanning the line and gets the
3597: group of characters @code{fred}. It looks them up in the name
3598: dictionary, but can't find them. It tries to treat them as a number, but
3599: they don't represent any legal number.
3600: @end itemize
1.21 crook 3601:
1.29 crook 3602: At this point, the text interpreter gives up and prints an error
3603: message. The error message shows exactly how far the text interpreter
3604: got in processing the line. In particular, it shows that the text
3605: interpreter made no attempt to do anything with the final character
3606: group, @code{dup}, even though we have good reason to believe that the
3607: text interpreter would have no problem looking that word up and
3608: executing it a second time.
1.21 crook 3609:
3610:
1.29 crook 3611: @comment ----------------------------------------------
3612: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3613: @section Stacks, postfix notation and parameter passing
3614: @cindex text interpreter
3615: @cindex outer interpreter
1.21 crook 3616:
1.29 crook 3617: In procedural programming languages (like C and Pascal), the
3618: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3619: functions or procedures are called with @dfn{explicit parameters}. For
3620: example, in C we might write:
1.21 crook 3621:
1.23 crook 3622: @example
1.29 crook 3623: total = total + new_volume(length,height,depth);
1.23 crook 3624: @end example
1.21 crook 3625:
1.23 crook 3626: @noindent
1.29 crook 3627: where new_volume is a function-call to another piece of code, and total,
3628: length, height and depth are all variables. length, height and depth are
3629: parameters to the function-call.
1.21 crook 3630:
1.29 crook 3631: In Forth, the equivalent of the function or procedure is the
3632: @dfn{definition} and parameters are implicitly passed between
3633: definitions using a shared stack that is visible to the
3634: programmer. Although Forth does support variables, the existence of the
3635: stack means that they are used far less often than in most other
3636: programming languages. When the text interpreter encounters a number, it
3637: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3638: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3639: used for any operation is implied unambiguously by the operation being
3640: performed. The stack used for all integer operations is called the @dfn{data
3641: stack} and, since this is the stack used most commonly, references to
3642: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3643:
1.29 crook 3644: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3645:
1.23 crook 3646: @example
1.30 anton 3647: @kbd{1 2 3@key{RET}} ok
1.23 crook 3648: @end example
1.21 crook 3649:
1.29 crook 3650: Then this instructs the text interpreter to placed three numbers on the
3651: (data) stack. An analogy for the behaviour of the stack is to take a
3652: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3653: the table. The 3 was the last card onto the pile (``last-in'') and if
3654: you take a card off the pile then, unless you're prepared to fiddle a
3655: bit, the card that you take off will be the 3 (``first-out''). The
3656: number that will be first-out of the stack is called the @dfn{top of
3657: stack}, which
3658: @cindex TOS definition
3659: is often abbreviated to @dfn{TOS}.
1.21 crook 3660:
1.29 crook 3661: To understand how parameters are passed in Forth, consider the
3662: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3663: be surprised to learn that this definition performs addition. More
3664: precisely, it adds two number together and produces a result. Where does
3665: it get the two numbers from? It takes the top two numbers off the
3666: stack. Where does it place the result? On the stack. You can act-out the
3667: behaviour of @code{+} with your playing cards like this:
1.21 crook 3668:
3669: @itemize @bullet
3670: @item
1.29 crook 3671: Pick up two cards from the stack on the table
1.21 crook 3672: @item
1.29 crook 3673: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3674: numbers''
1.21 crook 3675: @item
1.29 crook 3676: Decide that the answer is 5
1.21 crook 3677: @item
1.29 crook 3678: Shuffle the two cards back into the pack and find a 5
1.21 crook 3679: @item
1.29 crook 3680: Put a 5 on the remaining ace that's on the table.
1.21 crook 3681: @end itemize
3682:
1.29 crook 3683: If you don't have a pack of cards handy but you do have Forth running,
3684: you can use the definition @code{.s} to show the current state of the stack,
3685: without affecting the stack. Type:
1.21 crook 3686:
3687: @example
1.124 anton 3688: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3689: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3690: @end example
3691:
1.124 anton 3692: The text interpreter looks up the word @code{clearstacks} and executes
3693: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3694: left on it by earlier examples. The text interpreter pushes each of the
3695: three numbers in turn onto the stack. Finally, the text interpreter
3696: looks up the word @code{.s} and executes it. The effect of executing
3697: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3698: followed by a list of all the items on the stack; the item on the far
3699: right-hand side is the TOS.
1.21 crook 3700:
1.29 crook 3701: You can now type:
1.21 crook 3702:
1.29 crook 3703: @example
1.30 anton 3704: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3705: @end example
1.21 crook 3706:
1.29 crook 3707: @noindent
3708: which is correct; there are now 2 items on the stack and the result of
3709: the addition is 5.
1.23 crook 3710:
1.29 crook 3711: If you're playing with cards, try doing a second addition: pick up the
3712: two cards, work out that their sum is 6, shuffle them into the pack,
3713: look for a 6 and place that on the table. You now have just one item on
3714: the stack. What happens if you try to do a third addition? Pick up the
3715: first card, pick up the second card -- ah! There is no second card. This
3716: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3717: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3718: Underflow or an Invalid Memory Address error).
1.23 crook 3719:
1.29 crook 3720: The opposite situation to a stack underflow is a @dfn{stack overflow},
3721: which simply accepts that there is a finite amount of storage space
3722: reserved for the stack. To stretch the playing card analogy, if you had
3723: enough packs of cards and you piled the cards up on the table, you would
3724: eventually be unable to add another card; you'd hit the ceiling. Gforth
3725: allows you to set the maximum size of the stacks. In general, the only
3726: time that you will get a stack overflow is because a definition has a
3727: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3728:
1.29 crook 3729: There's one final use for the playing card analogy. If you model your
3730: stack using a pack of playing cards, the maximum number of items on
3731: your stack will be 52 (I assume you didn't use the Joker). The maximum
3732: @i{value} of any item on the stack is 13 (the King). In fact, the only
3733: possible numbers are positive integer numbers 1 through 13; you can't
3734: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3735: think about some of the cards, you can accommodate different
3736: numbers. For example, you could think of the Jack as representing 0,
3737: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3738: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3739: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3740:
1.29 crook 3741: In that analogy, the limit was the amount of information that a single
3742: stack entry could hold, and Forth has a similar limit. In Forth, the
3743: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3744: implementation dependent and affects the maximum value that a stack
3745: entry can hold. A Standard Forth provides a cell size of at least
3746: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3747:
1.29 crook 3748: Forth does not do any type checking for you, so you are free to
3749: manipulate and combine stack items in any way you wish. A convenient way
3750: of treating stack items is as 2's complement signed integers, and that
3751: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3752:
1.29 crook 3753: @example
1.30 anton 3754: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3755: @end example
1.21 crook 3756:
1.29 crook 3757: If you use numbers and definitions like @code{+} in order to turn Forth
3758: into a great big pocket calculator, you will realise that it's rather
3759: different from a normal calculator. Rather than typing 2 + 3 = you had
3760: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3761: result). The terminology used to describe this difference is to say that
3762: your calculator uses @dfn{Infix Notation} (parameters and operators are
3763: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3764: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3765:
1.29 crook 3766: Whilst postfix notation might look confusing to begin with, it has
3767: several important advantages:
1.21 crook 3768:
1.23 crook 3769: @itemize @bullet
3770: @item
1.29 crook 3771: it is unambiguous
1.23 crook 3772: @item
1.29 crook 3773: it is more concise
1.23 crook 3774: @item
1.29 crook 3775: it fits naturally with a stack-based system
1.23 crook 3776: @end itemize
1.21 crook 3777:
1.29 crook 3778: To examine these claims in more detail, consider these sums:
1.21 crook 3779:
1.29 crook 3780: @example
3781: 6 + 5 * 4 =
3782: 4 * 5 + 6 =
3783: @end example
1.21 crook 3784:
1.29 crook 3785: If you're just learning maths or your maths is very rusty, you will
3786: probably come up with the answer 44 for the first and 26 for the
3787: second. If you are a bit of a whizz at maths you will remember the
3788: @i{convention} that multiplication takes precendence over addition, and
3789: you'd come up with the answer 26 both times. To explain the answer 26
3790: to someone who got the answer 44, you'd probably rewrite the first sum
3791: like this:
1.21 crook 3792:
1.29 crook 3793: @example
3794: 6 + (5 * 4) =
3795: @end example
1.21 crook 3796:
1.29 crook 3797: If what you really wanted was to perform the addition before the
3798: multiplication, you would have to use parentheses to force it.
1.21 crook 3799:
1.29 crook 3800: If you did the first two sums on a pocket calculator you would probably
3801: get the right answers, unless you were very cautious and entered them using
3802: these keystroke sequences:
1.21 crook 3803:
1.29 crook 3804: 6 + 5 = * 4 =
3805: 4 * 5 = + 6 =
1.21 crook 3806:
1.29 crook 3807: Postfix notation is unambiguous because the order that the operators
3808: are applied is always explicit; that also means that parentheses are
3809: never required. The operators are @i{active} (the act of quoting the
3810: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3811:
1.29 crook 3812: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3813: equivalent ways:
1.26 crook 3814:
3815: @example
1.29 crook 3816: 6 5 4 * + or:
3817: 5 4 * 6 +
1.26 crook 3818: @end example
1.23 crook 3819:
1.29 crook 3820: An important thing that you should notice about this notation is that
3821: the @i{order} of the numbers does not change; if you want to subtract
3822: 2 from 10 you type @code{10 2 -}.
1.1 anton 3823:
1.29 crook 3824: The reason that Forth uses postfix notation is very simple to explain: it
3825: makes the implementation extremely simple, and it follows naturally from
3826: using the stack as a mechanism for passing parameters. Another way of
3827: thinking about this is to realise that all Forth definitions are
3828: @i{active}; they execute as they are encountered by the text
3829: interpreter. The result of this is that the syntax of Forth is trivially
3830: simple.
1.1 anton 3831:
3832:
3833:
1.29 crook 3834: @comment ----------------------------------------------
3835: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3836: @section Your first Forth definition
3837: @cindex first definition
1.1 anton 3838:
1.29 crook 3839: Until now, the examples we've seen have been trivial; we've just been
3840: using Forth as a bigger-than-pocket calculator. Also, each calculation
3841: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3842: again@footnote{That's not quite true. If you press the up-arrow key on
3843: your keyboard you should be able to scroll back to any earlier command,
3844: edit it and re-enter it.} In this section we'll see how to add new
3845: words to Forth's vocabulary.
1.1 anton 3846:
1.29 crook 3847: The easiest way to create a new word is to use a @dfn{colon
3848: definition}. We'll define a few and try them out before worrying too
3849: much about how they work. Try typing in these examples; be careful to
3850: copy the spaces accurately:
1.1 anton 3851:
1.29 crook 3852: @example
3853: : add-two 2 + . ;
3854: : greet ." Hello and welcome" ;
3855: : demo 5 add-two ;
3856: @end example
1.1 anton 3857:
1.29 crook 3858: @noindent
3859: Now try them out:
1.1 anton 3860:
1.29 crook 3861: @example
1.30 anton 3862: @kbd{greet@key{RET}} Hello and welcome ok
3863: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3864: @kbd{4 add-two@key{RET}} 6 ok
3865: @kbd{demo@key{RET}} 7 ok
3866: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3867: @end example
1.1 anton 3868:
1.29 crook 3869: The first new thing that we've introduced here is the pair of words
3870: @code{:} and @code{;}. These are used to start and terminate a new
3871: definition, respectively. The first word after the @code{:} is the name
3872: for the new definition.
1.1 anton 3873:
1.29 crook 3874: As you can see from the examples, a definition is built up of words that
3875: have already been defined; Forth makes no distinction between
3876: definitions that existed when you started the system up, and those that
3877: you define yourself.
1.1 anton 3878:
1.29 crook 3879: The examples also introduce the words @code{.} (dot), @code{."}
3880: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3881: the stack and displays it. It's like @code{.s} except that it only
3882: displays the top item of the stack and it is destructive; after it has
3883: executed, the number is no longer on the stack. There is always one
3884: space printed after the number, and no spaces before it. Dot-quote
3885: defines a string (a sequence of characters) that will be printed when
3886: the word is executed. The string can contain any printable characters
3887: except @code{"}. A @code{"} has a special function; it is not a Forth
3888: word but it acts as a delimiter (the way that delimiters work is
3889: described in the next section). Finally, @code{dup} duplicates the value
3890: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3891:
1.29 crook 3892: We already know that the text interpreter searches through the
3893: dictionary to locate names. If you've followed the examples earlier, you
3894: will already have a definition called @code{add-two}. Lets try modifying
3895: it by typing in a new definition:
1.1 anton 3896:
1.29 crook 3897: @example
1.30 anton 3898: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3899: @end example
1.5 anton 3900:
1.29 crook 3901: Forth recognised that we were defining a word that already exists, and
3902: printed a message to warn us of that fact. Let's try out the new
3903: definition:
1.5 anton 3904:
1.29 crook 3905: @example
1.30 anton 3906: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3907: @end example
1.1 anton 3908:
1.29 crook 3909: @noindent
3910: All that we've actually done here, though, is to create a new
3911: definition, with a particular name. The fact that there was already a
3912: definition with the same name did not make any difference to the way
3913: that the new definition was created (except that Forth printed a warning
3914: message). The old definition of add-two still exists (try @code{demo}
3915: again to see that this is true). Any new definition will use the new
3916: definition of @code{add-two}, but old definitions continue to use the
3917: version that already existed at the time that they were @code{compiled}.
1.1 anton 3918:
1.29 crook 3919: Before you go on to the next section, try defining and redefining some
3920: words of your own.
1.1 anton 3921:
1.29 crook 3922: @comment ----------------------------------------------
3923: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3924: @section How does that work?
3925: @cindex parsing words
1.1 anton 3926:
1.30 anton 3927: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3928:
3929: @c Is it a good idea to talk about the interpretation semantics of a
3930: @c number? We don't have an xt to go along with it. - anton
3931:
3932: @c Now that I have eliminated execution semantics, I wonder if it would not
3933: @c be better to keep them (or add run-time semantics), to make it easier to
3934: @c explain what compilation semantics usually does. - anton
3935:
1.44 crook 3936: @c nac-> I removed the term ``default compilation sematics'' from the
3937: @c introductory chapter. Removing ``execution semantics'' was making
3938: @c everything simpler to explain, then I think the use of this term made
3939: @c everything more complex again. I replaced it with ``default
3940: @c semantics'' (which is used elsewhere in the manual) by which I mean
3941: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3942: @c flag set''.
3943:
3944: @c anton: I have eliminated default semantics (except in one place where it
3945: @c means "default interpretation and compilation semantics"), because it
3946: @c makes no sense in the presence of combined words. I reverted to
3947: @c "execution semantics" where necessary.
3948:
3949: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3950: @c section (and, unusually for me, I think I even made it shorter!). See
3951: @c what you think -- I know I have not addressed your primary concern
3952: @c that it is too heavy-going for an introduction. From what I understood
3953: @c of your course notes it looks as though they might be a good framework.
3954: @c Things that I've tried to capture here are some things that came as a
3955: @c great revelation here when I first understood them. Also, I like the
3956: @c fact that a very simple code example shows up almost all of the issues
3957: @c that you need to understand to see how Forth works. That's unique and
3958: @c worthwhile to emphasise.
3959:
1.83 anton 3960: @c anton: I think it's a good idea to present the details, especially those
3961: @c that you found to be a revelation, and probably the tutorial tries to be
3962: @c too superficial and does not get some of the things across that make
3963: @c Forth special. I do believe that most of the time these things should
3964: @c be discussed at the end of a section or in separate sections instead of
3965: @c in the middle of a section (e.g., the stuff you added in "User-defined
3966: @c defining words" leads in a completely different direction from the rest
3967: @c of the section).
3968:
1.29 crook 3969: Now we're going to take another look at the definition of @code{add-two}
3970: from the previous section. From our knowledge of the way that the text
3971: interpreter works, we would have expected this result when we tried to
3972: define @code{add-two}:
1.21 crook 3973:
1.29 crook 3974: @example
1.44 crook 3975: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3976: *the terminal*:4: Undefined word
3977: : >>>add-two<<< 2 + . ;
1.29 crook 3978: @end example
1.28 crook 3979:
1.29 crook 3980: The reason that this didn't happen is bound up in the way that @code{:}
3981: works. The word @code{:} does two special things. The first special
3982: thing that it does prevents the text interpreter from ever seeing the
3983: characters @code{add-two}. The text interpreter uses a variable called
3984: @cindex modifying >IN
1.44 crook 3985: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3986: input line. When it encounters the word @code{:} it behaves in exactly
3987: the same way as it does for any other word; it looks it up in the name
3988: dictionary, finds its xt and executes it. When @code{:} executes, it
3989: looks at the input buffer, finds the word @code{add-two} and advances the
3990: value of @code{>IN} to point past it. It then does some other stuff
3991: associated with creating the new definition (including creating an entry
3992: for @code{add-two} in the name dictionary). When the execution of @code{:}
3993: completes, control returns to the text interpreter, which is oblivious
3994: to the fact that it has been tricked into ignoring part of the input
3995: line.
1.21 crook 3996:
1.29 crook 3997: @cindex parsing words
3998: Words like @code{:} -- words that advance the value of @code{>IN} and so
3999: prevent the text interpreter from acting on the whole of the input line
4000: -- are called @dfn{parsing words}.
1.21 crook 4001:
1.29 crook 4002: @cindex @code{state} - effect on the text interpreter
4003: @cindex text interpreter - effect of state
4004: The second special thing that @code{:} does is change the value of a
4005: variable called @code{state}, which affects the way that the text
4006: interpreter behaves. When Gforth starts up, @code{state} has the value
4007: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4008: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4009: the text interpreter is said to be @dfn{compiling}.
4010:
4011: In this example, the text interpreter is compiling when it processes the
4012: string ``@code{2 + . ;}''. It still breaks the string down into
4013: character sequences in the same way. However, instead of pushing the
4014: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4015: into the definition of @code{add-two} that will make the number @code{2} get
4016: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4017: the behaviours of @code{+} and @code{.} are also compiled into the
4018: definition.
4019:
4020: One category of words don't get compiled. These so-called @dfn{immediate
4021: words} get executed (performed @i{now}) regardless of whether the text
4022: interpreter is interpreting or compiling. The word @code{;} is an
4023: immediate word. Rather than being compiled into the definition, it
4024: executes. Its effect is to terminate the current definition, which
4025: includes changing the value of @code{state} back to 0.
4026:
4027: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4028: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4029: definition.
1.28 crook 4030:
1.30 anton 4031: In Forth, every word or number can be described in terms of two
1.29 crook 4032: properties:
1.28 crook 4033:
4034: @itemize @bullet
4035: @item
1.29 crook 4036: @cindex interpretation semantics
1.44 crook 4037: Its @dfn{interpretation semantics} describe how it will behave when the
4038: text interpreter encounters it in @dfn{interpret} state. The
4039: interpretation semantics of a word are represented by an @dfn{execution
4040: token}.
1.28 crook 4041: @item
1.29 crook 4042: @cindex compilation semantics
1.44 crook 4043: Its @dfn{compilation semantics} describe how it will behave when the
4044: text interpreter encounters it in @dfn{compile} state. The compilation
4045: semantics of a word are represented in an implementation-dependent way;
4046: Gforth uses a @dfn{compilation token}.
1.29 crook 4047: @end itemize
4048:
4049: @noindent
4050: Numbers are always treated in a fixed way:
4051:
4052: @itemize @bullet
1.28 crook 4053: @item
1.44 crook 4054: When the number is @dfn{interpreted}, its behaviour is to push the
4055: number onto the stack.
1.28 crook 4056: @item
1.30 anton 4057: When the number is @dfn{compiled}, a piece of code is appended to the
4058: current definition that pushes the number when it runs. (In other words,
4059: the compilation semantics of a number are to postpone its interpretation
4060: semantics until the run-time of the definition that it is being compiled
4061: into.)
1.29 crook 4062: @end itemize
4063:
1.44 crook 4064: Words don't behave in such a regular way, but most have @i{default
4065: semantics} which means that they behave like this:
1.29 crook 4066:
4067: @itemize @bullet
1.28 crook 4068: @item
1.30 anton 4069: The @dfn{interpretation semantics} of the word are to do something useful.
4070: @item
1.29 crook 4071: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4072: @dfn{interpretation semantics} to the current definition (so that its
4073: run-time behaviour is to do something useful).
1.28 crook 4074: @end itemize
4075:
1.30 anton 4076: @cindex immediate words
1.44 crook 4077: The actual behaviour of any particular word can be controlled by using
4078: the words @code{immediate} and @code{compile-only} when the word is
4079: defined. These words set flags in the name dictionary entry of the most
4080: recently defined word, and these flags are retrieved by the text
4081: interpreter when it finds the word in the name dictionary.
4082:
4083: A word that is marked as @dfn{immediate} has compilation semantics that
4084: are identical to its interpretation semantics. In other words, it
4085: behaves like this:
1.29 crook 4086:
4087: @itemize @bullet
4088: @item
1.30 anton 4089: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4090: @item
1.30 anton 4091: The @dfn{compilation semantics} of the word are to do something useful
4092: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4093: @end itemize
1.28 crook 4094:
1.44 crook 4095: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4096: performing the interpretation semantics of the word directly; an attempt
4097: to do so will generate an error. It is never necessary to use
4098: @code{compile-only} (and it is not even part of ANS Forth, though it is
4099: provided by many implementations) but it is good etiquette to apply it
4100: to a word that will not behave correctly (and might have unexpected
4101: side-effects) in interpret state. For example, it is only legal to use
4102: the conditional word @code{IF} within a definition. If you forget this
4103: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4104: @code{compile-only} allows the text interpreter to generate a helpful
4105: error message rather than subjecting you to the consequences of your
4106: folly.
4107:
1.29 crook 4108: This example shows the difference between an immediate and a
4109: non-immediate word:
1.28 crook 4110:
1.29 crook 4111: @example
4112: : show-state state @@ . ;
4113: : show-state-now show-state ; immediate
4114: : word1 show-state ;
4115: : word2 show-state-now ;
1.28 crook 4116: @end example
1.23 crook 4117:
1.29 crook 4118: The word @code{immediate} after the definition of @code{show-state-now}
4119: makes that word an immediate word. These definitions introduce a new
4120: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4121: variable, and leaves it on the stack. Therefore, the behaviour of
4122: @code{show-state} is to print a number that represents the current value
4123: of @code{state}.
1.28 crook 4124:
1.29 crook 4125: When you execute @code{word1}, it prints the number 0, indicating that
4126: the system is interpreting. When the text interpreter compiled the
4127: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4128: compilation semantics are to append its interpretation semantics to the
1.29 crook 4129: current definition. When you execute @code{word1}, it performs the
1.30 anton 4130: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4131: (and therefore @code{show-state}) are executed, the system is
4132: interpreting.
1.28 crook 4133:
1.30 anton 4134: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4135: you should have seen the number -1 printed, followed by ``@code{
4136: ok}''. When the text interpreter compiled the definition of
4137: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4138: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4139: semantics. It is executed straight away (even before the text
4140: interpreter has moved on to process another group of characters; the
4141: @code{;} in this example). The effect of executing it are to display the
4142: value of @code{state} @i{at the time that the definition of}
4143: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4144: system is compiling at this time. If you execute @code{word2} it does
4145: nothing at all.
1.28 crook 4146:
1.29 crook 4147: @cindex @code{."}, how it works
4148: Before leaving the subject of immediate words, consider the behaviour of
4149: @code{."} in the definition of @code{greet}, in the previous
4150: section. This word is both a parsing word and an immediate word. Notice
4151: that there is a space between @code{."} and the start of the text
4152: @code{Hello and welcome}, but that there is no space between the last
4153: letter of @code{welcome} and the @code{"} character. The reason for this
4154: is that @code{."} is a Forth word; it must have a space after it so that
4155: the text interpreter can identify it. The @code{"} is not a Forth word;
4156: it is a @dfn{delimiter}. The examples earlier show that, when the string
4157: is displayed, there is neither a space before the @code{H} nor after the
4158: @code{e}. Since @code{."} is an immediate word, it executes at the time
4159: that @code{greet} is defined. When it executes, its behaviour is to
4160: search forward in the input line looking for the delimiter. When it
4161: finds the delimiter, it updates @code{>IN} to point past the
4162: delimiter. It also compiles some magic code into the definition of
4163: @code{greet}; the xt of a run-time routine that prints a text string. It
4164: compiles the string @code{Hello and welcome} into memory so that it is
4165: available to be printed later. When the text interpreter gains control,
4166: the next word it finds in the input stream is @code{;} and so it
4167: terminates the definition of @code{greet}.
1.28 crook 4168:
4169:
4170: @comment ----------------------------------------------
1.29 crook 4171: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4172: @section Forth is written in Forth
4173: @cindex structure of Forth programs
4174:
4175: When you start up a Forth compiler, a large number of definitions
4176: already exist. In Forth, you develop a new application using bottom-up
4177: programming techniques to create new definitions that are defined in
4178: terms of existing definitions. As you create each definition you can
4179: test and debug it interactively.
4180:
4181: If you have tried out the examples in this section, you will probably
4182: have typed them in by hand; when you leave Gforth, your definitions will
4183: be lost. You can avoid this by using a text editor to enter Forth source
4184: code into a file, and then loading code from the file using
1.49 anton 4185: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4186: processed by the text interpreter, just as though you had typed it in by
4187: hand@footnote{Actually, there are some subtle differences -- see
4188: @ref{The Text Interpreter}.}.
4189:
4190: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4191: files for program entry (@pxref{Blocks}).
1.28 crook 4192:
1.29 crook 4193: In common with many, if not most, Forth compilers, most of Gforth is
4194: actually written in Forth. All of the @file{.fs} files in the
4195: installation directory@footnote{For example,
1.30 anton 4196: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4197: study to see examples of Forth programming.
1.28 crook 4198:
1.29 crook 4199: Gforth maintains a history file that records every line that you type to
4200: the text interpreter. This file is preserved between sessions, and is
4201: used to provide a command-line recall facility. If you enter long
4202: definitions by hand, you can use a text editor to paste them out of the
4203: history file into a Forth source file for reuse at a later time
1.49 anton 4204: (for more information @pxref{Command-line editing}).
1.28 crook 4205:
4206:
4207: @comment ----------------------------------------------
1.29 crook 4208: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4209: @section Review - elements of a Forth system
4210: @cindex elements of a Forth system
1.28 crook 4211:
1.29 crook 4212: To summarise this chapter:
1.28 crook 4213:
4214: @itemize @bullet
4215: @item
1.29 crook 4216: Forth programs use @dfn{factoring} to break a problem down into small
4217: fragments called @dfn{words} or @dfn{definitions}.
4218: @item
4219: Forth program development is an interactive process.
4220: @item
4221: The main command loop that accepts input, and controls both
4222: interpretation and compilation, is called the @dfn{text interpreter}
4223: (also known as the @dfn{outer interpreter}).
4224: @item
4225: Forth has a very simple syntax, consisting of words and numbers
4226: separated by spaces or carriage-return characters. Any additional syntax
4227: is imposed by @dfn{parsing words}.
4228: @item
4229: Forth uses a stack to pass parameters between words. As a result, it
4230: uses postfix notation.
4231: @item
4232: To use a word that has previously been defined, the text interpreter
4233: searches for the word in the @dfn{name dictionary}.
4234: @item
1.30 anton 4235: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4236: @item
1.29 crook 4237: The text interpreter uses the value of @code{state} to select between
4238: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4239: semantics} of a word that it encounters.
1.28 crook 4240: @item
1.30 anton 4241: The relationship between the @dfn{interpretation semantics} and
4242: @dfn{compilation semantics} for a word
1.29 crook 4243: depend upon the way in which the word was defined (for example, whether
4244: it is an @dfn{immediate} word).
1.28 crook 4245: @item
1.29 crook 4246: Forth definitions can be implemented in Forth (called @dfn{high-level
4247: definitions}) or in some other way (usually a lower-level language and
4248: as a result often called @dfn{low-level definitions}, @dfn{code
4249: definitions} or @dfn{primitives}).
1.28 crook 4250: @item
1.29 crook 4251: Many Forth systems are implemented mainly in Forth.
1.28 crook 4252: @end itemize
4253:
4254:
1.29 crook 4255: @comment ----------------------------------------------
1.48 anton 4256: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4257: @section Where To Go Next
4258: @cindex where to go next
1.28 crook 4259:
1.29 crook 4260: Amazing as it may seem, if you have read (and understood) this far, you
4261: know almost all the fundamentals about the inner workings of a Forth
4262: system. You certainly know enough to be able to read and understand the
4263: rest of this manual and the ANS Forth document, to learn more about the
4264: facilities that Forth in general and Gforth in particular provide. Even
4265: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4266: However, that's not a good idea just yet... better to try writing some
1.29 crook 4267: programs in Gforth.
1.28 crook 4268:
1.29 crook 4269: Forth has such a rich vocabulary that it can be hard to know where to
4270: start in learning it. This section suggests a few sets of words that are
4271: enough to write small but useful programs. Use the word index in this
4272: document to learn more about each word, then try it out and try to write
4273: small definitions using it. Start by experimenting with these words:
1.28 crook 4274:
4275: @itemize @bullet
4276: @item
1.29 crook 4277: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4278: @item
4279: Comparison: @code{MIN MAX =}
4280: @item
4281: Logic: @code{AND OR XOR NOT}
4282: @item
4283: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4284: @item
1.29 crook 4285: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4286: @item
1.29 crook 4287: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4288: @item
1.29 crook 4289: Defining words: @code{: ; CREATE}
1.28 crook 4290: @item
1.29 crook 4291: Memory allocation words: @code{ALLOT ,}
1.28 crook 4292: @item
1.29 crook 4293: Tools: @code{SEE WORDS .S MARKER}
4294: @end itemize
4295:
4296: When you have mastered those, go on to:
4297:
4298: @itemize @bullet
1.28 crook 4299: @item
1.29 crook 4300: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4301: @item
1.29 crook 4302: Memory access: @code{@@ !}
1.28 crook 4303: @end itemize
1.23 crook 4304:
1.29 crook 4305: When you have mastered these, there's nothing for it but to read through
4306: the whole of this manual and find out what you've missed.
4307:
4308: @comment ----------------------------------------------
1.48 anton 4309: @node Exercises, , Where to go next, Introduction
1.29 crook 4310: @section Exercises
4311: @cindex exercises
4312:
4313: TODO: provide a set of programming excercises linked into the stuff done
4314: already and into other sections of the manual. Provide solutions to all
4315: the exercises in a .fs file in the distribution.
4316:
4317: @c Get some inspiration from Starting Forth and Kelly&Spies.
4318:
4319: @c excercises:
4320: @c 1. take inches and convert to feet and inches.
4321: @c 2. take temperature and convert from fahrenheight to celcius;
4322: @c may need to care about symmetric vs floored??
4323: @c 3. take input line and do character substitution
4324: @c to encipher or decipher
4325: @c 4. as above but work on a file for in and out
4326: @c 5. take input line and convert to pig-latin
4327: @c
4328: @c thing of sets of things to exercise then come up with
4329: @c problems that need those things.
4330:
4331:
1.26 crook 4332: @c ******************************************************************
1.29 crook 4333: @node Words, Error messages, Introduction, Top
1.1 anton 4334: @chapter Forth Words
1.26 crook 4335: @cindex words
1.1 anton 4336:
4337: @menu
4338: * Notation::
1.65 anton 4339: * Case insensitivity::
4340: * Comments::
4341: * Boolean Flags::
1.1 anton 4342: * Arithmetic::
4343: * Stack Manipulation::
1.5 anton 4344: * Memory::
1.1 anton 4345: * Control Structures::
4346: * Defining Words::
1.65 anton 4347: * Interpretation and Compilation Semantics::
1.47 crook 4348: * Tokens for Words::
1.81 anton 4349: * Compiling words::
1.65 anton 4350: * The Text Interpreter::
1.111 anton 4351: * The Input Stream::
1.65 anton 4352: * Word Lists::
4353: * Environmental Queries::
1.12 anton 4354: * Files::
4355: * Blocks::
4356: * Other I/O::
1.121 anton 4357: * OS command line arguments::
1.78 anton 4358: * Locals::
4359: * Structures::
4360: * Object-oriented Forth::
1.12 anton 4361: * Programming Tools::
1.150 anton 4362: * C Interface::
1.12 anton 4363: * Assembler and Code Words::
4364: * Threading Words::
1.65 anton 4365: * Passing Commands to the OS::
4366: * Keeping track of Time::
4367: * Miscellaneous Words::
1.1 anton 4368: @end menu
4369:
1.65 anton 4370: @node Notation, Case insensitivity, Words, Words
1.1 anton 4371: @section Notation
4372: @cindex notation of glossary entries
4373: @cindex format of glossary entries
4374: @cindex glossary notation format
4375: @cindex word glossary entry format
4376:
4377: The Forth words are described in this section in the glossary notation
1.67 anton 4378: that has become a de-facto standard for Forth texts:
1.1 anton 4379:
4380: @format
1.29 crook 4381: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4382: @end format
1.29 crook 4383: @i{Description}
1.1 anton 4384:
4385: @table @var
4386: @item word
1.28 crook 4387: The name of the word.
1.1 anton 4388:
4389: @item Stack effect
4390: @cindex stack effect
1.29 crook 4391: The stack effect is written in the notation @code{@i{before} --
4392: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4393: stack entries before and after the execution of the word. The rest of
4394: the stack is not touched by the word. The top of stack is rightmost,
4395: i.e., a stack sequence is written as it is typed in. Note that Gforth
4396: uses a separate floating point stack, but a unified stack
1.29 crook 4397: notation. Also, return stack effects are not shown in @i{stack
4398: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4399: the type and/or the function of the item. See below for a discussion of
4400: the types.
4401:
4402: All words have two stack effects: A compile-time stack effect and a
4403: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4404: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4405: this standard behaviour, or the word does other unusual things at
4406: compile time, both stack effects are shown; otherwise only the run-time
4407: stack effect is shown.
4408:
4409: @cindex pronounciation of words
4410: @item pronunciation
4411: How the word is pronounced.
4412:
4413: @cindex wordset
1.67 anton 4414: @cindex environment wordset
1.1 anton 4415: @item wordset
1.21 crook 4416: The ANS Forth standard is divided into several word sets. A standard
4417: system need not support all of them. Therefore, in theory, the fewer
4418: word sets your program uses the more portable it will be. However, we
4419: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4420: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4421: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4422: describes words that will work in future releases of Gforth;
4423: @code{gforth-internal} words are more volatile. Environmental query
4424: strings are also displayed like words; you can recognize them by the
1.21 crook 4425: @code{environment} in the word set field.
1.1 anton 4426:
4427: @item Description
4428: A description of the behaviour of the word.
4429: @end table
4430:
4431: @cindex types of stack items
4432: @cindex stack item types
4433: The type of a stack item is specified by the character(s) the name
4434: starts with:
4435:
4436: @table @code
4437: @item f
4438: @cindex @code{f}, stack item type
4439: Boolean flags, i.e. @code{false} or @code{true}.
4440: @item c
4441: @cindex @code{c}, stack item type
4442: Char
4443: @item w
4444: @cindex @code{w}, stack item type
4445: Cell, can contain an integer or an address
4446: @item n
4447: @cindex @code{n}, stack item type
4448: signed integer
4449: @item u
4450: @cindex @code{u}, stack item type
4451: unsigned integer
4452: @item d
4453: @cindex @code{d}, stack item type
4454: double sized signed integer
4455: @item ud
4456: @cindex @code{ud}, stack item type
4457: double sized unsigned integer
4458: @item r
4459: @cindex @code{r}, stack item type
4460: Float (on the FP stack)
1.21 crook 4461: @item a-
1.1 anton 4462: @cindex @code{a_}, stack item type
4463: Cell-aligned address
1.21 crook 4464: @item c-
1.1 anton 4465: @cindex @code{c_}, stack item type
4466: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4467: @item f-
1.1 anton 4468: @cindex @code{f_}, stack item type
4469: Float-aligned address
1.21 crook 4470: @item df-
1.1 anton 4471: @cindex @code{df_}, stack item type
4472: Address aligned for IEEE double precision float
1.21 crook 4473: @item sf-
1.1 anton 4474: @cindex @code{sf_}, stack item type
4475: Address aligned for IEEE single precision float
4476: @item xt
4477: @cindex @code{xt}, stack item type
4478: Execution token, same size as Cell
4479: @item wid
4480: @cindex @code{wid}, stack item type
1.21 crook 4481: Word list ID, same size as Cell
1.68 anton 4482: @item ior, wior
4483: @cindex ior type description
4484: @cindex wior type description
4485: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4486: @item f83name
4487: @cindex @code{f83name}, stack item type
4488: Pointer to a name structure
4489: @item "
4490: @cindex @code{"}, stack item type
1.12 anton 4491: string in the input stream (not on the stack). The terminating character
4492: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4493: quotes.
4494: @end table
4495:
1.65 anton 4496: @comment ----------------------------------------------
4497: @node Case insensitivity, Comments, Notation, Words
4498: @section Case insensitivity
4499: @cindex case sensitivity
4500: @cindex upper and lower case
4501:
4502: Gforth is case-insensitive; you can enter definitions and invoke
4503: Standard words using upper, lower or mixed case (however,
4504: @pxref{core-idef, Implementation-defined options, Implementation-defined
4505: options}).
4506:
4507: ANS Forth only @i{requires} implementations to recognise Standard words
4508: when they are typed entirely in upper case. Therefore, a Standard
4509: program must use upper case for all Standard words. You can use whatever
4510: case you like for words that you define, but in a Standard program you
4511: have to use the words in the same case that you defined them.
4512:
4513: Gforth supports case sensitivity through @code{table}s (case-sensitive
4514: wordlists, @pxref{Word Lists}).
4515:
4516: Two people have asked how to convert Gforth to be case-sensitive; while
4517: we think this is a bad idea, you can change all wordlists into tables
4518: like this:
4519:
4520: @example
4521: ' table-find forth-wordlist wordlist-map @ !
4522: @end example
4523:
4524: Note that you now have to type the predefined words in the same case
4525: that we defined them, which are varying. You may want to convert them
4526: to your favourite case before doing this operation (I won't explain how,
4527: because if you are even contemplating doing this, you'd better have
4528: enough knowledge of Forth systems to know this already).
4529:
4530: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4531: @section Comments
1.26 crook 4532: @cindex comments
1.21 crook 4533:
1.29 crook 4534: Forth supports two styles of comment; the traditional @i{in-line} comment,
4535: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4536:
1.44 crook 4537:
1.23 crook 4538: doc-(
1.21 crook 4539: doc-\
1.23 crook 4540: doc-\G
1.21 crook 4541:
1.44 crook 4542:
1.21 crook 4543: @node Boolean Flags, Arithmetic, Comments, Words
4544: @section Boolean Flags
1.26 crook 4545: @cindex Boolean flags
1.21 crook 4546:
4547: A Boolean flag is cell-sized. A cell with all bits clear represents the
4548: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4549: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4550: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4551: @c on and off to Memory?
4552: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4553:
1.21 crook 4554: doc-true
4555: doc-false
1.29 crook 4556: doc-on
4557: doc-off
1.21 crook 4558:
1.44 crook 4559:
1.21 crook 4560: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4561: @section Arithmetic
4562: @cindex arithmetic words
4563:
4564: @cindex division with potentially negative operands
4565: Forth arithmetic is not checked, i.e., you will not hear about integer
4566: overflow on addition or multiplication, you may hear about division by
4567: zero if you are lucky. The operator is written after the operands, but
4568: the operands are still in the original order. I.e., the infix @code{2-1}
4569: corresponds to @code{2 1 -}. Forth offers a variety of division
4570: operators. If you perform division with potentially negative operands,
4571: you do not want to use @code{/} or @code{/mod} with its undefined
4572: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4573: former, @pxref{Mixed precision}).
1.26 crook 4574: @comment TODO discuss the different division forms and the std approach
1.1 anton 4575:
4576: @menu
4577: * Single precision::
1.67 anton 4578: * Double precision:: Double-cell integer arithmetic
1.1 anton 4579: * Bitwise operations::
1.67 anton 4580: * Numeric comparison::
1.29 crook 4581: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4582: * Floating Point::
4583: @end menu
4584:
1.67 anton 4585: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4586: @subsection Single precision
4587: @cindex single precision arithmetic words
4588:
1.67 anton 4589: @c !! cell undefined
4590:
4591: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4592: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4593: treat them. For the rules used by the text interpreter for recognising
4594: single-precision integers see @ref{Number Conversion}.
1.21 crook 4595:
1.67 anton 4596: These words are all defined for signed operands, but some of them also
4597: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4598: @code{*}.
1.44 crook 4599:
1.1 anton 4600: doc-+
1.21 crook 4601: doc-1+
1.128 anton 4602: doc-under+
1.1 anton 4603: doc--
1.21 crook 4604: doc-1-
1.1 anton 4605: doc-*
4606: doc-/
4607: doc-mod
4608: doc-/mod
4609: doc-negate
4610: doc-abs
4611: doc-min
4612: doc-max
1.27 crook 4613: doc-floored
1.1 anton 4614:
1.44 crook 4615:
1.67 anton 4616: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4617: @subsection Double precision
4618: @cindex double precision arithmetic words
4619:
1.49 anton 4620: For the rules used by the text interpreter for
4621: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4622:
4623: A double precision number is represented by a cell pair, with the most
1.67 anton 4624: significant cell at the TOS. It is trivial to convert an unsigned single
4625: to a double: simply push a @code{0} onto the TOS. Since numbers are
4626: represented by Gforth using 2's complement arithmetic, converting a
4627: signed single to a (signed) double requires sign-extension across the
4628: most significant cell. This can be achieved using @code{s>d}. The moral
4629: of the story is that you cannot convert a number without knowing whether
4630: it represents an unsigned or a signed number.
1.21 crook 4631:
1.67 anton 4632: These words are all defined for signed operands, but some of them also
4633: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4634:
1.21 crook 4635: doc-s>d
1.67 anton 4636: doc-d>s
1.21 crook 4637: doc-d+
4638: doc-d-
4639: doc-dnegate
4640: doc-dabs
4641: doc-dmin
4642: doc-dmax
4643:
1.44 crook 4644:
1.67 anton 4645: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4646: @subsection Bitwise operations
4647: @cindex bitwise operation words
4648:
4649:
4650: doc-and
4651: doc-or
4652: doc-xor
4653: doc-invert
4654: doc-lshift
4655: doc-rshift
4656: doc-2*
4657: doc-d2*
4658: doc-2/
4659: doc-d2/
4660:
4661:
4662: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4663: @subsection Numeric comparison
4664: @cindex numeric comparison words
4665:
1.67 anton 4666: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4667: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4668:
1.28 crook 4669: doc-<
4670: doc-<=
4671: doc-<>
4672: doc-=
4673: doc->
4674: doc->=
4675:
1.21 crook 4676: doc-0<
1.23 crook 4677: doc-0<=
1.21 crook 4678: doc-0<>
4679: doc-0=
1.23 crook 4680: doc-0>
4681: doc-0>=
1.28 crook 4682:
4683: doc-u<
4684: doc-u<=
1.44 crook 4685: @c u<> and u= exist but are the same as <> and =
1.31 anton 4686: @c doc-u<>
4687: @c doc-u=
1.28 crook 4688: doc-u>
4689: doc-u>=
4690:
4691: doc-within
4692:
4693: doc-d<
4694: doc-d<=
4695: doc-d<>
4696: doc-d=
4697: doc-d>
4698: doc-d>=
1.23 crook 4699:
1.21 crook 4700: doc-d0<
1.23 crook 4701: doc-d0<=
4702: doc-d0<>
1.21 crook 4703: doc-d0=
1.23 crook 4704: doc-d0>
4705: doc-d0>=
4706:
1.21 crook 4707: doc-du<
1.28 crook 4708: doc-du<=
1.44 crook 4709: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4710: @c doc-du<>
4711: @c doc-du=
1.28 crook 4712: doc-du>
4713: doc-du>=
1.1 anton 4714:
1.44 crook 4715:
1.21 crook 4716: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4717: @subsection Mixed precision
4718: @cindex mixed precision arithmetic words
4719:
1.44 crook 4720:
1.1 anton 4721: doc-m+
4722: doc-*/
4723: doc-*/mod
4724: doc-m*
4725: doc-um*
4726: doc-m*/
4727: doc-um/mod
4728: doc-fm/mod
4729: doc-sm/rem
4730:
1.44 crook 4731:
1.21 crook 4732: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4733: @subsection Floating Point
4734: @cindex floating point arithmetic words
4735:
1.49 anton 4736: For the rules used by the text interpreter for
4737: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4738:
1.67 anton 4739: Gforth has a separate floating point stack, but the documentation uses
4740: the unified notation.@footnote{It's easy to generate the separate
4741: notation from that by just separating the floating-point numbers out:
4742: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4743: r3 )}.}
1.1 anton 4744:
4745: @cindex floating-point arithmetic, pitfalls
4746: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4747: unwary (e.g., floating point addition is not associative) and even a
4748: few for the wary. You should not use them unless you know what you are
4749: doing or you don't care that the results you get are totally bogus. If
4750: you want to learn about the problems of floating point numbers (and
4751: how to avoid them), you might start with @cite{David Goldberg,
4752: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4753: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4754: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4755:
1.44 crook 4756:
1.21 crook 4757: doc-d>f
4758: doc-f>d
1.1 anton 4759: doc-f+
4760: doc-f-
4761: doc-f*
4762: doc-f/
4763: doc-fnegate
4764: doc-fabs
4765: doc-fmax
4766: doc-fmin
4767: doc-floor
4768: doc-fround
4769: doc-f**
4770: doc-fsqrt
4771: doc-fexp
4772: doc-fexpm1
4773: doc-fln
4774: doc-flnp1
4775: doc-flog
4776: doc-falog
1.32 anton 4777: doc-f2*
4778: doc-f2/
4779: doc-1/f
4780: doc-precision
4781: doc-set-precision
4782:
4783: @cindex angles in trigonometric operations
4784: @cindex trigonometric operations
4785: Angles in floating point operations are given in radians (a full circle
4786: has 2 pi radians).
4787:
1.1 anton 4788: doc-fsin
4789: doc-fcos
4790: doc-fsincos
4791: doc-ftan
4792: doc-fasin
4793: doc-facos
4794: doc-fatan
4795: doc-fatan2
4796: doc-fsinh
4797: doc-fcosh
4798: doc-ftanh
4799: doc-fasinh
4800: doc-facosh
4801: doc-fatanh
1.21 crook 4802: doc-pi
1.28 crook 4803:
1.32 anton 4804: @cindex equality of floats
4805: @cindex floating-point comparisons
1.31 anton 4806: One particular problem with floating-point arithmetic is that comparison
4807: for equality often fails when you would expect it to succeed. For this
4808: reason approximate equality is often preferred (but you still have to
1.67 anton 4809: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4810: differently from what you might expect. The comparison words are:
1.31 anton 4811:
4812: doc-f~rel
4813: doc-f~abs
1.68 anton 4814: doc-f~
1.31 anton 4815: doc-f=
4816: doc-f<>
4817:
4818: doc-f<
4819: doc-f<=
4820: doc-f>
4821: doc-f>=
4822:
1.21 crook 4823: doc-f0<
1.28 crook 4824: doc-f0<=
4825: doc-f0<>
1.21 crook 4826: doc-f0=
1.28 crook 4827: doc-f0>
4828: doc-f0>=
4829:
1.1 anton 4830:
4831: @node Stack Manipulation, Memory, Arithmetic, Words
4832: @section Stack Manipulation
4833: @cindex stack manipulation words
4834:
4835: @cindex floating-point stack in the standard
1.21 crook 4836: Gforth maintains a number of separate stacks:
4837:
1.29 crook 4838: @cindex data stack
4839: @cindex parameter stack
1.21 crook 4840: @itemize @bullet
4841: @item
1.29 crook 4842: A data stack (also known as the @dfn{parameter stack}) -- for
4843: characters, cells, addresses, and double cells.
1.21 crook 4844:
1.29 crook 4845: @cindex floating-point stack
1.21 crook 4846: @item
1.44 crook 4847: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4848:
1.29 crook 4849: @cindex return stack
1.21 crook 4850: @item
1.44 crook 4851: A return stack -- for holding the return addresses of colon
1.32 anton 4852: definitions and other (non-FP) data.
1.21 crook 4853:
1.29 crook 4854: @cindex locals stack
1.21 crook 4855: @item
1.44 crook 4856: A locals stack -- for holding local variables.
1.21 crook 4857: @end itemize
4858:
1.1 anton 4859: @menu
4860: * Data stack::
4861: * Floating point stack::
4862: * Return stack::
4863: * Locals stack::
4864: * Stack pointer manipulation::
4865: @end menu
4866:
4867: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4868: @subsection Data stack
4869: @cindex data stack manipulation words
4870: @cindex stack manipulations words, data stack
4871:
1.44 crook 4872:
1.1 anton 4873: doc-drop
4874: doc-nip
4875: doc-dup
4876: doc-over
4877: doc-tuck
4878: doc-swap
1.21 crook 4879: doc-pick
1.1 anton 4880: doc-rot
4881: doc--rot
4882: doc-?dup
4883: doc-roll
4884: doc-2drop
4885: doc-2nip
4886: doc-2dup
4887: doc-2over
4888: doc-2tuck
4889: doc-2swap
4890: doc-2rot
4891:
1.44 crook 4892:
1.1 anton 4893: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4894: @subsection Floating point stack
4895: @cindex floating-point stack manipulation words
4896: @cindex stack manipulation words, floating-point stack
4897:
1.32 anton 4898: Whilst every sane Forth has a separate floating-point stack, it is not
4899: strictly required; an ANS Forth system could theoretically keep
4900: floating-point numbers on the data stack. As an additional difficulty,
4901: you don't know how many cells a floating-point number takes. It is
4902: reportedly possible to write words in a way that they work also for a
4903: unified stack model, but we do not recommend trying it. Instead, just
4904: say that your program has an environmental dependency on a separate
4905: floating-point stack.
4906:
4907: doc-floating-stack
4908:
1.1 anton 4909: doc-fdrop
4910: doc-fnip
4911: doc-fdup
4912: doc-fover
4913: doc-ftuck
4914: doc-fswap
1.21 crook 4915: doc-fpick
1.1 anton 4916: doc-frot
4917:
1.44 crook 4918:
1.1 anton 4919: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4920: @subsection Return stack
4921: @cindex return stack manipulation words
4922: @cindex stack manipulation words, return stack
4923:
1.32 anton 4924: @cindex return stack and locals
4925: @cindex locals and return stack
4926: A Forth system is allowed to keep local variables on the
4927: return stack. This is reasonable, as local variables usually eliminate
4928: the need to use the return stack explicitly. So, if you want to produce
4929: a standard compliant program and you are using local variables in a
4930: word, forget about return stack manipulations in that word (refer to the
4931: standard document for the exact rules).
4932:
1.1 anton 4933: doc->r
4934: doc-r>
4935: doc-r@
4936: doc-rdrop
4937: doc-2>r
4938: doc-2r>
4939: doc-2r@
4940: doc-2rdrop
4941:
1.44 crook 4942:
1.1 anton 4943: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4944: @subsection Locals stack
4945:
1.78 anton 4946: Gforth uses an extra locals stack. It is described, along with the
4947: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4948:
1.1 anton 4949: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4950: @subsection Stack pointer manipulation
4951: @cindex stack pointer manipulation words
4952:
1.44 crook 4953: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4954: doc-sp0
1.1 anton 4955: doc-sp@
4956: doc-sp!
1.21 crook 4957: doc-fp0
1.1 anton 4958: doc-fp@
4959: doc-fp!
1.21 crook 4960: doc-rp0
1.1 anton 4961: doc-rp@
4962: doc-rp!
1.21 crook 4963: doc-lp0
1.1 anton 4964: doc-lp@
4965: doc-lp!
4966:
1.44 crook 4967:
1.1 anton 4968: @node Memory, Control Structures, Stack Manipulation, Words
4969: @section Memory
1.26 crook 4970: @cindex memory words
1.1 anton 4971:
1.32 anton 4972: @menu
4973: * Memory model::
4974: * Dictionary allocation::
4975: * Heap Allocation::
4976: * Memory Access::
4977: * Address arithmetic::
4978: * Memory Blocks::
4979: @end menu
4980:
1.67 anton 4981: In addition to the standard Forth memory allocation words, there is also
4982: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4983: garbage collector}.
4984:
1.32 anton 4985: @node Memory model, Dictionary allocation, Memory, Memory
4986: @subsection ANS Forth and Gforth memory models
4987:
4988: @c The ANS Forth description is a mess (e.g., is the heap part of
4989: @c the dictionary?), so let's not stick to closely with it.
4990:
1.67 anton 4991: ANS Forth considers a Forth system as consisting of several address
4992: spaces, of which only @dfn{data space} is managed and accessible with
4993: the memory words. Memory not necessarily in data space includes the
4994: stacks, the code (called code space) and the headers (called name
4995: space). In Gforth everything is in data space, but the code for the
4996: primitives is usually read-only.
1.32 anton 4997:
4998: Data space is divided into a number of areas: The (data space portion of
4999: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5000: refer to the search data structure embodied in word lists and headers,
5001: because it is used for looking up names, just as you would in a
5002: conventional dictionary.}, the heap, and a number of system-allocated
5003: buffers.
5004:
1.68 anton 5005: @cindex address arithmetic restrictions, ANS vs. Gforth
5006: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5007: In ANS Forth data space is also divided into contiguous regions. You
5008: can only use address arithmetic within a contiguous region, not between
5009: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5010: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5011: allocation}).
5012:
5013: Gforth provides one big address space, and address arithmetic can be
5014: performed between any addresses. However, in the dictionary headers or
5015: code are interleaved with data, so almost the only contiguous data space
5016: regions there are those described by ANS Forth as contiguous; but you
5017: can be sure that the dictionary is allocated towards increasing
5018: addresses even between contiguous regions. The memory order of
5019: allocations in the heap is platform-dependent (and possibly different
5020: from one run to the next).
5021:
1.27 crook 5022:
1.32 anton 5023: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5024: @subsection Dictionary allocation
1.27 crook 5025: @cindex reserving data space
5026: @cindex data space - reserving some
5027:
1.32 anton 5028: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5029: you want to deallocate X, you also deallocate everything
5030: allocated after X.
5031:
1.68 anton 5032: @cindex contiguous regions in dictionary allocation
1.32 anton 5033: The allocations using the words below are contiguous and grow the region
5034: towards increasing addresses. Other words that allocate dictionary
5035: memory of any kind (i.e., defining words including @code{:noname}) end
5036: the contiguous region and start a new one.
5037:
5038: In ANS Forth only @code{create}d words are guaranteed to produce an
5039: address that is the start of the following contiguous region. In
5040: particular, the cell allocated by @code{variable} is not guaranteed to
5041: be contiguous with following @code{allot}ed memory.
5042:
5043: You can deallocate memory by using @code{allot} with a negative argument
5044: (with some restrictions, see @code{allot}). For larger deallocations use
5045: @code{marker}.
1.27 crook 5046:
1.29 crook 5047:
1.27 crook 5048: doc-here
5049: doc-unused
5050: doc-allot
5051: doc-c,
1.29 crook 5052: doc-f,
1.27 crook 5053: doc-,
5054: doc-2,
5055:
1.32 anton 5056: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5057: course you should allocate memory in an aligned way, too. I.e., before
5058: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5059: The words below align @code{here} if it is not already. Basically it is
5060: only already aligned for a type, if the last allocation was a multiple
5061: of the size of this type and if @code{here} was aligned for this type
5062: before.
5063:
5064: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5065: ANS Forth (@code{maxalign}ed in Gforth).
5066:
5067: doc-align
5068: doc-falign
5069: doc-sfalign
5070: doc-dfalign
5071: doc-maxalign
5072: doc-cfalign
5073:
5074:
5075: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5076: @subsection Heap allocation
5077: @cindex heap allocation
5078: @cindex dynamic allocation of memory
5079: @cindex memory-allocation word set
5080:
1.68 anton 5081: @cindex contiguous regions and heap allocation
1.32 anton 5082: Heap allocation supports deallocation of allocated memory in any
5083: order. Dictionary allocation is not affected by it (i.e., it does not
5084: end a contiguous region). In Gforth, these words are implemented using
5085: the standard C library calls malloc(), free() and resize().
5086:
1.68 anton 5087: The memory region produced by one invocation of @code{allocate} or
5088: @code{resize} is internally contiguous. There is no contiguity between
5089: such a region and any other region (including others allocated from the
5090: heap).
5091:
1.32 anton 5092: doc-allocate
5093: doc-free
5094: doc-resize
5095:
1.27 crook 5096:
1.32 anton 5097: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5098: @subsection Memory Access
5099: @cindex memory access words
5100:
5101: doc-@
5102: doc-!
5103: doc-+!
5104: doc-c@
5105: doc-c!
5106: doc-2@
5107: doc-2!
5108: doc-f@
5109: doc-f!
5110: doc-sf@
5111: doc-sf!
5112: doc-df@
5113: doc-df!
1.144 anton 5114: doc-sw@
5115: doc-uw@
5116: doc-w!
5117: doc-sl@
5118: doc-ul@
5119: doc-l!
1.68 anton 5120:
1.32 anton 5121: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5122: @subsection Address arithmetic
1.1 anton 5123: @cindex address arithmetic words
5124:
1.67 anton 5125: Address arithmetic is the foundation on which you can build data
5126: structures like arrays, records (@pxref{Structures}) and objects
5127: (@pxref{Object-oriented Forth}).
1.32 anton 5128:
1.68 anton 5129: @cindex address unit
5130: @cindex au (address unit)
1.1 anton 5131: ANS Forth does not specify the sizes of the data types. Instead, it
5132: offers a number of words for computing sizes and doing address
1.29 crook 5133: arithmetic. Address arithmetic is performed in terms of address units
5134: (aus); on most systems the address unit is one byte. Note that a
5135: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5136: platforms where it is a noop, it compiles to nothing).
1.1 anton 5137:
1.67 anton 5138: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5139: you have the address of a cell, perform @code{1 cells +}, and you will
5140: have the address of the next cell.
5141:
1.68 anton 5142: @cindex contiguous regions and address arithmetic
1.67 anton 5143: In ANS Forth you can perform address arithmetic only within a contiguous
5144: region, i.e., if you have an address into one region, you can only add
5145: and subtract such that the result is still within the region; you can
5146: only subtract or compare addresses from within the same contiguous
5147: region. Reasons: several contiguous regions can be arranged in memory
5148: in any way; on segmented systems addresses may have unusual
5149: representations, such that address arithmetic only works within a
5150: region. Gforth provides a few more guarantees (linear address space,
5151: dictionary grows upwards), but in general I have found it easy to stay
5152: within contiguous regions (exception: computing and comparing to the
5153: address just beyond the end of an array).
5154:
1.1 anton 5155: @cindex alignment of addresses for types
5156: ANS Forth also defines words for aligning addresses for specific
5157: types. Many computers require that accesses to specific data types
5158: must only occur at specific addresses; e.g., that cells may only be
5159: accessed at addresses divisible by 4. Even if a machine allows unaligned
5160: accesses, it can usually perform aligned accesses faster.
5161:
5162: For the performance-conscious: alignment operations are usually only
5163: necessary during the definition of a data structure, not during the
5164: (more frequent) accesses to it.
5165:
5166: ANS Forth defines no words for character-aligning addresses. This is not
5167: an oversight, but reflects the fact that addresses that are not
5168: char-aligned have no use in the standard and therefore will not be
5169: created.
5170:
5171: @cindex @code{CREATE} and alignment
1.29 crook 5172: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5173: are cell-aligned; in addition, Gforth guarantees that these addresses
5174: are aligned for all purposes.
5175:
1.26 crook 5176: Note that the ANS Forth word @code{char} has nothing to do with address
5177: arithmetic.
1.1 anton 5178:
1.44 crook 5179:
1.1 anton 5180: doc-chars
5181: doc-char+
5182: doc-cells
5183: doc-cell+
5184: doc-cell
5185: doc-aligned
5186: doc-floats
5187: doc-float+
5188: doc-float
5189: doc-faligned
5190: doc-sfloats
5191: doc-sfloat+
5192: doc-sfaligned
5193: doc-dfloats
5194: doc-dfloat+
5195: doc-dfaligned
5196: doc-maxaligned
5197: doc-cfaligned
5198: doc-address-unit-bits
1.145 anton 5199: doc-/w
5200: doc-/l
1.44 crook 5201:
1.32 anton 5202: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5203: @subsection Memory Blocks
5204: @cindex memory block words
1.27 crook 5205: @cindex character strings - moving and copying
5206:
1.49 anton 5207: Memory blocks often represent character strings; For ways of storing
5208: character strings in memory see @ref{String Formats}. For other
5209: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5210:
1.67 anton 5211: A few of these words work on address unit blocks. In that case, you
5212: usually have to insert @code{CHARS} before the word when working on
5213: character strings. Most words work on character blocks, and expect a
5214: char-aligned address.
5215:
5216: When copying characters between overlapping memory regions, use
5217: @code{chars move} or choose carefully between @code{cmove} and
5218: @code{cmove>}.
1.44 crook 5219:
1.1 anton 5220: doc-move
5221: doc-erase
5222: doc-cmove
5223: doc-cmove>
5224: doc-fill
5225: doc-blank
1.21 crook 5226: doc-compare
1.111 anton 5227: doc-str=
5228: doc-str<
5229: doc-string-prefix?
1.21 crook 5230: doc-search
1.27 crook 5231: doc--trailing
5232: doc-/string
1.82 anton 5233: doc-bounds
1.141 anton 5234: doc-pad
1.111 anton 5235:
1.27 crook 5236: @comment TODO examples
5237:
1.1 anton 5238:
1.26 crook 5239: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5240: @section Control Structures
5241: @cindex control structures
5242:
1.33 anton 5243: Control structures in Forth cannot be used interpretively, only in a
5244: colon definition@footnote{To be precise, they have no interpretation
5245: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5246: not like this limitation, but have not seen a satisfying way around it
5247: yet, although many schemes have been proposed.
1.1 anton 5248:
5249: @menu
1.33 anton 5250: * Selection:: IF ... ELSE ... ENDIF
5251: * Simple Loops:: BEGIN ...
1.29 crook 5252: * Counted Loops:: DO
1.67 anton 5253: * Arbitrary control structures::
5254: * Calls and returns::
1.1 anton 5255: * Exception Handling::
5256: @end menu
5257:
5258: @node Selection, Simple Loops, Control Structures, Control Structures
5259: @subsection Selection
5260: @cindex selection control structures
5261: @cindex control structures for selection
5262:
5263: @cindex @code{IF} control structure
5264: @example
1.29 crook 5265: @i{flag}
1.1 anton 5266: IF
1.29 crook 5267: @i{code}
1.1 anton 5268: ENDIF
5269: @end example
1.21 crook 5270: @noindent
1.33 anton 5271:
1.44 crook 5272: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5273: with any bit set represents truth) @i{code} is executed.
1.33 anton 5274:
1.1 anton 5275: @example
1.29 crook 5276: @i{flag}
1.1 anton 5277: IF
1.29 crook 5278: @i{code1}
1.1 anton 5279: ELSE
1.29 crook 5280: @i{code2}
1.1 anton 5281: ENDIF
5282: @end example
5283:
1.44 crook 5284: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5285: executed.
1.33 anton 5286:
1.1 anton 5287: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5288: standard, and @code{ENDIF} is not, although it is quite popular. We
5289: recommend using @code{ENDIF}, because it is less confusing for people
5290: who also know other languages (and is not prone to reinforcing negative
5291: prejudices against Forth in these people). Adding @code{ENDIF} to a
5292: system that only supplies @code{THEN} is simple:
5293: @example
1.82 anton 5294: : ENDIF POSTPONE then ; immediate
1.1 anton 5295: @end example
5296:
5297: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5298: (adv.)} has the following meanings:
5299: @quotation
5300: ... 2b: following next after in order ... 3d: as a necessary consequence
5301: (if you were there, then you saw them).
5302: @end quotation
5303: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5304: and many other programming languages has the meaning 3d.]
5305:
1.21 crook 5306: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5307: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5308: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5309: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5310: @file{compat/control.fs}.
5311:
5312: @cindex @code{CASE} control structure
5313: @example
1.29 crook 5314: @i{n}
1.1 anton 5315: CASE
1.29 crook 5316: @i{n1} OF @i{code1} ENDOF
5317: @i{n2} OF @i{code2} ENDOF
1.1 anton 5318: @dots{}
1.68 anton 5319: ( n ) @i{default-code} ( n )
1.131 anton 5320: ENDCASE ( )
1.1 anton 5321: @end example
5322:
1.131 anton 5323: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5324: no @i{ni} matches, the optional @i{default-code} is executed. The
5325: optional default case can be added by simply writing the code after
5326: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5327: but must not consume it. The value @i{n} is consumed by this
5328: construction (either by a OF that matches, or by the ENDCASE, if no OF
5329: matches).
1.1 anton 5330:
1.69 anton 5331: @progstyle
1.131 anton 5332: To keep the code understandable, you should ensure that you change the
5333: stack in the same way (wrt. number and types of stack items consumed
5334: and pushed) on all paths through a selection construct.
1.69 anton 5335:
1.1 anton 5336: @node Simple Loops, Counted Loops, Selection, Control Structures
5337: @subsection Simple Loops
5338: @cindex simple loops
5339: @cindex loops without count
5340:
5341: @cindex @code{WHILE} loop
5342: @example
5343: BEGIN
1.29 crook 5344: @i{code1}
5345: @i{flag}
1.1 anton 5346: WHILE
1.29 crook 5347: @i{code2}
1.1 anton 5348: REPEAT
5349: @end example
5350:
1.29 crook 5351: @i{code1} is executed and @i{flag} is computed. If it is true,
5352: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5353: false, execution continues after the @code{REPEAT}.
5354:
5355: @cindex @code{UNTIL} loop
5356: @example
5357: BEGIN
1.29 crook 5358: @i{code}
5359: @i{flag}
1.1 anton 5360: UNTIL
5361: @end example
5362:
1.29 crook 5363: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5364:
1.69 anton 5365: @progstyle
5366: To keep the code understandable, a complete iteration of the loop should
5367: not change the number and types of the items on the stacks.
5368:
1.1 anton 5369: @cindex endless loop
5370: @cindex loops, endless
5371: @example
5372: BEGIN
1.29 crook 5373: @i{code}
1.1 anton 5374: AGAIN
5375: @end example
5376:
5377: This is an endless loop.
5378:
5379: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5380: @subsection Counted Loops
5381: @cindex counted loops
5382: @cindex loops, counted
5383: @cindex @code{DO} loops
5384:
5385: The basic counted loop is:
5386: @example
1.29 crook 5387: @i{limit} @i{start}
1.1 anton 5388: ?DO
1.29 crook 5389: @i{body}
1.1 anton 5390: LOOP
5391: @end example
5392:
1.29 crook 5393: This performs one iteration for every integer, starting from @i{start}
5394: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5395: accessed with @code{i}. For example, the loop:
1.1 anton 5396: @example
5397: 10 0 ?DO
5398: i .
5399: LOOP
5400: @end example
1.21 crook 5401: @noindent
5402: prints @code{0 1 2 3 4 5 6 7 8 9}
5403:
1.1 anton 5404: The index of the innermost loop can be accessed with @code{i}, the index
5405: of the next loop with @code{j}, and the index of the third loop with
5406: @code{k}.
5407:
1.44 crook 5408:
1.1 anton 5409: doc-i
5410: doc-j
5411: doc-k
5412:
1.44 crook 5413:
1.1 anton 5414: The loop control data are kept on the return stack, so there are some
1.21 crook 5415: restrictions on mixing return stack accesses and counted loop words. In
5416: particuler, if you put values on the return stack outside the loop, you
5417: cannot read them inside the loop@footnote{well, not in a way that is
5418: portable.}. If you put values on the return stack within a loop, you
5419: have to remove them before the end of the loop and before accessing the
5420: index of the loop.
1.1 anton 5421:
5422: There are several variations on the counted loop:
5423:
1.21 crook 5424: @itemize @bullet
5425: @item
5426: @code{LEAVE} leaves the innermost counted loop immediately; execution
5427: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5428:
5429: @example
5430: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5431: @end example
5432: prints @code{0 1 2 3}
5433:
1.1 anton 5434:
1.21 crook 5435: @item
5436: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5437: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5438: return stack so @code{EXIT} can get to its return address. For example:
5439:
5440: @example
5441: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5442: @end example
5443: prints @code{0 1 2 3}
5444:
5445:
5446: @item
1.29 crook 5447: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5448: (and @code{LOOP} iterates until they become equal by wrap-around
5449: arithmetic). This behaviour is usually not what you want. Therefore,
5450: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5451: @code{?DO}), which do not enter the loop if @i{start} is greater than
5452: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5453: unsigned loop parameters.
5454:
1.21 crook 5455: @item
5456: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5457: the loop, independent of the loop parameters. Do not use @code{DO}, even
5458: if you know that the loop is entered in any case. Such knowledge tends
5459: to become invalid during maintenance of a program, and then the
5460: @code{DO} will make trouble.
5461:
5462: @item
1.29 crook 5463: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5464: index by @i{n} instead of by 1. The loop is terminated when the border
5465: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5466:
1.21 crook 5467: @example
5468: 4 0 +DO i . 2 +LOOP
5469: @end example
5470: @noindent
5471: prints @code{0 2}
5472:
5473: @example
5474: 4 1 +DO i . 2 +LOOP
5475: @end example
5476: @noindent
5477: prints @code{1 3}
1.1 anton 5478:
1.68 anton 5479: @item
1.1 anton 5480: @cindex negative increment for counted loops
5481: @cindex counted loops with negative increment
1.29 crook 5482: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5483:
1.21 crook 5484: @example
5485: -1 0 ?DO i . -1 +LOOP
5486: @end example
5487: @noindent
5488: prints @code{0 -1}
1.1 anton 5489:
1.21 crook 5490: @example
5491: 0 0 ?DO i . -1 +LOOP
5492: @end example
5493: prints nothing.
1.1 anton 5494:
1.29 crook 5495: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5496: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5497: index by @i{u} each iteration. The loop is terminated when the border
5498: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5499: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5500:
1.21 crook 5501: @example
5502: -2 0 -DO i . 1 -LOOP
5503: @end example
5504: @noindent
5505: prints @code{0 -1}
1.1 anton 5506:
1.21 crook 5507: @example
5508: -1 0 -DO i . 1 -LOOP
5509: @end example
5510: @noindent
5511: prints @code{0}
5512:
5513: @example
5514: 0 0 -DO i . 1 -LOOP
5515: @end example
5516: @noindent
5517: prints nothing.
1.1 anton 5518:
1.21 crook 5519: @end itemize
1.1 anton 5520:
5521: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5522: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5523: for these words that uses only standard words is provided in
5524: @file{compat/loops.fs}.
1.1 anton 5525:
5526:
5527: @cindex @code{FOR} loops
1.26 crook 5528: Another counted loop is:
1.1 anton 5529: @example
1.29 crook 5530: @i{n}
1.1 anton 5531: FOR
1.29 crook 5532: @i{body}
1.1 anton 5533: NEXT
5534: @end example
5535: This is the preferred loop of native code compiler writers who are too
1.26 crook 5536: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5537: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5538: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5539: Forth systems may behave differently, even if they support @code{FOR}
5540: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5541:
5542: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5543: @subsection Arbitrary control structures
5544: @cindex control structures, user-defined
5545:
5546: @cindex control-flow stack
5547: ANS Forth permits and supports using control structures in a non-nested
5548: way. Information about incomplete control structures is stored on the
5549: control-flow stack. This stack may be implemented on the Forth data
5550: stack, and this is what we have done in Gforth.
5551:
5552: @cindex @code{orig}, control-flow stack item
5553: @cindex @code{dest}, control-flow stack item
5554: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5555: entry represents a backward branch target. A few words are the basis for
5556: building any control structure possible (except control structures that
5557: need storage, like calls, coroutines, and backtracking).
5558:
1.44 crook 5559:
1.1 anton 5560: doc-if
5561: doc-ahead
5562: doc-then
5563: doc-begin
5564: doc-until
5565: doc-again
5566: doc-cs-pick
5567: doc-cs-roll
5568:
1.44 crook 5569:
1.21 crook 5570: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5571: manipulate the control-flow stack in a portable way. Without them, you
5572: would need to know how many stack items are occupied by a control-flow
5573: entry (many systems use one cell. In Gforth they currently take three,
5574: but this may change in the future).
5575:
1.1 anton 5576: Some standard control structure words are built from these words:
5577:
1.44 crook 5578:
1.1 anton 5579: doc-else
5580: doc-while
5581: doc-repeat
5582:
1.44 crook 5583:
5584: @noindent
1.1 anton 5585: Gforth adds some more control-structure words:
5586:
1.44 crook 5587:
1.1 anton 5588: doc-endif
5589: doc-?dup-if
5590: doc-?dup-0=-if
5591:
1.44 crook 5592:
5593: @noindent
1.1 anton 5594: Counted loop words constitute a separate group of words:
5595:
1.44 crook 5596:
1.1 anton 5597: doc-?do
5598: doc-+do
5599: doc-u+do
5600: doc--do
5601: doc-u-do
5602: doc-do
5603: doc-for
5604: doc-loop
5605: doc-+loop
5606: doc--loop
5607: doc-next
5608: doc-leave
5609: doc-?leave
5610: doc-unloop
5611: doc-done
5612:
1.44 crook 5613:
1.21 crook 5614: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5615: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5616: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5617: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5618: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5619: resolved (by using one of the loop-ending words or @code{DONE}).
5620:
1.44 crook 5621: @noindent
1.26 crook 5622: Another group of control structure words are:
1.1 anton 5623:
1.44 crook 5624:
1.1 anton 5625: doc-case
5626: doc-endcase
5627: doc-of
5628: doc-endof
5629:
1.44 crook 5630:
1.21 crook 5631: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5632: @code{CS-ROLL}.
1.1 anton 5633:
5634: @subsubsection Programming Style
1.47 crook 5635: @cindex control structures programming style
5636: @cindex programming style, arbitrary control structures
1.1 anton 5637:
5638: In order to ensure readability we recommend that you do not create
5639: arbitrary control structures directly, but define new control structure
5640: words for the control structure you want and use these words in your
1.26 crook 5641: program. For example, instead of writing:
1.1 anton 5642:
5643: @example
1.26 crook 5644: BEGIN
1.1 anton 5645: ...
1.26 crook 5646: IF [ 1 CS-ROLL ]
1.1 anton 5647: ...
1.26 crook 5648: AGAIN THEN
1.1 anton 5649: @end example
5650:
1.21 crook 5651: @noindent
1.1 anton 5652: we recommend defining control structure words, e.g.,
5653:
5654: @example
1.26 crook 5655: : WHILE ( DEST -- ORIG DEST )
5656: POSTPONE IF
5657: 1 CS-ROLL ; immediate
5658:
5659: : REPEAT ( orig dest -- )
5660: POSTPONE AGAIN
5661: POSTPONE THEN ; immediate
1.1 anton 5662: @end example
5663:
1.21 crook 5664: @noindent
1.1 anton 5665: and then using these to create the control structure:
5666:
5667: @example
1.26 crook 5668: BEGIN
1.1 anton 5669: ...
1.26 crook 5670: WHILE
1.1 anton 5671: ...
1.26 crook 5672: REPEAT
1.1 anton 5673: @end example
5674:
5675: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5676: @code{WHILE} are predefined, so in this example it would not be
5677: necessary to define them.
5678:
5679: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5680: @subsection Calls and returns
5681: @cindex calling a definition
5682: @cindex returning from a definition
5683:
1.3 anton 5684: @cindex recursive definitions
5685: A definition can be called simply be writing the name of the definition
1.26 crook 5686: to be called. Normally a definition is invisible during its own
1.3 anton 5687: definition. If you want to write a directly recursive definition, you
1.26 crook 5688: can use @code{recursive} to make the current definition visible, or
5689: @code{recurse} to call the current definition directly.
1.3 anton 5690:
1.44 crook 5691:
1.3 anton 5692: doc-recursive
5693: doc-recurse
5694:
1.44 crook 5695:
1.21 crook 5696: @comment TODO add example of the two recursion methods
1.12 anton 5697: @quotation
5698: @progstyle
5699: I prefer using @code{recursive} to @code{recurse}, because calling the
5700: definition by name is more descriptive (if the name is well-chosen) than
5701: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5702: implementation, it is much better to read (and think) ``now sort the
5703: partitions'' than to read ``now do a recursive call''.
5704: @end quotation
1.3 anton 5705:
1.29 crook 5706: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5707:
5708: @example
1.28 crook 5709: Defer foo
1.3 anton 5710:
5711: : bar ( ... -- ... )
5712: ... foo ... ;
5713:
5714: :noname ( ... -- ... )
5715: ... bar ... ;
5716: IS foo
5717: @end example
5718:
1.170 pazsan 5719: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5720:
1.26 crook 5721: The current definition returns control to the calling definition when
1.33 anton 5722: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5723:
5724: doc-exit
5725: doc-;s
5726:
1.44 crook 5727:
1.1 anton 5728: @node Exception Handling, , Calls and returns, Control Structures
5729: @subsection Exception Handling
1.26 crook 5730: @cindex exceptions
1.1 anton 5731:
1.68 anton 5732: @c quit is a very bad idea for error handling,
5733: @c because it does not translate into a THROW
5734: @c it also does not belong into this chapter
5735:
5736: If a word detects an error condition that it cannot handle, it can
5737: @code{throw} an exception. In the simplest case, this will terminate
5738: your program, and report an appropriate error.
1.21 crook 5739:
1.68 anton 5740: doc-throw
1.1 anton 5741:
1.69 anton 5742: @code{Throw} consumes a cell-sized error number on the stack. There are
5743: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5744: Gforth (and most other systems) you can use the iors produced by various
5745: words as error numbers (e.g., a typical use of @code{allocate} is
5746: @code{allocate throw}). Gforth also provides the word @code{exception}
5747: to define your own error numbers (with decent error reporting); an ANS
5748: Forth version of this word (but without the error messages) is available
5749: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5750: numbers (anything outside the range -4095..0), but won't get nice error
5751: messages, only numbers. For example, try:
5752:
5753: @example
1.69 anton 5754: -10 throw \ ANS defined
5755: -267 throw \ system defined
5756: s" my error" exception throw \ user defined
5757: 7 throw \ arbitrary number
1.68 anton 5758: @end example
5759:
5760: doc---exception-exception
1.1 anton 5761:
1.69 anton 5762: A common idiom to @code{THROW} a specific error if a flag is true is
5763: this:
5764:
5765: @example
5766: @code{( flag ) 0<> @i{errno} and throw}
5767: @end example
5768:
5769: Your program can provide exception handlers to catch exceptions. An
5770: exception handler can be used to correct the problem, or to clean up
5771: some data structures and just throw the exception to the next exception
5772: handler. Note that @code{throw} jumps to the dynamically innermost
5773: exception handler. The system's exception handler is outermost, and just
5774: prints an error and restarts command-line interpretation (or, in batch
5775: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5776:
1.68 anton 5777: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5778:
1.68 anton 5779: doc-catch
1.160 anton 5780: doc-nothrow
1.68 anton 5781:
5782: The most common use of exception handlers is to clean up the state when
5783: an error happens. E.g.,
1.1 anton 5784:
1.26 crook 5785: @example
1.68 anton 5786: base @ >r hex \ actually the hex should be inside foo, or we h
5787: ['] foo catch ( nerror|0 )
5788: r> base !
1.69 anton 5789: ( nerror|0 ) throw \ pass it on
1.26 crook 5790: @end example
1.1 anton 5791:
1.69 anton 5792: A use of @code{catch} for handling the error @code{myerror} might look
5793: like this:
1.44 crook 5794:
1.68 anton 5795: @example
1.69 anton 5796: ['] foo catch
5797: CASE
1.160 anton 5798: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5799: dup throw \ default: pass other errors on, do nothing on non-errors
5800: ENDCASE
1.68 anton 5801: @end example
1.44 crook 5802:
1.68 anton 5803: Having to wrap the code into a separate word is often cumbersome,
5804: therefore Gforth provides an alternative syntax:
1.1 anton 5805:
5806: @example
1.69 anton 5807: TRY
1.68 anton 5808: @i{code1}
1.172 anton 5809: IFERROR
5810: @i{code2}
5811: THEN
5812: @i{code3}
1.69 anton 5813: ENDTRY
1.1 anton 5814: @end example
5815:
1.172 anton 5816: This performs @i{code1}. If @i{code1} completes normally, execution
5817: continues with @i{code3}. If @i{code1} or there is an exception
5818: before @code{endtry}, the stacks are reset to the state during
5819: @code{try}, the throw value is pushed on the data stack, and execution
5820: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26 crook 5821:
1.68 anton 5822: doc-try
5823: doc-endtry
1.172 anton 5824: doc-iferror
5825:
5826: If you don't need @i{code2}, you can write @code{restore} instead of
5827: @code{iferror then}:
5828:
5829: @example
5830: TRY
5831: @i{code1}
5832: RESTORE
5833: @i{code3}
5834: ENDTRY
5835: @end example
1.26 crook 5836:
1.172 anton 5837: @cindex unwind-protect
1.69 anton 5838: The cleanup example from above in this syntax:
1.26 crook 5839:
1.68 anton 5840: @example
1.174 anton 5841: base @@ @{ oldbase @}
1.172 anton 5842: TRY
1.68 anton 5843: hex foo \ now the hex is placed correctly
1.69 anton 5844: 0 \ value for throw
1.172 anton 5845: RESTORE
5846: oldbase base !
5847: ENDTRY
5848: throw
1.1 anton 5849: @end example
5850:
1.172 anton 5851: An additional advantage of this variant is that an exception between
5852: @code{restore} and @code{endtry} (e.g., from the user pressing
5853: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5854: so the base will be restored under all circumstances.
5855:
5856: However, you have to ensure that this code does not cause an exception
5857: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5858: Moreover, you should also make sure that the stack contents needed by
5859: the @code{iferror}/@code{restore} code exist everywhere between
5860: @code{try} and @code{endtry}; in our example this is achived by
5861: putting the data in a local before the @code{try} (you cannot use the
5862: return stack because the exception frame (@i{sys1}) is in the way
5863: there).
5864:
5865: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5866:
5867: @cindex @code{recover} (old Gforth versions)
5868: If you do not want this exception-restarting behaviour, you achieve
5869: this as follows:
5870:
5871: @example
5872: TRY
5873: @i{code1}
5874: ENDTRY-IFERROR
5875: @i{code2}
5876: THEN
5877: @end example
5878:
5879: If there is an exception in @i{code1}, then @i{code2} is executed,
5880: otherwise execution continues behind the @code{then} (or in a possible
5881: @code{else} branch). This corresponds to the construct
5882:
5883: @example
5884: TRY
5885: @i{code1}
5886: RECOVER
5887: @i{code2}
5888: ENDTRY
5889: @end example
5890:
5891: in Gforth before version 0.7. So you can directly replace
5892: @code{recover}-using code; however, we recommend that you check if it
5893: would not be better to use one of the other @code{try} variants while
5894: you are at it.
5895:
1.173 anton 5896: To ease the transition, Gforth provides two compatibility files:
5897: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5898: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5899: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5900: ... endtry} syntax on new systems, so you can use that file as a
5901: stopgap to run old programs. Both files work on any system (they just
5902: do nothing if the system already has the syntax it implements), so you
5903: can unconditionally @code{require} one of these files, even if you use
5904: a mix old and new systems.
5905:
1.172 anton 5906: doc-restore
5907: doc-endtry-iferror
5908:
5909: Here's the error handling example:
1.1 anton 5910:
1.68 anton 5911: @example
1.69 anton 5912: TRY
1.68 anton 5913: foo
1.172 anton 5914: ENDTRY-IFERROR
1.69 anton 5915: CASE
1.160 anton 5916: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5917: throw \ pass other errors on
5918: ENDCASE
1.172 anton 5919: THEN
1.68 anton 5920: @end example
1.1 anton 5921:
1.69 anton 5922: @progstyle
5923: As usual, you should ensure that the stack depth is statically known at
5924: the end: either after the @code{throw} for passing on errors, or after
5925: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5926: selection construct for handling the error).
5927:
1.68 anton 5928: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5929: and you can provide an error message. @code{Abort} just produces an
5930: ``Aborted'' error.
1.1 anton 5931:
1.68 anton 5932: The problem with these words is that exception handlers cannot
5933: differentiate between different @code{abort"}s; they just look like
5934: @code{-2 throw} to them (the error message cannot be accessed by
5935: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5936: exception handlers.
1.44 crook 5937:
1.68 anton 5938: doc-abort"
1.26 crook 5939: doc-abort
1.29 crook 5940:
5941:
1.44 crook 5942:
1.29 crook 5943: @c -------------------------------------------------------------
1.47 crook 5944: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5945: @section Defining Words
5946: @cindex defining words
5947:
1.47 crook 5948: Defining words are used to extend Forth by creating new entries in the dictionary.
5949:
1.29 crook 5950: @menu
1.67 anton 5951: * CREATE::
1.44 crook 5952: * Variables:: Variables and user variables
1.67 anton 5953: * Constants::
1.44 crook 5954: * Values:: Initialised variables
1.67 anton 5955: * Colon Definitions::
1.44 crook 5956: * Anonymous Definitions:: Definitions without names
1.69 anton 5957: * Supplying names:: Passing definition names as strings
1.67 anton 5958: * User-defined Defining Words::
1.170 pazsan 5959: * Deferred Words:: Allow forward references
1.67 anton 5960: * Aliases::
1.29 crook 5961: @end menu
5962:
1.44 crook 5963: @node CREATE, Variables, Defining Words, Defining Words
5964: @subsection @code{CREATE}
1.29 crook 5965: @cindex simple defining words
5966: @cindex defining words, simple
5967:
5968: Defining words are used to create new entries in the dictionary. The
5969: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5970: this:
5971:
5972: @example
5973: CREATE new-word1
5974: @end example
5975:
1.69 anton 5976: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5977: input stream (@code{new-word1} in our example). It generates a
5978: dictionary entry for @code{new-word1}. When @code{new-word1} is
5979: executed, all that it does is leave an address on the stack. The address
5980: represents the value of the data space pointer (@code{HERE}) at the time
5981: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5982: associating a name with the address of a region of memory.
1.29 crook 5983:
1.34 anton 5984: doc-create
5985:
1.69 anton 5986: Note that in ANS Forth guarantees only for @code{create} that its body
5987: is in dictionary data space (i.e., where @code{here}, @code{allot}
5988: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5989: @code{create}d words can be modified with @code{does>}
5990: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5991: can only be applied to @code{create}d words.
5992:
1.29 crook 5993: By extending this example to reserve some memory in data space, we end
1.69 anton 5994: up with something like a @i{variable}. Here are two different ways to do
5995: it:
1.29 crook 5996:
5997: @example
5998: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5999: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6000: @end example
6001:
6002: The variable can be examined and modified using @code{@@} (``fetch'') and
6003: @code{!} (``store'') like this:
6004:
6005: @example
6006: new-word2 @@ . \ get address, fetch from it and display
6007: 1234 new-word2 ! \ new value, get address, store to it
6008: @end example
6009:
1.44 crook 6010: @cindex arrays
6011: A similar mechanism can be used to create arrays. For example, an
6012: 80-character text input buffer:
1.29 crook 6013:
6014: @example
1.44 crook 6015: CREATE text-buf 80 chars allot
6016:
1.168 anton 6017: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6018: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6019: @end example
1.29 crook 6020:
1.44 crook 6021: You can build arbitrarily complex data structures by allocating
1.49 anton 6022: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6023: learn about some Gforth tools that make it easier,
1.49 anton 6024: @xref{Structures}.
1.44 crook 6025:
6026:
6027: @node Variables, Constants, CREATE, Defining Words
6028: @subsection Variables
6029: @cindex variables
6030:
6031: The previous section showed how a sequence of commands could be used to
6032: generate a variable. As a final refinement, the whole code sequence can
6033: be wrapped up in a defining word (pre-empting the subject of the next
6034: section), making it easier to create new variables:
6035:
6036: @example
6037: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6038: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6039:
6040: myvariableX foo \ variable foo starts off with an unknown value
6041: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6042:
6043: 45 3 * foo ! \ set foo to 135
6044: 1234 joe ! \ set joe to 1234
6045: 3 joe +! \ increment joe by 3.. to 1237
6046: @end example
6047:
6048: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6049: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6050: guarantee that a @code{Variable} is initialised when it is created
6051: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6052: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6053: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6054: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6055: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6056: store a boolean, you can use @code{on} and @code{off} to toggle its
6057: state.
1.29 crook 6058:
1.34 anton 6059: doc-variable
6060: doc-2variable
6061: doc-fvariable
6062:
1.29 crook 6063: @cindex user variables
6064: @cindex user space
6065: The defining word @code{User} behaves in the same way as @code{Variable}.
6066: The difference is that it reserves space in @i{user (data) space} rather
6067: than normal data space. In a Forth system that has a multi-tasker, each
6068: task has its own set of user variables.
6069:
1.34 anton 6070: doc-user
1.67 anton 6071: @c doc-udp
6072: @c doc-uallot
1.34 anton 6073:
1.29 crook 6074: @comment TODO is that stuff about user variables strictly correct? Is it
6075: @comment just terminal tasks that have user variables?
6076: @comment should document tasker.fs (with some examples) elsewhere
6077: @comment in this manual, then expand on user space and user variables.
6078:
1.44 crook 6079: @node Constants, Values, Variables, Defining Words
6080: @subsection Constants
6081: @cindex constants
6082:
6083: @code{Constant} allows you to declare a fixed value and refer to it by
6084: name. For example:
1.29 crook 6085:
6086: @example
6087: 12 Constant INCHES-PER-FOOT
6088: 3E+08 fconstant SPEED-O-LIGHT
6089: @end example
6090:
6091: A @code{Variable} can be both read and written, so its run-time
6092: behaviour is to supply an address through which its current value can be
6093: manipulated. In contrast, the value of a @code{Constant} cannot be
6094: changed once it has been declared@footnote{Well, often it can be -- but
6095: not in a Standard, portable way. It's safer to use a @code{Value} (read
6096: on).} so it's not necessary to supply the address -- it is more
6097: efficient to return the value of the constant directly. That's exactly
6098: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6099: the top of the stack (You can find one
6100: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6101:
1.69 anton 6102: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6103: double and floating-point constants, respectively.
6104:
1.34 anton 6105: doc-constant
6106: doc-2constant
6107: doc-fconstant
6108:
6109: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6110: @c nac-> How could that not be true in an ANS Forth? You can't define a
6111: @c constant, use it and then delete the definition of the constant..
1.69 anton 6112:
6113: @c anton->An ANS Forth system can compile a constant to a literal; On
6114: @c decompilation you would see only the number, just as if it had been used
6115: @c in the first place. The word will stay, of course, but it will only be
6116: @c used by the text interpreter (no run-time duties, except when it is
6117: @c POSTPONEd or somesuch).
6118:
6119: @c nac:
1.44 crook 6120: @c I agree that it's rather deep, but IMO it is an important difference
6121: @c relative to other programming languages.. often it's annoying: it
6122: @c certainly changes my programming style relative to C.
6123:
1.69 anton 6124: @c anton: In what way?
6125:
1.29 crook 6126: Constants in Forth behave differently from their equivalents in other
6127: programming languages. In other languages, a constant (such as an EQU in
6128: assembler or a #define in C) only exists at compile-time; in the
6129: executable program the constant has been translated into an absolute
6130: number and, unless you are using a symbolic debugger, it's impossible to
6131: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6132: an entry in the header space and remains there after the code that uses
6133: it has been defined. In fact, it must remain in the dictionary since it
6134: has run-time duties to perform. For example:
1.29 crook 6135:
6136: @example
6137: 12 Constant INCHES-PER-FOOT
6138: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6139: @end example
6140:
6141: @cindex in-lining of constants
6142: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6143: associated with the constant @code{INCHES-PER-FOOT}. If you use
6144: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6145: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6146: attempt to optimise constants by in-lining them where they are used. You
6147: can force Gforth to in-line a constant like this:
6148:
6149: @example
6150: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6151: @end example
6152:
6153: If you use @code{see} to decompile @i{this} version of
6154: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6155: longer present. To understand how this works, read
6156: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6157:
6158: In-lining constants in this way might improve execution time
6159: fractionally, and can ensure that a constant is now only referenced at
6160: compile-time. However, the definition of the constant still remains in
6161: the dictionary. Some Forth compilers provide a mechanism for controlling
6162: a second dictionary for holding transient words such that this second
6163: dictionary can be deleted later in order to recover memory
6164: space. However, there is no standard way of doing this.
6165:
6166:
1.44 crook 6167: @node Values, Colon Definitions, Constants, Defining Words
6168: @subsection Values
6169: @cindex values
1.34 anton 6170:
1.69 anton 6171: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6172: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6173: (not in ANS Forth) you can access (and change) a @code{value} also with
6174: @code{>body}.
6175:
6176: Here are some
6177: examples:
1.29 crook 6178:
6179: @example
1.69 anton 6180: 12 Value APPLES \ Define APPLES with an initial value of 12
6181: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6182: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6183: APPLES \ puts 35 on the top of the stack.
1.29 crook 6184: @end example
6185:
1.44 crook 6186: doc-value
6187: doc-to
1.29 crook 6188:
1.35 anton 6189:
1.69 anton 6190:
1.44 crook 6191: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6192: @subsection Colon Definitions
6193: @cindex colon definitions
1.35 anton 6194:
6195: @example
1.44 crook 6196: : name ( ... -- ... )
6197: word1 word2 word3 ;
1.29 crook 6198: @end example
6199:
1.44 crook 6200: @noindent
6201: Creates a word called @code{name} that, upon execution, executes
6202: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6203:
1.49 anton 6204: The explanation above is somewhat superficial. For simple examples of
6205: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6206: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6207: Compilation Semantics}.
1.29 crook 6208:
1.44 crook 6209: doc-:
6210: doc-;
1.1 anton 6211:
1.34 anton 6212:
1.69 anton 6213: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6214: @subsection Anonymous Definitions
6215: @cindex colon definitions
6216: @cindex defining words without name
1.34 anton 6217:
1.44 crook 6218: Sometimes you want to define an @dfn{anonymous word}; a word without a
6219: name. You can do this with:
1.1 anton 6220:
1.44 crook 6221: doc-:noname
1.1 anton 6222:
1.44 crook 6223: This leaves the execution token for the word on the stack after the
6224: closing @code{;}. Here's an example in which a deferred word is
6225: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6226:
1.29 crook 6227: @example
1.44 crook 6228: Defer deferred
6229: :noname ( ... -- ... )
6230: ... ;
6231: IS deferred
1.29 crook 6232: @end example
1.26 crook 6233:
1.44 crook 6234: @noindent
6235: Gforth provides an alternative way of doing this, using two separate
6236: words:
1.27 crook 6237:
1.44 crook 6238: doc-noname
6239: @cindex execution token of last defined word
1.116 anton 6240: doc-latestxt
1.1 anton 6241:
1.44 crook 6242: @noindent
6243: The previous example can be rewritten using @code{noname} and
1.116 anton 6244: @code{latestxt}:
1.1 anton 6245:
1.26 crook 6246: @example
1.44 crook 6247: Defer deferred
6248: noname : ( ... -- ... )
6249: ... ;
1.116 anton 6250: latestxt IS deferred
1.26 crook 6251: @end example
1.1 anton 6252:
1.29 crook 6253: @noindent
1.44 crook 6254: @code{noname} works with any defining word, not just @code{:}.
6255:
1.116 anton 6256: @code{latestxt} also works when the last word was not defined as
1.71 anton 6257: @code{noname}. It does not work for combined words, though. It also has
6258: the useful property that is is valid as soon as the header for a
6259: definition has been built. Thus:
1.44 crook 6260:
6261: @example
1.116 anton 6262: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6263: @end example
1.1 anton 6264:
1.44 crook 6265: @noindent
6266: prints 3 numbers; the last two are the same.
1.26 crook 6267:
1.69 anton 6268: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6269: @subsection Supplying the name of a defined word
6270: @cindex names for defined words
6271: @cindex defining words, name given in a string
6272:
6273: By default, a defining word takes the name for the defined word from the
6274: input stream. Sometimes you want to supply the name from a string. You
6275: can do this with:
6276:
6277: doc-nextname
6278:
6279: For example:
6280:
6281: @example
6282: s" foo" nextname create
6283: @end example
6284:
6285: @noindent
6286: is equivalent to:
6287:
6288: @example
6289: create foo
6290: @end example
6291:
6292: @noindent
6293: @code{nextname} works with any defining word.
6294:
1.1 anton 6295:
1.170 pazsan 6296: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6297: @subsection User-defined Defining Words
6298: @cindex user-defined defining words
6299: @cindex defining words, user-defined
1.1 anton 6300:
1.29 crook 6301: You can create a new defining word by wrapping defining-time code around
6302: an existing defining word and putting the sequence in a colon
1.69 anton 6303: definition.
6304:
6305: @c anton: This example is very complex and leads in a quite different
6306: @c direction from the CREATE-DOES> stuff that follows. It should probably
6307: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6308: @c subsection of Defining Words)
6309:
6310: For example, suppose that you have a word @code{stats} that
1.29 crook 6311: gathers statistics about colon definitions given the @i{xt} of the
6312: definition, and you want every colon definition in your application to
6313: make a call to @code{stats}. You can define and use a new version of
6314: @code{:} like this:
6315:
6316: @example
6317: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6318: ... ; \ other code
6319:
1.116 anton 6320: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6321:
6322: my: foo + - ;
6323: @end example
6324:
6325: When @code{foo} is defined using @code{my:} these steps occur:
6326:
6327: @itemize @bullet
6328: @item
6329: @code{my:} is executed.
6330: @item
6331: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6332: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6333: the input stream for a name, builds a dictionary header for the name
6334: @code{foo} and switches @code{state} from interpret to compile.
6335: @item
1.116 anton 6336: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6337: being defined -- @code{foo} -- onto the stack.
6338: @item
6339: The code that was produced by @code{postpone literal} is executed; this
6340: causes the value on the stack to be compiled as a literal in the code
6341: area of @code{foo}.
6342: @item
6343: The code @code{['] stats} compiles a literal into the definition of
6344: @code{my:}. When @code{compile,} is executed, that literal -- the
6345: execution token for @code{stats} -- is layed down in the code area of
6346: @code{foo} , following the literal@footnote{Strictly speaking, the
6347: mechanism that @code{compile,} uses to convert an @i{xt} into something
6348: in the code area is implementation-dependent. A threaded implementation
6349: might spit out the execution token directly whilst another
6350: implementation might spit out a native code sequence.}.
6351: @item
6352: At this point, the execution of @code{my:} is complete, and control
6353: returns to the text interpreter. The text interpreter is in compile
6354: state, so subsequent text @code{+ -} is compiled into the definition of
6355: @code{foo} and the @code{;} terminates the definition as always.
6356: @end itemize
6357:
6358: You can use @code{see} to decompile a word that was defined using
6359: @code{my:} and see how it is different from a normal @code{:}
6360: definition. For example:
6361:
6362: @example
6363: : bar + - ; \ like foo but using : rather than my:
6364: see bar
6365: : bar
6366: + - ;
6367: see foo
6368: : foo
6369: 107645672 stats + - ;
6370:
1.140 anton 6371: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6372: @end example
6373:
6374: You can use techniques like this to make new defining words in terms of
6375: @i{any} existing defining word.
1.1 anton 6376:
6377:
1.29 crook 6378: @cindex defining defining words
1.26 crook 6379: @cindex @code{CREATE} ... @code{DOES>}
6380: If you want the words defined with your defining words to behave
6381: differently from words defined with standard defining words, you can
6382: write your defining word like this:
1.1 anton 6383:
6384: @example
1.26 crook 6385: : def-word ( "name" -- )
1.29 crook 6386: CREATE @i{code1}
1.26 crook 6387: DOES> ( ... -- ... )
1.29 crook 6388: @i{code2} ;
1.26 crook 6389:
6390: def-word name
1.1 anton 6391: @end example
6392:
1.29 crook 6393: @cindex child words
6394: This fragment defines a @dfn{defining word} @code{def-word} and then
6395: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6396: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6397: is not executed at this time. The word @code{name} is sometimes called a
6398: @dfn{child} of @code{def-word}.
6399:
6400: When you execute @code{name}, the address of the body of @code{name} is
6401: put on the data stack and @i{code2} is executed (the address of the body
6402: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6403: @code{CREATE}, i.e., the address a @code{create}d word returns by
6404: default).
6405:
6406: @c anton:
6407: @c www.dictionary.com says:
6408: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6409: @c several generations of absence, usually caused by the chance
6410: @c recombination of genes. 2.An individual or a part that exhibits
6411: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6412: @c of previous behavior after a period of absence.
6413: @c
6414: @c Doesn't seem to fit.
1.29 crook 6415:
1.69 anton 6416: @c @cindex atavism in child words
1.33 anton 6417: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6418: similarly; they all have a common run-time behaviour determined by
6419: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6420: body of the child word. The structure of the data is common to all
6421: children of @code{def-word}, but the data values are specific -- and
6422: private -- to each child word. When a child word is executed, the
6423: address of its private data area is passed as a parameter on TOS to be
6424: used and manipulated@footnote{It is legitimate both to read and write to
6425: this data area.} by @i{code2}.
1.29 crook 6426:
6427: The two fragments of code that make up the defining words act (are
6428: executed) at two completely separate times:
1.1 anton 6429:
1.29 crook 6430: @itemize @bullet
6431: @item
6432: At @i{define time}, the defining word executes @i{code1} to generate a
6433: child word
6434: @item
6435: At @i{child execution time}, when a child word is invoked, @i{code2}
6436: is executed, using parameters (data) that are private and specific to
6437: the child word.
6438: @end itemize
6439:
1.44 crook 6440: Another way of understanding the behaviour of @code{def-word} and
6441: @code{name} is to say that, if you make the following definitions:
1.33 anton 6442: @example
6443: : def-word1 ( "name" -- )
6444: CREATE @i{code1} ;
6445:
6446: : action1 ( ... -- ... )
6447: @i{code2} ;
6448:
6449: def-word1 name1
6450: @end example
6451:
1.44 crook 6452: @noindent
6453: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6454:
1.29 crook 6455: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6456:
1.1 anton 6457: @example
1.29 crook 6458: : CONSTANT ( w "name" -- )
6459: CREATE ,
1.26 crook 6460: DOES> ( -- w )
6461: @@ ;
1.1 anton 6462: @end example
6463:
1.29 crook 6464: @comment There is a beautiful description of how this works and what
6465: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6466: @comment commentary on the Counting Fruits problem.
6467:
6468: When you create a constant with @code{5 CONSTANT five}, a set of
6469: define-time actions take place; first a new word @code{five} is created,
6470: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6471: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6472: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6473: no code of its own; it simply contains a data field and a pointer to the
6474: code that follows @code{DOES>} in its defining word. That makes words
6475: created in this way very compact.
6476:
6477: The final example in this section is intended to remind you that space
6478: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6479: both read and written by a Standard program@footnote{Exercise: use this
6480: example as a starting point for your own implementation of @code{Value}
6481: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6482: @code{[']}.}:
6483:
6484: @example
6485: : foo ( "name" -- )
6486: CREATE -1 ,
6487: DOES> ( -- )
1.33 anton 6488: @@ . ;
1.29 crook 6489:
6490: foo first-word
6491: foo second-word
6492:
6493: 123 ' first-word >BODY !
6494: @end example
6495:
6496: If @code{first-word} had been a @code{CREATE}d word, we could simply
6497: have executed it to get the address of its data field. However, since it
6498: was defined to have @code{DOES>} actions, its execution semantics are to
6499: perform those @code{DOES>} actions. To get the address of its data field
6500: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6501: translate the xt into the address of the data field. When you execute
6502: @code{first-word}, it will display @code{123}. When you execute
6503: @code{second-word} it will display @code{-1}.
1.26 crook 6504:
6505: @cindex stack effect of @code{DOES>}-parts
6506: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6507: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6508: the stack effect of the defined words, not the stack effect of the
6509: following code (the following code expects the address of the body on
6510: the top of stack, which is not reflected in the stack comment). This is
6511: the convention that I use and recommend (it clashes a bit with using
6512: locals declarations for stack effect specification, though).
1.1 anton 6513:
1.53 anton 6514: @menu
6515: * CREATE..DOES> applications::
6516: * CREATE..DOES> details::
1.63 anton 6517: * Advanced does> usage example::
1.155 anton 6518: * Const-does>::
1.53 anton 6519: @end menu
6520:
6521: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6522: @subsubsection Applications of @code{CREATE..DOES>}
6523: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6524:
1.26 crook 6525: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6526:
1.26 crook 6527: @cindex factoring similar colon definitions
6528: When you see a sequence of code occurring several times, and you can
6529: identify a meaning, you will factor it out as a colon definition. When
6530: you see similar colon definitions, you can factor them using
6531: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6532: that look very similar:
1.1 anton 6533: @example
1.26 crook 6534: : ori, ( reg-target reg-source n -- )
6535: 0 asm-reg-reg-imm ;
6536: : andi, ( reg-target reg-source n -- )
6537: 1 asm-reg-reg-imm ;
1.1 anton 6538: @end example
6539:
1.26 crook 6540: @noindent
6541: This could be factored with:
6542: @example
6543: : reg-reg-imm ( op-code -- )
6544: CREATE ,
6545: DOES> ( reg-target reg-source n -- )
6546: @@ asm-reg-reg-imm ;
6547:
6548: 0 reg-reg-imm ori,
6549: 1 reg-reg-imm andi,
6550: @end example
1.1 anton 6551:
1.26 crook 6552: @cindex currying
6553: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6554: supply a part of the parameters for a word (known as @dfn{currying} in
6555: the functional language community). E.g., @code{+} needs two
6556: parameters. Creating versions of @code{+} with one parameter fixed can
6557: be done like this:
1.82 anton 6558:
1.1 anton 6559: @example
1.82 anton 6560: : curry+ ( n1 "name" -- )
1.26 crook 6561: CREATE ,
6562: DOES> ( n2 -- n1+n2 )
6563: @@ + ;
6564:
6565: 3 curry+ 3+
6566: -2 curry+ 2-
1.1 anton 6567: @end example
6568:
1.91 anton 6569:
1.63 anton 6570: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6571: @subsubsection The gory details of @code{CREATE..DOES>}
6572: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6573:
1.26 crook 6574: doc-does>
1.1 anton 6575:
1.26 crook 6576: @cindex @code{DOES>} in a separate definition
6577: This means that you need not use @code{CREATE} and @code{DOES>} in the
6578: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6579: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6580: @example
6581: : does1
6582: DOES> ( ... -- ... )
1.44 crook 6583: ... ;
6584:
6585: : does2
6586: DOES> ( ... -- ... )
6587: ... ;
6588:
6589: : def-word ( ... -- ... )
6590: create ...
6591: IF
6592: does1
6593: ELSE
6594: does2
6595: ENDIF ;
6596: @end example
6597:
6598: In this example, the selection of whether to use @code{does1} or
1.69 anton 6599: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6600: @code{CREATE}d.
6601:
6602: @cindex @code{DOES>} in interpretation state
6603: In a standard program you can apply a @code{DOES>}-part only if the last
6604: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6605: will override the behaviour of the last word defined in any case. In a
6606: standard program, you can use @code{DOES>} only in a colon
6607: definition. In Gforth, you can also use it in interpretation state, in a
6608: kind of one-shot mode; for example:
6609: @example
6610: CREATE name ( ... -- ... )
6611: @i{initialization}
6612: DOES>
6613: @i{code} ;
6614: @end example
6615:
6616: @noindent
6617: is equivalent to the standard:
6618: @example
6619: :noname
6620: DOES>
6621: @i{code} ;
6622: CREATE name EXECUTE ( ... -- ... )
6623: @i{initialization}
6624: @end example
6625:
1.53 anton 6626: doc->body
6627:
1.152 pazsan 6628: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6629: @subsubsection Advanced does> usage example
6630:
6631: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6632: for disassembling instructions, that follow a very repetetive scheme:
6633:
6634: @example
6635: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6636: @var{entry-num} cells @var{table} + !
6637: @end example
6638:
6639: Of course, this inspires the idea to factor out the commonalities to
6640: allow a definition like
6641:
6642: @example
6643: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6644: @end example
6645:
6646: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6647: correlated. Moreover, before I wrote the disassembler, there already
6648: existed code that defines instructions like this:
1.63 anton 6649:
6650: @example
6651: @var{entry-num} @var{inst-format} @var{inst-name}
6652: @end example
6653:
6654: This code comes from the assembler and resides in
6655: @file{arch/mips/insts.fs}.
6656:
6657: So I had to define the @var{inst-format} words that performed the scheme
6658: above when executed. At first I chose to use run-time code-generation:
6659:
6660: @example
6661: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6662: :noname Postpone @var{disasm-operands}
6663: name Postpone sliteral Postpone type Postpone ;
6664: swap cells @var{table} + ! ;
6665: @end example
6666:
6667: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6668:
1.63 anton 6669: An alternative would have been to write this using
6670: @code{create}/@code{does>}:
6671:
6672: @example
6673: : @var{inst-format} ( entry-num "name" -- )
6674: here name string, ( entry-num c-addr ) \ parse and save "name"
6675: noname create , ( entry-num )
1.116 anton 6676: latestxt swap cells @var{table} + !
1.63 anton 6677: does> ( addr w -- )
6678: \ disassemble instruction w at addr
6679: @@ >r
6680: @var{disasm-operands}
6681: r> count type ;
6682: @end example
6683:
6684: Somehow the first solution is simpler, mainly because it's simpler to
6685: shift a string from definition-time to use-time with @code{sliteral}
6686: than with @code{string,} and friends.
6687:
6688: I wrote a lot of words following this scheme and soon thought about
6689: factoring out the commonalities among them. Note that this uses a
6690: two-level defining word, i.e., a word that defines ordinary defining
6691: words.
6692:
6693: This time a solution involving @code{postpone} and friends seemed more
6694: difficult (try it as an exercise), so I decided to use a
6695: @code{create}/@code{does>} word; since I was already at it, I also used
6696: @code{create}/@code{does>} for the lower level (try using
6697: @code{postpone} etc. as an exercise), resulting in the following
6698: definition:
6699:
6700: @example
6701: : define-format ( disasm-xt table-xt -- )
6702: \ define an instruction format that uses disasm-xt for
6703: \ disassembling and enters the defined instructions into table
6704: \ table-xt
6705: create 2,
6706: does> ( u "inst" -- )
6707: \ defines an anonymous word for disassembling instruction inst,
6708: \ and enters it as u-th entry into table-xt
6709: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6710: noname create 2, \ define anonymous word
1.116 anton 6711: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6712: does> ( addr w -- )
6713: \ disassemble instruction w at addr
6714: 2@@ >r ( addr w disasm-xt R: c-addr )
6715: execute ( R: c-addr ) \ disassemble operands
6716: r> count type ; \ print name
6717: @end example
6718:
6719: Note that the tables here (in contrast to above) do the @code{cells +}
6720: by themselves (that's why you have to pass an xt). This word is used in
6721: the following way:
6722:
6723: @example
6724: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6725: @end example
6726:
1.71 anton 6727: As shown above, the defined instruction format is then used like this:
6728:
6729: @example
6730: @var{entry-num} @var{inst-format} @var{inst-name}
6731: @end example
6732:
1.63 anton 6733: In terms of currying, this kind of two-level defining word provides the
6734: parameters in three stages: first @var{disasm-operands} and @var{table},
6735: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6736: the instruction to be disassembled.
6737:
6738: Of course this did not quite fit all the instruction format names used
6739: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6740: the parameters into the right form.
6741:
6742: If you have trouble following this section, don't worry. First, this is
6743: involved and takes time (and probably some playing around) to
6744: understand; second, this is the first two-level
6745: @code{create}/@code{does>} word I have written in seventeen years of
6746: Forth; and if I did not have @file{insts.fs} to start with, I may well
6747: have elected to use just a one-level defining word (with some repeating
6748: of parameters when using the defining word). So it is not necessary to
6749: understand this, but it may improve your understanding of Forth.
1.44 crook 6750:
6751:
1.152 pazsan 6752: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6753: @subsubsection @code{Const-does>}
6754:
6755: A frequent use of @code{create}...@code{does>} is for transferring some
6756: values from definition-time to run-time. Gforth supports this use with
6757:
6758: doc-const-does>
6759:
6760: A typical use of this word is:
6761:
6762: @example
6763: : curry+ ( n1 "name" -- )
6764: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6765: + ;
6766:
6767: 3 curry+ 3+
6768: @end example
6769:
6770: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6771: definition to run-time.
6772:
6773: The advantages of using @code{const-does>} are:
6774:
6775: @itemize
6776:
6777: @item
6778: You don't have to deal with storing and retrieving the values, i.e.,
6779: your program becomes more writable and readable.
6780:
6781: @item
6782: When using @code{does>}, you have to introduce a @code{@@} that cannot
6783: be optimized away (because you could change the data using
6784: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6785:
6786: @end itemize
6787:
6788: An ANS Forth implementation of @code{const-does>} is available in
6789: @file{compat/const-does.fs}.
6790:
6791:
1.170 pazsan 6792: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6793: @subsection Deferred Words
1.44 crook 6794: @cindex deferred words
6795:
6796: The defining word @code{Defer} allows you to define a word by name
6797: without defining its behaviour; the definition of its behaviour is
6798: deferred. Here are two situation where this can be useful:
6799:
6800: @itemize @bullet
6801: @item
6802: Where you want to allow the behaviour of a word to be altered later, and
6803: for all precompiled references to the word to change when its behaviour
6804: is changed.
6805: @item
6806: For mutual recursion; @xref{Calls and returns}.
6807: @end itemize
6808:
6809: In the following example, @code{foo} always invokes the version of
6810: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6811: always invokes the version that prints ``@code{Hello}''. There is no way
6812: of getting @code{foo} to use the later version without re-ordering the
6813: source code and recompiling it.
6814:
6815: @example
6816: : greet ." Good morning" ;
6817: : foo ... greet ... ;
6818: : greet ." Hello" ;
6819: : bar ... greet ... ;
6820: @end example
6821:
6822: This problem can be solved by defining @code{greet} as a @code{Defer}red
6823: word. The behaviour of a @code{Defer}red word can be defined and
6824: redefined at any time by using @code{IS} to associate the xt of a
6825: previously-defined word with it. The previous example becomes:
6826:
6827: @example
1.69 anton 6828: Defer greet ( -- )
1.44 crook 6829: : foo ... greet ... ;
6830: : bar ... greet ... ;
1.69 anton 6831: : greet1 ( -- ) ." Good morning" ;
6832: : greet2 ( -- ) ." Hello" ;
1.132 anton 6833: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6834: @end example
6835:
1.69 anton 6836: @progstyle
6837: You should write a stack comment for every deferred word, and put only
6838: XTs into deferred words that conform to this stack effect. Otherwise
6839: it's too difficult to use the deferred word.
6840:
1.44 crook 6841: A deferred word can be used to improve the statistics-gathering example
6842: from @ref{User-defined Defining Words}; rather than edit the
6843: application's source code to change every @code{:} to a @code{my:}, do
6844: this:
6845:
6846: @example
6847: : real: : ; \ retain access to the original
6848: defer : \ redefine as a deferred word
1.132 anton 6849: ' my: IS : \ use special version of :
1.44 crook 6850: \
6851: \ load application here
6852: \
1.132 anton 6853: ' real: IS : \ go back to the original
1.44 crook 6854: @end example
6855:
6856:
1.132 anton 6857: One thing to note is that @code{IS} has special compilation semantics,
6858: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6859:
6860: @example
6861: : set-greet ( xt -- )
1.132 anton 6862: IS greet ;
1.44 crook 6863:
6864: ' greet1 set-greet
6865: @end example
6866:
1.132 anton 6867: In situations where @code{IS} does not fit, use @code{defer!} instead.
6868:
1.69 anton 6869: A deferred word can only inherit execution semantics from the xt
6870: (because that is all that an xt can represent -- for more discussion of
6871: this @pxref{Tokens for Words}); by default it will have default
6872: interpretation and compilation semantics deriving from this execution
6873: semantics. However, you can change the interpretation and compilation
6874: semantics of the deferred word in the usual ways:
1.44 crook 6875:
6876: @example
1.132 anton 6877: : bar .... ; immediate
1.44 crook 6878: Defer fred immediate
6879: Defer jim
6880:
1.132 anton 6881: ' bar IS jim \ jim has default semantics
6882: ' bar IS fred \ fred is immediate
1.44 crook 6883: @end example
6884:
6885: doc-defer
1.132 anton 6886: doc-defer!
1.44 crook 6887: doc-is
1.132 anton 6888: doc-defer@
6889: doc-action-of
1.44 crook 6890: @comment TODO document these: what's defers [is]
6891: doc-defers
6892:
6893: @c Use @code{words-deferred} to see a list of deferred words.
6894:
1.132 anton 6895: Definitions of these words (except @code{defers}) in ANS Forth are
6896: provided in @file{compat/defer.fs}.
1.44 crook 6897:
6898:
1.170 pazsan 6899: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6900: @subsection Aliases
6901: @cindex aliases
1.1 anton 6902:
1.44 crook 6903: The defining word @code{Alias} allows you to define a word by name that
6904: has the same behaviour as some other word. Here are two situation where
6905: this can be useful:
1.1 anton 6906:
1.44 crook 6907: @itemize @bullet
6908: @item
6909: When you want access to a word's definition from a different word list
6910: (for an example of this, see the definition of the @code{Root} word list
6911: in the Gforth source).
6912: @item
6913: When you want to create a synonym; a definition that can be known by
6914: either of two names (for example, @code{THEN} and @code{ENDIF} are
6915: aliases).
6916: @end itemize
1.1 anton 6917:
1.69 anton 6918: Like deferred words, an alias has default compilation and interpretation
6919: semantics at the beginning (not the modifications of the other word),
6920: but you can change them in the usual ways (@code{immediate},
6921: @code{compile-only}). For example:
1.1 anton 6922:
6923: @example
1.44 crook 6924: : foo ... ; immediate
6925:
6926: ' foo Alias bar \ bar is not an immediate word
6927: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6928: @end example
6929:
1.44 crook 6930: Words that are aliases have the same xt, different headers in the
6931: dictionary, and consequently different name tokens (@pxref{Tokens for
6932: Words}) and possibly different immediate flags. An alias can only have
6933: default or immediate compilation semantics; you can define aliases for
6934: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6935:
1.44 crook 6936: doc-alias
1.1 anton 6937:
6938:
1.47 crook 6939: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6940: @section Interpretation and Compilation Semantics
1.26 crook 6941: @cindex semantics, interpretation and compilation
1.1 anton 6942:
1.71 anton 6943: @c !! state and ' are used without explanation
6944: @c example for immediate/compile-only? or is the tutorial enough
6945:
1.26 crook 6946: @cindex interpretation semantics
1.71 anton 6947: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6948: interpreter does when it encounters the word in interpret state. It also
6949: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6950: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6951: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6952: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6953:
1.26 crook 6954: @cindex compilation semantics
1.71 anton 6955: The @dfn{compilation semantics} of a (named) word are what the text
6956: interpreter does when it encounters the word in compile state. It also
6957: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6958: compiles@footnote{In standard terminology, ``appends to the current
6959: definition''.} the compilation semantics of @i{word}.
1.1 anton 6960:
1.26 crook 6961: @cindex execution semantics
6962: The standard also talks about @dfn{execution semantics}. They are used
6963: only for defining the interpretation and compilation semantics of many
6964: words. By default, the interpretation semantics of a word are to
6965: @code{execute} its execution semantics, and the compilation semantics of
6966: a word are to @code{compile,} its execution semantics.@footnote{In
6967: standard terminology: The default interpretation semantics are its
6968: execution semantics; the default compilation semantics are to append its
6969: execution semantics to the execution semantics of the current
6970: definition.}
6971:
1.71 anton 6972: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6973: the text interpreter, ticked, or @code{postpone}d, so they have no
6974: interpretation or compilation semantics. Their behaviour is represented
6975: by their XT (@pxref{Tokens for Words}), and we call it execution
6976: semantics, too.
6977:
1.26 crook 6978: @comment TODO expand, make it co-operate with new sections on text interpreter.
6979:
6980: @cindex immediate words
6981: @cindex compile-only words
6982: You can change the semantics of the most-recently defined word:
6983:
1.44 crook 6984:
1.26 crook 6985: doc-immediate
6986: doc-compile-only
6987: doc-restrict
6988:
1.82 anton 6989: By convention, words with non-default compilation semantics (e.g.,
6990: immediate words) often have names surrounded with brackets (e.g.,
6991: @code{[']}, @pxref{Execution token}).
1.44 crook 6992:
1.26 crook 6993: Note that ticking (@code{'}) a compile-only word gives an error
6994: (``Interpreting a compile-only word'').
1.1 anton 6995:
1.47 crook 6996: @menu
1.67 anton 6997: * Combined words::
1.47 crook 6998: @end menu
1.44 crook 6999:
1.71 anton 7000:
1.48 anton 7001: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7002: @subsection Combined Words
7003: @cindex combined words
7004:
7005: Gforth allows you to define @dfn{combined words} -- words that have an
7006: arbitrary combination of interpretation and compilation semantics.
7007:
1.26 crook 7008: doc-interpret/compile:
1.1 anton 7009:
1.26 crook 7010: This feature was introduced for implementing @code{TO} and @code{S"}. I
7011: recommend that you do not define such words, as cute as they may be:
7012: they make it hard to get at both parts of the word in some contexts.
7013: E.g., assume you want to get an execution token for the compilation
7014: part. Instead, define two words, one that embodies the interpretation
7015: part, and one that embodies the compilation part. Once you have done
7016: that, you can define a combined word with @code{interpret/compile:} for
7017: the convenience of your users.
1.1 anton 7018:
1.26 crook 7019: You might try to use this feature to provide an optimizing
7020: implementation of the default compilation semantics of a word. For
7021: example, by defining:
1.1 anton 7022: @example
1.26 crook 7023: :noname
7024: foo bar ;
7025: :noname
7026: POSTPONE foo POSTPONE bar ;
1.29 crook 7027: interpret/compile: opti-foobar
1.1 anton 7028: @end example
1.26 crook 7029:
1.23 crook 7030: @noindent
1.26 crook 7031: as an optimizing version of:
7032:
1.1 anton 7033: @example
1.26 crook 7034: : foobar
7035: foo bar ;
1.1 anton 7036: @end example
7037:
1.26 crook 7038: Unfortunately, this does not work correctly with @code{[compile]},
7039: because @code{[compile]} assumes that the compilation semantics of all
7040: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7041: opti-foobar} would compile compilation semantics, whereas
7042: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7043:
1.26 crook 7044: @cindex state-smart words (are a bad idea)
1.82 anton 7045: @anchor{state-smartness}
1.29 crook 7046: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7047: by @code{interpret/compile:} (words are state-smart if they check
7048: @code{STATE} during execution). E.g., they would try to code
7049: @code{foobar} like this:
1.1 anton 7050:
1.26 crook 7051: @example
7052: : foobar
7053: STATE @@
7054: IF ( compilation state )
7055: POSTPONE foo POSTPONE bar
7056: ELSE
7057: foo bar
7058: ENDIF ; immediate
7059: @end example
1.1 anton 7060:
1.26 crook 7061: Although this works if @code{foobar} is only processed by the text
7062: interpreter, it does not work in other contexts (like @code{'} or
7063: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7064: for a state-smart word, not for the interpretation semantics of the
7065: original @code{foobar}; when you execute this execution token (directly
7066: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7067: state, the result will not be what you expected (i.e., it will not
7068: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7069: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7070: M. Anton Ertl,
7071: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7072: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7073:
1.26 crook 7074: @cindex defining words with arbitrary semantics combinations
7075: It is also possible to write defining words that define words with
7076: arbitrary combinations of interpretation and compilation semantics. In
7077: general, they look like this:
1.1 anton 7078:
1.26 crook 7079: @example
7080: : def-word
7081: create-interpret/compile
1.29 crook 7082: @i{code1}
1.26 crook 7083: interpretation>
1.29 crook 7084: @i{code2}
1.26 crook 7085: <interpretation
7086: compilation>
1.29 crook 7087: @i{code3}
1.26 crook 7088: <compilation ;
7089: @end example
1.1 anton 7090:
1.29 crook 7091: For a @i{word} defined with @code{def-word}, the interpretation
7092: semantics are to push the address of the body of @i{word} and perform
7093: @i{code2}, and the compilation semantics are to push the address of
7094: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7095: can also be defined like this (except that the defined constants don't
7096: behave correctly when @code{[compile]}d):
1.1 anton 7097:
1.26 crook 7098: @example
7099: : constant ( n "name" -- )
7100: create-interpret/compile
7101: ,
7102: interpretation> ( -- n )
7103: @@
7104: <interpretation
7105: compilation> ( compilation. -- ; run-time. -- n )
7106: @@ postpone literal
7107: <compilation ;
7108: @end example
1.1 anton 7109:
1.44 crook 7110:
1.26 crook 7111: doc-create-interpret/compile
7112: doc-interpretation>
7113: doc-<interpretation
7114: doc-compilation>
7115: doc-<compilation
1.1 anton 7116:
1.44 crook 7117:
1.29 crook 7118: Words defined with @code{interpret/compile:} and
1.26 crook 7119: @code{create-interpret/compile} have an extended header structure that
7120: differs from other words; however, unless you try to access them with
7121: plain address arithmetic, you should not notice this. Words for
7122: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7123: @code{'} @i{word} @code{>body} also gives you the body of a word created
7124: with @code{create-interpret/compile}.
1.1 anton 7125:
1.44 crook 7126:
1.47 crook 7127: @c -------------------------------------------------------------
1.81 anton 7128: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7129: @section Tokens for Words
7130: @cindex tokens for words
7131:
7132: This section describes the creation and use of tokens that represent
7133: words.
7134:
1.71 anton 7135: @menu
7136: * Execution token:: represents execution/interpretation semantics
7137: * Compilation token:: represents compilation semantics
7138: * Name token:: represents named words
7139: @end menu
1.47 crook 7140:
1.71 anton 7141: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7142: @subsection Execution token
1.47 crook 7143:
7144: @cindex xt
7145: @cindex execution token
1.71 anton 7146: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7147: You can use @code{execute} to invoke this behaviour.
1.47 crook 7148:
1.71 anton 7149: @cindex tick (')
7150: You can use @code{'} to get an execution token that represents the
7151: interpretation semantics of a named word:
1.47 crook 7152:
7153: @example
1.97 anton 7154: 5 ' . ( n xt )
7155: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7156: @end example
1.47 crook 7157:
1.71 anton 7158: doc-'
7159:
7160: @code{'} parses at run-time; there is also a word @code{[']} that parses
7161: when it is compiled, and compiles the resulting XT:
7162:
7163: @example
7164: : foo ['] . execute ;
7165: 5 foo
7166: : bar ' execute ; \ by contrast,
7167: 5 bar . \ ' parses "." when bar executes
7168: @end example
7169:
7170: doc-[']
7171:
7172: If you want the execution token of @i{word}, write @code{['] @i{word}}
7173: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7174: @code{'} and @code{[']} behave somewhat unusually by complaining about
7175: compile-only words (because these words have no interpretation
7176: semantics). You might get what you want by using @code{COMP' @i{word}
7177: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7178: token}).
7179:
1.116 anton 7180: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7181: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7182: for the only behaviour the word has (the execution semantics). For
1.116 anton 7183: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7184: would produce if the word was defined anonymously.
7185:
7186: @example
7187: :noname ." hello" ;
7188: execute
1.47 crook 7189: @end example
7190:
1.71 anton 7191: An XT occupies one cell and can be manipulated like any other cell.
7192:
1.47 crook 7193: @cindex code field address
7194: @cindex CFA
1.71 anton 7195: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7196: operations that produce or consume it). For old hands: In Gforth, the
7197: XT is implemented as a code field address (CFA).
7198:
7199: doc-execute
7200: doc-perform
7201:
7202: @node Compilation token, Name token, Execution token, Tokens for Words
7203: @subsection Compilation token
1.47 crook 7204:
7205: @cindex compilation token
1.71 anton 7206: @cindex CT (compilation token)
7207: Gforth represents the compilation semantics of a named word by a
1.47 crook 7208: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7209: @i{xt} is an execution token. The compilation semantics represented by
7210: the compilation token can be performed with @code{execute}, which
7211: consumes the whole compilation token, with an additional stack effect
7212: determined by the represented compilation semantics.
7213:
7214: At present, the @i{w} part of a compilation token is an execution token,
7215: and the @i{xt} part represents either @code{execute} or
7216: @code{compile,}@footnote{Depending upon the compilation semantics of the
7217: word. If the word has default compilation semantics, the @i{xt} will
7218: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7219: @i{xt} will represent @code{execute}.}. However, don't rely on that
7220: knowledge, unless necessary; future versions of Gforth may introduce
7221: unusual compilation tokens (e.g., a compilation token that represents
7222: the compilation semantics of a literal).
7223:
1.71 anton 7224: You can perform the compilation semantics represented by the compilation
7225: token with @code{execute}. You can compile the compilation semantics
7226: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7227: equivalent to @code{postpone @i{word}}.
7228:
7229: doc-[comp']
7230: doc-comp'
7231: doc-postpone,
7232:
7233: @node Name token, , Compilation token, Tokens for Words
7234: @subsection Name token
1.47 crook 7235:
7236: @cindex name token
1.116 anton 7237: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7238: token is an abstract data type that occurs as argument or result of the
7239: words below.
7240:
7241: @c !! put this elswhere?
1.47 crook 7242: @cindex name field address
7243: @cindex NFA
1.116 anton 7244: The closest thing to the nt in older Forth systems is the name field
7245: address (NFA), but there are significant differences: in older Forth
7246: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7247: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7248: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7249: is a link field in the structure identified by the name token, but
7250: searching usually uses a hash table external to these structures; the
7251: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7252: implemented as the address of that count field.
1.47 crook 7253:
7254: doc-find-name
1.116 anton 7255: doc-latest
7256: doc->name
1.47 crook 7257: doc-name>int
7258: doc-name?int
7259: doc-name>comp
7260: doc-name>string
1.109 anton 7261: doc-id.
7262: doc-.name
7263: doc-.id
1.47 crook 7264:
1.81 anton 7265: @c ----------------------------------------------------------
7266: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7267: @section Compiling words
7268: @cindex compiling words
7269: @cindex macros
7270:
7271: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7272: between compilation and run-time. E.g., you can run arbitrary code
7273: between defining words (or for computing data used by defining words
7274: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7275: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7276: running arbitrary code while compiling a colon definition (exception:
7277: you must not allot dictionary space).
7278:
7279: @menu
7280: * Literals:: Compiling data values
7281: * Macros:: Compiling words
7282: @end menu
7283:
7284: @node Literals, Macros, Compiling words, Compiling words
7285: @subsection Literals
7286: @cindex Literals
7287:
7288: The simplest and most frequent example is to compute a literal during
7289: compilation. E.g., the following definition prints an array of strings,
7290: one string per line:
7291:
7292: @example
7293: : .strings ( addr u -- ) \ gforth
7294: 2* cells bounds U+DO
7295: cr i 2@@ type
7296: 2 cells +LOOP ;
7297: @end example
1.81 anton 7298:
1.82 anton 7299: With a simple-minded compiler like Gforth's, this computes @code{2
7300: cells} on every loop iteration. You can compute this value once and for
7301: all at compile time and compile it into the definition like this:
7302:
7303: @example
7304: : .strings ( addr u -- ) \ gforth
7305: 2* cells bounds U+DO
7306: cr i 2@@ type
7307: [ 2 cells ] literal +LOOP ;
7308: @end example
7309:
7310: @code{[} switches the text interpreter to interpret state (you will get
7311: an @code{ok} prompt if you type this example interactively and insert a
7312: newline between @code{[} and @code{]}), so it performs the
7313: interpretation semantics of @code{2 cells}; this computes a number.
7314: @code{]} switches the text interpreter back into compile state. It then
7315: performs @code{Literal}'s compilation semantics, which are to compile
7316: this number into the current word. You can decompile the word with
7317: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7318:
1.82 anton 7319: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7320: *} in this way.
1.81 anton 7321:
1.82 anton 7322: doc-[
7323: doc-]
1.81 anton 7324: doc-literal
7325: doc-]L
1.82 anton 7326:
7327: There are also words for compiling other data types than single cells as
7328: literals:
7329:
1.81 anton 7330: doc-2literal
7331: doc-fliteral
1.82 anton 7332: doc-sliteral
7333:
7334: @cindex colon-sys, passing data across @code{:}
7335: @cindex @code{:}, passing data across
7336: You might be tempted to pass data from outside a colon definition to the
7337: inside on the data stack. This does not work, because @code{:} puhes a
7338: colon-sys, making stuff below unaccessible. E.g., this does not work:
7339:
7340: @example
7341: 5 : foo literal ; \ error: "unstructured"
7342: @end example
7343:
7344: Instead, you have to pass the value in some other way, e.g., through a
7345: variable:
7346:
7347: @example
7348: variable temp
7349: 5 temp !
7350: : foo [ temp @@ ] literal ;
7351: @end example
7352:
7353:
7354: @node Macros, , Literals, Compiling words
7355: @subsection Macros
7356: @cindex Macros
7357: @cindex compiling compilation semantics
7358:
7359: @code{Literal} and friends compile data values into the current
7360: definition. You can also write words that compile other words into the
7361: current definition. E.g.,
7362:
7363: @example
7364: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7365: POSTPONE + ;
7366:
7367: : foo ( n1 n2 -- n )
7368: [ compile-+ ] ;
7369: 1 2 foo .
7370: @end example
7371:
7372: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7373: What happens in this example? @code{Postpone} compiles the compilation
7374: semantics of @code{+} into @code{compile-+}; later the text interpreter
7375: executes @code{compile-+} and thus the compilation semantics of +, which
7376: compile (the execution semantics of) @code{+} into
7377: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7378: should only be executed in compile state, so this example is not
7379: guaranteed to work on all standard systems, but on any decent system it
7380: will work.}
7381:
7382: doc-postpone
7383: doc-[compile]
7384:
7385: Compiling words like @code{compile-+} are usually immediate (or similar)
7386: so you do not have to switch to interpret state to execute them;
7387: mopifying the last example accordingly produces:
7388:
7389: @example
7390: : [compile-+] ( compilation: --; interpretation: -- )
7391: \ compiled code: ( n1 n2 -- n )
7392: POSTPONE + ; immediate
7393:
7394: : foo ( n1 n2 -- n )
7395: [compile-+] ;
7396: 1 2 foo .
7397: @end example
7398:
7399: Immediate compiling words are similar to macros in other languages (in
7400: particular, Lisp). The important differences to macros in, e.g., C are:
7401:
7402: @itemize @bullet
7403:
7404: @item
7405: You use the same language for defining and processing macros, not a
7406: separate preprocessing language and processor.
7407:
7408: @item
7409: Consequently, the full power of Forth is available in macro definitions.
7410: E.g., you can perform arbitrarily complex computations, or generate
7411: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7412: Tutorial}). This power is very useful when writing a parser generators
7413: or other code-generating software.
7414:
7415: @item
7416: Macros defined using @code{postpone} etc. deal with the language at a
7417: higher level than strings; name binding happens at macro definition
7418: time, so you can avoid the pitfalls of name collisions that can happen
7419: in C macros. Of course, Forth is a liberal language and also allows to
7420: shoot yourself in the foot with text-interpreted macros like
7421:
7422: @example
7423: : [compile-+] s" +" evaluate ; immediate
7424: @end example
7425:
7426: Apart from binding the name at macro use time, using @code{evaluate}
7427: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7428: @end itemize
7429:
7430: You may want the macro to compile a number into a word. The word to do
7431: it is @code{literal}, but you have to @code{postpone} it, so its
7432: compilation semantics take effect when the macro is executed, not when
7433: it is compiled:
7434:
7435: @example
7436: : [compile-5] ( -- ) \ compiled code: ( -- n )
7437: 5 POSTPONE literal ; immediate
7438:
7439: : foo [compile-5] ;
7440: foo .
7441: @end example
7442:
7443: You may want to pass parameters to a macro, that the macro should
7444: compile into the current definition. If the parameter is a number, then
7445: you can use @code{postpone literal} (similar for other values).
7446:
7447: If you want to pass a word that is to be compiled, the usual way is to
7448: pass an execution token and @code{compile,} it:
7449:
7450: @example
7451: : twice1 ( xt -- ) \ compiled code: ... -- ...
7452: dup compile, compile, ;
7453:
7454: : 2+ ( n1 -- n2 )
7455: [ ' 1+ twice1 ] ;
7456: @end example
7457:
7458: doc-compile,
7459:
7460: An alternative available in Gforth, that allows you to pass compile-only
7461: words as parameters is to use the compilation token (@pxref{Compilation
7462: token}). The same example in this technique:
7463:
7464: @example
7465: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7466: 2dup 2>r execute 2r> execute ;
7467:
7468: : 2+ ( n1 -- n2 )
7469: [ comp' 1+ twice ] ;
7470: @end example
7471:
7472: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7473: works even if the executed compilation semantics has an effect on the
7474: data stack.
7475:
7476: You can also define complete definitions with these words; this provides
7477: an alternative to using @code{does>} (@pxref{User-defined Defining
7478: Words}). E.g., instead of
7479:
7480: @example
7481: : curry+ ( n1 "name" -- )
7482: CREATE ,
7483: DOES> ( n2 -- n1+n2 )
7484: @@ + ;
7485: @end example
7486:
7487: you could define
7488:
7489: @example
7490: : curry+ ( n1 "name" -- )
7491: \ name execution: ( n2 -- n1+n2 )
7492: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7493:
1.82 anton 7494: -3 curry+ 3-
7495: see 3-
7496: @end example
1.81 anton 7497:
1.82 anton 7498: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7499: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7500:
1.82 anton 7501: This way of writing defining words is sometimes more, sometimes less
7502: convenient than using @code{does>} (@pxref{Advanced does> usage
7503: example}). One advantage of this method is that it can be optimized
7504: better, because the compiler knows that the value compiled with
7505: @code{literal} is fixed, whereas the data associated with a
7506: @code{create}d word can be changed.
1.47 crook 7507:
1.26 crook 7508: @c ----------------------------------------------------------
1.111 anton 7509: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7510: @section The Text Interpreter
7511: @cindex interpreter - outer
7512: @cindex text interpreter
7513: @cindex outer interpreter
1.1 anton 7514:
1.34 anton 7515: @c Should we really describe all these ugly details? IMO the text
7516: @c interpreter should be much cleaner, but that may not be possible within
7517: @c ANS Forth. - anton
1.44 crook 7518: @c nac-> I wanted to explain how it works to show how you can exploit
7519: @c it in your own programs. When I was writing a cross-compiler, figuring out
7520: @c some of these gory details was very helpful to me. None of the textbooks
7521: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7522: @c seems to positively avoid going into too much detail for some of
7523: @c the internals.
1.34 anton 7524:
1.71 anton 7525: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7526: @c it is; for the ugly details, I would prefer another place. I wonder
7527: @c whether we should have a chapter before "Words" that describes some
7528: @c basic concepts referred to in words, and a chapter after "Words" that
7529: @c describes implementation details.
7530:
1.29 crook 7531: The text interpreter@footnote{This is an expanded version of the
7532: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7533: that processes input from the current input device. It is also called
7534: the outer interpreter, in contrast to the inner interpreter
7535: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7536: implementations.
1.27 crook 7537:
1.29 crook 7538: @cindex interpret state
7539: @cindex compile state
7540: The text interpreter operates in one of two states: @dfn{interpret
7541: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7542: aptly-named variable @code{state}.
1.29 crook 7543:
7544: This section starts by describing how the text interpreter behaves when
7545: it is in interpret state, processing input from the user input device --
7546: the keyboard. This is the mode that a Forth system is in after it starts
7547: up.
7548:
7549: @cindex input buffer
7550: @cindex terminal input buffer
7551: The text interpreter works from an area of memory called the @dfn{input
7552: buffer}@footnote{When the text interpreter is processing input from the
7553: keyboard, this area of memory is called the @dfn{terminal input buffer}
7554: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7555: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7556: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7557: leading spaces (called @dfn{delimiters}) then parses a string (a
7558: sequence of non-space characters) until it reaches either a space
7559: character or the end of the buffer. Having parsed a string, it makes two
7560: attempts to process it:
1.27 crook 7561:
1.29 crook 7562: @cindex dictionary
1.27 crook 7563: @itemize @bullet
7564: @item
1.29 crook 7565: It looks for the string in a @dfn{dictionary} of definitions. If the
7566: string is found, the string names a @dfn{definition} (also known as a
7567: @dfn{word}) and the dictionary search returns information that allows
7568: the text interpreter to perform the word's @dfn{interpretation
7569: semantics}. In most cases, this simply means that the word will be
7570: executed.
1.27 crook 7571: @item
7572: If the string is not found in the dictionary, the text interpreter
1.29 crook 7573: attempts to treat it as a number, using the rules described in
7574: @ref{Number Conversion}. If the string represents a legal number in the
7575: current radix, the number is pushed onto a parameter stack (the data
7576: stack for integers, the floating-point stack for floating-point
7577: numbers).
7578: @end itemize
7579:
7580: If both attempts fail, or if the word is found in the dictionary but has
7581: no interpretation semantics@footnote{This happens if the word was
7582: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7583: remainder of the input buffer, issues an error message and waits for
7584: more input. If one of the attempts succeeds, the text interpreter
7585: repeats the parsing process until the whole of the input buffer has been
7586: processed, at which point it prints the status message ``@code{ ok}''
7587: and waits for more input.
7588:
1.71 anton 7589: @c anton: this should be in the input stream subsection (or below it)
7590:
1.29 crook 7591: @cindex parse area
7592: The text interpreter keeps track of its position in the input buffer by
7593: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7594: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7595: of the input buffer. The region from offset @code{>IN @@} to the end of
7596: the input buffer is called the @dfn{parse area}@footnote{In other words,
7597: the text interpreter processes the contents of the input buffer by
7598: parsing strings from the parse area until the parse area is empty.}.
7599: This example shows how @code{>IN} changes as the text interpreter parses
7600: the input buffer:
7601:
7602: @example
7603: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7604: CR ." ->" TYPE ." <-" ; IMMEDIATE
7605:
7606: 1 2 3 remaining + remaining .
7607:
7608: : foo 1 2 3 remaining SWAP remaining ;
7609: @end example
7610:
7611: @noindent
7612: The result is:
7613:
7614: @example
7615: ->+ remaining .<-
7616: ->.<-5 ok
7617:
7618: ->SWAP remaining ;-<
7619: ->;<- ok
7620: @end example
7621:
7622: @cindex parsing words
7623: The value of @code{>IN} can also be modified by a word in the input
7624: buffer that is executed by the text interpreter. This means that a word
7625: can ``trick'' the text interpreter into either skipping a section of the
7626: input buffer@footnote{This is how parsing words work.} or into parsing a
7627: section twice. For example:
1.27 crook 7628:
1.29 crook 7629: @example
1.71 anton 7630: : lat ." <<foo>>" ;
7631: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7632: @end example
7633:
7634: @noindent
7635: When @code{flat} is executed, this output is produced@footnote{Exercise
7636: for the reader: what would happen if the @code{3} were replaced with
7637: @code{4}?}:
7638:
7639: @example
1.71 anton 7640: <<bar>><<foo>>
1.29 crook 7641: @end example
7642:
1.71 anton 7643: This technique can be used to work around some of the interoperability
7644: problems of parsing words. Of course, it's better to avoid parsing
7645: words where possible.
7646:
1.29 crook 7647: @noindent
7648: Two important notes about the behaviour of the text interpreter:
1.27 crook 7649:
7650: @itemize @bullet
7651: @item
7652: It processes each input string to completion before parsing additional
1.29 crook 7653: characters from the input buffer.
7654: @item
7655: It treats the input buffer as a read-only region (and so must your code).
7656: @end itemize
7657:
7658: @noindent
7659: When the text interpreter is in compile state, its behaviour changes in
7660: these ways:
7661:
7662: @itemize @bullet
7663: @item
7664: If a parsed string is found in the dictionary, the text interpreter will
7665: perform the word's @dfn{compilation semantics}. In most cases, this
7666: simply means that the execution semantics of the word will be appended
7667: to the current definition.
1.27 crook 7668: @item
1.29 crook 7669: When a number is encountered, it is compiled into the current definition
7670: (as a literal) rather than being pushed onto a parameter stack.
7671: @item
7672: If an error occurs, @code{state} is modified to put the text interpreter
7673: back into interpret state.
7674: @item
7675: Each time a line is entered from the keyboard, Gforth prints
7676: ``@code{ compiled}'' rather than `` @code{ok}''.
7677: @end itemize
7678:
7679: @cindex text interpreter - input sources
7680: When the text interpreter is using an input device other than the
7681: keyboard, its behaviour changes in these ways:
7682:
7683: @itemize @bullet
7684: @item
7685: When the parse area is empty, the text interpreter attempts to refill
7686: the input buffer from the input source. When the input source is
1.71 anton 7687: exhausted, the input source is set back to the previous input source.
1.29 crook 7688: @item
7689: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7690: time the parse area is emptied.
7691: @item
7692: If an error occurs, the input source is set back to the user input
7693: device.
1.27 crook 7694: @end itemize
1.21 crook 7695:
1.49 anton 7696: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7697:
1.26 crook 7698: doc->in
1.27 crook 7699: doc-source
7700:
1.26 crook 7701: doc-tib
7702: doc-#tib
1.1 anton 7703:
1.44 crook 7704:
1.26 crook 7705: @menu
1.67 anton 7706: * Input Sources::
7707: * Number Conversion::
7708: * Interpret/Compile states::
7709: * Interpreter Directives::
1.26 crook 7710: @end menu
1.1 anton 7711:
1.29 crook 7712: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7713: @subsection Input Sources
7714: @cindex input sources
7715: @cindex text interpreter - input sources
7716:
1.44 crook 7717: By default, the text interpreter processes input from the user input
1.29 crook 7718: device (the keyboard) when Forth starts up. The text interpreter can
7719: process input from any of these sources:
7720:
7721: @itemize @bullet
7722: @item
7723: The user input device -- the keyboard.
7724: @item
7725: A file, using the words described in @ref{Forth source files}.
7726: @item
7727: A block, using the words described in @ref{Blocks}.
7728: @item
7729: A text string, using @code{evaluate}.
7730: @end itemize
7731:
7732: A program can identify the current input device from the values of
7733: @code{source-id} and @code{blk}.
7734:
1.44 crook 7735:
1.29 crook 7736: doc-source-id
7737: doc-blk
7738:
7739: doc-save-input
7740: doc-restore-input
7741:
7742: doc-evaluate
1.111 anton 7743: doc-query
1.1 anton 7744:
1.29 crook 7745:
1.44 crook 7746:
1.29 crook 7747: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7748: @subsection Number Conversion
7749: @cindex number conversion
7750: @cindex double-cell numbers, input format
7751: @cindex input format for double-cell numbers
7752: @cindex single-cell numbers, input format
7753: @cindex input format for single-cell numbers
7754: @cindex floating-point numbers, input format
7755: @cindex input format for floating-point numbers
1.1 anton 7756:
1.29 crook 7757: This section describes the rules that the text interpreter uses when it
7758: tries to convert a string into a number.
1.1 anton 7759:
1.26 crook 7760: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7761: number base@footnote{For example, 0-9 when the number base is decimal or
7762: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7763:
1.26 crook 7764: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7765:
1.29 crook 7766: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7767: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7768:
1.26 crook 7769: Let * represent any number of instances of the previous character
7770: (including none).
1.1 anton 7771:
1.26 crook 7772: Let any other character represent itself.
1.1 anton 7773:
1.29 crook 7774: @noindent
1.26 crook 7775: Now, the conversion rules are:
1.21 crook 7776:
1.26 crook 7777: @itemize @bullet
7778: @item
7779: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7780: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7781: @item
7782: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7783: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7784: arithmetic. Examples are -45 -5681 -0
7785: @item
7786: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7787: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7788: (all three of these represent the same number).
1.26 crook 7789: @item
7790: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7791: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7792: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7793: -34.65 (all three of these represent the same number).
1.26 crook 7794: @item
1.29 crook 7795: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7796: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7797: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7798: number) +12.E-4
1.26 crook 7799: @end itemize
1.1 anton 7800:
1.174 anton 7801: By default, the number base used for integer number conversion is
7802: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7803: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7804: change @code{base} anywhere, make sure to save the old value and
7805: restore it afterwards; better yet, use @code{base-execute}, which does
7806: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7807: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7808:
1.29 crook 7809: doc-dpl
1.174 anton 7810: doc-base-execute
1.26 crook 7811: doc-base
7812: doc-hex
7813: doc-decimal
1.1 anton 7814:
1.26 crook 7815: @cindex '-prefix for character strings
7816: @cindex &-prefix for decimal numbers
1.133 anton 7817: @cindex #-prefix for decimal numbers
1.26 crook 7818: @cindex %-prefix for binary numbers
7819: @cindex $-prefix for hexadecimal numbers
1.133 anton 7820: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7821: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7822: prefix@footnote{Some Forth implementations provide a similar scheme by
7823: implementing @code{$} etc. as parsing words that process the subsequent
7824: number in the input stream and push it onto the stack. For example, see
7825: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7826: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7827: is required between the prefix and the number.} before the first digit
1.133 anton 7828: of an (integer) number. The following prefixes are supported:
1.1 anton 7829:
1.26 crook 7830: @itemize @bullet
7831: @item
1.35 anton 7832: @code{&} -- decimal
1.26 crook 7833: @item
1.133 anton 7834: @code{#} -- decimal
7835: @item
1.35 anton 7836: @code{%} -- binary
1.26 crook 7837: @item
1.35 anton 7838: @code{$} -- hexadecimal
1.26 crook 7839: @item
1.133 anton 7840: @code{0x} -- hexadecimal, if base<33.
7841: @item
7842: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7843: optional @code{'} may be present after the character.
1.26 crook 7844: @end itemize
1.1 anton 7845:
1.26 crook 7846: Here are some examples, with the equivalent decimal number shown after
7847: in braces:
1.1 anton 7848:
1.26 crook 7849: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7850: 'A (65),
7851: -'a' (-97),
1.26 crook 7852: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7853:
1.26 crook 7854: @cindex number conversion - traps for the unwary
1.29 crook 7855: @noindent
1.26 crook 7856: Number conversion has a number of traps for the unwary:
1.1 anton 7857:
1.26 crook 7858: @itemize @bullet
7859: @item
7860: You cannot determine the current number base using the code sequence
1.35 anton 7861: @code{base @@ .} -- the number base is always 10 in the current number
7862: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7863: @item
7864: If the number base is set to a value greater than 14 (for example,
7865: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7866: it to be intepreted as either a single-precision integer or a
7867: floating-point number (Gforth treats it as an integer). The ambiguity
7868: can be resolved by explicitly stating the sign of the mantissa and/or
7869: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7870: ambiguity arises; either representation will be treated as a
7871: floating-point number.
7872: @item
1.29 crook 7873: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7874: It is used to specify file types.
7875: @item
1.72 anton 7876: ANS Forth requires the @code{.} of a double-precision number to be the
7877: final character in the string. Gforth allows the @code{.} to be
7878: anywhere after the first digit.
1.26 crook 7879: @item
7880: The number conversion process does not check for overflow.
7881: @item
1.72 anton 7882: In an ANS Forth program @code{base} is required to be decimal when
7883: converting floating-point numbers. In Gforth, number conversion to
7884: floating-point numbers always uses base &10, irrespective of the value
7885: of @code{base}.
1.26 crook 7886: @end itemize
1.1 anton 7887:
1.49 anton 7888: You can read numbers into your programs with the words described in
1.181 anton 7889: @ref{Line input and conversion}.
1.1 anton 7890:
1.82 anton 7891: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7892: @subsection Interpret/Compile states
7893: @cindex Interpret/Compile states
1.1 anton 7894:
1.29 crook 7895: A standard program is not permitted to change @code{state}
7896: explicitly. However, it can change @code{state} implicitly, using the
7897: words @code{[} and @code{]}. When @code{[} is executed it switches
7898: @code{state} to interpret state, and therefore the text interpreter
7899: starts interpreting. When @code{]} is executed it switches @code{state}
7900: to compile state and therefore the text interpreter starts
1.44 crook 7901: compiling. The most common usage for these words is for switching into
7902: interpret state and back from within a colon definition; this technique
1.49 anton 7903: can be used to compile a literal (for an example, @pxref{Literals}) or
7904: for conditional compilation (for an example, @pxref{Interpreter
7905: Directives}).
1.44 crook 7906:
1.35 anton 7907:
7908: @c This is a bad example: It's non-standard, and it's not necessary.
7909: @c However, I can't think of a good example for switching into compile
7910: @c state when there is no current word (@code{state}-smart words are not a
7911: @c good reason). So maybe we should use an example for switching into
7912: @c interpret @code{state} in a colon def. - anton
1.44 crook 7913: @c nac-> I agree. I started out by putting in the example, then realised
7914: @c that it was non-ANS, so wrote more words around it. I hope this
7915: @c re-written version is acceptable to you. I do want to keep the example
7916: @c as it is helpful for showing what is and what is not portable, particularly
7917: @c where it outlaws a style in common use.
7918:
1.72 anton 7919: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7920: @c that, we can also show what's not. In any case, I have written a
7921: @c section Compiling Words which also deals with [ ].
1.35 anton 7922:
1.95 anton 7923: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7924:
1.95 anton 7925: @c @code{[} and @code{]} also give you the ability to switch into compile
7926: @c state and back, but we cannot think of any useful Standard application
7927: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7928:
7929: @c @example
7930: @c : AA ." this is A" ;
7931: @c : BB ." this is B" ;
7932: @c : CC ." this is C" ;
7933:
7934: @c create table ] aa bb cc [
7935:
7936: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7937: @c cells table + @@ execute ;
7938: @c @end example
7939:
7940: @c This example builds a jump table; @code{0 go} will display ``@code{this
7941: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7942: @c defining @code{table} like this:
7943:
7944: @c @example
7945: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7946: @c @end example
7947:
7948: @c The problem with this code is that the definition of @code{table} is not
7949: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7950: @c @i{may} work on systems where code space and data space co-incide, the
7951: @c Standard only allows data space to be assigned for a @code{CREATE}d
7952: @c word. In addition, the Standard only allows @code{@@} to access data
7953: @c space, whilst this example is using it to access code space. The only
7954: @c portable, Standard way to build this table is to build it in data space,
7955: @c like this:
7956:
7957: @c @example
7958: @c create table ' aa , ' bb , ' cc ,
7959: @c @end example
1.29 crook 7960:
1.95 anton 7961: @c doc-state
1.44 crook 7962:
1.29 crook 7963:
1.82 anton 7964: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7965: @subsection Interpreter Directives
7966: @cindex interpreter directives
1.72 anton 7967: @cindex conditional compilation
1.1 anton 7968:
1.29 crook 7969: These words are usually used in interpret state; typically to control
7970: which parts of a source file are processed by the text
1.26 crook 7971: interpreter. There are only a few ANS Forth Standard words, but Gforth
7972: supplements these with a rich set of immediate control structure words
7973: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7974: used in compile state (@pxref{Control Structures}). Typical usages:
7975:
7976: @example
1.72 anton 7977: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7978: .
7979: .
1.72 anton 7980: HAVE-ASSEMBLER [IF]
1.29 crook 7981: : ASSEMBLER-FEATURE
7982: ...
7983: ;
7984: [ENDIF]
7985: .
7986: .
7987: : SEE
7988: ... \ general-purpose SEE code
1.72 anton 7989: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7990: ... \ assembler-specific SEE code
7991: [ [ENDIF] ]
7992: ;
7993: @end example
1.1 anton 7994:
1.44 crook 7995:
1.26 crook 7996: doc-[IF]
7997: doc-[ELSE]
7998: doc-[THEN]
7999: doc-[ENDIF]
1.1 anton 8000:
1.26 crook 8001: doc-[IFDEF]
8002: doc-[IFUNDEF]
1.1 anton 8003:
1.26 crook 8004: doc-[?DO]
8005: doc-[DO]
8006: doc-[FOR]
8007: doc-[LOOP]
8008: doc-[+LOOP]
8009: doc-[NEXT]
1.1 anton 8010:
1.26 crook 8011: doc-[BEGIN]
8012: doc-[UNTIL]
8013: doc-[AGAIN]
8014: doc-[WHILE]
8015: doc-[REPEAT]
1.1 anton 8016:
1.27 crook 8017:
1.26 crook 8018: @c -------------------------------------------------------------
1.111 anton 8019: @node The Input Stream, Word Lists, The Text Interpreter, Words
8020: @section The Input Stream
8021: @cindex input stream
8022:
8023: @c !! integrate this better with the "Text Interpreter" section
8024: The text interpreter reads from the input stream, which can come from
8025: several sources (@pxref{Input Sources}). Some words, in particular
8026: defining words, but also words like @code{'}, read parameters from the
8027: input stream instead of from the stack.
8028:
8029: Such words are called parsing words, because they parse the input
8030: stream. Parsing words are hard to use in other words, because it is
8031: hard to pass program-generated parameters through the input stream.
8032: They also usually have an unintuitive combination of interpretation and
8033: compilation semantics when implemented naively, leading to various
8034: approaches that try to produce a more intuitive behaviour
8035: (@pxref{Combined words}).
8036:
8037: It should be obvious by now that parsing words are a bad idea. If you
8038: want to implement a parsing word for convenience, also provide a factor
8039: of the word that does not parse, but takes the parameters on the stack.
8040: To implement the parsing word on top if it, you can use the following
8041: words:
8042:
8043: @c anton: these belong in the input stream section
8044: doc-parse
1.138 anton 8045: doc-parse-name
1.111 anton 8046: doc-parse-word
8047: doc-name
8048: doc-word
8049: doc-refill
8050:
8051: Conversely, if you have the bad luck (or lack of foresight) to have to
8052: deal with parsing words without having such factors, how do you pass a
8053: string that is not in the input stream to it?
8054:
8055: doc-execute-parsing
8056:
1.146 anton 8057: A definition of this word in ANS Forth is provided in
8058: @file{compat/execute-parsing.fs}.
8059:
1.111 anton 8060: If you want to run a parsing word on a file, the following word should
8061: help:
8062:
8063: doc-execute-parsing-file
8064:
8065: @c -------------------------------------------------------------
8066: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8067: @section Word Lists
8068: @cindex word lists
1.32 anton 8069: @cindex header space
1.1 anton 8070:
1.36 anton 8071: A wordlist is a list of named words; you can add new words and look up
8072: words by name (and you can remove words in a restricted way with
8073: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8074:
8075: @cindex search order stack
8076: The text interpreter searches the wordlists present in the search order
8077: (a stack of wordlists), from the top to the bottom. Within each
8078: wordlist, the search starts conceptually at the newest word; i.e., if
8079: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8080:
1.26 crook 8081: @cindex compilation word list
1.36 anton 8082: New words are added to the @dfn{compilation wordlist} (aka current
8083: wordlist).
1.1 anton 8084:
1.36 anton 8085: @cindex wid
8086: A word list is identified by a cell-sized word list identifier (@i{wid})
8087: in much the same way as a file is identified by a file handle. The
8088: numerical value of the wid has no (portable) meaning, and might change
8089: from session to session.
1.1 anton 8090:
1.29 crook 8091: The ANS Forth ``Search order'' word set is intended to provide a set of
8092: low-level tools that allow various different schemes to be
1.74 anton 8093: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8094: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8095: Forth.
1.1 anton 8096:
1.27 crook 8097: @comment TODO: locals section refers to here, saying that every word list (aka
8098: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8099: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8100:
1.45 crook 8101: @comment TODO: document markers, reveal, tables, mappedwordlist
8102:
8103: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8104: @comment word from the source files, rather than some alias.
1.44 crook 8105:
1.26 crook 8106: doc-forth-wordlist
8107: doc-definitions
8108: doc-get-current
8109: doc-set-current
8110: doc-get-order
1.185 anton 8111: doc-set-order
1.26 crook 8112: doc-wordlist
1.30 anton 8113: doc-table
1.79 anton 8114: doc->order
1.36 anton 8115: doc-previous
1.26 crook 8116: doc-also
1.185 anton 8117: doc-forth
1.26 crook 8118: doc-only
1.185 anton 8119: doc-order
1.15 anton 8120:
1.26 crook 8121: doc-find
8122: doc-search-wordlist
1.15 anton 8123:
1.26 crook 8124: doc-words
8125: doc-vlist
1.44 crook 8126: @c doc-words-deferred
1.1 anton 8127:
1.74 anton 8128: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8129: doc-root
8130: doc-vocabulary
8131: doc-seal
8132: doc-vocs
8133: doc-current
8134: doc-context
1.1 anton 8135:
1.44 crook 8136:
1.26 crook 8137: @menu
1.75 anton 8138: * Vocabularies::
1.67 anton 8139: * Why use word lists?::
1.75 anton 8140: * Word list example::
1.26 crook 8141: @end menu
8142:
1.75 anton 8143: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8144: @subsection Vocabularies
8145: @cindex Vocabularies, detailed explanation
8146:
8147: Here is an example of creating and using a new wordlist using ANS
8148: Forth words:
8149:
8150: @example
8151: wordlist constant my-new-words-wordlist
8152: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8153:
8154: \ add it to the search order
8155: also my-new-words
8156:
8157: \ alternatively, add it to the search order and make it
8158: \ the compilation word list
8159: also my-new-words definitions
8160: \ type "order" to see the problem
8161: @end example
8162:
8163: The problem with this example is that @code{order} has no way to
8164: associate the name @code{my-new-words} with the wid of the word list (in
8165: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8166: that has no associated name). There is no Standard way of associating a
8167: name with a wid.
8168:
8169: In Gforth, this example can be re-coded using @code{vocabulary}, which
8170: associates a name with a wid:
8171:
8172: @example
8173: vocabulary my-new-words
8174:
8175: \ add it to the search order
8176: also my-new-words
8177:
8178: \ alternatively, add it to the search order and make it
8179: \ the compilation word list
8180: my-new-words definitions
8181: \ type "order" to see that the problem is solved
8182: @end example
8183:
8184:
8185: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8186: @subsection Why use word lists?
8187: @cindex word lists - why use them?
8188:
1.74 anton 8189: Here are some reasons why people use wordlists:
1.26 crook 8190:
8191: @itemize @bullet
1.74 anton 8192:
8193: @c anton: Gforth's hashing implementation makes the search speed
8194: @c independent from the number of words. But it is linear with the number
8195: @c of wordlists that have to be searched, so in effect using more wordlists
8196: @c actually slows down compilation.
8197:
8198: @c @item
8199: @c To improve compilation speed by reducing the number of header space
8200: @c entries that must be searched. This is achieved by creating a new
8201: @c word list that contains all of the definitions that are used in the
8202: @c definition of a Forth system but which would not usually be used by
8203: @c programs running on that system. That word list would be on the search
8204: @c list when the Forth system was compiled but would be removed from the
8205: @c search list for normal operation. This can be a useful technique for
8206: @c low-performance systems (for example, 8-bit processors in embedded
8207: @c systems) but is unlikely to be necessary in high-performance desktop
8208: @c systems.
8209:
1.26 crook 8210: @item
8211: To prevent a set of words from being used outside the context in which
8212: they are valid. Two classic examples of this are an integrated editor
8213: (all of the edit commands are defined in a separate word list; the
8214: search order is set to the editor word list when the editor is invoked;
8215: the old search order is restored when the editor is terminated) and an
8216: integrated assembler (the op-codes for the machine are defined in a
8217: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8218:
8219: @item
8220: To organize the words of an application or library into a user-visible
8221: set (in @code{forth-wordlist} or some other common wordlist) and a set
8222: of helper words used just for the implementation (hidden in a separate
1.75 anton 8223: wordlist). This keeps @code{words}' output smaller, separates
8224: implementation and interface, and reduces the chance of name conflicts
8225: within the common wordlist.
1.74 anton 8226:
1.26 crook 8227: @item
8228: To prevent a name-space clash between multiple definitions with the same
8229: name. For example, when building a cross-compiler you might have a word
8230: @code{IF} that generates conditional code for your target system. By
8231: placing this definition in a different word list you can control whether
8232: the host system's @code{IF} or the target system's @code{IF} get used in
8233: any particular context by controlling the order of the word lists on the
8234: search order stack.
1.74 anton 8235:
1.26 crook 8236: @end itemize
1.1 anton 8237:
1.74 anton 8238: The downsides of using wordlists are:
8239:
8240: @itemize
8241:
8242: @item
8243: Debugging becomes more cumbersome.
8244:
8245: @item
8246: Name conflicts worked around with wordlists are still there, and you
8247: have to arrange the search order carefully to get the desired results;
8248: if you forget to do that, you get hard-to-find errors (as in any case
8249: where you read the code differently from the compiler; @code{see} can
1.75 anton 8250: help seeing which of several possible words the name resolves to in such
8251: cases). @code{See} displays just the name of the words, not what
8252: wordlist they belong to, so it might be misleading. Using unique names
8253: is a better approach to avoid name conflicts.
1.74 anton 8254:
8255: @item
8256: You have to explicitly undo any changes to the search order. In many
8257: cases it would be more convenient if this happened implicitly. Gforth
8258: currently does not provide such a feature, but it may do so in the
8259: future.
8260: @end itemize
8261:
8262:
1.75 anton 8263: @node Word list example, , Why use word lists?, Word Lists
8264: @subsection Word list example
8265: @cindex word lists - example
1.1 anton 8266:
1.74 anton 8267: The following example is from the
8268: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8269: garbage collector} and uses wordlists to separate public words from
8270: helper words:
8271:
8272: @example
8273: get-current ( wid )
8274: vocabulary garbage-collector also garbage-collector definitions
8275: ... \ define helper words
8276: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8277: ... \ define the public (i.e., API) words
8278: \ they can refer to the helper words
8279: previous \ restore original search order (helper words become invisible)
8280: @end example
8281:
1.26 crook 8282: @c -------------------------------------------------------------
8283: @node Environmental Queries, Files, Word Lists, Words
8284: @section Environmental Queries
8285: @cindex environmental queries
1.21 crook 8286:
1.26 crook 8287: ANS Forth introduced the idea of ``environmental queries'' as a way
8288: for a program running on a system to determine certain characteristics of the system.
8289: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8290:
1.32 anton 8291: The Standard requires that the header space used for environmental queries
8292: be distinct from the header space used for definitions.
1.21 crook 8293:
1.26 crook 8294: Typically, environmental queries are supported by creating a set of
1.29 crook 8295: definitions in a word list that is @i{only} used during environmental
1.26 crook 8296: queries; that is what Gforth does. There is no Standard way of adding
8297: definitions to the set of recognised environmental queries, but any
8298: implementation that supports the loading of optional word sets must have
8299: some mechanism for doing this (after loading the word set, the
8300: associated environmental query string must return @code{true}). In
8301: Gforth, the word list used to honour environmental queries can be
8302: manipulated just like any other word list.
1.21 crook 8303:
1.44 crook 8304:
1.26 crook 8305: doc-environment?
8306: doc-environment-wordlist
1.21 crook 8307:
1.26 crook 8308: doc-gforth
8309: doc-os-class
1.21 crook 8310:
1.44 crook 8311:
1.26 crook 8312: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8313: returning two items on the stack, querying it using @code{environment?}
8314: will return an additional item; the @code{true} flag that shows that the
8315: string was recognised.
1.21 crook 8316:
1.26 crook 8317: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8318:
1.26 crook 8319: Here are some examples of using environmental queries:
1.21 crook 8320:
1.26 crook 8321: @example
8322: s" address-unit-bits" environment? 0=
8323: [IF]
8324: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8325: [ELSE]
8326: drop \ ensure balanced stack effect
1.26 crook 8327: [THEN]
1.21 crook 8328:
1.75 anton 8329: \ this might occur in the prelude of a standard program that uses THROW
8330: s" exception" environment? [IF]
8331: 0= [IF]
8332: : throw abort" exception thrown" ;
8333: [THEN]
8334: [ELSE] \ we don't know, so make sure
8335: : throw abort" exception thrown" ;
8336: [THEN]
1.21 crook 8337:
1.26 crook 8338: s" gforth" environment? [IF] .( Gforth version ) TYPE
8339: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8340:
8341: \ a program using v*
8342: s" gforth" environment? [IF]
8343: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8344: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8345: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8346: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8347: LOOP
8348: 2drop 2drop ;
8349: [THEN]
8350: [ELSE] \
8351: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8352: ...
8353: [THEN]
1.26 crook 8354: @end example
1.21 crook 8355:
1.26 crook 8356: Here is an example of adding a definition to the environment word list:
1.21 crook 8357:
1.26 crook 8358: @example
8359: get-current environment-wordlist set-current
8360: true constant block
8361: true constant block-ext
8362: set-current
8363: @end example
1.21 crook 8364:
1.26 crook 8365: You can see what definitions are in the environment word list like this:
1.21 crook 8366:
1.26 crook 8367: @example
1.79 anton 8368: environment-wordlist >order words previous
1.26 crook 8369: @end example
1.21 crook 8370:
8371:
1.26 crook 8372: @c -------------------------------------------------------------
8373: @node Files, Blocks, Environmental Queries, Words
8374: @section Files
1.28 crook 8375: @cindex files
8376: @cindex I/O - file-handling
1.21 crook 8377:
1.26 crook 8378: Gforth provides facilities for accessing files that are stored in the
8379: host operating system's file-system. Files that are processed by Gforth
8380: can be divided into two categories:
1.21 crook 8381:
1.23 crook 8382: @itemize @bullet
8383: @item
1.29 crook 8384: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8385: @item
1.29 crook 8386: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8387: @end itemize
8388:
8389: @menu
1.48 anton 8390: * Forth source files::
8391: * General files::
1.167 anton 8392: * Redirection::
1.48 anton 8393: * Search Paths::
1.26 crook 8394: @end menu
8395:
8396: @c -------------------------------------------------------------
8397: @node Forth source files, General files, Files, Files
8398: @subsection Forth source files
8399: @cindex including files
8400: @cindex Forth source files
1.21 crook 8401:
1.26 crook 8402: The simplest way to interpret the contents of a file is to use one of
8403: these two formats:
1.21 crook 8404:
1.26 crook 8405: @example
8406: include mysource.fs
8407: s" mysource.fs" included
8408: @end example
1.21 crook 8409:
1.75 anton 8410: You usually want to include a file only if it is not included already
1.26 crook 8411: (by, say, another source file). In that case, you can use one of these
1.45 crook 8412: three formats:
1.21 crook 8413:
1.26 crook 8414: @example
8415: require mysource.fs
8416: needs mysource.fs
8417: s" mysource.fs" required
8418: @end example
1.21 crook 8419:
1.26 crook 8420: @cindex stack effect of included files
8421: @cindex including files, stack effect
1.45 crook 8422: It is good practice to write your source files such that interpreting them
8423: does not change the stack. Source files designed in this way can be used with
1.26 crook 8424: @code{required} and friends without complications. For example:
1.21 crook 8425:
1.26 crook 8426: @example
1.75 anton 8427: 1024 require foo.fs drop
1.26 crook 8428: @end example
1.21 crook 8429:
1.75 anton 8430: Here you want to pass the argument 1024 (e.g., a buffer size) to
8431: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8432: ), which allows its use with @code{require}. Of course with such
8433: parameters to required files, you have to ensure that the first
8434: @code{require} fits for all uses (i.e., @code{require} it early in the
8435: master load file).
1.44 crook 8436:
1.26 crook 8437: doc-include-file
8438: doc-included
1.28 crook 8439: doc-included?
1.26 crook 8440: doc-include
8441: doc-required
8442: doc-require
8443: doc-needs
1.75 anton 8444: @c doc-init-included-files @c internal
8445: doc-sourcefilename
8446: doc-sourceline#
1.44 crook 8447:
1.26 crook 8448: A definition in ANS Forth for @code{required} is provided in
8449: @file{compat/required.fs}.
1.21 crook 8450:
1.26 crook 8451: @c -------------------------------------------------------------
1.167 anton 8452: @node General files, Redirection, Forth source files, Files
1.26 crook 8453: @subsection General files
8454: @cindex general files
8455: @cindex file-handling
1.21 crook 8456:
1.75 anton 8457: Files are opened/created by name and type. The following file access
8458: methods (FAMs) are recognised:
1.44 crook 8459:
1.75 anton 8460: @cindex fam (file access method)
1.26 crook 8461: doc-r/o
8462: doc-r/w
8463: doc-w/o
8464: doc-bin
1.1 anton 8465:
1.44 crook 8466:
1.26 crook 8467: When a file is opened/created, it returns a file identifier,
1.29 crook 8468: @i{wfileid} that is used for all other file commands. All file
8469: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8470: successful operation and an implementation-defined non-zero value in the
8471: case of an error.
1.21 crook 8472:
1.44 crook 8473:
1.26 crook 8474: doc-open-file
8475: doc-create-file
1.21 crook 8476:
1.26 crook 8477: doc-close-file
8478: doc-delete-file
8479: doc-rename-file
8480: doc-read-file
8481: doc-read-line
1.154 anton 8482: doc-key-file
8483: doc-key?-file
1.26 crook 8484: doc-write-file
8485: doc-write-line
8486: doc-emit-file
8487: doc-flush-file
1.21 crook 8488:
1.26 crook 8489: doc-file-status
8490: doc-file-position
8491: doc-reposition-file
8492: doc-file-size
8493: doc-resize-file
1.21 crook 8494:
1.93 anton 8495: doc-slurp-file
8496: doc-slurp-fid
1.112 anton 8497: doc-stdin
8498: doc-stdout
8499: doc-stderr
1.44 crook 8500:
1.26 crook 8501: @c ---------------------------------------------------------
1.167 anton 8502: @node Redirection, Search Paths, General files, Files
8503: @subsection Redirection
8504: @cindex Redirection
8505: @cindex Input Redirection
8506: @cindex Output Redirection
8507:
8508: You can redirect the output of @code{type} and @code{emit} and all the
8509: words that use them (all output words that don't have an explicit
1.174 anton 8510: target file) to an arbitrary file with the @code{outfile-execute},
8511: used like this:
1.167 anton 8512:
8513: @example
1.174 anton 8514: : some-warning ( n -- )
8515: cr ." warning# " . ;
8516:
1.167 anton 8517: : print-some-warning ( n -- )
1.174 anton 8518: ['] some-warning stderr outfile-execute ;
1.167 anton 8519: @end example
8520:
1.174 anton 8521: After @code{some-warning} is executed, the original output direction
8522: is restored; this construct is safe against exceptions. Similarly,
8523: there is @code{infile-execute} for redirecting the input of @code{key}
8524: and its users (any input word that does not take a file explicitly).
8525:
8526: doc-outfile-execute
8527: doc-infile-execute
1.167 anton 8528:
8529: If you do not want to redirect the input or output to a file, you can
8530: also make use of the fact that @code{key}, @code{emit} and @code{type}
8531: are deferred words (@pxref{Deferred Words}). However, in that case
8532: you have to worry about the restoration and the protection against
8533: exceptions yourself; also, note that for redirecting the output in
8534: this way, you have to redirect both @code{emit} and @code{type}.
8535:
8536: @c ---------------------------------------------------------
8537: @node Search Paths, , Redirection, Files
1.26 crook 8538: @subsection Search Paths
8539: @cindex path for @code{included}
8540: @cindex file search path
8541: @cindex @code{include} search path
8542: @cindex search path for files
1.21 crook 8543:
1.26 crook 8544: If you specify an absolute filename (i.e., a filename starting with
8545: @file{/} or @file{~}, or with @file{:} in the second position (as in
8546: @samp{C:...})) for @code{included} and friends, that file is included
8547: just as you would expect.
1.21 crook 8548:
1.75 anton 8549: If the filename starts with @file{./}, this refers to the directory that
8550: the present file was @code{included} from. This allows files to include
8551: other files relative to their own position (irrespective of the current
8552: working directory or the absolute position). This feature is essential
8553: for libraries consisting of several files, where a file may include
8554: other files from the library. It corresponds to @code{#include "..."}
8555: in C. If the current input source is not a file, @file{.} refers to the
8556: directory of the innermost file being included, or, if there is no file
8557: being included, to the current working directory.
8558:
8559: For relative filenames (not starting with @file{./}), Gforth uses a
8560: search path similar to Forth's search order (@pxref{Word Lists}). It
8561: tries to find the given filename in the directories present in the path,
8562: and includes the first one it finds. There are separate search paths for
8563: Forth source files and general files. If the search path contains the
8564: directory @file{.}, this refers to the directory of the current file, or
8565: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8566:
1.26 crook 8567: Use @file{~+} to refer to the current working directory (as in the
8568: @code{bash}).
1.1 anton 8569:
1.75 anton 8570: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8571:
1.48 anton 8572: @menu
1.75 anton 8573: * Source Search Paths::
1.48 anton 8574: * General Search Paths::
8575: @end menu
8576:
1.26 crook 8577: @c ---------------------------------------------------------
1.75 anton 8578: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8579: @subsubsection Source Search Paths
8580: @cindex search path control, source files
1.5 anton 8581:
1.26 crook 8582: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8583: Gforth}). You can display it and change it using @code{fpath} in
8584: combination with the general path handling words.
1.5 anton 8585:
1.75 anton 8586: doc-fpath
8587: @c the functionality of the following words is easily available through
8588: @c fpath and the general path words. The may go away.
8589: @c doc-.fpath
8590: @c doc-fpath+
8591: @c doc-fpath=
8592: @c doc-open-fpath-file
1.44 crook 8593:
8594: @noindent
1.26 crook 8595: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8596:
1.26 crook 8597: @example
1.75 anton 8598: fpath path= /usr/lib/forth/|./
1.26 crook 8599: require timer.fs
8600: @end example
1.5 anton 8601:
1.75 anton 8602:
1.26 crook 8603: @c ---------------------------------------------------------
1.75 anton 8604: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8605: @subsubsection General Search Paths
1.75 anton 8606: @cindex search path control, source files
1.5 anton 8607:
1.26 crook 8608: Your application may need to search files in several directories, like
8609: @code{included} does. To facilitate this, Gforth allows you to define
8610: and use your own search paths, by providing generic equivalents of the
8611: Forth search path words:
1.5 anton 8612:
1.75 anton 8613: doc-open-path-file
8614: doc-path-allot
8615: doc-clear-path
8616: doc-also-path
1.26 crook 8617: doc-.path
8618: doc-path+
8619: doc-path=
1.5 anton 8620:
1.75 anton 8621: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8622:
1.75 anton 8623: Here's an example of creating an empty search path:
8624: @c
1.26 crook 8625: @example
1.75 anton 8626: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8627: @end example
1.5 anton 8628:
1.26 crook 8629: @c -------------------------------------------------------------
8630: @node Blocks, Other I/O, Files, Words
8631: @section Blocks
1.28 crook 8632: @cindex I/O - blocks
8633: @cindex blocks
8634:
8635: When you run Gforth on a modern desk-top computer, it runs under the
8636: control of an operating system which provides certain services. One of
8637: these services is @var{file services}, which allows Forth source code
8638: and data to be stored in files and read into Gforth (@pxref{Files}).
8639:
8640: Traditionally, Forth has been an important programming language on
8641: systems where it has interfaced directly to the underlying hardware with
8642: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8643: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8644:
8645: A block is a 1024-byte data area, which can be used to hold data or
8646: Forth source code. No structure is imposed on the contents of the
8647: block. A block is identified by its number; blocks are numbered
8648: contiguously from 1 to an implementation-defined maximum.
8649:
8650: A typical system that used blocks but no operating system might use a
8651: single floppy-disk drive for mass storage, with the disks formatted to
8652: provide 256-byte sectors. Blocks would be implemented by assigning the
8653: first four sectors of the disk to block 1, the second four sectors to
8654: block 2 and so on, up to the limit of the capacity of the disk. The disk
8655: would not contain any file system information, just the set of blocks.
8656:
1.29 crook 8657: @cindex blocks file
1.28 crook 8658: On systems that do provide file services, blocks are typically
1.29 crook 8659: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8660: file}. The size of the blocks file will be an exact multiple of 1024
8661: bytes, corresponding to the number of blocks it contains. This is the
8662: mechanism that Gforth uses.
8663:
1.29 crook 8664: @cindex @file{blocks.fb}
1.75 anton 8665: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8666: having specified a blocks file, Gforth defaults to the blocks file
8667: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8668: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8669:
1.29 crook 8670: @cindex block buffers
1.28 crook 8671: When you read and write blocks under program control, Gforth uses a
1.29 crook 8672: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8673: not used when you use @code{load} to interpret the contents of a block.
8674:
1.75 anton 8675: The behaviour of the block buffers is analagous to that of a cache.
8676: Each block buffer has three states:
1.28 crook 8677:
8678: @itemize @bullet
8679: @item
8680: Unassigned
8681: @item
8682: Assigned-clean
8683: @item
8684: Assigned-dirty
8685: @end itemize
8686:
1.29 crook 8687: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8688: block, the block (specified by its block number) must be assigned to a
8689: block buffer.
8690:
8691: The assignment of a block to a block buffer is performed by @code{block}
8692: or @code{buffer}. Use @code{block} when you wish to modify the existing
8693: contents of a block. Use @code{buffer} when you don't care about the
8694: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8695: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8696: with the particular block is already stored in a block buffer due to an
8697: earlier @code{block} command, @code{buffer} will return that block
8698: buffer and the existing contents of the block will be
8699: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8700: block buffer for the block.}.
1.28 crook 8701:
1.47 crook 8702: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8703: @code{buffer}, that block buffer becomes the @i{current block
8704: buffer}. Data may only be manipulated (read or written) within the
8705: current block buffer.
1.47 crook 8706:
8707: When the contents of the current block buffer has been modified it is
1.48 anton 8708: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8709: either abandon the changes (by doing nothing) or mark the block as
8710: changed (assigned-dirty), using @code{update}. Using @code{update} does
8711: not change the blocks file; it simply changes a block buffer's state to
8712: @i{assigned-dirty}. The block will be written implicitly when it's
8713: buffer is needed for another block, or explicitly by @code{flush} or
8714: @code{save-buffers}.
8715:
8716: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8717: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8718: @code{flush}.
1.28 crook 8719:
1.29 crook 8720: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8721: algorithm to assign a block buffer to a block. That means that any
8722: particular block can only be assigned to one specific block buffer,
1.29 crook 8723: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8724: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8725: the new block immediately. If it is @i{assigned-dirty} its current
8726: contents are written back to the blocks file on disk before it is
1.28 crook 8727: allocated to the new block.
8728:
8729: Although no structure is imposed on the contents of a block, it is
8730: traditional to display the contents as 16 lines each of 64 characters. A
8731: block provides a single, continuous stream of input (for example, it
8732: acts as a single parse area) -- there are no end-of-line characters
8733: within a block, and no end-of-file character at the end of a
8734: block. There are two consequences of this:
1.26 crook 8735:
1.28 crook 8736: @itemize @bullet
8737: @item
8738: The last character of one line wraps straight into the first character
8739: of the following line
8740: @item
8741: The word @code{\} -- comment to end of line -- requires special
8742: treatment; in the context of a block it causes all characters until the
8743: end of the current 64-character ``line'' to be ignored.
8744: @end itemize
8745:
8746: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8747: the current blocks file will be extended to the appropriate size and the
1.28 crook 8748: block buffer will be initialised with spaces.
8749:
1.47 crook 8750: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8751: for details) but doesn't encourage the use of blocks; the mechanism is
8752: only provided for backward compatibility -- ANS Forth requires blocks to
8753: be available when files are.
1.28 crook 8754:
8755: Common techniques that are used when working with blocks include:
8756:
8757: @itemize @bullet
8758: @item
8759: A screen editor that allows you to edit blocks without leaving the Forth
8760: environment.
8761: @item
8762: Shadow screens; where every code block has an associated block
8763: containing comments (for example: code in odd block numbers, comments in
8764: even block numbers). Typically, the block editor provides a convenient
8765: mechanism to toggle between code and comments.
8766: @item
8767: Load blocks; a single block (typically block 1) contains a number of
8768: @code{thru} commands which @code{load} the whole of the application.
8769: @end itemize
1.26 crook 8770:
1.29 crook 8771: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8772: integrated into a Forth programming environment.
1.26 crook 8773:
8774: @comment TODO what about errors on open-blocks?
1.44 crook 8775:
1.26 crook 8776: doc-open-blocks
8777: doc-use
1.75 anton 8778: doc-block-offset
1.26 crook 8779: doc-get-block-fid
8780: doc-block-position
1.28 crook 8781:
1.75 anton 8782: doc-list
1.28 crook 8783: doc-scr
8784:
1.184 anton 8785: doc-block
1.28 crook 8786: doc-buffer
8787:
1.75 anton 8788: doc-empty-buffers
8789: doc-empty-buffer
1.26 crook 8790: doc-update
1.28 crook 8791: doc-updated?
1.26 crook 8792: doc-save-buffers
1.75 anton 8793: doc-save-buffer
1.26 crook 8794: doc-flush
1.28 crook 8795:
1.26 crook 8796: doc-load
8797: doc-thru
8798: doc-+load
8799: doc-+thru
1.45 crook 8800: doc---gforthman--->
1.26 crook 8801: doc-block-included
8802:
1.44 crook 8803:
1.26 crook 8804: @c -------------------------------------------------------------
1.126 pazsan 8805: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8806: @section Other I/O
1.28 crook 8807: @cindex I/O - keyboard and display
1.26 crook 8808:
8809: @menu
8810: * Simple numeric output:: Predefined formats
8811: * Formatted numeric output:: Formatted (pictured) output
8812: * String Formats:: How Forth stores strings in memory
1.67 anton 8813: * Displaying characters and strings:: Other stuff
1.175 anton 8814: * Terminal output:: Cursor positioning etc.
1.181 anton 8815: * Single-key input::
8816: * Line input and conversion::
1.112 anton 8817: * Pipes:: How to create your own pipes
1.149 pazsan 8818: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8819: @end menu
8820:
8821: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8822: @subsection Simple numeric output
1.28 crook 8823: @cindex numeric output - simple/free-format
1.5 anton 8824:
1.26 crook 8825: The simplest output functions are those that display numbers from the
8826: data or floating-point stacks. Floating-point output is always displayed
8827: using base 10. Numbers displayed from the data stack use the value stored
8828: in @code{base}.
1.5 anton 8829:
1.44 crook 8830:
1.26 crook 8831: doc-.
8832: doc-dec.
8833: doc-hex.
8834: doc-u.
8835: doc-.r
8836: doc-u.r
8837: doc-d.
8838: doc-ud.
8839: doc-d.r
8840: doc-ud.r
8841: doc-f.
8842: doc-fe.
8843: doc-fs.
1.111 anton 8844: doc-f.rdp
1.44 crook 8845:
1.26 crook 8846: Examples of printing the number 1234.5678E23 in the different floating-point output
8847: formats are shown below:
1.5 anton 8848:
8849: @example
1.26 crook 8850: f. 123456779999999000000000000.
8851: fe. 123.456779999999E24
8852: fs. 1.23456779999999E26
1.5 anton 8853: @end example
8854:
8855:
1.26 crook 8856: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8857: @subsection Formatted numeric output
1.28 crook 8858: @cindex formatted numeric output
1.26 crook 8859: @cindex pictured numeric output
1.28 crook 8860: @cindex numeric output - formatted
1.26 crook 8861:
1.29 crook 8862: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8863: output} for formatted printing of integers. In this technique, digits
8864: are extracted from the number (using the current output radix defined by
8865: @code{base}), converted to ASCII codes and appended to a string that is
8866: built in a scratch-pad area of memory (@pxref{core-idef,
8867: Implementation-defined options, Implementation-defined
8868: options}). Arbitrary characters can be appended to the string during the
8869: extraction process. The completed string is specified by an address
8870: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8871: under program control.
1.5 anton 8872:
1.75 anton 8873: All of the integer output words described in the previous section
8874: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8875: numeric output.
1.5 anton 8876:
1.47 crook 8877: Three important things to remember about pictured numeric output:
1.5 anton 8878:
1.26 crook 8879: @itemize @bullet
8880: @item
1.28 crook 8881: It always operates on double-precision numbers; to display a
1.49 anton 8882: single-precision number, convert it first (for ways of doing this
8883: @pxref{Double precision}).
1.26 crook 8884: @item
1.28 crook 8885: It always treats the double-precision number as though it were
8886: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8887: @item
8888: The string is built up from right to left; least significant digit first.
8889: @end itemize
1.5 anton 8890:
1.44 crook 8891:
1.26 crook 8892: doc-<#
1.47 crook 8893: doc-<<#
1.26 crook 8894: doc-#
8895: doc-#s
8896: doc-hold
8897: doc-sign
8898: doc-#>
1.47 crook 8899: doc-#>>
1.5 anton 8900:
1.26 crook 8901: doc-represent
1.111 anton 8902: doc-f>str-rdp
8903: doc-f>buf-rdp
1.5 anton 8904:
1.44 crook 8905:
8906: @noindent
1.26 crook 8907: Here are some examples of using pictured numeric output:
1.5 anton 8908:
8909: @example
1.26 crook 8910: : my-u. ( u -- )
8911: \ Simplest use of pns.. behaves like Standard u.
8912: 0 \ convert to unsigned double
1.75 anton 8913: <<# \ start conversion
1.26 crook 8914: #s \ convert all digits
8915: #> \ complete conversion
1.75 anton 8916: TYPE SPACE \ display, with trailing space
8917: #>> ; \ release hold area
1.5 anton 8918:
1.26 crook 8919: : cents-only ( u -- )
8920: 0 \ convert to unsigned double
1.75 anton 8921: <<# \ start conversion
1.26 crook 8922: # # \ convert two least-significant digits
8923: #> \ complete conversion, discard other digits
1.75 anton 8924: TYPE SPACE \ display, with trailing space
8925: #>> ; \ release hold area
1.5 anton 8926:
1.26 crook 8927: : dollars-and-cents ( u -- )
8928: 0 \ convert to unsigned double
1.75 anton 8929: <<# \ start conversion
1.26 crook 8930: # # \ convert two least-significant digits
8931: [char] . hold \ insert decimal point
8932: #s \ convert remaining digits
8933: [char] $ hold \ append currency symbol
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: : my-. ( n -- )
8939: \ handling negatives.. behaves like Standard .
8940: s>d \ convert to signed double
8941: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8942: <<# \ start conversion
1.26 crook 8943: #s \ convert all digits
8944: rot sign \ get at sign byte, append "-" if needed
8945: #> \ complete conversion
1.75 anton 8946: TYPE SPACE \ display, with trailing space
8947: #>> ; \ release hold area
1.5 anton 8948:
1.26 crook 8949: : account. ( n -- )
1.75 anton 8950: \ accountants don't like minus signs, they use parentheses
1.26 crook 8951: \ for negative numbers
8952: s>d \ convert to signed double
8953: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8954: <<# \ start conversion
1.26 crook 8955: 2 pick \ get copy of sign byte
8956: 0< IF [char] ) hold THEN \ right-most character of output
8957: #s \ convert all digits
8958: rot \ get at sign byte
8959: 0< IF [char] ( hold THEN
8960: #> \ complete conversion
1.75 anton 8961: TYPE SPACE \ display, with trailing space
8962: #>> ; \ release hold area
8963:
1.5 anton 8964: @end example
8965:
1.26 crook 8966: Here are some examples of using these words:
1.5 anton 8967:
8968: @example
1.26 crook 8969: 1 my-u. 1
8970: hex -1 my-u. decimal FFFFFFFF
8971: 1 cents-only 01
8972: 1234 cents-only 34
8973: 2 dollars-and-cents $0.02
8974: 1234 dollars-and-cents $12.34
8975: 123 my-. 123
8976: -123 my. -123
8977: 123 account. 123
8978: -456 account. (456)
1.5 anton 8979: @end example
8980:
8981:
1.26 crook 8982: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8983: @subsection String Formats
1.27 crook 8984: @cindex strings - see character strings
8985: @cindex character strings - formats
1.28 crook 8986: @cindex I/O - see character strings
1.75 anton 8987: @cindex counted strings
8988:
8989: @c anton: this does not really belong here; maybe the memory section,
8990: @c or the principles chapter
1.26 crook 8991:
1.27 crook 8992: Forth commonly uses two different methods for representing character
8993: strings:
1.26 crook 8994:
8995: @itemize @bullet
8996: @item
8997: @cindex address of counted string
1.45 crook 8998: @cindex counted string
1.29 crook 8999: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9000: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9001: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9002: memory.
9003: @item
1.29 crook 9004: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9005: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9006: first byte of the string.
9007: @end itemize
9008:
9009: ANS Forth encourages the use of the second format when representing
1.75 anton 9010: strings.
1.26 crook 9011:
1.44 crook 9012:
1.26 crook 9013: doc-count
9014:
1.44 crook 9015:
1.49 anton 9016: For words that move, copy and search for strings see @ref{Memory
9017: Blocks}. For words that display characters and strings see
9018: @ref{Displaying characters and strings}.
1.26 crook 9019:
1.175 anton 9020: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9021: @subsection Displaying characters and strings
1.27 crook 9022: @cindex characters - compiling and displaying
9023: @cindex character strings - compiling and displaying
1.26 crook 9024:
9025: This section starts with a glossary of Forth words and ends with a set
9026: of examples.
9027:
9028: doc-bl
9029: doc-space
9030: doc-spaces
9031: doc-emit
9032: doc-toupper
9033: doc-."
9034: doc-.(
1.98 anton 9035: doc-.\"
1.26 crook 9036: doc-type
1.44 crook 9037: doc-typewhite
1.26 crook 9038: doc-cr
1.27 crook 9039: @cindex cursor control
1.26 crook 9040: doc-s"
1.98 anton 9041: doc-s\"
1.26 crook 9042: doc-c"
9043: doc-char
9044: doc-[char]
9045:
1.44 crook 9046:
9047: @noindent
1.26 crook 9048: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9049:
9050: @example
1.26 crook 9051: .( text-1)
9052: : my-word
9053: ." text-2" cr
9054: .( text-3)
9055: ;
9056:
9057: ." text-4"
9058:
9059: : my-char
9060: [char] ALPHABET emit
9061: char emit
9062: ;
1.5 anton 9063: @end example
9064:
1.26 crook 9065: When you load this code into Gforth, the following output is generated:
1.5 anton 9066:
1.26 crook 9067: @example
1.30 anton 9068: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9069: @end example
1.5 anton 9070:
1.26 crook 9071: @itemize @bullet
9072: @item
9073: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9074: is an immediate word; it behaves in the same way whether it is used inside
9075: or outside a colon definition.
9076: @item
9077: Message @code{text-4} is displayed because of Gforth's added interpretation
9078: semantics for @code{."}.
9079: @item
1.29 crook 9080: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9081: performs the compilation semantics for @code{."} within the definition of
9082: @code{my-word}.
9083: @end itemize
1.5 anton 9084:
1.26 crook 9085: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9086:
1.26 crook 9087: @example
1.30 anton 9088: @kbd{my-word @key{RET}} text-2
1.26 crook 9089: ok
1.30 anton 9090: @kbd{my-char fred @key{RET}} Af ok
9091: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9092: @end example
1.5 anton 9093:
9094: @itemize @bullet
9095: @item
1.26 crook 9096: Message @code{text-2} is displayed because of the run-time behaviour of
9097: @code{."}.
9098: @item
9099: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9100: on the stack at run-time. @code{emit} always displays the character
9101: when @code{my-char} is executed.
9102: @item
9103: @code{char} parses a string at run-time and the second @code{emit} displays
9104: the first character of the string.
1.5 anton 9105: @item
1.26 crook 9106: If you type @code{see my-char} you can see that @code{[char]} discarded
9107: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9108: definition of @code{my-char}.
1.5 anton 9109: @end itemize
9110:
9111:
1.181 anton 9112: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9113: @subsection Terminal output
9114: @cindex output to terminal
9115: @cindex terminal output
9116:
9117: If you are outputting to a terminal, you may want to control the
9118: positioning of the cursor:
9119: @cindex cursor positioning
9120:
9121: doc-at-xy
9122:
9123: In order to know where to position the cursor, it is often helpful to
9124: know the size of the screen:
9125: @cindex terminal size
9126:
9127: doc-form
9128:
9129: And sometimes you want to use:
9130: @cindex clear screen
9131:
9132: doc-page
9133:
9134: Note that on non-terminals you should use @code{12 emit}, not
9135: @code{page}, to get a form feed.
9136:
1.5 anton 9137:
1.181 anton 9138: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9139: @subsection Single-key input
9140: @cindex single-key input
9141: @cindex input, single-key
9142:
9143: If you want to get a single printable character, you can use
9144: @code{key}; to check whether a character is available for @code{key},
9145: you can use @code{key?}.
1.5 anton 9146:
1.181 anton 9147: doc-key
9148: doc-key?
1.27 crook 9149:
1.181 anton 9150: If you want to process a mix of printable and non-printable
9151: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9152: produces a keyboard event that you have to convert into a character
9153: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9154:
9155: Typical code for using EKEY looks like this:
9156:
9157: @example
9158: ekey ekey>char if ( c )
9159: ... \ do something with the character
9160: else ekey>fkey if ( key-id )
9161: case
9162: k-up of ... endof
9163: k-f1 of ... endof
9164: k-left k-shift-mask or k-ctrl-mask or of ... endof
9165: ...
9166: endcase
9167: else ( keyboard-event )
9168: drop \ just ignore an unknown keyboard event type
9169: then then
9170: @end example
1.44 crook 9171:
1.45 crook 9172: doc-ekey
1.141 anton 9173: doc-ekey>char
1.181 anton 9174: doc-ekey>fkey
1.45 crook 9175: doc-ekey?
1.141 anton 9176:
1.181 anton 9177: The key identifiers for cursor keys are:
1.141 anton 9178:
9179: doc-k-left
9180: doc-k-right
1.185 anton 9181: doc-k-up
9182: doc-k-down
9183: doc-k-home
9184: doc-k-end
1.141 anton 9185: doc-k-prior
9186: doc-k-next
9187: doc-k-insert
9188: doc-k-delete
9189:
1.181 anton 9190: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9191:
1.181 anton 9192: doc-k-f1
9193: doc-k-f2
9194: doc-k-f3
9195: doc-k-f4
9196: doc-k-f5
9197: doc-k-f6
9198: doc-k-f7
9199: doc-k-f8
9200: doc-k-f9
9201: doc-k-f10
9202: doc-k-f11
9203: doc-k-f12
9204:
9205: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9206:
9207: You can combine these key identifiers with masks for various shift keys:
9208:
9209: doc-k-shift-mask
9210: doc-k-ctrl-mask
9211: doc-k-alt-mask
9212:
9213: Note that, even if a Forth system has @code{ekey>fkey} and the key
9214: identifier words, the keys are not necessarily available or it may not
9215: necessarily be able to report all the keys and all the possible
9216: combinations with shift masks. Therefore, write your programs in such
9217: a way that they are still useful even if the keys and key combinations
9218: cannot be pressed or are not recognized.
9219:
9220: Examples: Older keyboards often do not have an F11 and F12 key. If
9221: you run Gforth in an xterm, the xterm catches a number of combinations
9222: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9223: Gforth currently does not recognize and report combinations with
9224: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9225: above would never be entered).
9226:
9227: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9228: you need the ANSI.SYS driver to get that behaviour); it works by
9229: recognizing the escape sequences that ANSI terminals send when such a
9230: key is pressed. If you have a terminal that sends other escape
9231: sequences, you will not get useful results on Gforth. Other Forth
9232: systems may work in a different way.
9233:
1.200 ! anton 9234: Gforth also provides a few words for outputting names of function
! 9235: keys:
! 9236:
! 9237: doc-fkey.
! 9238: doc-simple-fkey-string
! 9239:
1.181 anton 9240:
9241: @node Line input and conversion, Pipes, Single-key input, Other I/O
9242: @subsection Line input and conversion
9243: @cindex line input from terminal
9244: @cindex input, linewise from terminal
9245: @cindex convertin strings to numbers
9246: @cindex I/O - see input
9247:
9248: For ways of storing character strings in memory see @ref{String Formats}.
9249:
9250: @comment TODO examples for >number >float accept key key? pad parse word refill
9251: @comment then index them
1.141 anton 9252:
9253: Words for inputting one line from the keyboard:
9254:
9255: doc-accept
9256: doc-edit-line
9257:
9258: Conversion words:
9259:
1.143 anton 9260: doc-s>number?
9261: doc-s>unumber?
1.26 crook 9262: doc->number
9263: doc->float
1.143 anton 9264:
1.141 anton 9265:
1.27 crook 9266: @comment obsolescent words..
1.141 anton 9267: Obsolescent input and conversion words:
9268:
1.27 crook 9269: doc-convert
1.26 crook 9270: doc-expect
1.27 crook 9271: doc-span
1.5 anton 9272:
9273:
1.181 anton 9274: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9275: @subsection Pipes
9276: @cindex pipes, creating your own
9277:
9278: In addition to using Gforth in pipes created by other processes
9279: (@pxref{Gforth in pipes}), you can create your own pipe with
9280: @code{open-pipe}, and read from or write to it.
9281:
9282: doc-open-pipe
9283: doc-close-pipe
9284:
9285: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9286: you don't catch this exception, Gforth will catch it and exit, usually
9287: silently (@pxref{Gforth in pipes}). Since you probably do not want
9288: this, you should wrap a @code{catch} or @code{try} block around the code
9289: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9290: problem yourself, and then return to regular processing.
9291:
9292: doc-broken-pipe-error
9293:
1.155 anton 9294: @node Xchars and Unicode, , Pipes, Other I/O
9295: @subsection Xchars and Unicode
1.149 pazsan 9296:
1.188 pazsan 9297: ASCII is only appropriate for the English language. Most western
9298: languages however fit somewhat into the Forth frame, since a byte is
9299: sufficient to encode the few special characters in each (though not
9300: always the same encoding can be used; latin-1 is most widely used,
9301: though). For other languages, different char-sets have to be used,
9302: several of them variable-width. Most prominent representant is
9303: UTF-8. Let's call these extended characters xchars. The primitive
9304: fixed-size characters stored as bytes are called pchars in this
9305: section.
9306:
9307: The xchar words add a few data types:
9308:
9309: @itemize
9310:
9311: @item
9312: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9313: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9314: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9315: character set can be used.
9316:
9317: @item
9318: @var{xc-addr} is the address of an xchar in memory. Alignment
9319: requirements are the same as @var{c-addr}. The memory representation of an
9320: xchar differs from the stack representation, and depends on the
9321: encoding used. An xchar may use a variable number of pchars in memory.
9322:
9323: @item
9324: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9325: @var{xc-addr}, @var{u} pchars long.
9326:
9327: @end itemize
9328:
9329: doc-xc-size
9330: doc-x-size
9331: doc-xc@+
9332: doc-xc!+?
9333: doc-xchar+
9334: doc-xchar-
9335: doc-+x/string
9336: doc-x\string-
9337: doc--trailing-garbage
9338: doc-x-width
9339: doc-xkey
9340: doc-xemit
9341:
9342: There's a new environment query
9343:
9344: doc-xchar-encoding
1.112 anton 9345:
1.121 anton 9346: @node OS command line arguments, Locals, Other I/O, Words
9347: @section OS command line arguments
9348: @cindex OS command line arguments
9349: @cindex command line arguments, OS
9350: @cindex arguments, OS command line
9351:
9352: The usual way to pass arguments to Gforth programs on the command line
9353: is via the @option{-e} option, e.g.
9354:
9355: @example
9356: gforth -e "123 456" foo.fs -e bye
9357: @end example
9358:
9359: However, you may want to interpret the command-line arguments directly.
9360: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9361: through @code{next-arg}:
1.121 anton 9362:
1.123 anton 9363: doc-next-arg
1.121 anton 9364:
1.123 anton 9365: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9366:
9367: @example
9368: : echo ( -- )
1.122 anton 9369: begin
1.123 anton 9370: next-arg 2dup 0 0 d<> while
9371: type space
9372: repeat
9373: 2drop ;
1.121 anton 9374:
9375: echo cr bye
9376: @end example
9377:
9378: This can be invoked with
9379:
9380: @example
9381: gforth echo.fs hello world
9382: @end example
1.123 anton 9383:
9384: and it will print
9385:
9386: @example
9387: hello world
9388: @end example
9389:
9390: The next lower level of dealing with the OS command line are the
9391: following words:
9392:
9393: doc-arg
9394: doc-shift-args
9395:
9396: Finally, at the lowest level Gforth provides the following words:
9397:
9398: doc-argc
9399: doc-argv
1.121 anton 9400:
1.78 anton 9401: @c -------------------------------------------------------------
1.126 pazsan 9402: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9403: @section Locals
9404: @cindex locals
9405:
9406: Local variables can make Forth programming more enjoyable and Forth
9407: programs easier to read. Unfortunately, the locals of ANS Forth are
9408: laden with restrictions. Therefore, we provide not only the ANS Forth
9409: locals wordset, but also our own, more powerful locals wordset (we
9410: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9411:
1.78 anton 9412: The ideas in this section have also been published in M. Anton Ertl,
9413: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9414: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9415:
9416: @menu
1.78 anton 9417: * Gforth locals::
9418: * ANS Forth locals::
1.5 anton 9419: @end menu
9420:
1.78 anton 9421: @node Gforth locals, ANS Forth locals, Locals, Locals
9422: @subsection Gforth locals
9423: @cindex Gforth locals
9424: @cindex locals, Gforth style
1.5 anton 9425:
1.78 anton 9426: Locals can be defined with
1.44 crook 9427:
1.78 anton 9428: @example
9429: @{ local1 local2 ... -- comment @}
9430: @end example
9431: or
9432: @example
9433: @{ local1 local2 ... @}
9434: @end example
1.5 anton 9435:
1.78 anton 9436: E.g.,
9437: @example
9438: : max @{ n1 n2 -- n3 @}
9439: n1 n2 > if
9440: n1
9441: else
9442: n2
9443: endif ;
9444: @end example
1.44 crook 9445:
1.78 anton 9446: The similarity of locals definitions with stack comments is intended. A
9447: locals definition often replaces the stack comment of a word. The order
9448: of the locals corresponds to the order in a stack comment and everything
9449: after the @code{--} is really a comment.
1.77 anton 9450:
1.78 anton 9451: This similarity has one disadvantage: It is too easy to confuse locals
9452: declarations with stack comments, causing bugs and making them hard to
9453: find. However, this problem can be avoided by appropriate coding
9454: conventions: Do not use both notations in the same program. If you do,
9455: they should be distinguished using additional means, e.g. by position.
1.77 anton 9456:
1.78 anton 9457: @cindex types of locals
9458: @cindex locals types
9459: The name of the local may be preceded by a type specifier, e.g.,
9460: @code{F:} for a floating point value:
1.5 anton 9461:
1.78 anton 9462: @example
9463: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9464: \ complex multiplication
9465: Ar Br f* Ai Bi f* f-
9466: Ar Bi f* Ai Br f* f+ ;
9467: @end example
1.44 crook 9468:
1.78 anton 9469: @cindex flavours of locals
9470: @cindex locals flavours
9471: @cindex value-flavoured locals
9472: @cindex variable-flavoured locals
9473: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9474: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9475: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9476: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9477: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9478: produces its address (which becomes invalid when the variable's scope is
9479: left). E.g., the standard word @code{emit} can be defined in terms of
9480: @code{type} like this:
1.5 anton 9481:
1.78 anton 9482: @example
9483: : emit @{ C^ char* -- @}
9484: char* 1 type ;
9485: @end example
1.5 anton 9486:
1.78 anton 9487: @cindex default type of locals
9488: @cindex locals, default type
9489: A local without type specifier is a @code{W:} local. Both flavours of
9490: locals are initialized with values from the data or FP stack.
1.44 crook 9491:
1.78 anton 9492: Currently there is no way to define locals with user-defined data
9493: structures, but we are working on it.
1.5 anton 9494:
1.78 anton 9495: Gforth allows defining locals everywhere in a colon definition. This
9496: poses the following questions:
1.5 anton 9497:
1.78 anton 9498: @menu
9499: * Where are locals visible by name?::
9500: * How long do locals live?::
9501: * Locals programming style::
9502: * Locals implementation::
9503: @end menu
1.44 crook 9504:
1.78 anton 9505: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9506: @subsubsection Where are locals visible by name?
9507: @cindex locals visibility
9508: @cindex visibility of locals
9509: @cindex scope of locals
1.5 anton 9510:
1.78 anton 9511: Basically, the answer is that locals are visible where you would expect
9512: it in block-structured languages, and sometimes a little longer. If you
9513: want to restrict the scope of a local, enclose its definition in
9514: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9515:
9516:
1.78 anton 9517: doc-scope
9518: doc-endscope
1.5 anton 9519:
9520:
1.78 anton 9521: These words behave like control structure words, so you can use them
9522: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9523: arbitrary ways.
1.77 anton 9524:
1.78 anton 9525: If you want a more exact answer to the visibility question, here's the
9526: basic principle: A local is visible in all places that can only be
9527: reached through the definition of the local@footnote{In compiler
9528: construction terminology, all places dominated by the definition of the
9529: local.}. In other words, it is not visible in places that can be reached
9530: without going through the definition of the local. E.g., locals defined
9531: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9532: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9533: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9534:
1.78 anton 9535: The reasoning behind this solution is: We want to have the locals
9536: visible as long as it is meaningful. The user can always make the
9537: visibility shorter by using explicit scoping. In a place that can
9538: only be reached through the definition of a local, the meaning of a
9539: local name is clear. In other places it is not: How is the local
9540: initialized at the control flow path that does not contain the
9541: definition? Which local is meant, if the same name is defined twice in
9542: two independent control flow paths?
1.77 anton 9543:
1.78 anton 9544: This should be enough detail for nearly all users, so you can skip the
9545: rest of this section. If you really must know all the gory details and
9546: options, read on.
1.77 anton 9547:
1.78 anton 9548: In order to implement this rule, the compiler has to know which places
9549: are unreachable. It knows this automatically after @code{AHEAD},
9550: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9551: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9552: compiler that the control flow never reaches that place. If
9553: @code{UNREACHABLE} is not used where it could, the only consequence is
9554: that the visibility of some locals is more limited than the rule above
9555: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9556: lie to the compiler), buggy code will be produced.
1.77 anton 9557:
1.5 anton 9558:
1.78 anton 9559: doc-unreachable
1.5 anton 9560:
1.23 crook 9561:
1.78 anton 9562: Another problem with this rule is that at @code{BEGIN}, the compiler
9563: does not know which locals will be visible on the incoming
9564: back-edge. All problems discussed in the following are due to this
9565: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9566: loops as examples; the discussion also applies to @code{?DO} and other
9567: loops). Perhaps the most insidious example is:
1.26 crook 9568: @example
1.78 anton 9569: AHEAD
9570: BEGIN
9571: x
9572: [ 1 CS-ROLL ] THEN
9573: @{ x @}
9574: ...
9575: UNTIL
1.26 crook 9576: @end example
1.23 crook 9577:
1.78 anton 9578: This should be legal according to the visibility rule. The use of
9579: @code{x} can only be reached through the definition; but that appears
9580: textually below the use.
9581:
9582: From this example it is clear that the visibility rules cannot be fully
9583: implemented without major headaches. Our implementation treats common
9584: cases as advertised and the exceptions are treated in a safe way: The
9585: compiler makes a reasonable guess about the locals visible after a
9586: @code{BEGIN}; if it is too pessimistic, the
9587: user will get a spurious error about the local not being defined; if the
9588: compiler is too optimistic, it will notice this later and issue a
9589: warning. In the case above the compiler would complain about @code{x}
9590: being undefined at its use. You can see from the obscure examples in
9591: this section that it takes quite unusual control structures to get the
9592: compiler into trouble, and even then it will often do fine.
1.23 crook 9593:
1.78 anton 9594: If the @code{BEGIN} is reachable from above, the most optimistic guess
9595: is that all locals visible before the @code{BEGIN} will also be
9596: visible after the @code{BEGIN}. This guess is valid for all loops that
9597: are entered only through the @code{BEGIN}, in particular, for normal
9598: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9599: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9600: compiler. When the branch to the @code{BEGIN} is finally generated by
9601: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9602: warns the user if it was too optimistic:
1.26 crook 9603: @example
1.78 anton 9604: IF
9605: @{ x @}
9606: BEGIN
9607: \ x ?
9608: [ 1 cs-roll ] THEN
9609: ...
9610: UNTIL
1.26 crook 9611: @end example
1.23 crook 9612:
1.78 anton 9613: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9614: optimistically assumes that it lives until the @code{THEN}. It notices
9615: this difference when it compiles the @code{UNTIL} and issues a
9616: warning. The user can avoid the warning, and make sure that @code{x}
9617: is not used in the wrong area by using explicit scoping:
9618: @example
9619: IF
9620: SCOPE
9621: @{ x @}
9622: ENDSCOPE
9623: BEGIN
9624: [ 1 cs-roll ] THEN
9625: ...
9626: UNTIL
9627: @end example
1.23 crook 9628:
1.78 anton 9629: Since the guess is optimistic, there will be no spurious error messages
9630: about undefined locals.
1.44 crook 9631:
1.78 anton 9632: If the @code{BEGIN} is not reachable from above (e.g., after
9633: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9634: optimistic guess, as the locals visible after the @code{BEGIN} may be
9635: defined later. Therefore, the compiler assumes that no locals are
9636: visible after the @code{BEGIN}. However, the user can use
9637: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9638: visible at the BEGIN as at the point where the top control-flow stack
9639: item was created.
1.23 crook 9640:
1.44 crook 9641:
1.78 anton 9642: doc-assume-live
1.26 crook 9643:
1.23 crook 9644:
1.78 anton 9645: @noindent
9646: E.g.,
9647: @example
9648: @{ x @}
9649: AHEAD
9650: ASSUME-LIVE
9651: BEGIN
9652: x
9653: [ 1 CS-ROLL ] THEN
9654: ...
9655: UNTIL
9656: @end example
1.44 crook 9657:
1.78 anton 9658: Other cases where the locals are defined before the @code{BEGIN} can be
9659: handled by inserting an appropriate @code{CS-ROLL} before the
9660: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9661: behind the @code{ASSUME-LIVE}).
1.23 crook 9662:
1.78 anton 9663: Cases where locals are defined after the @code{BEGIN} (but should be
9664: visible immediately after the @code{BEGIN}) can only be handled by
9665: rearranging the loop. E.g., the ``most insidious'' example above can be
9666: arranged into:
9667: @example
9668: BEGIN
9669: @{ x @}
9670: ... 0=
9671: WHILE
9672: x
9673: REPEAT
9674: @end example
1.44 crook 9675:
1.78 anton 9676: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9677: @subsubsection How long do locals live?
9678: @cindex locals lifetime
9679: @cindex lifetime of locals
1.23 crook 9680:
1.78 anton 9681: The right answer for the lifetime question would be: A local lives at
9682: least as long as it can be accessed. For a value-flavoured local this
9683: means: until the end of its visibility. However, a variable-flavoured
9684: local could be accessed through its address far beyond its visibility
9685: scope. Ultimately, this would mean that such locals would have to be
9686: garbage collected. Since this entails un-Forth-like implementation
9687: complexities, I adopted the same cowardly solution as some other
9688: languages (e.g., C): The local lives only as long as it is visible;
9689: afterwards its address is invalid (and programs that access it
9690: afterwards are erroneous).
1.23 crook 9691:
1.78 anton 9692: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9693: @subsubsection Locals programming style
9694: @cindex locals programming style
9695: @cindex programming style, locals
1.23 crook 9696:
1.78 anton 9697: The freedom to define locals anywhere has the potential to change
9698: programming styles dramatically. In particular, the need to use the
9699: return stack for intermediate storage vanishes. Moreover, all stack
9700: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9701: determined arguments) can be eliminated: If the stack items are in the
9702: wrong order, just write a locals definition for all of them; then
9703: write the items in the order you want.
1.23 crook 9704:
1.78 anton 9705: This seems a little far-fetched and eliminating stack manipulations is
9706: unlikely to become a conscious programming objective. Still, the number
9707: of stack manipulations will be reduced dramatically if local variables
9708: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9709: a traditional implementation of @code{max}).
1.23 crook 9710:
1.78 anton 9711: This shows one potential benefit of locals: making Forth programs more
9712: readable. Of course, this benefit will only be realized if the
9713: programmers continue to honour the principle of factoring instead of
9714: using the added latitude to make the words longer.
1.23 crook 9715:
1.78 anton 9716: @cindex single-assignment style for locals
9717: Using @code{TO} can and should be avoided. Without @code{TO},
9718: every value-flavoured local has only a single assignment and many
9719: advantages of functional languages apply to Forth. I.e., programs are
9720: easier to analyse, to optimize and to read: It is clear from the
9721: definition what the local stands for, it does not turn into something
9722: different later.
1.23 crook 9723:
1.78 anton 9724: E.g., a definition using @code{TO} might look like this:
9725: @example
9726: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9727: u1 u2 min 0
9728: ?do
9729: addr1 c@@ addr2 c@@ -
9730: ?dup-if
9731: unloop exit
9732: then
9733: addr1 char+ TO addr1
9734: addr2 char+ TO addr2
9735: loop
9736: u1 u2 - ;
1.26 crook 9737: @end example
1.78 anton 9738: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9739: every loop iteration. @code{strcmp} is a typical example of the
9740: readability problems of using @code{TO}. When you start reading
9741: @code{strcmp}, you think that @code{addr1} refers to the start of the
9742: string. Only near the end of the loop you realize that it is something
9743: else.
1.23 crook 9744:
1.78 anton 9745: This can be avoided by defining two locals at the start of the loop that
9746: are initialized with the right value for the current iteration.
9747: @example
9748: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9749: addr1 addr2
9750: u1 u2 min 0
9751: ?do @{ s1 s2 @}
9752: s1 c@@ s2 c@@ -
9753: ?dup-if
9754: unloop exit
9755: then
9756: s1 char+ s2 char+
9757: loop
9758: 2drop
9759: u1 u2 - ;
9760: @end example
9761: Here it is clear from the start that @code{s1} has a different value
9762: in every loop iteration.
1.23 crook 9763:
1.78 anton 9764: @node Locals implementation, , Locals programming style, Gforth locals
9765: @subsubsection Locals implementation
9766: @cindex locals implementation
9767: @cindex implementation of locals
1.23 crook 9768:
1.78 anton 9769: @cindex locals stack
9770: Gforth uses an extra locals stack. The most compelling reason for
9771: this is that the return stack is not float-aligned; using an extra stack
9772: also eliminates the problems and restrictions of using the return stack
9773: as locals stack. Like the other stacks, the locals stack grows toward
9774: lower addresses. A few primitives allow an efficient implementation:
9775:
9776:
9777: doc-@local#
9778: doc-f@local#
9779: doc-laddr#
9780: doc-lp+!#
9781: doc-lp!
9782: doc->l
9783: doc-f>l
9784:
9785:
9786: In addition to these primitives, some specializations of these
9787: primitives for commonly occurring inline arguments are provided for
9788: efficiency reasons, e.g., @code{@@local0} as specialization of
9789: @code{@@local#} for the inline argument 0. The following compiling words
9790: compile the right specialized version, or the general version, as
9791: appropriate:
1.23 crook 9792:
1.5 anton 9793:
1.107 dvdkhlng 9794: @c doc-compile-@local
9795: @c doc-compile-f@local
1.78 anton 9796: doc-compile-lp+!
1.5 anton 9797:
9798:
1.78 anton 9799: Combinations of conditional branches and @code{lp+!#} like
9800: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9801: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9802:
1.78 anton 9803: A special area in the dictionary space is reserved for keeping the
9804: local variable names. @code{@{} switches the dictionary pointer to this
9805: area and @code{@}} switches it back and generates the locals
9806: initializing code. @code{W:} etc.@ are normal defining words. This
9807: special area is cleared at the start of every colon definition.
1.5 anton 9808:
1.78 anton 9809: @cindex word list for defining locals
9810: A special feature of Gforth's dictionary is used to implement the
9811: definition of locals without type specifiers: every word list (aka
9812: vocabulary) has its own methods for searching
9813: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9814: with a special search method: When it is searched for a word, it
9815: actually creates that word using @code{W:}. @code{@{} changes the search
9816: order to first search the word list containing @code{@}}, @code{W:} etc.,
9817: and then the word list for defining locals without type specifiers.
1.5 anton 9818:
1.78 anton 9819: The lifetime rules support a stack discipline within a colon
9820: definition: The lifetime of a local is either nested with other locals
9821: lifetimes or it does not overlap them.
1.23 crook 9822:
1.78 anton 9823: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9824: pointer manipulation is generated. Between control structure words
9825: locals definitions can push locals onto the locals stack. @code{AGAIN}
9826: is the simplest of the other three control flow words. It has to
9827: restore the locals stack depth of the corresponding @code{BEGIN}
9828: before branching. The code looks like this:
9829: @format
9830: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9831: @code{branch} <begin>
9832: @end format
1.26 crook 9833:
1.78 anton 9834: @code{UNTIL} is a little more complicated: If it branches back, it
9835: must adjust the stack just like @code{AGAIN}. But if it falls through,
9836: the locals stack must not be changed. The compiler generates the
9837: following code:
9838: @format
9839: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9840: @end format
9841: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9842:
1.78 anton 9843: @code{THEN} can produce somewhat inefficient code:
9844: @format
9845: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9846: <orig target>:
9847: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9848: @end format
9849: The second @code{lp+!#} adjusts the locals stack pointer from the
9850: level at the @i{orig} point to the level after the @code{THEN}. The
9851: first @code{lp+!#} adjusts the locals stack pointer from the current
9852: level to the level at the orig point, so the complete effect is an
9853: adjustment from the current level to the right level after the
9854: @code{THEN}.
1.26 crook 9855:
1.78 anton 9856: @cindex locals information on the control-flow stack
9857: @cindex control-flow stack items, locals information
9858: In a conventional Forth implementation a dest control-flow stack entry
9859: is just the target address and an orig entry is just the address to be
9860: patched. Our locals implementation adds a word list to every orig or dest
9861: item. It is the list of locals visible (or assumed visible) at the point
9862: described by the entry. Our implementation also adds a tag to identify
9863: the kind of entry, in particular to differentiate between live and dead
9864: (reachable and unreachable) orig entries.
1.26 crook 9865:
1.78 anton 9866: A few unusual operations have to be performed on locals word lists:
1.44 crook 9867:
1.5 anton 9868:
1.78 anton 9869: doc-common-list
9870: doc-sub-list?
9871: doc-list-size
1.52 anton 9872:
9873:
1.78 anton 9874: Several features of our locals word list implementation make these
9875: operations easy to implement: The locals word lists are organised as
9876: linked lists; the tails of these lists are shared, if the lists
9877: contain some of the same locals; and the address of a name is greater
9878: than the address of the names behind it in the list.
1.5 anton 9879:
1.78 anton 9880: Another important implementation detail is the variable
9881: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9882: determine if they can be reached directly or only through the branch
9883: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9884: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9885: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9886:
1.78 anton 9887: Counted loops are similar to other loops in most respects, but
9888: @code{LEAVE} requires special attention: It performs basically the same
9889: service as @code{AHEAD}, but it does not create a control-flow stack
9890: entry. Therefore the information has to be stored elsewhere;
9891: traditionally, the information was stored in the target fields of the
9892: branches created by the @code{LEAVE}s, by organizing these fields into a
9893: linked list. Unfortunately, this clever trick does not provide enough
9894: space for storing our extended control flow information. Therefore, we
9895: introduce another stack, the leave stack. It contains the control-flow
9896: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9897:
1.78 anton 9898: Local names are kept until the end of the colon definition, even if
9899: they are no longer visible in any control-flow path. In a few cases
9900: this may lead to increased space needs for the locals name area, but
9901: usually less than reclaiming this space would cost in code size.
1.5 anton 9902:
1.44 crook 9903:
1.78 anton 9904: @node ANS Forth locals, , Gforth locals, Locals
9905: @subsection ANS Forth locals
9906: @cindex locals, ANS Forth style
1.5 anton 9907:
1.78 anton 9908: The ANS Forth locals wordset does not define a syntax for locals, but
9909: words that make it possible to define various syntaxes. One of the
9910: possible syntaxes is a subset of the syntax we used in the Gforth locals
9911: wordset, i.e.:
1.29 crook 9912:
9913: @example
1.78 anton 9914: @{ local1 local2 ... -- comment @}
9915: @end example
9916: @noindent
9917: or
9918: @example
9919: @{ local1 local2 ... @}
1.29 crook 9920: @end example
9921:
1.78 anton 9922: The order of the locals corresponds to the order in a stack comment. The
9923: restrictions are:
1.5 anton 9924:
1.78 anton 9925: @itemize @bullet
9926: @item
9927: Locals can only be cell-sized values (no type specifiers are allowed).
9928: @item
9929: Locals can be defined only outside control structures.
9930: @item
9931: Locals can interfere with explicit usage of the return stack. For the
9932: exact (and long) rules, see the standard. If you don't use return stack
9933: accessing words in a definition using locals, you will be all right. The
9934: purpose of this rule is to make locals implementation on the return
9935: stack easier.
9936: @item
9937: The whole definition must be in one line.
9938: @end itemize
1.5 anton 9939:
1.78 anton 9940: Locals defined in ANS Forth behave like @code{VALUE}s
9941: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9942: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9943:
1.78 anton 9944: Since the syntax above is supported by Gforth directly, you need not do
9945: anything to use it. If you want to port a program using this syntax to
9946: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9947: syntax on the other system.
1.5 anton 9948:
1.78 anton 9949: Note that a syntax shown in the standard, section A.13 looks
9950: similar, but is quite different in having the order of locals
9951: reversed. Beware!
1.5 anton 9952:
1.78 anton 9953: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9954:
1.78 anton 9955: doc-(local)
1.5 anton 9956:
1.78 anton 9957: The ANS Forth locals extension wordset defines a syntax using
9958: @code{locals|}, but it is so awful that we strongly recommend not to use
9959: it. We have implemented this syntax to make porting to Gforth easy, but
9960: do not document it here. The problem with this syntax is that the locals
9961: are defined in an order reversed with respect to the standard stack
9962: comment notation, making programs harder to read, and easier to misread
9963: and miswrite. The only merit of this syntax is that it is easy to
9964: implement using the ANS Forth locals wordset.
1.53 anton 9965:
9966:
1.78 anton 9967: @c ----------------------------------------------------------
9968: @node Structures, Object-oriented Forth, Locals, Words
9969: @section Structures
9970: @cindex structures
9971: @cindex records
1.53 anton 9972:
1.78 anton 9973: This section presents the structure package that comes with Gforth. A
9974: version of the package implemented in ANS Forth is available in
9975: @file{compat/struct.fs}. This package was inspired by a posting on
9976: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9977: possibly John Hayes). A version of this section has been published in
9978: M. Anton Ertl,
9979: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9980: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9981: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9982:
1.78 anton 9983: @menu
9984: * Why explicit structure support?::
9985: * Structure Usage::
9986: * Structure Naming Convention::
9987: * Structure Implementation::
9988: * Structure Glossary::
1.183 anton 9989: * Forth200x Structures::
1.78 anton 9990: @end menu
1.55 anton 9991:
1.78 anton 9992: @node Why explicit structure support?, Structure Usage, Structures, Structures
9993: @subsection Why explicit structure support?
1.53 anton 9994:
1.78 anton 9995: @cindex address arithmetic for structures
9996: @cindex structures using address arithmetic
9997: If we want to use a structure containing several fields, we could simply
9998: reserve memory for it, and access the fields using address arithmetic
9999: (@pxref{Address arithmetic}). As an example, consider a structure with
10000: the following fields
1.57 anton 10001:
1.78 anton 10002: @table @code
10003: @item a
10004: is a float
10005: @item b
10006: is a cell
10007: @item c
10008: is a float
10009: @end table
1.57 anton 10010:
1.78 anton 10011: Given the (float-aligned) base address of the structure we get the
10012: address of the field
1.52 anton 10013:
1.78 anton 10014: @table @code
10015: @item a
10016: without doing anything further.
10017: @item b
10018: with @code{float+}
10019: @item c
10020: with @code{float+ cell+ faligned}
10021: @end table
1.52 anton 10022:
1.78 anton 10023: It is easy to see that this can become quite tiring.
1.52 anton 10024:
1.78 anton 10025: Moreover, it is not very readable, because seeing a
10026: @code{cell+} tells us neither which kind of structure is
10027: accessed nor what field is accessed; we have to somehow infer the kind
10028: of structure, and then look up in the documentation, which field of
10029: that structure corresponds to that offset.
1.53 anton 10030:
1.78 anton 10031: Finally, this kind of address arithmetic also causes maintenance
10032: troubles: If you add or delete a field somewhere in the middle of the
10033: structure, you have to find and change all computations for the fields
10034: afterwards.
1.52 anton 10035:
1.78 anton 10036: So, instead of using @code{cell+} and friends directly, how
10037: about storing the offsets in constants:
1.52 anton 10038:
1.78 anton 10039: @example
10040: 0 constant a-offset
10041: 0 float+ constant b-offset
10042: 0 float+ cell+ faligned c-offset
10043: @end example
1.64 pazsan 10044:
1.78 anton 10045: Now we can get the address of field @code{x} with @code{x-offset
10046: +}. This is much better in all respects. Of course, you still
10047: have to change all later offset definitions if you add a field. You can
10048: fix this by declaring the offsets in the following way:
1.57 anton 10049:
1.78 anton 10050: @example
10051: 0 constant a-offset
10052: a-offset float+ constant b-offset
10053: b-offset cell+ faligned constant c-offset
10054: @end example
1.57 anton 10055:
1.78 anton 10056: Since we always use the offsets with @code{+}, we could use a defining
10057: word @code{cfield} that includes the @code{+} in the action of the
10058: defined word:
1.64 pazsan 10059:
1.78 anton 10060: @example
10061: : cfield ( n "name" -- )
10062: create ,
10063: does> ( name execution: addr1 -- addr2 )
10064: @@ + ;
1.64 pazsan 10065:
1.78 anton 10066: 0 cfield a
10067: 0 a float+ cfield b
10068: 0 b cell+ faligned cfield c
10069: @end example
1.64 pazsan 10070:
1.78 anton 10071: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10072:
1.78 anton 10073: The structure field words now can be used quite nicely. However,
10074: their definition is still a bit cumbersome: We have to repeat the
10075: name, the information about size and alignment is distributed before
10076: and after the field definitions etc. The structure package presented
10077: here addresses these problems.
1.64 pazsan 10078:
1.78 anton 10079: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10080: @subsection Structure Usage
10081: @cindex structure usage
1.57 anton 10082:
1.78 anton 10083: @cindex @code{field} usage
10084: @cindex @code{struct} usage
10085: @cindex @code{end-struct} usage
10086: You can define a structure for a (data-less) linked list with:
1.57 anton 10087: @example
1.78 anton 10088: struct
10089: cell% field list-next
10090: end-struct list%
1.57 anton 10091: @end example
10092:
1.78 anton 10093: With the address of the list node on the stack, you can compute the
10094: address of the field that contains the address of the next node with
10095: @code{list-next}. E.g., you can determine the length of a list
10096: with:
1.57 anton 10097:
10098: @example
1.78 anton 10099: : list-length ( list -- n )
10100: \ "list" is a pointer to the first element of a linked list
10101: \ "n" is the length of the list
10102: 0 BEGIN ( list1 n1 )
10103: over
10104: WHILE ( list1 n1 )
10105: 1+ swap list-next @@ swap
10106: REPEAT
10107: nip ;
1.57 anton 10108: @end example
10109:
1.78 anton 10110: You can reserve memory for a list node in the dictionary with
10111: @code{list% %allot}, which leaves the address of the list node on the
10112: stack. For the equivalent allocation on the heap you can use @code{list%
10113: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10114: use @code{list% %allocate}). You can get the the size of a list
10115: node with @code{list% %size} and its alignment with @code{list%
10116: %alignment}.
10117:
10118: Note that in ANS Forth the body of a @code{create}d word is
10119: @code{aligned} but not necessarily @code{faligned};
10120: therefore, if you do a:
1.57 anton 10121:
10122: @example
1.78 anton 10123: create @emph{name} foo% %allot drop
1.57 anton 10124: @end example
10125:
1.78 anton 10126: @noindent
10127: then the memory alloted for @code{foo%} is guaranteed to start at the
10128: body of @code{@emph{name}} only if @code{foo%} contains only character,
10129: cell and double fields. Therefore, if your structure contains floats,
10130: better use
1.57 anton 10131:
10132: @example
1.78 anton 10133: foo% %allot constant @emph{name}
1.57 anton 10134: @end example
10135:
1.78 anton 10136: @cindex structures containing structures
10137: You can include a structure @code{foo%} as a field of
10138: another structure, like this:
1.65 anton 10139: @example
1.78 anton 10140: struct
10141: ...
10142: foo% field ...
10143: ...
10144: end-struct ...
1.65 anton 10145: @end example
1.52 anton 10146:
1.78 anton 10147: @cindex structure extension
10148: @cindex extended records
10149: Instead of starting with an empty structure, you can extend an
10150: existing structure. E.g., a plain linked list without data, as defined
10151: above, is hardly useful; You can extend it to a linked list of integers,
10152: like this:@footnote{This feature is also known as @emph{extended
10153: records}. It is the main innovation in the Oberon language; in other
10154: words, adding this feature to Modula-2 led Wirth to create a new
10155: language, write a new compiler etc. Adding this feature to Forth just
10156: required a few lines of code.}
1.52 anton 10157:
1.78 anton 10158: @example
10159: list%
10160: cell% field intlist-int
10161: end-struct intlist%
10162: @end example
1.55 anton 10163:
1.78 anton 10164: @code{intlist%} is a structure with two fields:
10165: @code{list-next} and @code{intlist-int}.
1.55 anton 10166:
1.78 anton 10167: @cindex structures containing arrays
10168: You can specify an array type containing @emph{n} elements of
10169: type @code{foo%} like this:
1.55 anton 10170:
10171: @example
1.78 anton 10172: foo% @emph{n} *
1.56 anton 10173: @end example
1.55 anton 10174:
1.78 anton 10175: You can use this array type in any place where you can use a normal
10176: type, e.g., when defining a @code{field}, or with
10177: @code{%allot}.
10178:
10179: @cindex first field optimization
10180: The first field is at the base address of a structure and the word for
10181: this field (e.g., @code{list-next}) actually does not change the address
10182: on the stack. You may be tempted to leave it away in the interest of
10183: run-time and space efficiency. This is not necessary, because the
10184: structure package optimizes this case: If you compile a first-field
10185: words, no code is generated. So, in the interest of readability and
10186: maintainability you should include the word for the field when accessing
10187: the field.
1.52 anton 10188:
10189:
1.78 anton 10190: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10191: @subsection Structure Naming Convention
10192: @cindex structure naming convention
1.52 anton 10193:
1.78 anton 10194: The field names that come to (my) mind are often quite generic, and,
10195: if used, would cause frequent name clashes. E.g., many structures
10196: probably contain a @code{counter} field. The structure names
10197: that come to (my) mind are often also the logical choice for the names
10198: of words that create such a structure.
1.52 anton 10199:
1.78 anton 10200: Therefore, I have adopted the following naming conventions:
1.52 anton 10201:
1.78 anton 10202: @itemize @bullet
10203: @cindex field naming convention
10204: @item
10205: The names of fields are of the form
10206: @code{@emph{struct}-@emph{field}}, where
10207: @code{@emph{struct}} is the basic name of the structure, and
10208: @code{@emph{field}} is the basic name of the field. You can
10209: think of field words as converting the (address of the)
10210: structure into the (address of the) field.
1.52 anton 10211:
1.78 anton 10212: @cindex structure naming convention
10213: @item
10214: The names of structures are of the form
10215: @code{@emph{struct}%}, where
10216: @code{@emph{struct}} is the basic name of the structure.
10217: @end itemize
1.52 anton 10218:
1.78 anton 10219: This naming convention does not work that well for fields of extended
10220: structures; e.g., the integer list structure has a field
10221: @code{intlist-int}, but has @code{list-next}, not
10222: @code{intlist-next}.
1.53 anton 10223:
1.78 anton 10224: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10225: @subsection Structure Implementation
10226: @cindex structure implementation
10227: @cindex implementation of structures
1.52 anton 10228:
1.78 anton 10229: The central idea in the implementation is to pass the data about the
10230: structure being built on the stack, not in some global
10231: variable. Everything else falls into place naturally once this design
10232: decision is made.
1.53 anton 10233:
1.78 anton 10234: The type description on the stack is of the form @emph{align
10235: size}. Keeping the size on the top-of-stack makes dealing with arrays
10236: very simple.
1.53 anton 10237:
1.78 anton 10238: @code{field} is a defining word that uses @code{Create}
10239: and @code{DOES>}. The body of the field contains the offset
10240: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10241:
10242: @example
1.78 anton 10243: @@ +
1.53 anton 10244: @end example
10245:
1.78 anton 10246: @noindent
10247: i.e., add the offset to the address, giving the stack effect
10248: @i{addr1 -- addr2} for a field.
10249:
10250: @cindex first field optimization, implementation
10251: This simple structure is slightly complicated by the optimization
10252: for fields with offset 0, which requires a different
10253: @code{DOES>}-part (because we cannot rely on there being
10254: something on the stack if such a field is invoked during
10255: compilation). Therefore, we put the different @code{DOES>}-parts
10256: in separate words, and decide which one to invoke based on the
10257: offset. For a zero offset, the field is basically a noop; it is
10258: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10259:
1.183 anton 10260: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10261: @subsection Structure Glossary
10262: @cindex structure glossary
1.53 anton 10263:
1.5 anton 10264:
1.78 anton 10265: doc-%align
10266: doc-%alignment
10267: doc-%alloc
10268: doc-%allocate
10269: doc-%allot
10270: doc-cell%
10271: doc-char%
10272: doc-dfloat%
10273: doc-double%
10274: doc-end-struct
10275: doc-field
10276: doc-float%
10277: doc-naligned
10278: doc-sfloat%
10279: doc-%size
10280: doc-struct
1.54 anton 10281:
10282:
1.183 anton 10283: @node Forth200x Structures, , Structure Glossary, Structures
10284: @subsection Forth200x Structures
10285: @cindex Structures in Forth200x
10286:
10287: The Forth 200x standard defines a slightly less convenient form of
10288: structures. In general (when using @code{field+}, you have to perform
10289: the alignment yourself, but there are a number of convenience words
10290: (e.g., @code{field:} that perform the alignment for you.
10291:
10292: A typical usage example is:
10293:
10294: @example
10295: 0
10296: field: s-a
10297: faligned 2 floats +field s-b
10298: constant s-struct
10299: @end example
10300:
10301: An alternative way of writing this structure is:
10302:
10303: @example
10304: begin-structure s-struct
10305: field: s-a
10306: faligned 2 floats +field s-b
10307: end-structure
10308: @end example
10309:
10310: doc-begin-structure
10311: doc-end-structure
10312: doc-+field
10313: doc-cfield:
10314: doc-field:
10315: doc-2field:
10316: doc-ffield:
10317: doc-sffield:
10318: doc-dffield:
10319:
1.26 crook 10320: @c -------------------------------------------------------------
1.78 anton 10321: @node Object-oriented Forth, Programming Tools, Structures, Words
10322: @section Object-oriented Forth
10323:
10324: Gforth comes with three packages for object-oriented programming:
10325: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10326: is preloaded, so you have to @code{include} them before use. The most
10327: important differences between these packages (and others) are discussed
10328: in @ref{Comparison with other object models}. All packages are written
10329: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10330:
1.78 anton 10331: @menu
10332: * Why object-oriented programming?::
10333: * Object-Oriented Terminology::
10334: * Objects::
10335: * OOF::
10336: * Mini-OOF::
10337: * Comparison with other object models::
10338: @end menu
1.5 anton 10339:
1.78 anton 10340: @c ----------------------------------------------------------------
10341: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10342: @subsection Why object-oriented programming?
10343: @cindex object-oriented programming motivation
10344: @cindex motivation for object-oriented programming
1.44 crook 10345:
1.78 anton 10346: Often we have to deal with several data structures (@emph{objects}),
10347: that have to be treated similarly in some respects, but differently in
10348: others. Graphical objects are the textbook example: circles, triangles,
10349: dinosaurs, icons, and others, and we may want to add more during program
10350: development. We want to apply some operations to any graphical object,
10351: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10352: has to do something different for every kind of object.
10353: @comment TODO add some other operations eg perimeter, area
10354: @comment and tie in to concrete examples later..
1.5 anton 10355:
1.78 anton 10356: We could implement @code{draw} as a big @code{CASE}
10357: control structure that executes the appropriate code depending on the
10358: kind of object to be drawn. This would be not be very elegant, and,
10359: moreover, we would have to change @code{draw} every time we add
10360: a new kind of graphical object (say, a spaceship).
1.44 crook 10361:
1.78 anton 10362: What we would rather do is: When defining spaceships, we would tell
10363: the system: ``Here's how you @code{draw} a spaceship; you figure
10364: out the rest''.
1.5 anton 10365:
1.78 anton 10366: This is the problem that all systems solve that (rightfully) call
10367: themselves object-oriented; the object-oriented packages presented here
10368: solve this problem (and not much else).
10369: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10370:
1.78 anton 10371: @c ------------------------------------------------------------------------
10372: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10373: @subsection Object-Oriented Terminology
10374: @cindex object-oriented terminology
10375: @cindex terminology for object-oriented programming
1.5 anton 10376:
1.78 anton 10377: This section is mainly for reference, so you don't have to understand
10378: all of it right away. The terminology is mainly Smalltalk-inspired. In
10379: short:
1.44 crook 10380:
1.78 anton 10381: @table @emph
10382: @cindex class
10383: @item class
10384: a data structure definition with some extras.
1.5 anton 10385:
1.78 anton 10386: @cindex object
10387: @item object
10388: an instance of the data structure described by the class definition.
1.5 anton 10389:
1.78 anton 10390: @cindex instance variables
10391: @item instance variables
10392: fields of the data structure.
1.5 anton 10393:
1.78 anton 10394: @cindex selector
10395: @cindex method selector
10396: @cindex virtual function
10397: @item selector
10398: (or @emph{method selector}) a word (e.g.,
10399: @code{draw}) that performs an operation on a variety of data
10400: structures (classes). A selector describes @emph{what} operation to
10401: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10402:
1.78 anton 10403: @cindex method
10404: @item method
10405: the concrete definition that performs the operation
10406: described by the selector for a specific class. A method specifies
10407: @emph{how} the operation is performed for a specific class.
1.5 anton 10408:
1.78 anton 10409: @cindex selector invocation
10410: @cindex message send
10411: @cindex invoking a selector
10412: @item selector invocation
10413: a call of a selector. One argument of the call (the TOS (top-of-stack))
10414: is used for determining which method is used. In Smalltalk terminology:
10415: a message (consisting of the selector and the other arguments) is sent
10416: to the object.
1.5 anton 10417:
1.78 anton 10418: @cindex receiving object
10419: @item receiving object
10420: the object used for determining the method executed by a selector
10421: invocation. In the @file{objects.fs} model, it is the object that is on
10422: the TOS when the selector is invoked. (@emph{Receiving} comes from
10423: the Smalltalk @emph{message} terminology.)
1.5 anton 10424:
1.78 anton 10425: @cindex child class
10426: @cindex parent class
10427: @cindex inheritance
10428: @item child class
10429: a class that has (@emph{inherits}) all properties (instance variables,
10430: selectors, methods) from a @emph{parent class}. In Smalltalk
10431: terminology: The subclass inherits from the superclass. In C++
10432: terminology: The derived class inherits from the base class.
1.5 anton 10433:
1.78 anton 10434: @end table
1.5 anton 10435:
1.78 anton 10436: @c If you wonder about the message sending terminology, it comes from
10437: @c a time when each object had it's own task and objects communicated via
10438: @c message passing; eventually the Smalltalk developers realized that
10439: @c they can do most things through simple (indirect) calls. They kept the
10440: @c terminology.
1.5 anton 10441:
1.78 anton 10442: @c --------------------------------------------------------------
10443: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10444: @subsection The @file{objects.fs} model
10445: @cindex objects
10446: @cindex object-oriented programming
1.26 crook 10447:
1.78 anton 10448: @cindex @file{objects.fs}
10449: @cindex @file{oof.fs}
1.26 crook 10450:
1.78 anton 10451: This section describes the @file{objects.fs} package. This material also
10452: has been published in M. Anton Ertl,
10453: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10454: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10455: 37--43.
10456: @c McKewan's and Zsoter's packages
1.26 crook 10457:
1.78 anton 10458: This section assumes that you have read @ref{Structures}.
1.5 anton 10459:
1.78 anton 10460: The techniques on which this model is based have been used to implement
10461: the parser generator, Gray, and have also been used in Gforth for
10462: implementing the various flavours of word lists (hashed or not,
10463: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10464:
10465:
1.26 crook 10466: @menu
1.78 anton 10467: * Properties of the Objects model::
10468: * Basic Objects Usage::
10469: * The Objects base class::
10470: * Creating objects::
10471: * Object-Oriented Programming Style::
10472: * Class Binding::
10473: * Method conveniences::
10474: * Classes and Scoping::
10475: * Dividing classes::
10476: * Object Interfaces::
10477: * Objects Implementation::
10478: * Objects Glossary::
1.26 crook 10479: @end menu
1.5 anton 10480:
1.78 anton 10481: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10482:
1.78 anton 10483: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10484: @subsubsection Properties of the @file{objects.fs} model
10485: @cindex @file{objects.fs} properties
1.5 anton 10486:
1.78 anton 10487: @itemize @bullet
10488: @item
10489: It is straightforward to pass objects on the stack. Passing
10490: selectors on the stack is a little less convenient, but possible.
1.44 crook 10491:
1.78 anton 10492: @item
10493: Objects are just data structures in memory, and are referenced by their
10494: address. You can create words for objects with normal defining words
10495: like @code{constant}. Likewise, there is no difference between instance
10496: variables that contain objects and those that contain other data.
1.5 anton 10497:
1.78 anton 10498: @item
10499: Late binding is efficient and easy to use.
1.44 crook 10500:
1.78 anton 10501: @item
10502: It avoids parsing, and thus avoids problems with state-smartness
10503: and reduced extensibility; for convenience there are a few parsing
10504: words, but they have non-parsing counterparts. There are also a few
10505: defining words that parse. This is hard to avoid, because all standard
10506: defining words parse (except @code{:noname}); however, such
10507: words are not as bad as many other parsing words, because they are not
10508: state-smart.
1.5 anton 10509:
1.78 anton 10510: @item
10511: It does not try to incorporate everything. It does a few things and does
10512: them well (IMO). In particular, this model was not designed to support
10513: information hiding (although it has features that may help); you can use
10514: a separate package for achieving this.
1.5 anton 10515:
1.78 anton 10516: @item
10517: It is layered; you don't have to learn and use all features to use this
10518: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10519: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10520: are optional and independent of each other.
1.5 anton 10521:
1.78 anton 10522: @item
10523: An implementation in ANS Forth is available.
1.5 anton 10524:
1.78 anton 10525: @end itemize
1.5 anton 10526:
1.44 crook 10527:
1.78 anton 10528: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10529: @subsubsection Basic @file{objects.fs} Usage
10530: @cindex basic objects usage
10531: @cindex objects, basic usage
1.5 anton 10532:
1.78 anton 10533: You can define a class for graphical objects like this:
1.44 crook 10534:
1.78 anton 10535: @cindex @code{class} usage
10536: @cindex @code{end-class} usage
10537: @cindex @code{selector} usage
1.5 anton 10538: @example
1.78 anton 10539: object class \ "object" is the parent class
10540: selector draw ( x y graphical -- )
10541: end-class graphical
10542: @end example
10543:
10544: This code defines a class @code{graphical} with an
10545: operation @code{draw}. We can perform the operation
10546: @code{draw} on any @code{graphical} object, e.g.:
10547:
10548: @example
10549: 100 100 t-rex draw
1.26 crook 10550: @end example
1.5 anton 10551:
1.78 anton 10552: @noindent
10553: where @code{t-rex} is a word (say, a constant) that produces a
10554: graphical object.
10555:
10556: @comment TODO add a 2nd operation eg perimeter.. and use for
10557: @comment a concrete example
1.5 anton 10558:
1.78 anton 10559: @cindex abstract class
10560: How do we create a graphical object? With the present definitions,
10561: we cannot create a useful graphical object. The class
10562: @code{graphical} describes graphical objects in general, but not
10563: any concrete graphical object type (C++ users would call it an
10564: @emph{abstract class}); e.g., there is no method for the selector
10565: @code{draw} in the class @code{graphical}.
1.5 anton 10566:
1.78 anton 10567: For concrete graphical objects, we define child classes of the
10568: class @code{graphical}, e.g.:
1.5 anton 10569:
1.78 anton 10570: @cindex @code{overrides} usage
10571: @cindex @code{field} usage in class definition
1.26 crook 10572: @example
1.78 anton 10573: graphical class \ "graphical" is the parent class
10574: cell% field circle-radius
1.5 anton 10575:
1.78 anton 10576: :noname ( x y circle -- )
10577: circle-radius @@ draw-circle ;
10578: overrides draw
1.5 anton 10579:
1.78 anton 10580: :noname ( n-radius circle -- )
10581: circle-radius ! ;
10582: overrides construct
1.5 anton 10583:
1.78 anton 10584: end-class circle
10585: @end example
1.44 crook 10586:
1.78 anton 10587: Here we define a class @code{circle} as a child of @code{graphical},
10588: with field @code{circle-radius} (which behaves just like a field
10589: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10590: for the selectors @code{draw} and @code{construct} (@code{construct} is
10591: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10592:
1.78 anton 10593: Now we can create a circle on the heap (i.e.,
10594: @code{allocate}d memory) with:
1.44 crook 10595:
1.78 anton 10596: @cindex @code{heap-new} usage
1.5 anton 10597: @example
1.78 anton 10598: 50 circle heap-new constant my-circle
1.5 anton 10599: @end example
10600:
1.78 anton 10601: @noindent
10602: @code{heap-new} invokes @code{construct}, thus
10603: initializing the field @code{circle-radius} with 50. We can draw
10604: this new circle at (100,100) with:
1.5 anton 10605:
10606: @example
1.78 anton 10607: 100 100 my-circle draw
1.5 anton 10608: @end example
10609:
1.78 anton 10610: @cindex selector invocation, restrictions
10611: @cindex class definition, restrictions
10612: Note: You can only invoke a selector if the object on the TOS
10613: (the receiving object) belongs to the class where the selector was
10614: defined or one of its descendents; e.g., you can invoke
10615: @code{draw} only for objects belonging to @code{graphical}
10616: or its descendents (e.g., @code{circle}). Immediately before
10617: @code{end-class}, the search order has to be the same as
10618: immediately after @code{class}.
10619:
10620: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10621: @subsubsection The @file{object.fs} base class
10622: @cindex @code{object} class
10623:
10624: When you define a class, you have to specify a parent class. So how do
10625: you start defining classes? There is one class available from the start:
10626: @code{object}. It is ancestor for all classes and so is the
10627: only class that has no parent. It has two selectors: @code{construct}
10628: and @code{print}.
10629:
10630: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10631: @subsubsection Creating objects
10632: @cindex creating objects
10633: @cindex object creation
10634: @cindex object allocation options
10635:
10636: @cindex @code{heap-new} discussion
10637: @cindex @code{dict-new} discussion
10638: @cindex @code{construct} discussion
10639: You can create and initialize an object of a class on the heap with
10640: @code{heap-new} ( ... class -- object ) and in the dictionary
10641: (allocation with @code{allot}) with @code{dict-new} (
10642: ... class -- object ). Both words invoke @code{construct}, which
10643: consumes the stack items indicated by "..." above.
10644:
10645: @cindex @code{init-object} discussion
10646: @cindex @code{class-inst-size} discussion
10647: If you want to allocate memory for an object yourself, you can get its
10648: alignment and size with @code{class-inst-size 2@@} ( class --
10649: align size ). Once you have memory for an object, you can initialize
10650: it with @code{init-object} ( ... class object -- );
10651: @code{construct} does only a part of the necessary work.
10652:
10653: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10654: @subsubsection Object-Oriented Programming Style
10655: @cindex object-oriented programming style
10656: @cindex programming style, object-oriented
1.5 anton 10657:
1.78 anton 10658: This section is not exhaustive.
1.5 anton 10659:
1.78 anton 10660: @cindex stack effects of selectors
10661: @cindex selectors and stack effects
10662: In general, it is a good idea to ensure that all methods for the
10663: same selector have the same stack effect: when you invoke a selector,
10664: you often have no idea which method will be invoked, so, unless all
10665: methods have the same stack effect, you will not know the stack effect
10666: of the selector invocation.
1.5 anton 10667:
1.78 anton 10668: One exception to this rule is methods for the selector
10669: @code{construct}. We know which method is invoked, because we
10670: specify the class to be constructed at the same place. Actually, I
10671: defined @code{construct} as a selector only to give the users a
10672: convenient way to specify initialization. The way it is used, a
10673: mechanism different from selector invocation would be more natural
10674: (but probably would take more code and more space to explain).
1.5 anton 10675:
1.78 anton 10676: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10677: @subsubsection Class Binding
10678: @cindex class binding
10679: @cindex early binding
1.5 anton 10680:
1.78 anton 10681: @cindex late binding
10682: Normal selector invocations determine the method at run-time depending
10683: on the class of the receiving object. This run-time selection is called
10684: @i{late binding}.
1.5 anton 10685:
1.78 anton 10686: Sometimes it's preferable to invoke a different method. For example,
10687: you might want to use the simple method for @code{print}ing
10688: @code{object}s instead of the possibly long-winded @code{print} method
10689: of the receiver class. You can achieve this by replacing the invocation
10690: of @code{print} with:
1.5 anton 10691:
1.78 anton 10692: @cindex @code{[bind]} usage
1.5 anton 10693: @example
1.78 anton 10694: [bind] object print
1.5 anton 10695: @end example
10696:
1.78 anton 10697: @noindent
10698: in compiled code or:
10699:
10700: @cindex @code{bind} usage
1.5 anton 10701: @example
1.78 anton 10702: bind object print
1.5 anton 10703: @end example
10704:
1.78 anton 10705: @cindex class binding, alternative to
10706: @noindent
10707: in interpreted code. Alternatively, you can define the method with a
10708: name (e.g., @code{print-object}), and then invoke it through the
10709: name. Class binding is just a (often more convenient) way to achieve
10710: the same effect; it avoids name clutter and allows you to invoke
10711: methods directly without naming them first.
1.5 anton 10712:
1.78 anton 10713: @cindex superclass binding
10714: @cindex parent class binding
10715: A frequent use of class binding is this: When we define a method
10716: for a selector, we often want the method to do what the selector does
10717: in the parent class, and a little more. There is a special word for
10718: this purpose: @code{[parent]}; @code{[parent]
10719: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10720: selector}}, where @code{@emph{parent}} is the parent
10721: class of the current class. E.g., a method definition might look like:
1.44 crook 10722:
1.78 anton 10723: @cindex @code{[parent]} usage
10724: @example
10725: :noname
10726: dup [parent] foo \ do parent's foo on the receiving object
10727: ... \ do some more
10728: ; overrides foo
10729: @end example
1.6 pazsan 10730:
1.78 anton 10731: @cindex class binding as optimization
10732: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10733: March 1997), Andrew McKewan presents class binding as an optimization
10734: technique. I recommend not using it for this purpose unless you are in
10735: an emergency. Late binding is pretty fast with this model anyway, so the
10736: benefit of using class binding is small; the cost of using class binding
10737: where it is not appropriate is reduced maintainability.
1.44 crook 10738:
1.78 anton 10739: While we are at programming style questions: You should bind
10740: selectors only to ancestor classes of the receiving object. E.g., say,
10741: you know that the receiving object is of class @code{foo} or its
10742: descendents; then you should bind only to @code{foo} and its
10743: ancestors.
1.12 anton 10744:
1.78 anton 10745: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10746: @subsubsection Method conveniences
10747: @cindex method conveniences
1.44 crook 10748:
1.78 anton 10749: In a method you usually access the receiving object pretty often. If
10750: you define the method as a plain colon definition (e.g., with
10751: @code{:noname}), you may have to do a lot of stack
10752: gymnastics. To avoid this, you can define the method with @code{m:
10753: ... ;m}. E.g., you could define the method for
10754: @code{draw}ing a @code{circle} with
1.6 pazsan 10755:
1.78 anton 10756: @cindex @code{this} usage
10757: @cindex @code{m:} usage
10758: @cindex @code{;m} usage
10759: @example
10760: m: ( x y circle -- )
10761: ( x y ) this circle-radius @@ draw-circle ;m
10762: @end example
1.6 pazsan 10763:
1.78 anton 10764: @cindex @code{exit} in @code{m: ... ;m}
10765: @cindex @code{exitm} discussion
10766: @cindex @code{catch} in @code{m: ... ;m}
10767: When this method is executed, the receiver object is removed from the
10768: stack; you can access it with @code{this} (admittedly, in this
10769: example the use of @code{m: ... ;m} offers no advantage). Note
10770: that I specify the stack effect for the whole method (i.e. including
10771: the receiver object), not just for the code between @code{m:}
10772: and @code{;m}. You cannot use @code{exit} in
10773: @code{m:...;m}; instead, use
10774: @code{exitm}.@footnote{Moreover, for any word that calls
10775: @code{catch} and was defined before loading
10776: @code{objects.fs}, you have to redefine it like I redefined
10777: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10778:
1.78 anton 10779: @cindex @code{inst-var} usage
10780: You will frequently use sequences of the form @code{this
10781: @emph{field}} (in the example above: @code{this
10782: circle-radius}). If you use the field only in this way, you can
10783: define it with @code{inst-var} and eliminate the
10784: @code{this} before the field name. E.g., the @code{circle}
10785: class above could also be defined with:
1.6 pazsan 10786:
1.78 anton 10787: @example
10788: graphical class
10789: cell% inst-var radius
1.6 pazsan 10790:
1.78 anton 10791: m: ( x y circle -- )
10792: radius @@ draw-circle ;m
10793: overrides draw
1.6 pazsan 10794:
1.78 anton 10795: m: ( n-radius circle -- )
10796: radius ! ;m
10797: overrides construct
1.6 pazsan 10798:
1.78 anton 10799: end-class circle
10800: @end example
1.6 pazsan 10801:
1.78 anton 10802: @code{radius} can only be used in @code{circle} and its
10803: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10804:
1.78 anton 10805: @cindex @code{inst-value} usage
10806: You can also define fields with @code{inst-value}, which is
10807: to @code{inst-var} what @code{value} is to
10808: @code{variable}. You can change the value of such a field with
10809: @code{[to-inst]}. E.g., we could also define the class
10810: @code{circle} like this:
1.44 crook 10811:
1.78 anton 10812: @example
10813: graphical class
10814: inst-value radius
1.6 pazsan 10815:
1.78 anton 10816: m: ( x y circle -- )
10817: radius draw-circle ;m
10818: overrides draw
1.44 crook 10819:
1.78 anton 10820: m: ( n-radius circle -- )
10821: [to-inst] radius ;m
10822: overrides construct
1.6 pazsan 10823:
1.78 anton 10824: end-class circle
10825: @end example
1.6 pazsan 10826:
1.78 anton 10827: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10828:
1.78 anton 10829: @c Finally, you can define named methods with @code{:m}. One use of this
10830: @c feature is the definition of words that occur only in one class and are
10831: @c not intended to be overridden, but which still need method context
10832: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10833: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10834:
10835:
1.78 anton 10836: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10837: @subsubsection Classes and Scoping
10838: @cindex classes and scoping
10839: @cindex scoping and classes
1.6 pazsan 10840:
1.78 anton 10841: Inheritance is frequent, unlike structure extension. This exacerbates
10842: the problem with the field name convention (@pxref{Structure Naming
10843: Convention}): One always has to remember in which class the field was
10844: originally defined; changing a part of the class structure would require
10845: changes for renaming in otherwise unaffected code.
1.6 pazsan 10846:
1.78 anton 10847: @cindex @code{inst-var} visibility
10848: @cindex @code{inst-value} visibility
10849: To solve this problem, I added a scoping mechanism (which was not in my
10850: original charter): A field defined with @code{inst-var} (or
10851: @code{inst-value}) is visible only in the class where it is defined and in
10852: the descendent classes of this class. Using such fields only makes
10853: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10854:
1.78 anton 10855: This scoping mechanism allows us to use the unadorned field name,
10856: because name clashes with unrelated words become much less likely.
1.6 pazsan 10857:
1.78 anton 10858: @cindex @code{protected} discussion
10859: @cindex @code{private} discussion
10860: Once we have this mechanism, we can also use it for controlling the
10861: visibility of other words: All words defined after
10862: @code{protected} are visible only in the current class and its
10863: descendents. @code{public} restores the compilation
10864: (i.e. @code{current}) word list that was in effect before. If you
10865: have several @code{protected}s without an intervening
10866: @code{public} or @code{set-current}, @code{public}
10867: will restore the compilation word list in effect before the first of
10868: these @code{protected}s.
1.6 pazsan 10869:
1.78 anton 10870: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10871: @subsubsection Dividing classes
10872: @cindex Dividing classes
10873: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10874:
1.78 anton 10875: You may want to do the definition of methods separate from the
10876: definition of the class, its selectors, fields, and instance variables,
10877: i.e., separate the implementation from the definition. You can do this
10878: in the following way:
1.6 pazsan 10879:
1.78 anton 10880: @example
10881: graphical class
10882: inst-value radius
10883: end-class circle
1.6 pazsan 10884:
1.78 anton 10885: ... \ do some other stuff
1.6 pazsan 10886:
1.78 anton 10887: circle methods \ now we are ready
1.44 crook 10888:
1.78 anton 10889: m: ( x y circle -- )
10890: radius draw-circle ;m
10891: overrides draw
1.6 pazsan 10892:
1.78 anton 10893: m: ( n-radius circle -- )
10894: [to-inst] radius ;m
10895: overrides construct
1.44 crook 10896:
1.78 anton 10897: end-methods
10898: @end example
1.7 pazsan 10899:
1.78 anton 10900: You can use several @code{methods}...@code{end-methods} sections. The
10901: only things you can do to the class in these sections are: defining
10902: methods, and overriding the class's selectors. You must not define new
10903: selectors or fields.
1.7 pazsan 10904:
1.78 anton 10905: Note that you often have to override a selector before using it. In
10906: particular, you usually have to override @code{construct} with a new
10907: method before you can invoke @code{heap-new} and friends. E.g., you
10908: must not create a circle before the @code{overrides construct} sequence
10909: in the example above.
1.7 pazsan 10910:
1.78 anton 10911: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10912: @subsubsection Object Interfaces
10913: @cindex object interfaces
10914: @cindex interfaces for objects
1.7 pazsan 10915:
1.78 anton 10916: In this model you can only call selectors defined in the class of the
10917: receiving objects or in one of its ancestors. If you call a selector
10918: with a receiving object that is not in one of these classes, the
10919: result is undefined; if you are lucky, the program crashes
10920: immediately.
1.7 pazsan 10921:
1.78 anton 10922: @cindex selectors common to hardly-related classes
10923: Now consider the case when you want to have a selector (or several)
10924: available in two classes: You would have to add the selector to a
10925: common ancestor class, in the worst case to @code{object}. You
10926: may not want to do this, e.g., because someone else is responsible for
10927: this ancestor class.
1.7 pazsan 10928:
1.78 anton 10929: The solution for this problem is interfaces. An interface is a
10930: collection of selectors. If a class implements an interface, the
10931: selectors become available to the class and its descendents. A class
10932: can implement an unlimited number of interfaces. For the problem
10933: discussed above, we would define an interface for the selector(s), and
10934: both classes would implement the interface.
1.7 pazsan 10935:
1.78 anton 10936: As an example, consider an interface @code{storage} for
10937: writing objects to disk and getting them back, and a class
10938: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10939:
1.78 anton 10940: @cindex @code{interface} usage
10941: @cindex @code{end-interface} usage
10942: @cindex @code{implementation} usage
10943: @example
10944: interface
10945: selector write ( file object -- )
10946: selector read1 ( file object -- )
10947: end-interface storage
1.13 pazsan 10948:
1.78 anton 10949: bar class
10950: storage implementation
1.13 pazsan 10951:
1.78 anton 10952: ... overrides write
10953: ... overrides read1
10954: ...
10955: end-class foo
10956: @end example
1.13 pazsan 10957:
1.78 anton 10958: @noindent
10959: (I would add a word @code{read} @i{( file -- object )} that uses
10960: @code{read1} internally, but that's beyond the point illustrated
10961: here.)
1.13 pazsan 10962:
1.78 anton 10963: Note that you cannot use @code{protected} in an interface; and
10964: of course you cannot define fields.
1.13 pazsan 10965:
1.78 anton 10966: In the Neon model, all selectors are available for all classes;
10967: therefore it does not need interfaces. The price you pay in this model
10968: is slower late binding, and therefore, added complexity to avoid late
10969: binding.
1.13 pazsan 10970:
1.78 anton 10971: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10972: @subsubsection @file{objects.fs} Implementation
10973: @cindex @file{objects.fs} implementation
1.13 pazsan 10974:
1.78 anton 10975: @cindex @code{object-map} discussion
10976: An object is a piece of memory, like one of the data structures
10977: described with @code{struct...end-struct}. It has a field
10978: @code{object-map} that points to the method map for the object's
10979: class.
1.13 pazsan 10980:
1.78 anton 10981: @cindex method map
10982: @cindex virtual function table
10983: The @emph{method map}@footnote{This is Self terminology; in C++
10984: terminology: virtual function table.} is an array that contains the
10985: execution tokens (@i{xt}s) of the methods for the object's class. Each
10986: selector contains an offset into a method map.
1.13 pazsan 10987:
1.78 anton 10988: @cindex @code{selector} implementation, class
10989: @code{selector} is a defining word that uses
10990: @code{CREATE} and @code{DOES>}. The body of the
10991: selector contains the offset; the @code{DOES>} action for a
10992: class selector is, basically:
1.8 pazsan 10993:
10994: @example
1.78 anton 10995: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10996: @end example
10997:
1.78 anton 10998: Since @code{object-map} is the first field of the object, it
10999: does not generate any code. As you can see, calling a selector has a
11000: small, constant cost.
1.26 crook 11001:
1.78 anton 11002: @cindex @code{current-interface} discussion
11003: @cindex class implementation and representation
11004: A class is basically a @code{struct} combined with a method
11005: map. During the class definition the alignment and size of the class
11006: are passed on the stack, just as with @code{struct}s, so
11007: @code{field} can also be used for defining class
11008: fields. However, passing more items on the stack would be
11009: inconvenient, so @code{class} builds a data structure in memory,
11010: which is accessed through the variable
11011: @code{current-interface}. After its definition is complete, the
11012: class is represented on the stack by a pointer (e.g., as parameter for
11013: a child class definition).
1.26 crook 11014:
1.78 anton 11015: A new class starts off with the alignment and size of its parent,
11016: and a copy of the parent's method map. Defining new fields extends the
11017: size and alignment; likewise, defining new selectors extends the
11018: method map. @code{overrides} just stores a new @i{xt} in the method
11019: map at the offset given by the selector.
1.13 pazsan 11020:
1.78 anton 11021: @cindex class binding, implementation
11022: Class binding just gets the @i{xt} at the offset given by the selector
11023: from the class's method map and @code{compile,}s (in the case of
11024: @code{[bind]}) it.
1.13 pazsan 11025:
1.78 anton 11026: @cindex @code{this} implementation
11027: @cindex @code{catch} and @code{this}
11028: @cindex @code{this} and @code{catch}
11029: I implemented @code{this} as a @code{value}. At the
11030: start of an @code{m:...;m} method the old @code{this} is
11031: stored to the return stack and restored at the end; and the object on
11032: the TOS is stored @code{TO this}. This technique has one
11033: disadvantage: If the user does not leave the method via
11034: @code{;m}, but via @code{throw} or @code{exit},
11035: @code{this} is not restored (and @code{exit} may
11036: crash). To deal with the @code{throw} problem, I have redefined
11037: @code{catch} to save and restore @code{this}; the same
11038: should be done with any word that can catch an exception. As for
11039: @code{exit}, I simply forbid it (as a replacement, there is
11040: @code{exitm}).
1.13 pazsan 11041:
1.78 anton 11042: @cindex @code{inst-var} implementation
11043: @code{inst-var} is just the same as @code{field}, with
11044: a different @code{DOES>} action:
1.13 pazsan 11045: @example
1.78 anton 11046: @@ this +
1.8 pazsan 11047: @end example
1.78 anton 11048: Similar for @code{inst-value}.
1.8 pazsan 11049:
1.78 anton 11050: @cindex class scoping implementation
11051: Each class also has a word list that contains the words defined with
11052: @code{inst-var} and @code{inst-value}, and its protected
11053: words. It also has a pointer to its parent. @code{class} pushes
11054: the word lists of the class and all its ancestors onto the search order stack,
11055: and @code{end-class} drops them.
1.20 pazsan 11056:
1.78 anton 11057: @cindex interface implementation
11058: An interface is like a class without fields, parent and protected
11059: words; i.e., it just has a method map. If a class implements an
11060: interface, its method map contains a pointer to the method map of the
11061: interface. The positive offsets in the map are reserved for class
11062: methods, therefore interface map pointers have negative
11063: offsets. Interfaces have offsets that are unique throughout the
11064: system, unlike class selectors, whose offsets are only unique for the
11065: classes where the selector is available (invokable).
1.20 pazsan 11066:
1.78 anton 11067: This structure means that interface selectors have to perform one
11068: indirection more than class selectors to find their method. Their body
11069: contains the interface map pointer offset in the class method map, and
11070: the method offset in the interface method map. The
11071: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11072:
11073: @example
1.78 anton 11074: ( object selector-body )
11075: 2dup selector-interface @@ ( object selector-body object interface-offset )
11076: swap object-map @@ + @@ ( object selector-body map )
11077: swap selector-offset @@ + @@ execute
1.20 pazsan 11078: @end example
11079:
1.78 anton 11080: where @code{object-map} and @code{selector-offset} are
11081: first fields and generate no code.
1.20 pazsan 11082:
1.78 anton 11083: As a concrete example, consider the following code:
1.20 pazsan 11084:
11085: @example
1.78 anton 11086: interface
11087: selector if1sel1
11088: selector if1sel2
11089: end-interface if1
1.20 pazsan 11090:
1.78 anton 11091: object class
11092: if1 implementation
11093: selector cl1sel1
11094: cell% inst-var cl1iv1
1.20 pazsan 11095:
1.78 anton 11096: ' m1 overrides construct
11097: ' m2 overrides if1sel1
11098: ' m3 overrides if1sel2
11099: ' m4 overrides cl1sel2
11100: end-class cl1
1.20 pazsan 11101:
1.78 anton 11102: create obj1 object dict-new drop
11103: create obj2 cl1 dict-new drop
11104: @end example
1.20 pazsan 11105:
1.78 anton 11106: The data structure created by this code (including the data structure
11107: for @code{object}) is shown in the
11108: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11109: @comment TODO add this diagram..
1.20 pazsan 11110:
1.78 anton 11111: @node Objects Glossary, , Objects Implementation, Objects
11112: @subsubsection @file{objects.fs} Glossary
11113: @cindex @file{objects.fs} Glossary
1.20 pazsan 11114:
11115:
1.78 anton 11116: doc---objects-bind
11117: doc---objects-<bind>
11118: doc---objects-bind'
11119: doc---objects-[bind]
11120: doc---objects-class
11121: doc---objects-class->map
11122: doc---objects-class-inst-size
11123: doc---objects-class-override!
1.79 anton 11124: doc---objects-class-previous
11125: doc---objects-class>order
1.78 anton 11126: doc---objects-construct
11127: doc---objects-current'
11128: doc---objects-[current]
11129: doc---objects-current-interface
11130: doc---objects-dict-new
11131: doc---objects-end-class
11132: doc---objects-end-class-noname
11133: doc---objects-end-interface
11134: doc---objects-end-interface-noname
11135: doc---objects-end-methods
11136: doc---objects-exitm
11137: doc---objects-heap-new
11138: doc---objects-implementation
11139: doc---objects-init-object
11140: doc---objects-inst-value
11141: doc---objects-inst-var
11142: doc---objects-interface
11143: doc---objects-m:
11144: doc---objects-:m
11145: doc---objects-;m
11146: doc---objects-method
11147: doc---objects-methods
11148: doc---objects-object
11149: doc---objects-overrides
11150: doc---objects-[parent]
11151: doc---objects-print
11152: doc---objects-protected
11153: doc---objects-public
11154: doc---objects-selector
11155: doc---objects-this
11156: doc---objects-<to-inst>
11157: doc---objects-[to-inst]
11158: doc---objects-to-this
11159: doc---objects-xt-new
1.20 pazsan 11160:
11161:
1.78 anton 11162: @c -------------------------------------------------------------
11163: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11164: @subsection The @file{oof.fs} model
11165: @cindex oof
11166: @cindex object-oriented programming
1.20 pazsan 11167:
1.78 anton 11168: @cindex @file{objects.fs}
11169: @cindex @file{oof.fs}
1.20 pazsan 11170:
1.78 anton 11171: This section describes the @file{oof.fs} package.
1.20 pazsan 11172:
1.78 anton 11173: The package described in this section has been used in bigFORTH since 1991, and
11174: used for two large applications: a chromatographic system used to
11175: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11176:
1.78 anton 11177: You can find a description (in German) of @file{oof.fs} in @cite{Object
11178: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11179: 10(2), 1994.
1.20 pazsan 11180:
1.78 anton 11181: @menu
11182: * Properties of the OOF model::
11183: * Basic OOF Usage::
11184: * The OOF base class::
11185: * Class Declaration::
11186: * Class Implementation::
11187: @end menu
1.20 pazsan 11188:
1.78 anton 11189: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11190: @subsubsection Properties of the @file{oof.fs} model
11191: @cindex @file{oof.fs} properties
1.20 pazsan 11192:
1.78 anton 11193: @itemize @bullet
11194: @item
11195: This model combines object oriented programming with information
11196: hiding. It helps you writing large application, where scoping is
11197: necessary, because it provides class-oriented scoping.
1.20 pazsan 11198:
1.78 anton 11199: @item
11200: Named objects, object pointers, and object arrays can be created,
11201: selector invocation uses the ``object selector'' syntax. Selector invocation
11202: to objects and/or selectors on the stack is a bit less convenient, but
11203: possible.
1.44 crook 11204:
1.78 anton 11205: @item
11206: Selector invocation and instance variable usage of the active object is
11207: straightforward, since both make use of the active object.
1.44 crook 11208:
1.78 anton 11209: @item
11210: Late binding is efficient and easy to use.
1.20 pazsan 11211:
1.78 anton 11212: @item
11213: State-smart objects parse selectors. However, extensibility is provided
11214: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11215:
1.78 anton 11216: @item
11217: An implementation in ANS Forth is available.
1.20 pazsan 11218:
1.78 anton 11219: @end itemize
1.23 crook 11220:
11221:
1.78 anton 11222: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11223: @subsubsection Basic @file{oof.fs} Usage
11224: @cindex @file{oof.fs} usage
1.23 crook 11225:
1.78 anton 11226: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11227:
1.78 anton 11228: You can define a class for graphical objects like this:
1.23 crook 11229:
1.78 anton 11230: @cindex @code{class} usage
11231: @cindex @code{class;} usage
11232: @cindex @code{method} usage
11233: @example
11234: object class graphical \ "object" is the parent class
1.139 pazsan 11235: method draw ( x y -- )
1.78 anton 11236: class;
11237: @end example
1.23 crook 11238:
1.78 anton 11239: This code defines a class @code{graphical} with an
11240: operation @code{draw}. We can perform the operation
11241: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11242:
1.78 anton 11243: @example
11244: 100 100 t-rex draw
11245: @end example
1.23 crook 11246:
1.78 anton 11247: @noindent
11248: where @code{t-rex} is an object or object pointer, created with e.g.
11249: @code{graphical : t-rex}.
1.23 crook 11250:
1.78 anton 11251: @cindex abstract class
11252: How do we create a graphical object? With the present definitions,
11253: we cannot create a useful graphical object. The class
11254: @code{graphical} describes graphical objects in general, but not
11255: any concrete graphical object type (C++ users would call it an
11256: @emph{abstract class}); e.g., there is no method for the selector
11257: @code{draw} in the class @code{graphical}.
1.23 crook 11258:
1.78 anton 11259: For concrete graphical objects, we define child classes of the
11260: class @code{graphical}, e.g.:
1.23 crook 11261:
1.78 anton 11262: @example
11263: graphical class circle \ "graphical" is the parent class
11264: cell var circle-radius
11265: how:
11266: : draw ( x y -- )
11267: circle-radius @@ draw-circle ;
1.23 crook 11268:
1.139 pazsan 11269: : init ( n-radius -- )
1.78 anton 11270: circle-radius ! ;
11271: class;
11272: @end example
1.1 anton 11273:
1.78 anton 11274: Here we define a class @code{circle} as a child of @code{graphical},
11275: with a field @code{circle-radius}; it defines new methods for the
11276: selectors @code{draw} and @code{init} (@code{init} is defined in
11277: @code{object}, the parent class of @code{graphical}).
1.1 anton 11278:
1.78 anton 11279: Now we can create a circle in the dictionary with:
1.1 anton 11280:
1.78 anton 11281: @example
11282: 50 circle : my-circle
11283: @end example
1.21 crook 11284:
1.78 anton 11285: @noindent
11286: @code{:} invokes @code{init}, thus initializing the field
11287: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11288: with:
1.1 anton 11289:
1.78 anton 11290: @example
11291: 100 100 my-circle draw
11292: @end example
1.1 anton 11293:
1.78 anton 11294: @cindex selector invocation, restrictions
11295: @cindex class definition, restrictions
11296: Note: You can only invoke a selector if the receiving object belongs to
11297: the class where the selector was defined or one of its descendents;
11298: e.g., you can invoke @code{draw} only for objects belonging to
11299: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11300: mechanism will check if you try to invoke a selector that is not
11301: defined in this class hierarchy, so you'll get an error at compilation
11302: time.
1.1 anton 11303:
11304:
1.78 anton 11305: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11306: @subsubsection The @file{oof.fs} base class
11307: @cindex @file{oof.fs} base class
1.1 anton 11308:
1.78 anton 11309: When you define a class, you have to specify a parent class. So how do
11310: you start defining classes? There is one class available from the start:
11311: @code{object}. You have to use it as ancestor for all classes. It is the
11312: only class that has no parent. Classes are also objects, except that
11313: they don't have instance variables; class manipulation such as
11314: inheritance or changing definitions of a class is handled through
11315: selectors of the class @code{object}.
1.1 anton 11316:
1.78 anton 11317: @code{object} provides a number of selectors:
1.1 anton 11318:
1.78 anton 11319: @itemize @bullet
11320: @item
11321: @code{class} for subclassing, @code{definitions} to add definitions
11322: later on, and @code{class?} to get type informations (is the class a
11323: subclass of the class passed on the stack?).
1.1 anton 11324:
1.78 anton 11325: doc---object-class
11326: doc---object-definitions
11327: doc---object-class?
1.1 anton 11328:
11329:
1.26 crook 11330: @item
1.78 anton 11331: @code{init} and @code{dispose} as constructor and destructor of the
11332: object. @code{init} is invocated after the object's memory is allocated,
11333: while @code{dispose} also handles deallocation. Thus if you redefine
11334: @code{dispose}, you have to call the parent's dispose with @code{super
11335: dispose}, too.
11336:
11337: doc---object-init
11338: doc---object-dispose
11339:
1.1 anton 11340:
1.26 crook 11341: @item
1.78 anton 11342: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11343: @code{[]} to create named and unnamed objects and object arrays or
11344: object pointers.
11345:
11346: doc---object-new
11347: doc---object-new[]
11348: doc---object-:
11349: doc---object-ptr
11350: doc---object-asptr
11351: doc---object-[]
11352:
1.1 anton 11353:
1.26 crook 11354: @item
1.78 anton 11355: @code{::} and @code{super} for explicit scoping. You should use explicit
11356: scoping only for super classes or classes with the same set of instance
11357: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11358:
1.78 anton 11359: doc---object-::
11360: doc---object-super
1.21 crook 11361:
11362:
1.26 crook 11363: @item
1.78 anton 11364: @code{self} to get the address of the object
1.21 crook 11365:
1.78 anton 11366: doc---object-self
1.21 crook 11367:
11368:
1.78 anton 11369: @item
11370: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11371: pointers and instance defers.
1.21 crook 11372:
1.78 anton 11373: doc---object-bind
11374: doc---object-bound
11375: doc---object-link
11376: doc---object-is
1.21 crook 11377:
11378:
1.78 anton 11379: @item
11380: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11381: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11382:
1.78 anton 11383: doc---object-'
11384: doc---object-postpone
1.21 crook 11385:
11386:
1.78 anton 11387: @item
11388: @code{with} and @code{endwith} to select the active object from the
11389: stack, and enable its scope. Using @code{with} and @code{endwith}
11390: also allows you to create code using selector @code{postpone} without being
11391: trapped by the state-smart objects.
1.21 crook 11392:
1.78 anton 11393: doc---object-with
11394: doc---object-endwith
1.21 crook 11395:
11396:
1.78 anton 11397: @end itemize
1.21 crook 11398:
1.78 anton 11399: @node Class Declaration, Class Implementation, The OOF base class, OOF
11400: @subsubsection Class Declaration
11401: @cindex class declaration
1.21 crook 11402:
1.78 anton 11403: @itemize @bullet
11404: @item
11405: Instance variables
1.21 crook 11406:
1.78 anton 11407: doc---oof-var
1.21 crook 11408:
11409:
1.78 anton 11410: @item
11411: Object pointers
1.21 crook 11412:
1.78 anton 11413: doc---oof-ptr
11414: doc---oof-asptr
1.21 crook 11415:
11416:
1.78 anton 11417: @item
11418: Instance defers
1.21 crook 11419:
1.78 anton 11420: doc---oof-defer
1.21 crook 11421:
11422:
1.78 anton 11423: @item
11424: Method selectors
1.21 crook 11425:
1.78 anton 11426: doc---oof-early
11427: doc---oof-method
1.21 crook 11428:
11429:
1.78 anton 11430: @item
11431: Class-wide variables
1.21 crook 11432:
1.78 anton 11433: doc---oof-static
1.21 crook 11434:
11435:
1.78 anton 11436: @item
11437: End declaration
1.1 anton 11438:
1.78 anton 11439: doc---oof-how:
11440: doc---oof-class;
1.21 crook 11441:
11442:
1.78 anton 11443: @end itemize
1.21 crook 11444:
1.78 anton 11445: @c -------------------------------------------------------------
11446: @node Class Implementation, , Class Declaration, OOF
11447: @subsubsection Class Implementation
11448: @cindex class implementation
1.21 crook 11449:
1.78 anton 11450: @c -------------------------------------------------------------
11451: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11452: @subsection The @file{mini-oof.fs} model
11453: @cindex mini-oof
1.21 crook 11454:
1.78 anton 11455: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11456: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11457: and reduces to the bare minimum of features. This is based on a posting
11458: of Bernd Paysan in comp.lang.forth.
1.21 crook 11459:
1.78 anton 11460: @menu
11461: * Basic Mini-OOF Usage::
11462: * Mini-OOF Example::
11463: * Mini-OOF Implementation::
11464: @end menu
1.21 crook 11465:
1.78 anton 11466: @c -------------------------------------------------------------
11467: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11468: @subsubsection Basic @file{mini-oof.fs} Usage
11469: @cindex mini-oof usage
1.21 crook 11470:
1.78 anton 11471: There is a base class (@code{class}, which allocates one cell for the
11472: object pointer) plus seven other words: to define a method, a variable,
11473: a class; to end a class, to resolve binding, to allocate an object and
11474: to compile a class method.
11475: @comment TODO better description of the last one
1.26 crook 11476:
1.21 crook 11477:
1.78 anton 11478: doc-object
11479: doc-method
11480: doc-var
11481: doc-class
11482: doc-end-class
11483: doc-defines
11484: doc-new
11485: doc-::
1.21 crook 11486:
11487:
11488:
1.78 anton 11489: @c -------------------------------------------------------------
11490: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11491: @subsubsection Mini-OOF Example
11492: @cindex mini-oof example
1.1 anton 11493:
1.78 anton 11494: A short example shows how to use this package. This example, in slightly
11495: extended form, is supplied as @file{moof-exm.fs}
11496: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11497:
1.26 crook 11498: @example
1.78 anton 11499: object class
11500: method init
11501: method draw
11502: end-class graphical
1.26 crook 11503: @end example
1.20 pazsan 11504:
1.78 anton 11505: This code defines a class @code{graphical} with an
11506: operation @code{draw}. We can perform the operation
11507: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11508:
1.26 crook 11509: @example
1.78 anton 11510: 100 100 t-rex draw
1.26 crook 11511: @end example
1.12 anton 11512:
1.78 anton 11513: where @code{t-rex} is an object or object pointer, created with e.g.
11514: @code{graphical new Constant t-rex}.
1.12 anton 11515:
1.78 anton 11516: For concrete graphical objects, we define child classes of the
11517: class @code{graphical}, e.g.:
1.12 anton 11518:
1.26 crook 11519: @example
11520: graphical class
1.78 anton 11521: cell var circle-radius
11522: end-class circle \ "graphical" is the parent class
1.12 anton 11523:
1.78 anton 11524: :noname ( x y -- )
11525: circle-radius @@ draw-circle ; circle defines draw
11526: :noname ( r -- )
11527: circle-radius ! ; circle defines init
11528: @end example
1.12 anton 11529:
1.78 anton 11530: There is no implicit init method, so we have to define one. The creation
11531: code of the object now has to call init explicitely.
1.21 crook 11532:
1.78 anton 11533: @example
11534: circle new Constant my-circle
11535: 50 my-circle init
1.12 anton 11536: @end example
11537:
1.78 anton 11538: It is also possible to add a function to create named objects with
11539: automatic call of @code{init}, given that all objects have @code{init}
11540: on the same place:
1.38 anton 11541:
1.78 anton 11542: @example
11543: : new: ( .. o "name" -- )
11544: new dup Constant init ;
11545: 80 circle new: large-circle
11546: @end example
1.12 anton 11547:
1.78 anton 11548: We can draw this new circle at (100,100) with:
1.12 anton 11549:
1.78 anton 11550: @example
11551: 100 100 my-circle draw
11552: @end example
1.12 anton 11553:
1.78 anton 11554: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11555: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11556:
1.78 anton 11557: Object-oriented systems with late binding typically use a
11558: ``vtable''-approach: the first variable in each object is a pointer to a
11559: table, which contains the methods as function pointers. The vtable
11560: may also contain other information.
1.12 anton 11561:
1.79 anton 11562: So first, let's declare selectors:
1.37 anton 11563:
11564: @example
1.79 anton 11565: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11566: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11567: @end example
1.37 anton 11568:
1.79 anton 11569: During selector declaration, the number of selectors and instance
11570: variables is on the stack (in address units). @code{method} creates one
11571: selector and increments the selector number. To execute a selector, it
1.78 anton 11572: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11573: executes the method @i{xt} stored there. Each selector takes the object
11574: it is invoked with as top of stack parameter; it passes the parameters
11575: (including the object) unchanged to the appropriate method which should
1.78 anton 11576: consume that object.
1.37 anton 11577:
1.78 anton 11578: Now, we also have to declare instance variables
1.37 anton 11579:
1.78 anton 11580: @example
1.79 anton 11581: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11582: DOES> ( o -- addr ) @@ + ;
1.37 anton 11583: @end example
11584:
1.78 anton 11585: As before, a word is created with the current offset. Instance
11586: variables can have different sizes (cells, floats, doubles, chars), so
11587: all we do is take the size and add it to the offset. If your machine
11588: has alignment restrictions, put the proper @code{aligned} or
11589: @code{faligned} before the variable, to adjust the variable
11590: offset. That's why it is on the top of stack.
1.37 anton 11591:
1.78 anton 11592: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11593:
1.78 anton 11594: @example
11595: Create object 1 cells , 2 cells ,
1.79 anton 11596: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11597: @end example
1.12 anton 11598:
1.78 anton 11599: For inheritance, the vtable of the parent object has to be
11600: copied when a new, derived class is declared. This gives all the
11601: methods of the parent class, which can be overridden, though.
1.12 anton 11602:
1.78 anton 11603: @example
1.79 anton 11604: : end-class ( class selectors vars "name" -- )
1.78 anton 11605: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11606: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11607: @end example
1.12 anton 11608:
1.78 anton 11609: The first line creates the vtable, initialized with
11610: @code{noop}s. The second line is the inheritance mechanism, it
11611: copies the xts from the parent vtable.
1.12 anton 11612:
1.78 anton 11613: We still have no way to define new methods, let's do that now:
1.12 anton 11614:
1.26 crook 11615: @example
1.79 anton 11616: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11617: @end example
1.12 anton 11618:
1.78 anton 11619: To allocate a new object, we need a word, too:
1.12 anton 11620:
1.78 anton 11621: @example
11622: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11623: @end example
11624:
1.78 anton 11625: Sometimes derived classes want to access the method of the
11626: parent object. There are two ways to achieve this with Mini-OOF:
11627: first, you could use named words, and second, you could look up the
11628: vtable of the parent object.
1.12 anton 11629:
1.78 anton 11630: @example
11631: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11632: @end example
1.12 anton 11633:
11634:
1.78 anton 11635: Nothing can be more confusing than a good example, so here is
11636: one. First let's declare a text object (called
11637: @code{button}), that stores text and position:
1.12 anton 11638:
1.78 anton 11639: @example
11640: object class
11641: cell var text
11642: cell var len
11643: cell var x
11644: cell var y
11645: method init
11646: method draw
11647: end-class button
11648: @end example
1.12 anton 11649:
1.78 anton 11650: @noindent
11651: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11652:
1.26 crook 11653: @example
1.78 anton 11654: :noname ( o -- )
11655: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11656: button defines draw
11657: :noname ( addr u o -- )
11658: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11659: button defines init
1.26 crook 11660: @end example
1.12 anton 11661:
1.78 anton 11662: @noindent
11663: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11664: new data and no new selectors:
1.78 anton 11665:
11666: @example
11667: button class
11668: end-class bold-button
1.12 anton 11669:
1.78 anton 11670: : bold 27 emit ." [1m" ;
11671: : normal 27 emit ." [0m" ;
11672: @end example
1.1 anton 11673:
1.78 anton 11674: @noindent
11675: The class @code{bold-button} has a different draw method to
11676: @code{button}, but the new method is defined in terms of the draw method
11677: for @code{button}:
1.20 pazsan 11678:
1.78 anton 11679: @example
11680: :noname bold [ button :: draw ] normal ; bold-button defines draw
11681: @end example
1.21 crook 11682:
1.78 anton 11683: @noindent
1.79 anton 11684: Finally, create two objects and apply selectors:
1.21 crook 11685:
1.26 crook 11686: @example
1.78 anton 11687: button new Constant foo
11688: s" thin foo" foo init
11689: page
11690: foo draw
11691: bold-button new Constant bar
11692: s" fat bar" bar init
11693: 1 bar y !
11694: bar draw
1.26 crook 11695: @end example
1.21 crook 11696:
11697:
1.78 anton 11698: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11699: @subsection Comparison with other object models
11700: @cindex comparison of object models
11701: @cindex object models, comparison
11702:
11703: Many object-oriented Forth extensions have been proposed (@cite{A survey
11704: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11705: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11706: relation of the object models described here to two well-known and two
11707: closely-related (by the use of method maps) models. Andras Zsoter
11708: helped us with this section.
11709:
11710: @cindex Neon model
11711: The most popular model currently seems to be the Neon model (see
11712: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11713: 1997) by Andrew McKewan) but this model has a number of limitations
11714: @footnote{A longer version of this critique can be
11715: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11716: Dimensions, May 1997) by Anton Ertl.}:
11717:
11718: @itemize @bullet
11719: @item
11720: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11721: to pass objects on the stack.
1.21 crook 11722:
1.78 anton 11723: @item
11724: It requires that the selector parses the input stream (at
1.79 anton 11725: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11726: hard to find.
1.21 crook 11727:
1.78 anton 11728: @item
1.79 anton 11729: It allows using every selector on every object; this eliminates the
11730: need for interfaces, but makes it harder to create efficient
11731: implementations.
1.78 anton 11732: @end itemize
1.21 crook 11733:
1.78 anton 11734: @cindex Pountain's object-oriented model
11735: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11736: Press, London, 1987) by Dick Pountain. However, it is not really about
11737: object-oriented programming, because it hardly deals with late
11738: binding. Instead, it focuses on features like information hiding and
11739: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11740:
1.78 anton 11741: @cindex Zsoter's object-oriented model
1.79 anton 11742: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11743: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11744: describes a model that makes heavy use of an active object (like
11745: @code{this} in @file{objects.fs}): The active object is not only used
11746: for accessing all fields, but also specifies the receiving object of
11747: every selector invocation; you have to change the active object
11748: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11749: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11750: the method entry point is unnecessary with Zsoter's model, because the
11751: receiving object is the active object already. On the other hand, the
11752: explicit change is absolutely necessary in that model, because otherwise
11753: no one could ever change the active object. An ANS Forth implementation
11754: of this model is available through
11755: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11756:
1.78 anton 11757: @cindex @file{oof.fs}, differences to other models
11758: The @file{oof.fs} model combines information hiding and overloading
11759: resolution (by keeping names in various word lists) with object-oriented
11760: programming. It sets the active object implicitly on method entry, but
11761: also allows explicit changing (with @code{>o...o>} or with
11762: @code{with...endwith}). It uses parsing and state-smart objects and
11763: classes for resolving overloading and for early binding: the object or
11764: class parses the selector and determines the method from this. If the
11765: selector is not parsed by an object or class, it performs a call to the
11766: selector for the active object (late binding), like Zsoter's model.
11767: Fields are always accessed through the active object. The big
11768: disadvantage of this model is the parsing and the state-smartness, which
11769: reduces extensibility and increases the opportunities for subtle bugs;
11770: essentially, you are only safe if you never tick or @code{postpone} an
11771: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11772:
1.78 anton 11773: @cindex @file{mini-oof.fs}, differences to other models
11774: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11775: version of the @file{objects.fs} model, but syntactically it is a
11776: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11777:
11778:
1.78 anton 11779: @c -------------------------------------------------------------
1.150 anton 11780: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11781: @section Programming Tools
11782: @cindex programming tools
1.21 crook 11783:
1.78 anton 11784: @c !! move this and assembler down below OO stuff.
1.21 crook 11785:
1.78 anton 11786: @menu
1.150 anton 11787: * Examining:: Data and Code.
11788: * Forgetting words:: Usually before reloading.
1.78 anton 11789: * Debugging:: Simple and quick.
11790: * Assertions:: Making your programs self-checking.
11791: * Singlestep Debugger:: Executing your program word by word.
11792: @end menu
1.21 crook 11793:
1.78 anton 11794: @node Examining, Forgetting words, Programming Tools, Programming Tools
11795: @subsection Examining data and code
11796: @cindex examining data and code
11797: @cindex data examination
11798: @cindex code examination
1.44 crook 11799:
1.78 anton 11800: The following words inspect the stack non-destructively:
1.21 crook 11801:
1.78 anton 11802: doc-.s
11803: doc-f.s
1.158 anton 11804: doc-maxdepth-.s
1.44 crook 11805:
1.78 anton 11806: There is a word @code{.r} but it does @i{not} display the return stack!
11807: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11808:
1.78 anton 11809: doc-depth
11810: doc-fdepth
11811: doc-clearstack
1.124 anton 11812: doc-clearstacks
1.21 crook 11813:
1.78 anton 11814: The following words inspect memory.
1.21 crook 11815:
1.78 anton 11816: doc-?
11817: doc-dump
1.21 crook 11818:
1.78 anton 11819: And finally, @code{see} allows to inspect code:
1.21 crook 11820:
1.78 anton 11821: doc-see
11822: doc-xt-see
1.111 anton 11823: doc-simple-see
11824: doc-simple-see-range
1.182 anton 11825: doc-see-code
11826: doc-see-code-range
1.21 crook 11827:
1.78 anton 11828: @node Forgetting words, Debugging, Examining, Programming Tools
11829: @subsection Forgetting words
11830: @cindex words, forgetting
11831: @cindex forgeting words
1.21 crook 11832:
1.78 anton 11833: @c anton: other, maybe better places for this subsection: Defining Words;
11834: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11835:
1.78 anton 11836: Forth allows you to forget words (and everything that was alloted in the
11837: dictonary after them) in a LIFO manner.
1.21 crook 11838:
1.78 anton 11839: doc-marker
1.21 crook 11840:
1.78 anton 11841: The most common use of this feature is during progam development: when
11842: you change a source file, forget all the words it defined and load it
11843: again (since you also forget everything defined after the source file
11844: was loaded, you have to reload that, too). Note that effects like
11845: storing to variables and destroyed system words are not undone when you
11846: forget words. With a system like Gforth, that is fast enough at
11847: starting up and compiling, I find it more convenient to exit and restart
11848: Gforth, as this gives me a clean slate.
1.21 crook 11849:
1.78 anton 11850: Here's an example of using @code{marker} at the start of a source file
11851: that you are debugging; it ensures that you only ever have one copy of
11852: the file's definitions compiled at any time:
1.21 crook 11853:
1.78 anton 11854: @example
11855: [IFDEF] my-code
11856: my-code
11857: [ENDIF]
1.26 crook 11858:
1.78 anton 11859: marker my-code
11860: init-included-files
1.21 crook 11861:
1.78 anton 11862: \ .. definitions start here
11863: \ .
11864: \ .
11865: \ end
11866: @end example
1.21 crook 11867:
1.26 crook 11868:
1.78 anton 11869: @node Debugging, Assertions, Forgetting words, Programming Tools
11870: @subsection Debugging
11871: @cindex debugging
1.21 crook 11872:
1.78 anton 11873: Languages with a slow edit/compile/link/test development loop tend to
11874: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11875:
1.78 anton 11876: A much better (faster) way in fast-compiling languages is to add
11877: printing code at well-selected places, let the program run, look at
11878: the output, see where things went wrong, add more printing code, etc.,
11879: until the bug is found.
1.21 crook 11880:
1.78 anton 11881: The simple debugging aids provided in @file{debugs.fs}
11882: are meant to support this style of debugging.
1.21 crook 11883:
1.78 anton 11884: The word @code{~~} prints debugging information (by default the source
11885: location and the stack contents). It is easy to insert. If you use Emacs
11886: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11887: query-replace them with nothing). The deferred words
1.101 anton 11888: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11889: @code{~~}. The default source location output format works well with
11890: Emacs' compilation mode, so you can step through the program at the
11891: source level using @kbd{C-x `} (the advantage over a stepping debugger
11892: is that you can step in any direction and you know where the crash has
11893: happened or where the strange data has occurred).
1.21 crook 11894:
1.78 anton 11895: doc-~~
11896: doc-printdebugdata
1.101 anton 11897: doc-.debugline
1.21 crook 11898:
1.106 anton 11899: @cindex filenames in @code{~~} output
11900: @code{~~} (and assertions) will usually print the wrong file name if a
11901: marker is executed in the same file after their occurance. They will
11902: print @samp{*somewhere*} as file name if a marker is executed in the
11903: same file before their occurance.
11904:
11905:
1.78 anton 11906: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11907: @subsection Assertions
11908: @cindex assertions
1.21 crook 11909:
1.78 anton 11910: It is a good idea to make your programs self-checking, especially if you
11911: make an assumption that may become invalid during maintenance (for
11912: example, that a certain field of a data structure is never zero). Gforth
11913: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11914:
11915: @example
1.78 anton 11916: assert( @i{flag} )
1.26 crook 11917: @end example
11918:
1.78 anton 11919: The code between @code{assert(} and @code{)} should compute a flag, that
11920: should be true if everything is alright and false otherwise. It should
11921: not change anything else on the stack. The overall stack effect of the
11922: assertion is @code{( -- )}. E.g.
1.21 crook 11923:
1.26 crook 11924: @example
1.78 anton 11925: assert( 1 1 + 2 = ) \ what we learn in school
11926: assert( dup 0<> ) \ assert that the top of stack is not zero
11927: assert( false ) \ this code should not be reached
1.21 crook 11928: @end example
11929:
1.78 anton 11930: The need for assertions is different at different times. During
11931: debugging, we want more checking, in production we sometimes care more
11932: for speed. Therefore, assertions can be turned off, i.e., the assertion
11933: becomes a comment. Depending on the importance of an assertion and the
11934: time it takes to check it, you may want to turn off some assertions and
11935: keep others turned on. Gforth provides several levels of assertions for
11936: this purpose:
11937:
11938:
11939: doc-assert0(
11940: doc-assert1(
11941: doc-assert2(
11942: doc-assert3(
11943: doc-assert(
11944: doc-)
1.21 crook 11945:
11946:
1.78 anton 11947: The variable @code{assert-level} specifies the highest assertions that
11948: are turned on. I.e., at the default @code{assert-level} of one,
11949: @code{assert0(} and @code{assert1(} assertions perform checking, while
11950: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11951:
1.78 anton 11952: The value of @code{assert-level} is evaluated at compile-time, not at
11953: run-time. Therefore you cannot turn assertions on or off at run-time;
11954: you have to set the @code{assert-level} appropriately before compiling a
11955: piece of code. You can compile different pieces of code at different
11956: @code{assert-level}s (e.g., a trusted library at level 1 and
11957: newly-written code at level 3).
1.26 crook 11958:
11959:
1.78 anton 11960: doc-assert-level
1.26 crook 11961:
11962:
1.78 anton 11963: If an assertion fails, a message compatible with Emacs' compilation mode
11964: is produced and the execution is aborted (currently with @code{ABORT"}.
11965: If there is interest, we will introduce a special throw code. But if you
11966: intend to @code{catch} a specific condition, using @code{throw} is
11967: probably more appropriate than an assertion).
1.106 anton 11968:
11969: @cindex filenames in assertion output
11970: Assertions (and @code{~~}) will usually print the wrong file name if a
11971: marker is executed in the same file after their occurance. They will
11972: print @samp{*somewhere*} as file name if a marker is executed in the
11973: same file before their occurance.
1.44 crook 11974:
1.78 anton 11975: Definitions in ANS Forth for these assertion words are provided
11976: in @file{compat/assert.fs}.
1.26 crook 11977:
1.44 crook 11978:
1.78 anton 11979: @node Singlestep Debugger, , Assertions, Programming Tools
11980: @subsection Singlestep Debugger
11981: @cindex singlestep Debugger
11982: @cindex debugging Singlestep
1.44 crook 11983:
1.189 anton 11984: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 11985:
1.78 anton 11986: When you create a new word there's often the need to check whether it
11987: behaves correctly or not. You can do this by typing @code{dbg
11988: badword}. A debug session might look like this:
1.26 crook 11989:
1.78 anton 11990: @example
11991: : badword 0 DO i . LOOP ; ok
11992: 2 dbg badword
11993: : badword
11994: Scanning code...
1.44 crook 11995:
1.78 anton 11996: Nesting debugger ready!
1.44 crook 11997:
1.78 anton 11998: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11999: 400D4740 8049F68 DO -> [ 0 ]
12000: 400D4744 804A0C8 i -> [ 1 ] 00000
12001: 400D4748 400C5E60 . -> 0 [ 0 ]
12002: 400D474C 8049D0C LOOP -> [ 0 ]
12003: 400D4744 804A0C8 i -> [ 1 ] 00001
12004: 400D4748 400C5E60 . -> 1 [ 0 ]
12005: 400D474C 8049D0C LOOP -> [ 0 ]
12006: 400D4758 804B384 ; -> ok
12007: @end example
1.21 crook 12008:
1.78 anton 12009: Each line displayed is one step. You always have to hit return to
12010: execute the next word that is displayed. If you don't want to execute
12011: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12012: an overview what keys are available:
1.44 crook 12013:
1.78 anton 12014: @table @i
1.44 crook 12015:
1.78 anton 12016: @item @key{RET}
12017: Next; Execute the next word.
1.21 crook 12018:
1.78 anton 12019: @item n
12020: Nest; Single step through next word.
1.44 crook 12021:
1.78 anton 12022: @item u
12023: Unnest; Stop debugging and execute rest of word. If we got to this word
12024: with nest, continue debugging with the calling word.
1.44 crook 12025:
1.78 anton 12026: @item d
12027: Done; Stop debugging and execute rest.
1.21 crook 12028:
1.78 anton 12029: @item s
12030: Stop; Abort immediately.
1.44 crook 12031:
1.78 anton 12032: @end table
1.44 crook 12033:
1.78 anton 12034: Debugging large application with this mechanism is very difficult, because
12035: you have to nest very deeply into the program before the interesting part
12036: begins. This takes a lot of time.
1.26 crook 12037:
1.78 anton 12038: To do it more directly put a @code{BREAK:} command into your source code.
12039: When program execution reaches @code{BREAK:} the single step debugger is
12040: invoked and you have all the features described above.
1.44 crook 12041:
1.78 anton 12042: If you have more than one part to debug it is useful to know where the
12043: program has stopped at the moment. You can do this by the
12044: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12045: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12046:
1.26 crook 12047:
1.78 anton 12048: doc-dbg
12049: doc-break:
12050: doc-break"
1.44 crook 12051:
1.150 anton 12052: @c ------------------------------------------------------------
12053: @node C Interface, Assembler and Code Words, Programming Tools, Words
12054: @section C Interface
12055: @cindex C interface
12056: @cindex foreign language interface
12057: @cindex interface to C functions
12058:
1.178 anton 12059: Note that the C interface is not yet complete; callbacks are missing,
12060: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12061:
12062: @menu
12063: * Calling C Functions::
12064: * Declaring C Functions::
1.180 anton 12065: * Calling C function pointers::
1.196 anton 12066: * Defining library interfaces::
12067: * Declaring OS-level libraries::
1.150 anton 12068: * Callbacks::
1.178 anton 12069: * C interface internals::
1.155 anton 12070: * Low-Level C Interface Words::
1.150 anton 12071: @end menu
12072:
1.151 pazsan 12073: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12074: @subsection Calling C functions
1.155 anton 12075: @cindex C functions, calls to
12076: @cindex calling C functions
1.150 anton 12077:
1.151 pazsan 12078: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12079: can call it as follows: You push the arguments on the stack(s), and
12080: then call the word for the C function. The arguments have to be
12081: pushed in the same order as the arguments appear in the C
12082: documentation (i.e., the first argument is deepest on the stack).
12083: Integer and pointer arguments have to be pushed on the data stack,
12084: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12085: by the called C function.
1.150 anton 12086:
1.155 anton 12087: On returning from the C function, the return value, if any, resides on
12088: the appropriate stack: an integer return value is pushed on the data
12089: stack, an FP return value on the FP stack, and a void return value
12090: results in not pushing anything. Note that most C functions have a
12091: return value, even if that is often not used in C; in Forth, you have
12092: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12093:
1.177 anton 12094: The C interface automatically converts between the C type and the
12095: Forth type as necessary, on a best-effort basis (in some cases, there
12096: may be some loss).
1.150 anton 12097:
12098: As an example, consider the POSIX function @code{lseek()}:
12099:
12100: @example
12101: off_t lseek(int fd, off_t offset, int whence);
12102: @end example
12103:
12104: This function takes three integer arguments, and returns an integer
12105: argument, so a Forth call for setting the current file offset to the
12106: start of the file could look like this:
12107:
12108: @example
12109: fd @@ 0 SEEK_SET lseek -1 = if
12110: ... \ error handling
12111: then
12112: @end example
12113:
12114: You might be worried that an @code{off_t} does not fit into a cell, so
12115: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12116: of the return values. In that case, in your declaration of the
12117: function (@pxref{Declaring C Functions}) you should declare it to use
12118: double-cells for the off_t argument and return value, and maybe give
12119: the resulting Forth word a different name, like @code{dlseek}; the
12120: result could be called like this:
1.150 anton 12121:
12122: @example
12123: fd @@ 0. SEEK_SET dlseek -1. d= if
12124: ... \ error handling
12125: then
12126: @end example
12127:
12128: Passing and returning structs or unions is currently not supported by
12129: our interface@footnote{If you know the calling convention of your C
12130: compiler, you usually can call such functions in some way, but that
12131: way is usually not portable between platforms, and sometimes not even
12132: between C compilers.}.
12133:
1.177 anton 12134: Calling functions with a variable number of arguments (@emph{variadic}
12135: functions, e.g., @code{printf()}) is only supported by having you
12136: declare one function-calling word for each argument pattern, and
12137: calling the appropriate word for the desired pattern.
12138:
1.150 anton 12139:
1.155 anton 12140:
1.180 anton 12141: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12142: @subsection Declaring C Functions
1.155 anton 12143: @cindex C functions, declarations
12144: @cindex declaring C functions
1.150 anton 12145:
12146: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12147: it. The declaration consists of two parts:
12148:
12149: @table @b
12150:
12151: @item The C part
1.179 anton 12152: is the C declaration of the function, or more typically and portably,
12153: a C-style @code{#include} of a file that contains the declaration of
12154: the C function.
1.177 anton 12155:
12156: @item The Forth part
12157: declares the Forth types of the parameters and the Forth word name
12158: corresponding to the C function.
12159:
12160: @end table
12161:
12162: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12163: declarations are:
12164:
12165: @example
12166: \c #define _FILE_OFFSET_BITS 64
12167: \c #include <sys/types.h>
12168: \c #include <unistd.h>
12169: c-function lseek lseek n n n -- n
12170: c-function dlseek lseek n d n -- d
12171: @end example
12172:
1.178 anton 12173: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12174: of the line is ordinary C code. You can use as many lines of C
12175: declarations as you like, and they are visible for all further
12176: function declarations.
12177:
12178: The Forth part declares each interface word with @code{c-function},
12179: followed by the Forth name of the word, the C name of the called
12180: function, and the stack effect of the word. The stack effect contains
1.178 anton 12181: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12182: exactly one type for the return value. The possible types are:
12183:
12184: @table @code
12185:
12186: @item n
12187: single-cell integer
12188:
12189: @item a
12190: address (single-cell)
12191:
12192: @item d
12193: double-cell integer
12194:
12195: @item r
12196: floating-point value
12197:
12198: @item func
12199: C function pointer
12200:
12201: @item void
12202: no value (used as return type for void functions)
12203:
12204: @end table
12205:
12206: @cindex variadic C functions
12207:
12208: To deal with variadic C functions, you can declare one Forth word for
12209: every pattern you want to use, e.g.:
12210:
12211: @example
12212: \c #include <stdio.h>
12213: c-function printf-nr printf a n r -- n
12214: c-function printf-rn printf a r n -- n
12215: @end example
12216:
12217: Note that with C functions declared as variadic (or if you don't
12218: provide a prototype), the C interface has no C type to convert to, so
12219: no automatic conversion happens, which may lead to portability
12220: problems in some cases. In such cases you can perform the conversion
12221: explicitly on the C level, e.g., as follows:
12222:
12223: @example
1.178 anton 12224: \c #define printfll(s,ll) printf(s,(long long)ll)
12225: c-function printfll printfll a n -- n
1.177 anton 12226: @end example
12227:
12228: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12229: that casts (converts) the Forth single-cell integer into a
12230: C @code{long long} before calling @code{printf()}.
1.177 anton 12231:
12232: doc-\c
12233: doc-c-function
12234:
12235: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12236: dynamic linking. If these features are not available, there are
12237: other, less convenient and less portable C interfaces in @file{lib.fs}
12238: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12239: mostly incompatible with each other and with the documented C
12240: interface; you can find some examples for the @file{lib.fs} interface
12241: in @file{lib.fs}.
1.177 anton 12242:
12243:
1.196 anton 12244: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180 anton 12245: @subsection Calling C function pointers from Forth
12246: @cindex C function pointers, calling from Forth
1.177 anton 12247:
1.180 anton 12248: If you come across a C function pointer (e.g., in some C-constructed
12249: structure) and want to call it from your Forth program, you can also
12250: use the features explained until now to achieve that, as follows:
1.150 anton 12251:
1.180 anton 12252: Let us assume that there is a C function pointer type @code{func1}
12253: defined in some header file @file{func1.h}, and you know that these
12254: functions take one integer argument and return an integer result; and
12255: you want to call functions through such pointers. Just define
1.155 anton 12256:
1.180 anton 12257: @example
12258: \c #include <func1.h>
12259: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12260: c-function call-func1 call_func1 n func -- n
12261: @end example
12262:
12263: and then you can call a function pointed to by, say @code{func1a} as
12264: follows:
12265:
12266: @example
12267: -5 func1a call-func1 .
12268: @end example
12269:
12270: In the C part, @code{call_func} is defined as a macro to avoid having
12271: to declare the exact parameter and return types, so the C compiler
12272: knows them from the declaration of @code{func1}.
12273:
12274: The Forth word @code{call-func1} is similar to @code{execute}, except
12275: that it takes a C @code{func1} pointer instead of a Forth execution
12276: token, and it is specific to @code{func1} pointers. For each type of
12277: function pointer you want to call from Forth, you have to define
12278: a separate calling word.
12279:
12280:
1.196 anton 12281: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12282: @subsection Defining library interfaces
12283: @cindex giving a name to a library interface
12284: @cindex library interface names
12285:
12286: You can give a name to a bunch of C function declarations (a library
12287: interface), as follows:
12288:
12289: @example
12290: c-library lseek-lib
12291: \c #define _FILE_OFFSET_BITS 64
12292: ...
12293: end-c-library
12294: @end example
12295:
12296: The effect of giving such a name to the interface is that the
12297: generated files will contain that name, and when you use the interface
12298: a second time, it will use the existing files instead of generating
12299: and compiling them again, saving you time. Note that even if you
12300: change the declarations, the old (stale) files will be used, probably
12301: leading to errors. So, during development of the declarations we
12302: recommend not using @code{c-library}.
12303:
12304: Note that the library name is not allocated in the dictionary and
12305: therefore does not shadow dictionary names. It is used in the file
12306: system, so you have to use naming conventions appropriate for file
12307: systems. Also, you must not call a function you declare after
12308: @code{c-library} before you perform @code{end-c-library}.
12309:
12310: A major benefit of these named library interfaces is that, once they
12311: are generated, the tools used to generated them (in particular, the C
12312: compiler and libtool) are no longer needed, so the interface can be
12313: used even on machines that do not have the tools installed.
12314:
12315: doc-c-library-name
12316: doc-c-library
12317: doc-end-c-library
12318:
12319:
12320: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12321: @subsection Declaring OS-level libraries
1.195 anton 12322: @cindex Shared libraries in C interface
12323: @cindex Dynamically linked libraries in C interface
12324: @cindex Libraries in C interface
12325:
1.196 anton 12326: For calling some C functions, you need to link with a specific
12327: OS-level library that contains that function. E.g., the @code{sin}
12328: function requires linking a special library by using the command line
12329: switch @code{-lm}. In our C iterface you do the equivalent thing by
12330: calling @code{add-lib} as follows:
1.195 anton 12331:
12332: @example
12333: clear-libs
12334: s" m" add-lib
12335: \c #include <math.h>
12336: c-function sin sin r -- r
12337: @end example
12338:
12339: First, you clear any libraries that may have been declared earlier
12340: (you don't need them for @code{sin}); then you add the @code{m}
12341: library (actually @code{libm.so} or somesuch) to the currently
12342: declared libraries; you can add as many as you need. Finally you
12343: declare the function as shown above. Typically you will use the same
12344: set of library declarations for many function declarations; you need
12345: to write only one set for that, right at the beginning.
12346:
1.196 anton 12347: Note that you must not call @code{clear-libs} inside
12348: @code{c-library...end-c-library}; however, @code{c-library} performs
12349: the function of @code{clear-libs}, so @code{clear-libs} is not
12350: necessary, and you usually want to put @code{add-lib} calls inside
12351: @code{c-library...end-c-library}.
12352:
1.195 anton 12353: doc-clear-libs
12354: doc-add-lib
12355:
12356:
1.196 anton 12357: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150 anton 12358: @subsection Callbacks
1.155 anton 12359: @cindex Callback functions written in Forth
12360: @cindex C function pointers to Forth words
12361:
1.177 anton 12362: Callbacks are not yet supported by the documented C interface. You
12363: can use the undocumented @file{lib.fs} interface for callbacks.
12364:
1.155 anton 12365: In some cases you have to pass a function pointer to a C function,
12366: i.e., the library wants to call back to your application (and the
12367: pointed-to function is called a callback function). You can pass the
12368: address of an existing C function (that you get with @code{lib-sym},
12369: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12370: function, you probably want to define the function as a Forth word.
12371:
12372: @c I don't understand the existing callback interface from the example - anton
12373:
1.165 anton 12374:
12375: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12376: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12377: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12378: @c > > C-Funktionsadresse auf dem TOS).
12379: @c >
12380: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12381: @c > gesehen habe, wozu das gut ist.
12382: @c
12383: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12384: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12385: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12386: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12387: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12388: @c demselben Prototyp.
12389:
12390:
1.178 anton 12391: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12392: @subsection How the C interface works
12393:
12394: The documented C interface works by generating a C code out of the
12395: declarations.
12396:
12397: In particular, for every Forth word declared with @code{c-function},
12398: it generates a wrapper function in C that takes the Forth data from
12399: the Forth stacks, and calls the target C function with these data as
12400: arguments. The C compiler then performs an implicit conversion
12401: between the Forth type from the stack, and the C type for the
12402: parameter, which is given by the C function prototype. After the C
12403: function returns, the return value is likewise implicitly converted to
12404: a Forth type and written back on the stack.
12405:
12406: The @code{\c} lines are literally included in the C code (but without
12407: the @code{\c}), and provide the necessary declarations so that the C
12408: compiler knows the C types and has enough information to perform the
12409: conversion.
12410:
12411: These wrapper functions are eventually compiled and dynamically linked
12412: into Gforth, and then they can be called.
12413:
1.195 anton 12414: The libraries added with @code{add-lib} are used in the compile
12415: command line to specify dependent libraries with @code{-l@var{lib}},
12416: causing these libraries to be dynamically linked when the wrapper
12417: function is linked.
12418:
1.177 anton 12419:
1.178 anton 12420: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12421: @subsection Low-Level C Interface Words
1.44 crook 12422:
1.155 anton 12423: doc-open-lib
12424: doc-lib-sym
1.196 anton 12425: doc-lib-error
1.177 anton 12426: doc-call-c
1.26 crook 12427:
1.78 anton 12428: @c -------------------------------------------------------------
1.150 anton 12429: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12430: @section Assembler and Code Words
12431: @cindex assembler
12432: @cindex code words
1.44 crook 12433:
1.78 anton 12434: @menu
12435: * Code and ;code::
12436: * Common Assembler:: Assembler Syntax
12437: * Common Disassembler::
12438: * 386 Assembler:: Deviations and special cases
12439: * Alpha Assembler:: Deviations and special cases
12440: * MIPS assembler:: Deviations and special cases
1.161 anton 12441: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 12442: * ARM Assembler:: Deviations and special cases
1.78 anton 12443: * Other assemblers:: How to write them
12444: @end menu
1.21 crook 12445:
1.78 anton 12446: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12447: @subsection @code{Code} and @code{;code}
1.26 crook 12448:
1.78 anton 12449: Gforth provides some words for defining primitives (words written in
12450: machine code), and for defining the machine-code equivalent of
12451: @code{DOES>}-based defining words. However, the machine-independent
12452: nature of Gforth poses a few problems: First of all, Gforth runs on
12453: several architectures, so it can provide no standard assembler. What's
12454: worse is that the register allocation not only depends on the processor,
12455: but also on the @code{gcc} version and options used.
1.44 crook 12456:
1.78 anton 12457: The words that Gforth offers encapsulate some system dependences (e.g.,
12458: the header structure), so a system-independent assembler may be used in
12459: Gforth. If you do not have an assembler, you can compile machine code
12460: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12461: because these words emit stuff in @i{data} space; it works because
12462: Gforth has unified code/data spaces. Assembler isn't likely to be
12463: portable anyway.}.
1.21 crook 12464:
1.44 crook 12465:
1.78 anton 12466: doc-assembler
12467: doc-init-asm
12468: doc-code
12469: doc-end-code
12470: doc-;code
12471: doc-flush-icache
1.44 crook 12472:
1.21 crook 12473:
1.78 anton 12474: If @code{flush-icache} does not work correctly, @code{code} words
12475: etc. will not work (reliably), either.
1.44 crook 12476:
1.78 anton 12477: The typical usage of these @code{code} words can be shown most easily by
12478: analogy to the equivalent high-level defining words:
1.44 crook 12479:
1.78 anton 12480: @example
12481: : foo code foo
12482: <high-level Forth words> <assembler>
12483: ; end-code
12484:
12485: : bar : bar
12486: <high-level Forth words> <high-level Forth words>
12487: CREATE CREATE
12488: <high-level Forth words> <high-level Forth words>
12489: DOES> ;code
12490: <high-level Forth words> <assembler>
12491: ; end-code
12492: @end example
1.21 crook 12493:
1.78 anton 12494: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12495:
1.78 anton 12496: @cindex registers of the inner interpreter
12497: In the assembly code you will want to refer to the inner interpreter's
12498: registers (e.g., the data stack pointer) and you may want to use other
12499: registers for temporary storage. Unfortunately, the register allocation
12500: is installation-dependent.
1.44 crook 12501:
1.78 anton 12502: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12503: (return stack pointer) may be in different places in @code{gforth} and
12504: @code{gforth-fast}, or different installations. This means that you
12505: cannot write a @code{NEXT} routine that works reliably on both versions
12506: or different installations; so for doing @code{NEXT}, I recommend
12507: jumping to @code{' noop >code-address}, which contains nothing but a
12508: @code{NEXT}.
1.21 crook 12509:
1.78 anton 12510: For general accesses to the inner interpreter's registers, the easiest
12511: solution is to use explicit register declarations (@pxref{Explicit Reg
12512: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12513: all of the inner interpreter's registers: You have to compile Gforth
12514: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12515: the appropriate declarations must be present in the @code{machine.h}
12516: file (see @code{mips.h} for an example; you can find a full list of all
12517: declarable register symbols with @code{grep register engine.c}). If you
12518: give explicit registers to all variables that are declared at the
12519: beginning of @code{engine()}, you should be able to use the other
12520: caller-saved registers for temporary storage. Alternatively, you can use
12521: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12522: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12523: reserve a register (however, this restriction on register allocation may
12524: slow Gforth significantly).
1.44 crook 12525:
1.78 anton 12526: If this solution is not viable (e.g., because @code{gcc} does not allow
12527: you to explicitly declare all the registers you need), you have to find
12528: out by looking at the code where the inner interpreter's registers
12529: reside and which registers can be used for temporary storage. You can
12530: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12531:
1.78 anton 12532: In any case, it is good practice to abstract your assembly code from the
12533: actual register allocation. E.g., if the data stack pointer resides in
12534: register @code{$17}, create an alias for this register called @code{sp},
12535: and use that in your assembly code.
1.21 crook 12536:
1.78 anton 12537: @cindex code words, portable
12538: Another option for implementing normal and defining words efficiently
12539: is to add the desired functionality to the source of Gforth. For normal
12540: words you just have to edit @file{primitives} (@pxref{Automatic
12541: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12542: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12543: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12544:
1.78 anton 12545: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12546: @subsection Common Assembler
1.44 crook 12547:
1.78 anton 12548: The assemblers in Gforth generally use a postfix syntax, i.e., the
12549: instruction name follows the operands.
1.21 crook 12550:
1.78 anton 12551: The operands are passed in the usual order (the same that is used in the
12552: manual of the architecture). Since they all are Forth words, they have
12553: to be separated by spaces; you can also use Forth words to compute the
12554: operands.
1.44 crook 12555:
1.78 anton 12556: The instruction names usually end with a @code{,}. This makes it easier
12557: to visually separate instructions if you put several of them on one
12558: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12559:
1.78 anton 12560: Registers are usually specified by number; e.g., (decimal) @code{11}
12561: specifies registers R11 and F11 on the Alpha architecture (which one,
12562: depends on the instruction). The usual names are also available, e.g.,
12563: @code{s2} for R11 on Alpha.
1.21 crook 12564:
1.78 anton 12565: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12566: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12567: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12568: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12569: conditions are specified in a way specific to each assembler.
1.1 anton 12570:
1.78 anton 12571: Note that the register assignments of the Gforth engine can change
12572: between Gforth versions, or even between different compilations of the
12573: same Gforth version (e.g., if you use a different GCC version). So if
12574: you want to refer to Gforth's registers (e.g., the stack pointer or
12575: TOS), I recommend defining your own words for refering to these
12576: registers, and using them later on; then you can easily adapt to a
12577: changed register assignment. The stability of the register assignment
12578: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12579:
1.100 anton 12580: The most common use of these registers is to dispatch to the next word
12581: (the @code{next} routine). A portable way to do this is to jump to
12582: @code{' noop >code-address} (of course, this is less efficient than
12583: integrating the @code{next} code and scheduling it well).
1.1 anton 12584:
1.96 anton 12585: Another difference between Gforth version is that the top of stack is
12586: kept in memory in @code{gforth} and, on most platforms, in a register in
12587: @code{gforth-fast}.
12588:
1.78 anton 12589: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12590: @subsection Common Disassembler
1.127 anton 12591: @cindex disassembler, general
12592: @cindex gdb disassembler
1.1 anton 12593:
1.78 anton 12594: You can disassemble a @code{code} word with @code{see}
12595: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12596:
1.127 anton 12597: doc-discode
1.44 crook 12598:
1.127 anton 12599: There are two kinds of disassembler for Gforth: The Forth disassembler
12600: (available on some CPUs) and the gdb disassembler (available on
12601: platforms with @command{gdb} and @command{mktemp}). If both are
12602: available, the Forth disassembler is used by default. If you prefer
12603: the gdb disassembler, say
12604:
12605: @example
12606: ' disasm-gdb is discode
12607: @end example
12608:
12609: If neither is available, @code{discode} performs @code{dump}.
12610:
12611: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12612: assembler (i.e., same syntax, etc.). It also includes additional
12613: information in comments. In particular, the address of the instruction
12614: is given in a comment before the instruction.
1.1 anton 12615:
1.127 anton 12616: The gdb disassembler produces output in the same format as the gdb
12617: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12618: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12619: the 386 and AMD64 architectures).
12620:
1.78 anton 12621: @code{See} may display more or less than the actual code of the word,
12622: because the recognition of the end of the code is unreliable. You can
1.127 anton 12623: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12624: the code word is not immediately followed by a named word. If you have
1.116 anton 12625: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12626: to ensure that the end is recognized.
1.21 crook 12627:
1.78 anton 12628: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12629: @subsection 386 Assembler
1.44 crook 12630:
1.78 anton 12631: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12632: available under GPL, and originally part of bigFORTH.
1.21 crook 12633:
1.78 anton 12634: The 386 disassembler included in Gforth was written by Andrew McKewan
12635: and is in the public domain.
1.21 crook 12636:
1.91 anton 12637: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12638:
1.78 anton 12639: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12640:
1.78 anton 12641: The assembler includes all instruction of the Athlon, i.e. 486 core
12642: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12643: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12644: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12645:
1.78 anton 12646: There are several prefixes to switch between different operation sizes,
12647: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12648: double-word accesses. Addressing modes can be switched with @code{.wa}
12649: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12650: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12651:
1.78 anton 12652: For floating point operations, the prefixes are @code{.fs} (IEEE
12653: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12654: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12655:
1.78 anton 12656: The MMX opcodes don't have size prefixes, they are spelled out like in
12657: the Intel assembler. Instead of move from and to memory, there are
12658: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12659:
1.78 anton 12660: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12661: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12662: e.g., @code{3 #}. Here are some examples of addressing modes in various
12663: syntaxes:
1.21 crook 12664:
1.26 crook 12665: @example
1.91 anton 12666: Gforth Intel (NASM) AT&T (gas) Name
12667: .w ax ax %ax register (16 bit)
12668: ax eax %eax register (32 bit)
12669: 3 # offset 3 $3 immediate
12670: 1000 #) byte ptr 1000 1000 displacement
12671: bx ) [ebx] (%ebx) base
12672: 100 di d) 100[edi] 100(%edi) base+displacement
12673: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12674: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12675: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12676: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12677: @end example
12678:
12679: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12680: @code{DI)} to enforce 32-bit displacement fields (useful for
12681: later patching).
1.21 crook 12682:
1.78 anton 12683: Some example of instructions are:
1.1 anton 12684:
12685: @example
1.78 anton 12686: ax bx mov \ move ebx,eax
12687: 3 # ax mov \ mov eax,3
1.137 pazsan 12688: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12689: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12690: .w ax bx mov \ mov bx,ax
1.1 anton 12691: @end example
12692:
1.78 anton 12693: The following forms are supported for binary instructions:
1.1 anton 12694:
12695: @example
1.78 anton 12696: <reg> <reg> <inst>
12697: <n> # <reg> <inst>
12698: <mem> <reg> <inst>
12699: <reg> <mem> <inst>
1.136 pazsan 12700: <n> # <mem> <inst>
1.1 anton 12701: @end example
12702:
1.136 pazsan 12703: The shift/rotate syntax is:
1.1 anton 12704:
1.26 crook 12705: @example
1.78 anton 12706: <reg/mem> 1 # shl \ shortens to shift without immediate
12707: <reg/mem> 4 # shl
12708: <reg/mem> cl shl
1.26 crook 12709: @end example
1.1 anton 12710:
1.78 anton 12711: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12712: the byte version.
1.1 anton 12713:
1.78 anton 12714: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12715: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12716: pc < >= <= >}. (Note that most of these words shadow some Forth words
12717: when @code{assembler} is in front of @code{forth} in the search path,
12718: e.g., in @code{code} words). Currently the control structure words use
12719: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12720: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12721:
1.78 anton 12722: Here is an example of a @code{code} word (assumes that the stack pointer
12723: is in esi and the TOS is in ebx):
1.21 crook 12724:
1.26 crook 12725: @example
1.78 anton 12726: code my+ ( n1 n2 -- n )
12727: 4 si D) bx add
12728: 4 # si add
12729: Next
12730: end-code
1.26 crook 12731: @end example
1.21 crook 12732:
1.161 anton 12733:
1.78 anton 12734: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12735: @subsection Alpha Assembler
1.21 crook 12736:
1.78 anton 12737: The Alpha assembler and disassembler were originally written by Bernd
12738: Thallner.
1.26 crook 12739:
1.78 anton 12740: The register names @code{a0}--@code{a5} are not available to avoid
12741: shadowing hex numbers.
1.2 jwilke 12742:
1.78 anton 12743: Immediate forms of arithmetic instructions are distinguished by a
12744: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12745: does not count as arithmetic instruction).
1.2 jwilke 12746:
1.78 anton 12747: You have to specify all operands to an instruction, even those that
12748: other assemblers consider optional, e.g., the destination register for
12749: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12750:
1.78 anton 12751: You can specify conditions for @code{if,} by removing the first @code{b}
12752: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12753:
1.26 crook 12754: @example
1.78 anton 12755: 11 fgt if, \ if F11>0e
12756: ...
12757: endif,
1.26 crook 12758: @end example
1.2 jwilke 12759:
1.78 anton 12760: @code{fbgt,} gives @code{fgt}.
12761:
1.161 anton 12762: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12763: @subsection MIPS assembler
1.2 jwilke 12764:
1.78 anton 12765: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12766:
1.78 anton 12767: Currently the assembler and disassembler only cover the MIPS-I
12768: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12769:
1.78 anton 12770: The register names @code{$a0}--@code{$a3} are not available to avoid
12771: shadowing hex numbers.
1.2 jwilke 12772:
1.78 anton 12773: Because there is no way to distinguish registers from immediate values,
12774: you have to explicitly use the immediate forms of instructions, i.e.,
12775: @code{addiu,}, not just @code{addu,} (@command{as} does this
12776: implicitly).
1.2 jwilke 12777:
1.78 anton 12778: If the architecture manual specifies several formats for the instruction
12779: (e.g., for @code{jalr,}), you usually have to use the one with more
12780: arguments (i.e., two for @code{jalr,}). When in doubt, see
12781: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12782:
1.78 anton 12783: Branches and jumps in the MIPS architecture have a delay slot. You have
12784: to fill it yourself (the simplest way is to use @code{nop,}), the
12785: assembler does not do it for you (unlike @command{as}). Even
12786: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12787: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12788: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12789:
1.78 anton 12790: Note that you must not put branches, jumps, or @code{li,} into the delay
12791: slot: @code{li,} may expand to several instructions, and control flow
12792: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12793:
1.78 anton 12794: For branches the argument specifying the target is a relative address;
12795: You have to add the address of the delay slot to get the absolute
12796: address.
1.1 anton 12797:
1.78 anton 12798: The MIPS architecture also has load delay slots and restrictions on
12799: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12800: yourself to satisfy these restrictions, the assembler does not do it for
12801: you.
1.1 anton 12802:
1.78 anton 12803: You can specify the conditions for @code{if,} etc. by taking a
12804: conditional branch and leaving away the @code{b} at the start and the
12805: @code{,} at the end. E.g.,
1.1 anton 12806:
1.26 crook 12807: @example
1.78 anton 12808: 4 5 eq if,
12809: ... \ do something if $4 equals $5
12810: then,
1.26 crook 12811: @end example
1.1 anton 12812:
1.161 anton 12813:
1.193 dvdkhlng 12814: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161 anton 12815: @subsection PowerPC assembler
12816:
1.162 anton 12817: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12818: Revucky.
12819:
1.162 anton 12820: This assembler does not follow the convention of ending mnemonic names
12821: with a ``,'', so some mnemonic names shadow regular Forth words (in
12822: particular: @code{and or xor fabs}); so if you want to use the Forth
12823: words, you have to make them visible first, e.g., with @code{also
12824: forth}.
12825:
1.161 anton 12826: Registers are referred to by their number, e.g., @code{9} means the
12827: integer register 9 or the FP register 9 (depending on the
12828: instruction).
12829:
12830: Because there is no way to distinguish registers from immediate values,
12831: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12832: @code{addi,}, not just @code{add,}.
1.161 anton 12833:
1.162 anton 12834: The assembler and disassembler usually support the most general form
1.161 anton 12835: of an instruction, but usually not the shorter forms (especially for
12836: branches).
12837:
12838:
1.193 dvdkhlng 12839: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12840: @subsection ARM Assembler
1.161 anton 12841:
1.193 dvdkhlng 12842: The ARM assembler included in Gforth was written from scratch by David
12843: Kuehling.
12844:
12845: The assembler includes all instruction of ARM architecture version 4,
12846: but does not (yet) have support for Thumb instructions. It also lacks
12847: support for any co-processors.
12848:
12849: The assembler uses a postfix syntax with the target operand specified
12850: last. For load/store instructions the last operand will be the
12851: register(s) to be loaded from/stored to.
12852:
12853: Registers are specified by their names @code{r0} through @code{r15},
12854: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12855: @code{fp} provided for convenience. Note that @code{ip} means intra
12856: procedure call scratch register (@code{r12}) and does not refer to the
12857: instruction pointer.
12858:
12859: Condition codes can be specified anywhere in the instruction, but will
12860: be most readable if specified just in front of the mnemonic. The 'S'
12861: flag is not a separate word, but encoded into instruction mnemonics,
12862: ie. just use @code{adds,} instead of @code{add,} if you want the
12863: status register to be updated.
12864:
12865: The following table lists the syntax of operands for general
12866: instructions:
12867:
12868: @example
12869: Gforth normal assembler description
12870: 123 # #123 immediate
12871: r12 r12 register
12872: r12 4 #LSL r12, LSL #4 shift left by immediate
12873: r12 r1 #LSL r12, LSL r1 shift left by register
12874: r12 4 #LSR r12, LSR #4 shift right by immediate
12875: r12 r1 #LSR r12, LSR r1 shift right by register
12876: r12 4 #ASR r12, ASR #4 arithmetic shift right
12877: r12 r1 #ASR r12, ASR r1 ... by register
12878: r12 4 #ROR r12, ROR #4 rotate right by immediate
12879: r12 r1 #ROR r12, ROR r1 ... by register
12880: r12 RRX r12, RRX rotate right with extend by 1
12881: @end example
12882:
12883: Memory operand syntax is listed in this table:
12884:
12885: @example
12886: Gforth normal assembler description
12887: r4 ] [r4] register
12888: r4 4 #] [r4, #+4] register with immediate offset
12889: r4 -4 #] [r4, #-4] with negative offset
12890: r4 r1 +] [r4, +r1] register with register offset
12891: r4 r1 -] [r4, -r1] with negated register offset
12892: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
12893: r4 4 #]! [r4, #+4]! immediate preincrement
12894: r4 r1 +]! [r4, +r1]! register preincrement
12895: r4 r1 -]! [r4, +r1]! register predecrement
12896: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
12897: r4 -4 ]# [r4], #-4 immediate postdecrement
12898: r4 r1 ]+ [r4], r1 register postincrement
12899: r4 r1 ]- [r4], -r1 register postdecrement
12900: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
12901: ' xyz >body [#] xyz PC-relative addressing
12902: @end example
12903:
12904: Register lists for load/store multiple instructions are started and
12905: terminated by using the words @code{@{} and @code{@}}
12906: respectivly. Between braces, register names can be listed one by one,
12907: or register ranges can be formed by using the postfix operator
12908: @code{r-r}. The @code{^} flag is not encoded in the register list
12909: operand, but instead directly encoded into the instruction mnemonic,
12910: ie. use @code{^ldm,} and @code{^stm,}.
12911:
12912: Addressing modes for load/store multiple are not encoded as
12913: instruction suffixes, but instead specified after the register that
12914: supplies the address. Use one of @code{DA}, @code{IA}, @code{DB},
12915: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
12916:
12917: The following table gives some examples:
12918:
12919: @example
12920: Gforth normal assembler
12921: @{ r0 r7 r8 @} r4 ia stm, stmia @{r0,r7,r8@}, r4
12922: @{ r0 r7 r8 @} r4 db! ldm, ldmdb @{r0,r7,r8@}, r4!
12923: @{ r0 r15 r-r @} sp ia! ^ldm, ldmfd @{r0-r15@}^, sp!
12924: @end example
12925:
12926: Conditions for control structure words are specified in front of a
12927: word:
12928:
12929: @example
12930: r1 r2 cmp, \ compare r1 and r2
12931: eq if, \ equal?
12932: ... \ code executed if r1 == r2
12933: then,
12934: @end example
12935:
12936: Here is an example of a @code{code} word (assumes that the stack
12937: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
12938: clobbered):
12939:
12940: @example
12941: code my+ ( n1 n2 -- n3 )
12942: r9 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
12943: r2 r3 r3 add, \ r3 = n2+n1
12944: r9 -4 #]! r3 str, \ push r3
12945: next,
12946: end-code
12947: @end example
12948:
12949: Look at @file{arch/arm/asm-example.fs} for more examples.
12950:
12951: @node Other assemblers, , ARM Assembler, Assembler and Code Words
1.78 anton 12952: @subsection Other assemblers
12953:
12954: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12955: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12956: an assembler already. If you are writing them from scratch, please use
12957: a similar syntax style as the one we use (i.e., postfix, commas at the
12958: end of the instruction names, @pxref{Common Assembler}); make the output
12959: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12960: similar to the style we used.
12961:
12962: Hints on implementation: The most important part is to have a good test
12963: suite that contains all instructions. Once you have that, the rest is
12964: easy. For actual coding you can take a look at
12965: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12966: the assembler and disassembler, avoiding redundancy and some potential
12967: bugs. You can also look at that file (and @pxref{Advanced does> usage
12968: example}) to get ideas how to factor a disassembler.
12969:
12970: Start with the disassembler, because it's easier to reuse data from the
12971: disassembler for the assembler than the other way round.
1.1 anton 12972:
1.78 anton 12973: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12974: how simple it can be.
1.1 anton 12975:
1.161 anton 12976:
12977:
12978:
1.78 anton 12979: @c -------------------------------------------------------------
12980: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12981: @section Threading Words
12982: @cindex threading words
1.1 anton 12983:
1.78 anton 12984: @cindex code address
12985: These words provide access to code addresses and other threading stuff
12986: in Gforth (and, possibly, other interpretive Forths). It more or less
12987: abstracts away the differences between direct and indirect threading
12988: (and, for direct threading, the machine dependences). However, at
12989: present this wordset is still incomplete. It is also pretty low-level;
12990: some day it will hopefully be made unnecessary by an internals wordset
12991: that abstracts implementation details away completely.
1.1 anton 12992:
1.78 anton 12993: The terminology used here stems from indirect threaded Forth systems; in
12994: such a system, the XT of a word is represented by the CFA (code field
12995: address) of a word; the CFA points to a cell that contains the code
12996: address. The code address is the address of some machine code that
12997: performs the run-time action of invoking the word (e.g., the
12998: @code{dovar:} routine pushes the address of the body of the word (a
12999: variable) on the stack
13000: ).
1.1 anton 13001:
1.78 anton 13002: @cindex code address
13003: @cindex code field address
13004: In an indirect threaded Forth, you can get the code address of @i{name}
13005: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13006: >code-address}, independent of the threading method.
1.1 anton 13007:
1.78 anton 13008: doc-threading-method
13009: doc->code-address
13010: doc-code-address!
1.1 anton 13011:
1.78 anton 13012: @cindex @code{does>}-handler
13013: @cindex @code{does>}-code
13014: For a word defined with @code{DOES>}, the code address usually points to
13015: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13016: routine (in Gforth on some platforms, it can also point to the dodoes
13017: routine itself). What you are typically interested in, though, is
13018: whether a word is a @code{DOES>}-defined word, and what Forth code it
13019: executes; @code{>does-code} tells you that.
1.1 anton 13020:
1.78 anton 13021: doc->does-code
1.1 anton 13022:
1.78 anton 13023: To create a @code{DOES>}-defined word with the following basic words,
13024: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13025: @code{/does-handler} aus behind you have to place your executable Forth
13026: code. Finally you have to create a word and modify its behaviour with
13027: @code{does-handler!}.
1.1 anton 13028:
1.78 anton 13029: doc-does-code!
13030: doc-does-handler!
13031: doc-/does-handler
1.1 anton 13032:
1.78 anton 13033: The code addresses produced by various defining words are produced by
13034: the following words:
1.1 anton 13035:
1.78 anton 13036: doc-docol:
13037: doc-docon:
13038: doc-dovar:
13039: doc-douser:
13040: doc-dodefer:
13041: doc-dofield:
1.1 anton 13042:
1.99 anton 13043: @cindex definer
13044: The following two words generalize @code{>code-address},
13045: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13046:
13047: doc->definer
13048: doc-definer!
13049:
1.26 crook 13050: @c -------------------------------------------------------------
1.78 anton 13051: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 13052: @section Passing Commands to the Operating System
13053: @cindex operating system - passing commands
13054: @cindex shell commands
13055:
13056: Gforth allows you to pass an arbitrary string to the host operating
13057: system shell (if such a thing exists) for execution.
13058:
13059: doc-sh
13060: doc-system
13061: doc-$?
1.23 crook 13062: doc-getenv
1.44 crook 13063:
1.26 crook 13064: @c -------------------------------------------------------------
1.47 crook 13065: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13066: @section Keeping track of Time
13067: @cindex time-related words
13068:
13069: doc-ms
13070: doc-time&date
1.79 anton 13071: doc-utime
13072: doc-cputime
1.47 crook 13073:
13074:
13075: @c -------------------------------------------------------------
13076: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 13077: @section Miscellaneous Words
13078: @cindex miscellaneous words
13079:
1.29 crook 13080: @comment TODO find homes for these
13081:
1.26 crook 13082: These section lists the ANS Forth words that are not documented
1.21 crook 13083: elsewhere in this manual. Ultimately, they all need proper homes.
13084:
1.68 anton 13085: doc-quit
1.44 crook 13086:
1.26 crook 13087: The following ANS Forth words are not currently supported by Gforth
1.27 crook 13088: (@pxref{ANS conformance}):
1.21 crook 13089:
13090: @code{EDITOR}
13091: @code{EMIT?}
13092: @code{FORGET}
13093:
1.24 anton 13094: @c ******************************************************************
13095: @node Error messages, Tools, Words, Top
13096: @chapter Error messages
13097: @cindex error messages
13098: @cindex backtrace
13099:
13100: A typical Gforth error message looks like this:
13101:
13102: @example
1.86 anton 13103: in file included from \evaluated string/:-1
1.24 anton 13104: in file included from ./yyy.fs:1
13105: ./xxx.fs:4: Invalid memory address
1.134 anton 13106: >>>bar<<<
1.79 anton 13107: Backtrace:
1.25 anton 13108: $400E664C @@
13109: $400E6664 foo
1.24 anton 13110: @end example
13111:
13112: The message identifying the error is @code{Invalid memory address}. The
13113: error happened when text-interpreting line 4 of the file
13114: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13115: word on the line where the error happened, is pointed out (with
1.134 anton 13116: @code{>>>} and @code{<<<}).
1.24 anton 13117:
13118: The file containing the error was included in line 1 of @file{./yyy.fs},
13119: and @file{yyy.fs} was included from a non-file (in this case, by giving
13120: @file{yyy.fs} as command-line parameter to Gforth).
13121:
13122: At the end of the error message you find a return stack dump that can be
13123: interpreted as a backtrace (possibly empty). On top you find the top of
13124: the return stack when the @code{throw} happened, and at the bottom you
13125: find the return stack entry just above the return stack of the topmost
13126: text interpreter.
13127:
13128: To the right of most return stack entries you see a guess for the word
13129: that pushed that return stack entry as its return address. This gives a
13130: backtrace. In our case we see that @code{bar} called @code{foo}, and
13131: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13132: address} exception).
13133:
13134: Note that the backtrace is not perfect: We don't know which return stack
13135: entries are return addresses (so we may get false positives); and in
13136: some cases (e.g., for @code{abort"}) we cannot determine from the return
13137: address the word that pushed the return address, so for some return
13138: addresses you see no names in the return stack dump.
1.25 anton 13139:
13140: @cindex @code{catch} and backtraces
13141: The return stack dump represents the return stack at the time when a
13142: specific @code{throw} was executed. In programs that make use of
13143: @code{catch}, it is not necessarily clear which @code{throw} should be
13144: used for the return stack dump (e.g., consider one @code{throw} that
13145: indicates an error, which is caught, and during recovery another error
1.160 anton 13146: happens; which @code{throw} should be used for the stack dump?).
13147: Gforth presents the return stack dump for the first @code{throw} after
13148: the last executed (not returned-to) @code{catch} or @code{nothrow};
13149: this works well in the usual case. To get the right backtrace, you
13150: usually want to insert @code{nothrow} or @code{['] false catch drop}
13151: after a @code{catch} if the error is not rethrown.
1.25 anton 13152:
13153: @cindex @code{gforth-fast} and backtraces
13154: @cindex @code{gforth-fast}, difference from @code{gforth}
13155: @cindex backtraces with @code{gforth-fast}
13156: @cindex return stack dump with @code{gforth-fast}
1.79 anton 13157: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 13158: from primitives (e.g., invalid memory address, stack empty etc.);
13159: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 13160: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 13161: exception caused by a primitive in @code{gforth-fast}, you will
13162: typically see no return stack dump at all; however, if the exception is
13163: caught by @code{catch} (e.g., for restoring some state), and then
13164: @code{throw}n again, the return stack dump will be for the first such
13165: @code{throw}.
1.2 jwilke 13166:
1.5 anton 13167: @c ******************************************************************
1.24 anton 13168: @node Tools, ANS conformance, Error messages, Top
1.1 anton 13169: @chapter Tools
13170:
13171: @menu
13172: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 13173: * Stack depth changes:: Where does this stack item come from?
1.1 anton 13174: @end menu
13175:
13176: See also @ref{Emacs and Gforth}.
13177:
1.126 pazsan 13178: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 13179: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13180: @cindex @file{ans-report.fs}
13181: @cindex report the words used in your program
13182: @cindex words used in your program
13183:
13184: If you want to label a Forth program as ANS Forth Program, you must
13185: document which wordsets the program uses; for extension wordsets, it is
13186: helpful to list the words the program requires from these wordsets
13187: (because Forth systems are allowed to provide only some words of them).
13188:
13189: The @file{ans-report.fs} tool makes it easy for you to determine which
13190: words from which wordset and which non-ANS words your application
13191: uses. You simply have to include @file{ans-report.fs} before loading the
13192: program you want to check. After loading your program, you can get the
13193: report with @code{print-ans-report}. A typical use is to run this as
13194: batch job like this:
13195: @example
13196: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13197: @end example
13198:
13199: The output looks like this (for @file{compat/control.fs}):
13200: @example
13201: The program uses the following words
13202: from CORE :
13203: : POSTPONE THEN ; immediate ?dup IF 0=
13204: from BLOCK-EXT :
13205: \
13206: from FILE :
13207: (
13208: @end example
13209:
13210: @subsection Caveats
13211:
13212: Note that @file{ans-report.fs} just checks which words are used, not whether
13213: they are used in an ANS Forth conforming way!
13214:
13215: Some words are defined in several wordsets in the
13216: standard. @file{ans-report.fs} reports them for only one of the
13217: wordsets, and not necessarily the one you expect. It depends on usage
13218: which wordset is the right one to specify. E.g., if you only use the
13219: compilation semantics of @code{S"}, it is a Core word; if you also use
13220: its interpretation semantics, it is a File word.
1.124 anton 13221:
13222:
1.127 anton 13223: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13224: @section Stack depth changes during interpretation
13225: @cindex @file{depth-changes.fs}
13226: @cindex depth changes during interpretation
13227: @cindex stack depth changes during interpretation
13228: @cindex items on the stack after interpretation
13229:
13230: Sometimes you notice that, after loading a file, there are items left
13231: on the stack. The tool @file{depth-changes.fs} helps you find out
13232: quickly where in the file these stack items are coming from.
13233:
13234: The simplest way of using @file{depth-changes.fs} is to include it
13235: before the file(s) you want to check, e.g.:
13236:
13237: @example
13238: gforth depth-changes.fs my-file.fs
13239: @end example
13240:
13241: This will compare the stack depths of the data and FP stack at every
13242: empty line (in interpretation state) against these depths at the last
13243: empty line (in interpretation state). If the depths are not equal,
13244: the position in the file and the stack contents are printed with
13245: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13246: change has occured in the paragraph of non-empty lines before the
13247: indicated line. It is a good idea to leave an empty line at the end
13248: of the file, so the last paragraph is checked, too.
13249:
13250: Checking only at empty lines usually works well, but sometimes you
13251: have big blocks of non-empty lines (e.g., when building a big table),
13252: and you want to know where in this block the stack depth changed. You
13253: can check all interpreted lines with
13254:
13255: @example
13256: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13257: @end example
13258:
13259: This checks the stack depth at every end-of-line. So the depth change
13260: occured in the line reported by the @code{~~} (not in the line
13261: before).
13262:
13263: Note that, while this offers better accuracy in indicating where the
13264: stack depth changes, it will often report many intentional stack depth
13265: changes (e.g., when an interpreted computation stretches across
13266: several lines). You can suppress the checking of some lines by
13267: putting backslashes at the end of these lines (not followed by white
13268: space), and using
13269:
13270: @example
13271: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13272: @end example
1.1 anton 13273:
13274: @c ******************************************************************
1.65 anton 13275: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13276: @chapter ANS conformance
13277: @cindex ANS conformance of Gforth
13278:
13279: To the best of our knowledge, Gforth is an
13280:
13281: ANS Forth System
13282: @itemize @bullet
13283: @item providing the Core Extensions word set
13284: @item providing the Block word set
13285: @item providing the Block Extensions word set
13286: @item providing the Double-Number word set
13287: @item providing the Double-Number Extensions word set
13288: @item providing the Exception word set
13289: @item providing the Exception Extensions word set
13290: @item providing the Facility word set
1.40 anton 13291: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13292: @item providing the File Access word set
13293: @item providing the File Access Extensions word set
13294: @item providing the Floating-Point word set
13295: @item providing the Floating-Point Extensions word set
13296: @item providing the Locals word set
13297: @item providing the Locals Extensions word set
13298: @item providing the Memory-Allocation word set
13299: @item providing the Memory-Allocation Extensions word set (that one's easy)
13300: @item providing the Programming-Tools word set
13301: @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
13302: @item providing the Search-Order word set
13303: @item providing the Search-Order Extensions word set
13304: @item providing the String word set
13305: @item providing the String Extensions word set (another easy one)
13306: @end itemize
13307:
1.118 anton 13308: Gforth has the following environmental restrictions:
13309:
13310: @cindex environmental restrictions
13311: @itemize @bullet
13312: @item
13313: While processing the OS command line, if an exception is not caught,
13314: Gforth exits with a non-zero exit code instyead of performing QUIT.
13315:
13316: @item
13317: When an @code{throw} is performed after a @code{query}, Gforth does not
13318: allways restore the input source specification in effect at the
13319: corresponding catch.
13320:
13321: @end itemize
13322:
13323:
1.1 anton 13324: @cindex system documentation
13325: In addition, ANS Forth systems are required to document certain
13326: implementation choices. This chapter tries to meet these
13327: requirements. In many cases it gives a way to ask the system for the
13328: information instead of providing the information directly, in
13329: particular, if the information depends on the processor, the operating
13330: system or the installation options chosen, or if they are likely to
13331: change during the maintenance of Gforth.
13332:
13333: @comment The framework for the rest has been taken from pfe.
13334:
13335: @menu
13336: * The Core Words::
13337: * The optional Block word set::
13338: * The optional Double Number word set::
13339: * The optional Exception word set::
13340: * The optional Facility word set::
13341: * The optional File-Access word set::
13342: * The optional Floating-Point word set::
13343: * The optional Locals word set::
13344: * The optional Memory-Allocation word set::
13345: * The optional Programming-Tools word set::
13346: * The optional Search-Order word set::
13347: @end menu
13348:
13349:
13350: @c =====================================================================
13351: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13352: @comment node-name, next, previous, up
13353: @section The Core Words
13354: @c =====================================================================
13355: @cindex core words, system documentation
13356: @cindex system documentation, core words
13357:
13358: @menu
13359: * core-idef:: Implementation Defined Options
13360: * core-ambcond:: Ambiguous Conditions
13361: * core-other:: Other System Documentation
13362: @end menu
13363:
13364: @c ---------------------------------------------------------------------
13365: @node core-idef, core-ambcond, The Core Words, The Core Words
13366: @subsection Implementation Defined Options
13367: @c ---------------------------------------------------------------------
13368: @cindex core words, implementation-defined options
13369: @cindex implementation-defined options, core words
13370:
13371:
13372: @table @i
13373: @item (Cell) aligned addresses:
13374: @cindex cell-aligned addresses
13375: @cindex aligned addresses
13376: processor-dependent. Gforth's alignment words perform natural alignment
13377: (e.g., an address aligned for a datum of size 8 is divisible by
13378: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13379:
13380: @item @code{EMIT} and non-graphic characters:
13381: @cindex @code{EMIT} and non-graphic characters
13382: @cindex non-graphic characters and @code{EMIT}
13383: The character is output using the C library function (actually, macro)
13384: @code{putc}.
13385:
13386: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13387: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13388: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13389: @cindex @code{ACCEPT}, editing
13390: @cindex @code{EXPECT}, editing
13391: This is modeled on the GNU readline library (@pxref{Readline
13392: Interaction, , Command Line Editing, readline, The GNU Readline
13393: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13394: producing a full word completion every time you type it (instead of
1.28 crook 13395: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13396:
13397: @item character set:
13398: @cindex character set
13399: The character set of your computer and display device. Gforth is
13400: 8-bit-clean (but some other component in your system may make trouble).
13401:
13402: @item Character-aligned address requirements:
13403: @cindex character-aligned address requirements
13404: installation-dependent. Currently a character is represented by a C
13405: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13406: (Comments on that requested).
13407:
13408: @item character-set extensions and matching of names:
13409: @cindex character-set extensions and matching of names
1.26 crook 13410: @cindex case-sensitivity for name lookup
13411: @cindex name lookup, case-sensitivity
13412: @cindex locale and case-sensitivity
1.21 crook 13413: Any character except the ASCII NUL character can be used in a
1.1 anton 13414: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13415: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13416: function is probably influenced by the locale. E.g., the @code{C} locale
13417: does not know about accents and umlauts, so they are matched
13418: case-sensitively in that locale. For portability reasons it is best to
13419: write programs such that they work in the @code{C} locale. Then one can
13420: use libraries written by a Polish programmer (who might use words
13421: containing ISO Latin-2 encoded characters) and by a French programmer
13422: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13423: funny results for some of the words (which ones, depends on the font you
13424: are using)). Also, the locale you prefer may not be available in other
13425: operating systems. Hopefully, Unicode will solve these problems one day.
13426:
13427: @item conditions under which control characters match a space delimiter:
13428: @cindex space delimiters
13429: @cindex control characters as delimiters
1.117 anton 13430: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13431: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13432: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13433: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13434: interpreter (aka text interpreter) by default, treats all white-space
13435: characters as delimiters.
13436:
1.26 crook 13437: @item format of the control-flow stack:
13438: @cindex control-flow stack, format
13439: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13440: stack item in cells is given by the constant @code{cs-item-size}. At the
13441: time of this writing, an item consists of a (pointer to a) locals list
13442: (third), an address in the code (second), and a tag for identifying the
13443: item (TOS). The following tags are used: @code{defstart},
13444: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13445: @code{scopestart}.
13446:
13447: @item conversion of digits > 35
13448: @cindex digits > 35
13449: The characters @code{[\]^_'} are the digits with the decimal value
13450: 36@minus{}41. There is no way to input many of the larger digits.
13451:
13452: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13453: @cindex @code{EXPECT}, display after end of input
13454: @cindex @code{ACCEPT}, display after end of input
13455: The cursor is moved to the end of the entered string. If the input is
13456: terminated using the @kbd{Return} key, a space is typed.
13457:
13458: @item exception abort sequence of @code{ABORT"}:
13459: @cindex exception abort sequence of @code{ABORT"}
13460: @cindex @code{ABORT"}, exception abort sequence
13461: The error string is stored into the variable @code{"error} and a
13462: @code{-2 throw} is performed.
13463:
13464: @item input line terminator:
13465: @cindex input line terminator
13466: @cindex line terminator on input
1.26 crook 13467: @cindex newline character on input
1.1 anton 13468: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13469: lines. One of these characters is typically produced when you type the
13470: @kbd{Enter} or @kbd{Return} key.
13471:
13472: @item maximum size of a counted string:
13473: @cindex maximum size of a counted string
13474: @cindex counted string, maximum size
13475: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13476: on all platforms, but this may change.
1.1 anton 13477:
13478: @item maximum size of a parsed string:
13479: @cindex maximum size of a parsed string
13480: @cindex parsed string, maximum size
13481: Given by the constant @code{/line}. Currently 255 characters.
13482:
13483: @item maximum size of a definition name, in characters:
13484: @cindex maximum size of a definition name, in characters
13485: @cindex name, maximum length
1.113 anton 13486: MAXU/8
1.1 anton 13487:
13488: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13489: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13490: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13491: MAXU/8
1.1 anton 13492:
13493: @item method of selecting the user input device:
13494: @cindex user input device, method of selecting
13495: The user input device is the standard input. There is currently no way to
13496: change it from within Gforth. However, the input can typically be
13497: redirected in the command line that starts Gforth.
13498:
13499: @item method of selecting the user output device:
13500: @cindex user output device, method of selecting
13501: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13502: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13503: output when the user output device is a terminal, otherwise the output
13504: is buffered.
1.1 anton 13505:
13506: @item methods of dictionary compilation:
13507: What are we expected to document here?
13508:
13509: @item number of bits in one address unit:
13510: @cindex number of bits in one address unit
13511: @cindex address unit, size in bits
13512: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13513: platforms.
1.1 anton 13514:
13515: @item number representation and arithmetic:
13516: @cindex number representation and arithmetic
1.79 anton 13517: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13518:
13519: @item ranges for integer types:
13520: @cindex ranges for integer types
13521: @cindex integer types, ranges
13522: Installation-dependent. Make environmental queries for @code{MAX-N},
13523: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13524: unsigned (and positive) types is 0. The lower bound for signed types on
13525: two's complement and one's complement machines machines can be computed
13526: by adding 1 to the upper bound.
13527:
13528: @item read-only data space regions:
13529: @cindex read-only data space regions
13530: @cindex data-space, read-only regions
13531: The whole Forth data space is writable.
13532:
13533: @item size of buffer at @code{WORD}:
13534: @cindex size of buffer at @code{WORD}
13535: @cindex @code{WORD} buffer size
13536: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13537: shared with the pictured numeric output string. If overwriting
13538: @code{PAD} is acceptable, it is as large as the remaining dictionary
13539: space, although only as much can be sensibly used as fits in a counted
13540: string.
13541:
13542: @item size of one cell in address units:
13543: @cindex cell size
13544: @code{1 cells .}.
13545:
13546: @item size of one character in address units:
13547: @cindex char size
1.79 anton 13548: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13549:
13550: @item size of the keyboard terminal buffer:
13551: @cindex size of the keyboard terminal buffer
13552: @cindex terminal buffer, size
13553: Varies. You can determine the size at a specific time using @code{lp@@
13554: tib - .}. It is shared with the locals stack and TIBs of files that
13555: include the current file. You can change the amount of space for TIBs
13556: and locals stack at Gforth startup with the command line option
13557: @code{-l}.
13558:
13559: @item size of the pictured numeric output buffer:
13560: @cindex size of the pictured numeric output buffer
13561: @cindex pictured numeric output buffer, size
13562: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13563: shared with @code{WORD}.
13564:
13565: @item size of the scratch area returned by @code{PAD}:
13566: @cindex size of the scratch area returned by @code{PAD}
13567: @cindex @code{PAD} size
13568: The remainder of dictionary space. @code{unused pad here - - .}.
13569:
13570: @item system case-sensitivity characteristics:
13571: @cindex case-sensitivity characteristics
1.26 crook 13572: Dictionary searches are case-insensitive (except in
1.1 anton 13573: @code{TABLE}s). However, as explained above under @i{character-set
13574: extensions}, the matching for non-ASCII characters is determined by the
13575: locale you are using. In the default @code{C} locale all non-ASCII
13576: characters are matched case-sensitively.
13577:
13578: @item system prompt:
13579: @cindex system prompt
13580: @cindex prompt
13581: @code{ ok} in interpret state, @code{ compiled} in compile state.
13582:
13583: @item division rounding:
13584: @cindex division rounding
1.166 anton 13585: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13586: division (with the default installation of Gforth). You can check
13587: this with @code{s" floored" environment? drop .}. If you write
13588: programs that need a specific division rounding, best use
13589: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13590:
13591: @item values of @code{STATE} when true:
13592: @cindex @code{STATE} values
13593: -1.
13594:
13595: @item values returned after arithmetic overflow:
13596: On two's complement machines, arithmetic is performed modulo
13597: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13598: arithmetic (with appropriate mapping for signed types). Division by
13599: zero typically results in a @code{-55 throw} (Floating-point
13600: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13601: division overflow can result in these throws, or in @code{-11 throw};
13602: in @code{gforth-fast} division overflow and divide by zero may also
13603: result in returning bogus results without producing an exception.
1.1 anton 13604:
13605: @item whether the current definition can be found after @t{DOES>}:
13606: @cindex @t{DOES>}, visibility of current definition
13607: No.
13608:
13609: @end table
13610:
13611: @c ---------------------------------------------------------------------
13612: @node core-ambcond, core-other, core-idef, The Core Words
13613: @subsection Ambiguous conditions
13614: @c ---------------------------------------------------------------------
13615: @cindex core words, ambiguous conditions
13616: @cindex ambiguous conditions, core words
13617:
13618: @table @i
13619:
13620: @item a name is neither a word nor a number:
13621: @cindex name not found
1.26 crook 13622: @cindex undefined word
1.80 anton 13623: @code{-13 throw} (Undefined word).
1.1 anton 13624:
13625: @item a definition name exceeds the maximum length allowed:
1.26 crook 13626: @cindex word name too long
1.1 anton 13627: @code{-19 throw} (Word name too long)
13628:
13629: @item addressing a region not inside the various data spaces of the forth system:
13630: @cindex Invalid memory address
1.32 anton 13631: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13632: typically readable. Accessing other addresses gives results dependent on
13633: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13634: address).
13635:
13636: @item argument type incompatible with parameter:
1.26 crook 13637: @cindex argument type mismatch
1.1 anton 13638: This is usually not caught. Some words perform checks, e.g., the control
13639: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13640: mismatch).
13641:
13642: @item attempting to obtain the execution token of a word with undefined execution semantics:
13643: @cindex Interpreting a compile-only word, for @code{'} etc.
13644: @cindex execution token of words with undefined execution semantics
13645: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13646: get an execution token for @code{compile-only-error} (which performs a
13647: @code{-14 throw} when executed).
13648:
13649: @item dividing by zero:
13650: @cindex dividing by zero
13651: @cindex floating point unidentified fault, integer division
1.80 anton 13652: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13653: zero); on other systems, this typically results in a @code{-55 throw}
13654: (Floating-point unidentified fault).
1.1 anton 13655:
13656: @item insufficient data stack or return stack space:
13657: @cindex insufficient data stack or return stack space
13658: @cindex stack overflow
1.26 crook 13659: @cindex address alignment exception, stack overflow
1.1 anton 13660: @cindex Invalid memory address, stack overflow
13661: Depending on the operating system, the installation, and the invocation
13662: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13663: it is not checked. If it is checked, you typically get a @code{-3 throw}
13664: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13665: throw} (Invalid memory address) (depending on the platform and how you
13666: achieved the overflow) as soon as the overflow happens. If it is not
13667: checked, overflows typically result in mysterious illegal memory
13668: accesses, producing @code{-9 throw} (Invalid memory address) or
13669: @code{-23 throw} (Address alignment exception); they might also destroy
13670: the internal data structure of @code{ALLOCATE} and friends, resulting in
13671: various errors in these words.
1.1 anton 13672:
13673: @item insufficient space for loop control parameters:
13674: @cindex insufficient space for loop control parameters
1.80 anton 13675: Like other return stack overflows.
1.1 anton 13676:
13677: @item insufficient space in the dictionary:
13678: @cindex insufficient space in the dictionary
13679: @cindex dictionary overflow
1.12 anton 13680: If you try to allot (either directly with @code{allot}, or indirectly
13681: with @code{,}, @code{create} etc.) more memory than available in the
13682: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13683: to access memory beyond the end of the dictionary, the results are
13684: similar to stack overflows.
1.1 anton 13685:
13686: @item interpreting a word with undefined interpretation semantics:
13687: @cindex interpreting a word with undefined interpretation semantics
13688: @cindex Interpreting a compile-only word
13689: For some words, we have defined interpretation semantics. For the
13690: others: @code{-14 throw} (Interpreting a compile-only word).
13691:
13692: @item modifying the contents of the input buffer or a string literal:
13693: @cindex modifying the contents of the input buffer or a string literal
13694: These are located in writable memory and can be modified.
13695:
13696: @item overflow of the pictured numeric output string:
13697: @cindex overflow of the pictured numeric output string
13698: @cindex pictured numeric output string, overflow
1.24 anton 13699: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13700:
13701: @item parsed string overflow:
13702: @cindex parsed string overflow
13703: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13704:
13705: @item producing a result out of range:
13706: @cindex result out of range
13707: On two's complement machines, arithmetic is performed modulo
13708: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13709: arithmetic (with appropriate mapping for signed types). Division by
13710: zero typically results in a @code{-10 throw} (divide by zero) or
13711: @code{-55 throw} (floating point unidentified fault). Overflow on
13712: division may result in these errors or in @code{-11 throw} (result out
13713: of range). @code{Gforth-fast} may silently produce bogus results on
13714: division overflow or division by zero. @code{Convert} and
1.24 anton 13715: @code{>number} currently overflow silently.
1.1 anton 13716:
13717: @item reading from an empty data or return stack:
13718: @cindex stack empty
13719: @cindex stack underflow
1.24 anton 13720: @cindex return stack underflow
1.1 anton 13721: The data stack is checked by the outer (aka text) interpreter after
13722: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13723: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13724: depending on operating system, installation, and invocation. If they are
13725: caught by a check, they typically result in @code{-4 throw} (Stack
13726: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13727: (Invalid memory address), depending on the platform and which stack
13728: underflows and by how much. Note that even if the system uses checking
13729: (through the MMU), your program may have to underflow by a significant
13730: number of stack items to trigger the reaction (the reason for this is
13731: that the MMU, and therefore the checking, works with a page-size
13732: granularity). If there is no checking, the symptoms resulting from an
13733: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13734: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13735: (Invalid memory address) and Illegal Instruction (typically @code{-260
13736: throw}).
1.1 anton 13737:
13738: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13739: @cindex unexpected end of the input buffer
13740: @cindex zero-length string as a name
13741: @cindex Attempt to use zero-length string as a name
13742: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13743: use zero-length string as a name). Words like @code{'} probably will not
13744: find what they search. Note that it is possible to create zero-length
13745: names with @code{nextname} (should it not?).
13746:
13747: @item @code{>IN} greater than input buffer:
13748: @cindex @code{>IN} greater than input buffer
13749: The next invocation of a parsing word returns a string with length 0.
13750:
13751: @item @code{RECURSE} appears after @code{DOES>}:
13752: @cindex @code{RECURSE} appears after @code{DOES>}
13753: Compiles a recursive call to the defining word, not to the defined word.
13754:
13755: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13756: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13757: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13758: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13759: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13760: the end of the file was reached), its source-id may be
13761: reused. Therefore, restoring an input source specification referencing a
13762: closed file may lead to unpredictable results instead of a @code{-12
13763: THROW}.
13764:
13765: In the future, Gforth may be able to restore input source specifications
13766: from other than the current input source.
13767:
13768: @item data space containing definitions gets de-allocated:
13769: @cindex data space containing definitions gets de-allocated
13770: Deallocation with @code{allot} is not checked. This typically results in
13771: memory access faults or execution of illegal instructions.
13772:
13773: @item data space read/write with incorrect alignment:
13774: @cindex data space read/write with incorrect alignment
13775: @cindex alignment faults
1.26 crook 13776: @cindex address alignment exception
1.1 anton 13777: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13778: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13779: alignment turned on, incorrect alignment results in a @code{-9 throw}
13780: (Invalid memory address). There are reportedly some processors with
1.12 anton 13781: alignment restrictions that do not report violations.
1.1 anton 13782:
13783: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13784: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13785: Like other alignment errors.
13786:
13787: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13788: Like other stack underflows.
13789:
13790: @item loop control parameters not available:
13791: @cindex loop control parameters not available
13792: Not checked. The counted loop words simply assume that the top of return
13793: stack items are loop control parameters and behave accordingly.
13794:
13795: @item most recent definition does not have a name (@code{IMMEDIATE}):
13796: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13797: @cindex last word was headerless
13798: @code{abort" last word was headerless"}.
13799:
13800: @item name not defined by @code{VALUE} used by @code{TO}:
13801: @cindex name not defined by @code{VALUE} used by @code{TO}
13802: @cindex @code{TO} on non-@code{VALUE}s
13803: @cindex Invalid name argument, @code{TO}
13804: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13805: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13806:
13807: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13808: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13809: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13810: @code{-13 throw} (Undefined word)
13811:
13812: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13813: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13814: Gforth behaves as if they were of the same type. I.e., you can predict
13815: the behaviour by interpreting all parameters as, e.g., signed.
13816:
13817: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13818: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13819: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13820: compilation semantics of @code{TO}.
13821:
13822: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13823: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13824: @cindex @code{WORD}, string overflow
13825: Not checked. The string will be ok, but the count will, of course,
13826: contain only the least significant bits of the length.
13827:
13828: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13829: @cindex @code{LSHIFT}, large shift counts
13830: @cindex @code{RSHIFT}, large shift counts
13831: Processor-dependent. Typical behaviours are returning 0 and using only
13832: the low bits of the shift count.
13833:
13834: @item word not defined via @code{CREATE}:
13835: @cindex @code{>BODY} of non-@code{CREATE}d words
13836: @code{>BODY} produces the PFA of the word no matter how it was defined.
13837:
13838: @cindex @code{DOES>} of non-@code{CREATE}d words
13839: @code{DOES>} changes the execution semantics of the last defined word no
13840: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13841: @code{CREATE , DOES>}.
13842:
13843: @item words improperly used outside @code{<#} and @code{#>}:
13844: Not checked. As usual, you can expect memory faults.
13845:
13846: @end table
13847:
13848:
13849: @c ---------------------------------------------------------------------
13850: @node core-other, , core-ambcond, The Core Words
13851: @subsection Other system documentation
13852: @c ---------------------------------------------------------------------
13853: @cindex other system documentation, core words
13854: @cindex core words, other system documentation
13855:
13856: @table @i
13857: @item nonstandard words using @code{PAD}:
13858: @cindex @code{PAD} use by nonstandard words
13859: None.
13860:
13861: @item operator's terminal facilities available:
13862: @cindex operator's terminal facilities available
1.80 anton 13863: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13864: and you can give commands to Gforth interactively. The actual facilities
13865: available depend on how you invoke Gforth.
13866:
13867: @item program data space available:
13868: @cindex program data space available
13869: @cindex data space available
13870: @code{UNUSED .} gives the remaining dictionary space. The total
13871: dictionary space can be specified with the @code{-m} switch
13872: (@pxref{Invoking Gforth}) when Gforth starts up.
13873:
13874: @item return stack space available:
13875: @cindex return stack space available
13876: You can compute the total return stack space in cells with
13877: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13878: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13879:
13880: @item stack space available:
13881: @cindex stack space available
13882: You can compute the total data stack space in cells with
13883: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13884: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13885:
13886: @item system dictionary space required, in address units:
13887: @cindex system dictionary space required, in address units
13888: Type @code{here forthstart - .} after startup. At the time of this
13889: writing, this gives 80080 (bytes) on a 32-bit system.
13890: @end table
13891:
13892:
13893: @c =====================================================================
13894: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13895: @section The optional Block word set
13896: @c =====================================================================
13897: @cindex system documentation, block words
13898: @cindex block words, system documentation
13899:
13900: @menu
13901: * block-idef:: Implementation Defined Options
13902: * block-ambcond:: Ambiguous Conditions
13903: * block-other:: Other System Documentation
13904: @end menu
13905:
13906:
13907: @c ---------------------------------------------------------------------
13908: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13909: @subsection Implementation Defined Options
13910: @c ---------------------------------------------------------------------
13911: @cindex implementation-defined options, block words
13912: @cindex block words, implementation-defined options
13913:
13914: @table @i
13915: @item the format for display by @code{LIST}:
13916: @cindex @code{LIST} display format
13917: First the screen number is displayed, then 16 lines of 64 characters,
13918: each line preceded by the line number.
13919:
13920: @item the length of a line affected by @code{\}:
13921: @cindex length of a line affected by @code{\}
13922: @cindex @code{\}, line length in blocks
13923: 64 characters.
13924: @end table
13925:
13926:
13927: @c ---------------------------------------------------------------------
13928: @node block-ambcond, block-other, block-idef, The optional Block word set
13929: @subsection Ambiguous conditions
13930: @c ---------------------------------------------------------------------
13931: @cindex block words, ambiguous conditions
13932: @cindex ambiguous conditions, block words
13933:
13934: @table @i
13935: @item correct block read was not possible:
13936: @cindex block read not possible
13937: Typically results in a @code{throw} of some OS-derived value (between
13938: -512 and -2048). If the blocks file was just not long enough, blanks are
13939: supplied for the missing portion.
13940:
13941: @item I/O exception in block transfer:
13942: @cindex I/O exception in block transfer
13943: @cindex block transfer, I/O exception
13944: Typically results in a @code{throw} of some OS-derived value (between
13945: -512 and -2048).
13946:
13947: @item invalid block number:
13948: @cindex invalid block number
13949: @cindex block number invalid
13950: @code{-35 throw} (Invalid block number)
13951:
13952: @item a program directly alters the contents of @code{BLK}:
13953: @cindex @code{BLK}, altering @code{BLK}
13954: The input stream is switched to that other block, at the same
13955: position. If the storing to @code{BLK} happens when interpreting
13956: non-block input, the system will get quite confused when the block ends.
13957:
13958: @item no current block buffer for @code{UPDATE}:
13959: @cindex @code{UPDATE}, no current block buffer
13960: @code{UPDATE} has no effect.
13961:
13962: @end table
13963:
13964: @c ---------------------------------------------------------------------
13965: @node block-other, , block-ambcond, The optional Block word set
13966: @subsection Other system documentation
13967: @c ---------------------------------------------------------------------
13968: @cindex other system documentation, block words
13969: @cindex block words, other system documentation
13970:
13971: @table @i
13972: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13973: No restrictions (yet).
13974:
13975: @item the number of blocks available for source and data:
13976: depends on your disk space.
13977:
13978: @end table
13979:
13980:
13981: @c =====================================================================
13982: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13983: @section The optional Double Number word set
13984: @c =====================================================================
13985: @cindex system documentation, double words
13986: @cindex double words, system documentation
13987:
13988: @menu
13989: * double-ambcond:: Ambiguous Conditions
13990: @end menu
13991:
13992:
13993: @c ---------------------------------------------------------------------
13994: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13995: @subsection Ambiguous conditions
13996: @c ---------------------------------------------------------------------
13997: @cindex double words, ambiguous conditions
13998: @cindex ambiguous conditions, double words
13999:
14000: @table @i
1.29 crook 14001: @item @i{d} outside of range of @i{n} in @code{D>S}:
14002: @cindex @code{D>S}, @i{d} out of range of @i{n}
14003: The least significant cell of @i{d} is produced.
1.1 anton 14004:
14005: @end table
14006:
14007:
14008: @c =====================================================================
14009: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14010: @section The optional Exception word set
14011: @c =====================================================================
14012: @cindex system documentation, exception words
14013: @cindex exception words, system documentation
14014:
14015: @menu
14016: * exception-idef:: Implementation Defined Options
14017: @end menu
14018:
14019:
14020: @c ---------------------------------------------------------------------
14021: @node exception-idef, , The optional Exception word set, The optional Exception word set
14022: @subsection Implementation Defined Options
14023: @c ---------------------------------------------------------------------
14024: @cindex implementation-defined options, exception words
14025: @cindex exception words, implementation-defined options
14026:
14027: @table @i
14028: @item @code{THROW}-codes used in the system:
14029: @cindex @code{THROW}-codes used in the system
14030: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 14031: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 14032: codes -512@minus{}-2047 are used for OS errors (for file and memory
14033: allocation operations). The mapping from OS error numbers to throw codes
14034: is -512@minus{}@code{errno}. One side effect of this mapping is that
14035: undefined OS errors produce a message with a strange number; e.g.,
14036: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14037: @end table
14038:
14039: @c =====================================================================
14040: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14041: @section The optional Facility word set
14042: @c =====================================================================
14043: @cindex system documentation, facility words
14044: @cindex facility words, system documentation
14045:
14046: @menu
14047: * facility-idef:: Implementation Defined Options
14048: * facility-ambcond:: Ambiguous Conditions
14049: @end menu
14050:
14051:
14052: @c ---------------------------------------------------------------------
14053: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14054: @subsection Implementation Defined Options
14055: @c ---------------------------------------------------------------------
14056: @cindex implementation-defined options, facility words
14057: @cindex facility words, implementation-defined options
14058:
14059: @table @i
14060: @item encoding of keyboard events (@code{EKEY}):
14061: @cindex keyboard events, encoding in @code{EKEY}
14062: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 14063: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 14064: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14065: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14066: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14067: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 14068:
1.1 anton 14069:
14070: @item duration of a system clock tick:
14071: @cindex duration of a system clock tick
14072: @cindex clock tick duration
14073: System dependent. With respect to @code{MS}, the time is specified in
14074: microseconds. How well the OS and the hardware implement this, is
14075: another question.
14076:
14077: @item repeatability to be expected from the execution of @code{MS}:
14078: @cindex repeatability to be expected from the execution of @code{MS}
14079: @cindex @code{MS}, repeatability to be expected
14080: System dependent. On Unix, a lot depends on load. If the system is
14081: lightly loaded, and the delay is short enough that Gforth does not get
14082: swapped out, the performance should be acceptable. Under MS-DOS and
14083: other single-tasking systems, it should be good.
14084:
14085: @end table
14086:
14087:
14088: @c ---------------------------------------------------------------------
14089: @node facility-ambcond, , facility-idef, The optional Facility word set
14090: @subsection Ambiguous conditions
14091: @c ---------------------------------------------------------------------
14092: @cindex facility words, ambiguous conditions
14093: @cindex ambiguous conditions, facility words
14094:
14095: @table @i
14096: @item @code{AT-XY} can't be performed on user output device:
14097: @cindex @code{AT-XY} can't be performed on user output device
14098: Largely terminal dependent. No range checks are done on the arguments.
14099: No errors are reported. You may see some garbage appearing, you may see
14100: simply nothing happen.
14101:
14102: @end table
14103:
14104:
14105: @c =====================================================================
14106: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14107: @section The optional File-Access word set
14108: @c =====================================================================
14109: @cindex system documentation, file words
14110: @cindex file words, system documentation
14111:
14112: @menu
14113: * file-idef:: Implementation Defined Options
14114: * file-ambcond:: Ambiguous Conditions
14115: @end menu
14116:
14117: @c ---------------------------------------------------------------------
14118: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14119: @subsection Implementation Defined Options
14120: @c ---------------------------------------------------------------------
14121: @cindex implementation-defined options, file words
14122: @cindex file words, implementation-defined options
14123:
14124: @table @i
14125: @item file access methods used:
14126: @cindex file access methods used
14127: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14128: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14129: @code{wb}): The file is cleared, if it exists, and created, if it does
14130: not (with both @code{open-file} and @code{create-file}). Under Unix
14131: @code{create-file} creates a file with 666 permissions modified by your
14132: umask.
14133:
14134: @item file exceptions:
14135: @cindex file exceptions
14136: The file words do not raise exceptions (except, perhaps, memory access
14137: faults when you pass illegal addresses or file-ids).
14138:
14139: @item file line terminator:
14140: @cindex file line terminator
14141: System-dependent. Gforth uses C's newline character as line
14142: terminator. What the actual character code(s) of this are is
14143: system-dependent.
14144:
14145: @item file name format:
14146: @cindex file name format
14147: System dependent. Gforth just uses the file name format of your OS.
14148:
14149: @item information returned by @code{FILE-STATUS}:
14150: @cindex @code{FILE-STATUS}, returned information
14151: @code{FILE-STATUS} returns the most powerful file access mode allowed
14152: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14153: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14154: along with the returned mode.
14155:
14156: @item input file state after an exception when including source:
14157: @cindex exception when including source
14158: All files that are left via the exception are closed.
14159:
1.29 crook 14160: @item @i{ior} values and meaning:
14161: @cindex @i{ior} values and meaning
1.68 anton 14162: @cindex @i{wior} values and meaning
1.29 crook 14163: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14164: intended as throw codes. They typically are in the range
14165: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14166: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14167:
14168: @item maximum depth of file input nesting:
14169: @cindex maximum depth of file input nesting
14170: @cindex file input nesting, maximum depth
14171: limited by the amount of return stack, locals/TIB stack, and the number
14172: of open files available. This should not give you troubles.
14173:
14174: @item maximum size of input line:
14175: @cindex maximum size of input line
14176: @cindex input line size, maximum
14177: @code{/line}. Currently 255.
14178:
14179: @item methods of mapping block ranges to files:
14180: @cindex mapping block ranges to files
14181: @cindex files containing blocks
14182: @cindex blocks in files
14183: By default, blocks are accessed in the file @file{blocks.fb} in the
14184: current working directory. The file can be switched with @code{USE}.
14185:
14186: @item number of string buffers provided by @code{S"}:
14187: @cindex @code{S"}, number of string buffers
14188: 1
14189:
14190: @item size of string buffer used by @code{S"}:
14191: @cindex @code{S"}, size of string buffer
14192: @code{/line}. currently 255.
14193:
14194: @end table
14195:
14196: @c ---------------------------------------------------------------------
14197: @node file-ambcond, , file-idef, The optional File-Access word set
14198: @subsection Ambiguous conditions
14199: @c ---------------------------------------------------------------------
14200: @cindex file words, ambiguous conditions
14201: @cindex ambiguous conditions, file words
14202:
14203: @table @i
14204: @item attempting to position a file outside its boundaries:
14205: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14206: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14207: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14208:
14209: @item attempting to read from file positions not yet written:
14210: @cindex reading from file positions not yet written
14211: End-of-file, i.e., zero characters are read and no error is reported.
14212:
1.29 crook 14213: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14214: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14215: An appropriate exception may be thrown, but a memory fault or other
14216: problem is more probable.
14217:
1.29 crook 14218: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14219: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14220: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14221: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14222: thrown.
14223:
14224: @item named file cannot be opened (@code{INCLUDED}):
14225: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14226: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14227:
14228: @item requesting an unmapped block number:
14229: @cindex unmapped block numbers
14230: There are no unmapped legal block numbers. On some operating systems,
14231: writing a block with a large number may overflow the file system and
14232: have an error message as consequence.
14233:
14234: @item using @code{source-id} when @code{blk} is non-zero:
14235: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14236: @code{source-id} performs its function. Typically it will give the id of
14237: the source which loaded the block. (Better ideas?)
14238:
14239: @end table
14240:
14241:
14242: @c =====================================================================
14243: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14244: @section The optional Floating-Point word set
14245: @c =====================================================================
14246: @cindex system documentation, floating-point words
14247: @cindex floating-point words, system documentation
14248:
14249: @menu
14250: * floating-idef:: Implementation Defined Options
14251: * floating-ambcond:: Ambiguous Conditions
14252: @end menu
14253:
14254:
14255: @c ---------------------------------------------------------------------
14256: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14257: @subsection Implementation Defined Options
14258: @c ---------------------------------------------------------------------
14259: @cindex implementation-defined options, floating-point words
14260: @cindex floating-point words, implementation-defined options
14261:
14262: @table @i
14263: @item format and range of floating point numbers:
14264: @cindex format and range of floating point numbers
14265: @cindex floating point numbers, format and range
14266: System-dependent; the @code{double} type of C.
14267:
1.29 crook 14268: @item results of @code{REPRESENT} when @i{float} is out of range:
14269: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14270: System dependent; @code{REPRESENT} is implemented using the C library
14271: function @code{ecvt()} and inherits its behaviour in this respect.
14272:
14273: @item rounding or truncation of floating-point numbers:
14274: @cindex rounding of floating-point numbers
14275: @cindex truncation of floating-point numbers
14276: @cindex floating-point numbers, rounding or truncation
14277: System dependent; the rounding behaviour is inherited from the hosting C
14278: compiler. IEEE-FP-based (i.e., most) systems by default round to
14279: nearest, and break ties by rounding to even (i.e., such that the last
14280: bit of the mantissa is 0).
14281:
14282: @item size of floating-point stack:
14283: @cindex floating-point stack size
14284: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14285: the floating-point stack (in floats). You can specify this on startup
14286: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14287:
14288: @item width of floating-point stack:
14289: @cindex floating-point stack width
14290: @code{1 floats}.
14291:
14292: @end table
14293:
14294:
14295: @c ---------------------------------------------------------------------
14296: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14297: @subsection Ambiguous conditions
14298: @c ---------------------------------------------------------------------
14299: @cindex floating-point words, ambiguous conditions
14300: @cindex ambiguous conditions, floating-point words
14301:
14302: @table @i
14303: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14304: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14305: System-dependent. Typically results in a @code{-23 THROW} like other
14306: alignment violations.
14307:
14308: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14309: @cindex @code{f@@} used with an address that is not float aligned
14310: @cindex @code{f!} used with an address that is not float aligned
14311: System-dependent. Typically results in a @code{-23 THROW} like other
14312: alignment violations.
14313:
14314: @item floating-point result out of range:
14315: @cindex floating-point result out of range
1.80 anton 14316: System-dependent. Can result in a @code{-43 throw} (floating point
14317: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14318: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14319: unidentified fault), or can produce a special value representing, e.g.,
14320: Infinity.
14321:
14322: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14323: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14324: System-dependent. Typically results in an alignment fault like other
14325: alignment violations.
14326:
1.35 anton 14327: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14328: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14329: The floating-point number is converted into decimal nonetheless.
14330:
14331: @item Both arguments are equal to zero (@code{FATAN2}):
14332: @cindex @code{FATAN2}, both arguments are equal to zero
14333: System-dependent. @code{FATAN2} is implemented using the C library
14334: function @code{atan2()}.
14335:
1.29 crook 14336: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14337: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14338: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14339: because of small errors and the tan will be a very large (or very small)
14340: but finite number.
14341:
1.29 crook 14342: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14343: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14344: The result is rounded to the nearest float.
14345:
14346: @item dividing by zero:
14347: @cindex dividing by zero, floating-point
14348: @cindex floating-point dividing by zero
14349: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14350: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14351: (floating point divide by zero) or @code{-55 throw} (Floating-point
14352: unidentified fault).
1.1 anton 14353:
14354: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14355: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14356: System dependent. On IEEE-FP based systems the number is converted into
14357: an infinity.
14358:
1.29 crook 14359: @item @i{float}<1 (@code{FACOSH}):
14360: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14361: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14362: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14363:
1.29 crook 14364: @item @i{float}=<-1 (@code{FLNP1}):
14365: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14366: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14367: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14368: negative infinity for @i{float}=-1).
1.1 anton 14369:
1.29 crook 14370: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14371: @cindex @code{FLN}, @i{float}=<0
14372: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14373: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14374: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14375: negative infinity for @i{float}=0).
1.1 anton 14376:
1.29 crook 14377: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14378: @cindex @code{FASINH}, @i{float}<0
14379: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14380: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14381: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14382: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14383: C library?).
1.1 anton 14384:
1.29 crook 14385: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14386: @cindex @code{FACOS}, |@i{float}|>1
14387: @cindex @code{FASIN}, |@i{float}|>1
14388: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14389: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14390: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14391:
1.29 crook 14392: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14393: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14394: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14395: Platform-dependent; typically, some double number is produced and no
14396: error is reported.
1.1 anton 14397:
14398: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14399: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14400: @code{Precision} characters of the numeric output area are used. If
14401: @code{precision} is too high, these words will smash the data or code
14402: close to @code{here}.
1.1 anton 14403: @end table
14404:
14405: @c =====================================================================
14406: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14407: @section The optional Locals word set
14408: @c =====================================================================
14409: @cindex system documentation, locals words
14410: @cindex locals words, system documentation
14411:
14412: @menu
14413: * locals-idef:: Implementation Defined Options
14414: * locals-ambcond:: Ambiguous Conditions
14415: @end menu
14416:
14417:
14418: @c ---------------------------------------------------------------------
14419: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14420: @subsection Implementation Defined Options
14421: @c ---------------------------------------------------------------------
14422: @cindex implementation-defined options, locals words
14423: @cindex locals words, implementation-defined options
14424:
14425: @table @i
14426: @item maximum number of locals in a definition:
14427: @cindex maximum number of locals in a definition
14428: @cindex locals, maximum number in a definition
14429: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14430: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14431: characters. The number of locals in a definition is bounded by the size
14432: of locals-buffer, which contains the names of the locals.
14433:
14434: @end table
14435:
14436:
14437: @c ---------------------------------------------------------------------
14438: @node locals-ambcond, , locals-idef, The optional Locals word set
14439: @subsection Ambiguous conditions
14440: @c ---------------------------------------------------------------------
14441: @cindex locals words, ambiguous conditions
14442: @cindex ambiguous conditions, locals words
14443:
14444: @table @i
14445: @item executing a named local in interpretation state:
14446: @cindex local in interpretation state
14447: @cindex Interpreting a compile-only word, for a local
14448: Locals have no interpretation semantics. If you try to perform the
14449: interpretation semantics, you will get a @code{-14 throw} somewhere
14450: (Interpreting a compile-only word). If you perform the compilation
14451: semantics, the locals access will be compiled (irrespective of state).
14452:
1.29 crook 14453: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14454: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14455: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14456: @cindex Invalid name argument, @code{TO}
14457: @code{-32 throw} (Invalid name argument)
14458:
14459: @end table
14460:
14461:
14462: @c =====================================================================
14463: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14464: @section The optional Memory-Allocation word set
14465: @c =====================================================================
14466: @cindex system documentation, memory-allocation words
14467: @cindex memory-allocation words, system documentation
14468:
14469: @menu
14470: * memory-idef:: Implementation Defined Options
14471: @end menu
14472:
14473:
14474: @c ---------------------------------------------------------------------
14475: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14476: @subsection Implementation Defined Options
14477: @c ---------------------------------------------------------------------
14478: @cindex implementation-defined options, memory-allocation words
14479: @cindex memory-allocation words, implementation-defined options
14480:
14481: @table @i
1.29 crook 14482: @item values and meaning of @i{ior}:
14483: @cindex @i{ior} values and meaning
14484: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14485: intended as throw codes. They typically are in the range
14486: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14487: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14488:
14489: @end table
14490:
14491: @c =====================================================================
14492: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14493: @section The optional Programming-Tools word set
14494: @c =====================================================================
14495: @cindex system documentation, programming-tools words
14496: @cindex programming-tools words, system documentation
14497:
14498: @menu
14499: * programming-idef:: Implementation Defined Options
14500: * programming-ambcond:: Ambiguous Conditions
14501: @end menu
14502:
14503:
14504: @c ---------------------------------------------------------------------
14505: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14506: @subsection Implementation Defined Options
14507: @c ---------------------------------------------------------------------
14508: @cindex implementation-defined options, programming-tools words
14509: @cindex programming-tools words, implementation-defined options
14510:
14511: @table @i
14512: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14513: @cindex @code{;CODE} ending sequence
14514: @cindex @code{CODE} ending sequence
14515: @code{END-CODE}
14516:
14517: @item manner of processing input following @code{;CODE} and @code{CODE}:
14518: @cindex @code{;CODE}, processing input
14519: @cindex @code{CODE}, processing input
14520: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14521: the input is processed by the text interpreter, (starting) in interpret
14522: state.
14523:
14524: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14525: @cindex @code{ASSEMBLER}, search order capability
14526: The ANS Forth search order word set.
14527:
14528: @item source and format of display by @code{SEE}:
14529: @cindex @code{SEE}, source and format of output
1.80 anton 14530: The source for @code{see} is the executable code used by the inner
1.1 anton 14531: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14532: (and on some platforms, assembly code for primitives) as well as
14533: possible.
1.1 anton 14534:
14535: @end table
14536:
14537: @c ---------------------------------------------------------------------
14538: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14539: @subsection Ambiguous conditions
14540: @c ---------------------------------------------------------------------
14541: @cindex programming-tools words, ambiguous conditions
14542: @cindex ambiguous conditions, programming-tools words
14543:
14544: @table @i
14545:
1.21 crook 14546: @item deleting the compilation word list (@code{FORGET}):
14547: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14548: Not implemented (yet).
14549:
1.29 crook 14550: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14551: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14552: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14553: @cindex control-flow stack underflow
14554: This typically results in an @code{abort"} with a descriptive error
14555: message (may change into a @code{-22 throw} (Control structure mismatch)
14556: in the future). You may also get a memory access error. If you are
14557: unlucky, this ambiguous condition is not caught.
14558:
1.29 crook 14559: @item @i{name} can't be found (@code{FORGET}):
14560: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14561: Not implemented (yet).
14562:
1.29 crook 14563: @item @i{name} not defined via @code{CREATE}:
14564: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14565: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14566: the execution semantics of the last defined word no matter how it was
14567: defined.
14568:
14569: @item @code{POSTPONE} applied to @code{[IF]}:
14570: @cindex @code{POSTPONE} applied to @code{[IF]}
14571: @cindex @code{[IF]} and @code{POSTPONE}
14572: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14573: equivalent to @code{[IF]}.
14574:
14575: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14576: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14577: Continue in the same state of conditional compilation in the next outer
14578: input source. Currently there is no warning to the user about this.
14579:
14580: @item removing a needed definition (@code{FORGET}):
14581: @cindex @code{FORGET}, removing a needed definition
14582: Not implemented (yet).
14583:
14584: @end table
14585:
14586:
14587: @c =====================================================================
14588: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14589: @section The optional Search-Order word set
14590: @c =====================================================================
14591: @cindex system documentation, search-order words
14592: @cindex search-order words, system documentation
14593:
14594: @menu
14595: * search-idef:: Implementation Defined Options
14596: * search-ambcond:: Ambiguous Conditions
14597: @end menu
14598:
14599:
14600: @c ---------------------------------------------------------------------
14601: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14602: @subsection Implementation Defined Options
14603: @c ---------------------------------------------------------------------
14604: @cindex implementation-defined options, search-order words
14605: @cindex search-order words, implementation-defined options
14606:
14607: @table @i
14608: @item maximum number of word lists in search order:
14609: @cindex maximum number of word lists in search order
14610: @cindex search order, maximum depth
14611: @code{s" wordlists" environment? drop .}. Currently 16.
14612:
14613: @item minimum search order:
14614: @cindex minimum search order
14615: @cindex search order, minimum
14616: @code{root root}.
14617:
14618: @end table
14619:
14620: @c ---------------------------------------------------------------------
14621: @node search-ambcond, , search-idef, The optional Search-Order word set
14622: @subsection Ambiguous conditions
14623: @c ---------------------------------------------------------------------
14624: @cindex search-order words, ambiguous conditions
14625: @cindex ambiguous conditions, search-order words
14626:
14627: @table @i
1.21 crook 14628: @item changing the compilation word list (during compilation):
14629: @cindex changing the compilation word list (during compilation)
14630: @cindex compilation word list, change before definition ends
14631: The word is entered into the word list that was the compilation word list
1.1 anton 14632: at the start of the definition. Any changes to the name field (e.g.,
14633: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14634: are applied to the latest defined word (as reported by @code{latest} or
14635: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14636:
14637: @item search order empty (@code{previous}):
14638: @cindex @code{previous}, search order empty
1.26 crook 14639: @cindex vocstack empty, @code{previous}
1.1 anton 14640: @code{abort" Vocstack empty"}.
14641:
14642: @item too many word lists in search order (@code{also}):
14643: @cindex @code{also}, too many word lists in search order
1.26 crook 14644: @cindex vocstack full, @code{also}
1.1 anton 14645: @code{abort" Vocstack full"}.
14646:
14647: @end table
14648:
14649: @c ***************************************************************
1.65 anton 14650: @node Standard vs Extensions, Model, ANS conformance, Top
14651: @chapter Should I use Gforth extensions?
14652: @cindex Gforth extensions
14653:
14654: As you read through the rest of this manual, you will see documentation
14655: for @i{Standard} words, and documentation for some appealing Gforth
14656: @i{extensions}. You might ask yourself the question: @i{``Should I
14657: restrict myself to the standard, or should I use the extensions?''}
14658:
14659: The answer depends on the goals you have for the program you are working
14660: on:
14661:
14662: @itemize @bullet
14663:
14664: @item Is it just for yourself or do you want to share it with others?
14665:
14666: @item
14667: If you want to share it, do the others all use Gforth?
14668:
14669: @item
14670: If it is just for yourself, do you want to restrict yourself to Gforth?
14671:
14672: @end itemize
14673:
14674: If restricting the program to Gforth is ok, then there is no reason not
14675: to use extensions. It is still a good idea to keep to the standard
14676: where it is easy, in case you want to reuse these parts in another
14677: program that you want to be portable.
14678:
14679: If you want to be able to port the program to other Forth systems, there
14680: are the following points to consider:
14681:
14682: @itemize @bullet
14683:
14684: @item
14685: Most Forth systems that are being maintained support the ANS Forth
14686: standard. So if your program complies with the standard, it will be
14687: portable among many systems.
14688:
14689: @item
14690: A number of the Gforth extensions can be implemented in ANS Forth using
14691: public-domain files provided in the @file{compat/} directory. These are
14692: mentioned in the text in passing. There is no reason not to use these
14693: extensions, your program will still be ANS Forth compliant; just include
14694: the appropriate compat files with your program.
14695:
14696: @item
14697: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14698: analyse your program and determine what non-Standard words it relies
14699: upon. However, it does not check whether you use standard words in a
14700: non-standard way.
14701:
14702: @item
14703: Some techniques are not standardized by ANS Forth, and are hard or
14704: impossible to implement in a standard way, but can be implemented in
14705: most Forth systems easily, and usually in similar ways (e.g., accessing
14706: word headers). Forth has a rich historical precedent for programmers
14707: taking advantage of implementation-dependent features of their tools
14708: (for example, relying on a knowledge of the dictionary
14709: structure). Sometimes these techniques are necessary to extract every
14710: last bit of performance from the hardware, sometimes they are just a
14711: programming shorthand.
14712:
14713: @item
14714: Does using a Gforth extension save more work than the porting this part
14715: to other Forth systems (if any) will cost?
14716:
14717: @item
14718: Is the additional functionality worth the reduction in portability and
14719: the additional porting problems?
14720:
14721: @end itemize
14722:
14723: In order to perform these consideratios, you need to know what's
14724: standard and what's not. This manual generally states if something is
1.81 anton 14725: non-standard, but the authoritative source is the
14726: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14727: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14728: into the thought processes of the technical committee.
14729:
14730: Note also that portability between Forth systems is not the only
14731: portability issue; there is also the issue of portability between
14732: different platforms (processor/OS combinations).
14733:
14734: @c ***************************************************************
14735: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14736: @chapter Model
14737:
14738: This chapter has yet to be written. It will contain information, on
14739: which internal structures you can rely.
14740:
14741: @c ***************************************************************
14742: @node Integrating Gforth, Emacs and Gforth, Model, Top
14743: @chapter Integrating Gforth into C programs
14744:
14745: This is not yet implemented.
14746:
14747: Several people like to use Forth as scripting language for applications
14748: that are otherwise written in C, C++, or some other language.
14749:
14750: The Forth system ATLAST provides facilities for embedding it into
14751: applications; unfortunately it has several disadvantages: most
14752: importantly, it is not based on ANS Forth, and it is apparently dead
14753: (i.e., not developed further and not supported). The facilities
1.21 crook 14754: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14755: making the switch should not be hard.
14756:
14757: We also tried to design the interface such that it can easily be
14758: implemented by other Forth systems, so that we may one day arrive at a
14759: standardized interface. Such a standard interface would allow you to
14760: replace the Forth system without having to rewrite C code.
14761:
14762: You embed the Gforth interpreter by linking with the library
14763: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14764: global symbols in this library that belong to the interface, have the
14765: prefix @code{forth_}. (Global symbols that are used internally have the
14766: prefix @code{gforth_}).
14767:
14768: You can include the declarations of Forth types and the functions and
14769: variables of the interface with @code{#include <forth.h>}.
14770:
14771: Types.
14772:
14773: Variables.
14774:
14775: Data and FP Stack pointer. Area sizes.
14776:
14777: functions.
14778:
14779: forth_init(imagefile)
14780: forth_evaluate(string) exceptions?
14781: forth_goto(address) (or forth_execute(xt)?)
14782: forth_continue() (a corountining mechanism)
14783:
14784: Adding primitives.
14785:
14786: No checking.
14787:
14788: Signals?
14789:
14790: Accessing the Stacks
14791:
1.26 crook 14792: @c ******************************************************************
1.1 anton 14793: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14794: @chapter Emacs and Gforth
14795: @cindex Emacs and Gforth
14796:
14797: @cindex @file{gforth.el}
14798: @cindex @file{forth.el}
14799: @cindex Rydqvist, Goran
1.107 dvdkhlng 14800: @cindex Kuehling, David
1.1 anton 14801: @cindex comment editing commands
14802: @cindex @code{\}, editing with Emacs
14803: @cindex debug tracer editing commands
14804: @cindex @code{~~}, removal with Emacs
14805: @cindex Forth mode in Emacs
1.107 dvdkhlng 14806:
1.1 anton 14807: Gforth comes with @file{gforth.el}, an improved version of
14808: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14809: improvements are:
14810:
14811: @itemize @bullet
14812: @item
1.107 dvdkhlng 14813: A better handling of indentation.
14814: @item
14815: A custom hilighting engine for Forth-code.
1.26 crook 14816: @item
14817: Comment paragraph filling (@kbd{M-q})
14818: @item
14819: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14820: @item
14821: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14822: @item
14823: Support of the @code{info-lookup} feature for looking up the
14824: documentation of a word.
1.107 dvdkhlng 14825: @item
14826: Support for reading and writing blocks files.
1.26 crook 14827: @end itemize
14828:
1.107 dvdkhlng 14829: To get a basic description of these features, enter Forth mode and
14830: type @kbd{C-h m}.
1.1 anton 14831:
14832: @cindex source location of error or debugging output in Emacs
14833: @cindex error output, finding the source location in Emacs
14834: @cindex debugging output, finding the source location in Emacs
14835: In addition, Gforth supports Emacs quite well: The source code locations
14836: given in error messages, debugging output (from @code{~~}) and failed
14837: assertion messages are in the right format for Emacs' compilation mode
14838: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14839: Manual}) so the source location corresponding to an error or other
14840: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14841: @kbd{C-c C-c} for the error under the cursor).
14842:
1.107 dvdkhlng 14843: @cindex viewing the documentation of a word in Emacs
14844: @cindex context-sensitive help
14845: Moreover, for words documented in this manual, you can look up the
14846: glossary entry quickly by using @kbd{C-h TAB}
14847: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14848: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14849: later and does not work for words containing @code{:}.
14850:
14851: @menu
14852: * Installing gforth.el:: Making Emacs aware of Forth.
14853: * Emacs Tags:: Viewing the source of a word in Emacs.
14854: * Hilighting:: Making Forth code look prettier.
14855: * Auto-Indentation:: Customizing auto-indentation.
14856: * Blocks Files:: Reading and writing blocks files.
14857: @end menu
14858:
14859: @c ----------------------------------
1.109 anton 14860: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14861: @section Installing gforth.el
14862: @cindex @file{.emacs}
14863: @cindex @file{gforth.el}, installation
14864: To make the features from @file{gforth.el} available in Emacs, add
14865: the following lines to your @file{.emacs} file:
14866:
14867: @example
14868: (autoload 'forth-mode "gforth.el")
14869: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14870: auto-mode-alist))
14871: (autoload 'forth-block-mode "gforth.el")
14872: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14873: auto-mode-alist))
14874: (add-hook 'forth-mode-hook (function (lambda ()
14875: ;; customize variables here:
14876: (setq forth-indent-level 4)
14877: (setq forth-minor-indent-level 2)
14878: (setq forth-hilight-level 3)
14879: ;;; ...
14880: )))
14881: @end example
14882:
14883: @c ----------------------------------
14884: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14885: @section Emacs Tags
1.1 anton 14886: @cindex @file{TAGS} file
14887: @cindex @file{etags.fs}
14888: @cindex viewing the source of a word in Emacs
1.43 anton 14889: @cindex @code{require}, placement in files
14890: @cindex @code{include}, placement in files
1.107 dvdkhlng 14891: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14892: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14893: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14894: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14895: several tags files at the same time (e.g., one for the Gforth sources
14896: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14897: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14898: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14899: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14900: with @file{etags.fs}, you should avoid putting definitions both before
14901: and after @code{require} etc., otherwise you will see the same file
14902: visited several times by commands like @code{tags-search}.
1.1 anton 14903:
1.107 dvdkhlng 14904: @c ----------------------------------
14905: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14906: @section Hilighting
14907: @cindex hilighting Forth code in Emacs
14908: @cindex highlighting Forth code in Emacs
14909: @file{gforth.el} comes with a custom source hilighting engine. When
14910: you open a file in @code{forth-mode}, it will be completely parsed,
14911: assigning faces to keywords, comments, strings etc. While you edit
14912: the file, modified regions get parsed and updated on-the-fly.
14913:
14914: Use the variable `forth-hilight-level' to change the level of
14915: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14916: you set the hilighting level to 0, the parser will still work in the
14917: background, collecting information about whether regions of text are
14918: ``compiled'' or ``interpreted''. Those information are required for
14919: auto-indentation to work properly. Set `forth-disable-parser' to
14920: non-nil if your computer is too slow to handle parsing. This will
14921: have an impact on the smartness of the auto-indentation engine,
14922: though.
14923:
14924: Sometimes Forth sources define new features that should be hilighted,
14925: new control structures, defining-words etc. You can use the variable
14926: `forth-custom-words' to make @code{forth-mode} hilight additional
14927: words and constructs. See the docstring of `forth-words' for details
14928: (in Emacs, type @kbd{C-h v forth-words}).
14929:
14930: `forth-custom-words' is meant to be customized in your
14931: @file{.emacs} file. To customize hilighing in a file-specific manner,
14932: set `forth-local-words' in a local-variables section at the end of
14933: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14934:
14935: Example:
14936: @example
14937: 0 [IF]
14938: Local Variables:
14939: forth-local-words:
14940: ((("t:") definition-starter (font-lock-keyword-face . 1)
14941: "[ \t\n]" t name (font-lock-function-name-face . 3))
14942: ((";t") definition-ender (font-lock-keyword-face . 1)))
14943: End:
14944: [THEN]
14945: @end example
14946:
14947: @c ----------------------------------
14948: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14949: @section Auto-Indentation
14950: @cindex auto-indentation of Forth code in Emacs
14951: @cindex indentation of Forth code in Emacs
14952: @code{forth-mode} automatically tries to indent lines in a smart way,
14953: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14954:
14955: Simple customization can be achieved by setting
14956: `forth-indent-level' and `forth-minor-indent-level' in your
14957: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14958: per default by multiples of 4 columns. To use the more traditional
14959: 3-column indentation, add the following lines to your @file{.emacs}:
14960:
14961: @example
14962: (add-hook 'forth-mode-hook (function (lambda ()
14963: ;; customize variables here:
14964: (setq forth-indent-level 3)
14965: (setq forth-minor-indent-level 1)
14966: )))
14967: @end example
14968:
14969: If you want indentation to recognize non-default words, customize it
14970: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14971: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14972: v forth-indent-words}).
14973:
14974: To customize indentation in a file-specific manner, set
14975: `forth-local-indent-words' in a local-variables section at the end of
14976: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14977: Emacs Manual}).
14978:
14979: Example:
14980: @example
14981: 0 [IF]
14982: Local Variables:
14983: forth-local-indent-words:
14984: ((("t:") (0 . 2) (0 . 2))
14985: ((";t") (-2 . 0) (0 . -2)))
14986: End:
14987: [THEN]
14988: @end example
14989:
14990: @c ----------------------------------
1.109 anton 14991: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14992: @section Blocks Files
14993: @cindex blocks files, use with Emacs
14994: @code{forth-mode} Autodetects blocks files by checking whether the
14995: length of the first line exceeds 1023 characters. It then tries to
14996: convert the file into normal text format. When you save the file, it
14997: will be written to disk as normal stream-source file.
14998:
14999: If you want to write blocks files, use @code{forth-blocks-mode}. It
15000: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 15001:
1.107 dvdkhlng 15002: @itemize @bullet
15003: @item
15004: Files are written to disk in blocks file format.
15005: @item
15006: Screen numbers are displayed in the mode line (enumerated beginning
15007: with the value of `forth-block-base')
15008: @item
15009: Warnings are displayed when lines exceed 64 characters.
15010: @item
15011: The beginning of the currently edited block is marked with an
15012: overlay-arrow.
15013: @end itemize
1.41 anton 15014:
1.107 dvdkhlng 15015: There are some restrictions you should be aware of. When you open a
15016: blocks file that contains tabulator or newline characters, these
15017: characters will be translated into spaces when the file is written
15018: back to disk. If tabs or newlines are encountered during blocks file
15019: reading, an error is output to the echo area. So have a look at the
15020: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 15021:
1.107 dvdkhlng 15022: Please consult the docstring of @code{forth-blocks-mode} for more
15023: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 15024:
1.26 crook 15025: @c ******************************************************************
1.1 anton 15026: @node Image Files, Engine, Emacs and Gforth, Top
15027: @chapter Image Files
1.26 crook 15028: @cindex image file
15029: @cindex @file{.fi} files
1.1 anton 15030: @cindex precompiled Forth code
15031: @cindex dictionary in persistent form
15032: @cindex persistent form of dictionary
15033:
15034: An image file is a file containing an image of the Forth dictionary,
15035: i.e., compiled Forth code and data residing in the dictionary. By
15036: convention, we use the extension @code{.fi} for image files.
15037:
15038: @menu
1.18 anton 15039: * Image Licensing Issues:: Distribution terms for images.
15040: * Image File Background:: Why have image files?
1.67 anton 15041: * Non-Relocatable Image Files:: don't always work.
1.18 anton 15042: * Data-Relocatable Image Files:: are better.
1.67 anton 15043: * Fully Relocatable Image Files:: better yet.
1.18 anton 15044: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 15045: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 15046: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 15047: @end menu
15048:
1.18 anton 15049: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15050: @section Image Licensing Issues
15051: @cindex license for images
15052: @cindex image license
15053:
15054: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15055: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15056: original image; i.e., according to copyright law it is a derived work of
15057: the original image.
15058:
15059: Since Gforth is distributed under the GNU GPL, the newly created image
15060: falls under the GNU GPL, too. In particular, this means that if you
15061: distribute the image, you have to make all of the sources for the image
1.113 anton 15062: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 15063: GNU General Public License (Section 3)}.
15064:
15065: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15066: contains only code compiled from the sources you gave it; if none of
15067: these sources is under the GPL, the terms discussed above do not apply
15068: to the image. However, if your image needs an engine (a gforth binary)
15069: that is under the GPL, you should make sure that you distribute both in
15070: a way that is at most a @emph{mere aggregation}, if you don't want the
15071: terms of the GPL to apply to the image.
15072:
15073: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 15074: @section Image File Background
15075: @cindex image file background
15076:
1.80 anton 15077: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 15078: definitions written in Forth. Since the Forth compiler itself belongs to
15079: those definitions, it is not possible to start the system with the
1.80 anton 15080: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 15081: code as an image file in nearly executable form. When Gforth starts up,
15082: a C routine loads the image file into memory, optionally relocates the
15083: addresses, then sets up the memory (stacks etc.) according to
15084: information in the image file, and (finally) starts executing Forth
15085: code.
1.1 anton 15086:
15087: The image file variants represent different compromises between the
15088: goals of making it easy to generate image files and making them
15089: portable.
15090:
15091: @cindex relocation at run-time
1.26 crook 15092: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 15093: run-time. This avoids many of the complications discussed below (image
15094: files are data relocatable without further ado), but costs performance
15095: (one addition per memory access).
15096:
15097: @cindex relocation at load-time
1.26 crook 15098: By contrast, the Gforth loader performs relocation at image load time. The
15099: loader also has to replace tokens that represent primitive calls with the
1.1 anton 15100: appropriate code-field addresses (or code addresses in the case of
15101: direct threading).
15102:
15103: There are three kinds of image files, with different degrees of
15104: relocatability: non-relocatable, data-relocatable, and fully relocatable
15105: image files.
15106:
15107: @cindex image file loader
15108: @cindex relocating loader
15109: @cindex loader for image files
15110: These image file variants have several restrictions in common; they are
15111: caused by the design of the image file loader:
15112:
15113: @itemize @bullet
15114: @item
15115: There is only one segment; in particular, this means, that an image file
15116: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 15117: them). The contents of the stacks are not represented, either.
1.1 anton 15118:
15119: @item
15120: The only kinds of relocation supported are: adding the same offset to
15121: all cells that represent data addresses; and replacing special tokens
15122: with code addresses or with pieces of machine code.
15123:
15124: If any complex computations involving addresses are performed, the
15125: results cannot be represented in the image file. Several applications that
15126: use such computations come to mind:
15127: @itemize @minus
15128: @item
15129: Hashing addresses (or data structures which contain addresses) for table
15130: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15131: purpose, you will have no problem, because the hash tables are
15132: recomputed automatically when the system is started. If you use your own
15133: hash tables, you will have to do something similar.
15134:
15135: @item
15136: There's a cute implementation of doubly-linked lists that uses
15137: @code{XOR}ed addresses. You could represent such lists as singly-linked
15138: in the image file, and restore the doubly-linked representation on
15139: startup.@footnote{In my opinion, though, you should think thrice before
15140: using a doubly-linked list (whatever implementation).}
15141:
15142: @item
15143: The code addresses of run-time routines like @code{docol:} cannot be
15144: represented in the image file (because their tokens would be replaced by
15145: machine code in direct threaded implementations). As a workaround,
15146: compute these addresses at run-time with @code{>code-address} from the
15147: executions tokens of appropriate words (see the definitions of
1.80 anton 15148: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 15149:
15150: @item
15151: On many architectures addresses are represented in machine code in some
15152: shifted or mangled form. You cannot put @code{CODE} words that contain
15153: absolute addresses in this form in a relocatable image file. Workarounds
15154: are representing the address in some relative form (e.g., relative to
15155: the CFA, which is present in some register), or loading the address from
15156: a place where it is stored in a non-mangled form.
15157: @end itemize
15158: @end itemize
15159:
15160: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15161: @section Non-Relocatable Image Files
15162: @cindex non-relocatable image files
1.26 crook 15163: @cindex image file, non-relocatable
1.1 anton 15164:
15165: These files are simple memory dumps of the dictionary. They are specific
15166: to the executable (i.e., @file{gforth} file) they were created
15167: with. What's worse, they are specific to the place on which the
15168: dictionary resided when the image was created. Now, there is no
15169: guarantee that the dictionary will reside at the same place the next
15170: time you start Gforth, so there's no guarantee that a non-relocatable
15171: image will work the next time (Gforth will complain instead of crashing,
15172: though).
15173:
15174: You can create a non-relocatable image file with
15175:
1.44 crook 15176:
1.1 anton 15177: doc-savesystem
15178:
1.44 crook 15179:
1.1 anton 15180: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15181: @section Data-Relocatable Image Files
15182: @cindex data-relocatable image files
1.26 crook 15183: @cindex image file, data-relocatable
1.1 anton 15184:
15185: These files contain relocatable data addresses, but fixed code addresses
15186: (instead of tokens). They are specific to the executable (i.e.,
15187: @file{gforth} file) they were created with. For direct threading on some
15188: architectures (e.g., the i386), data-relocatable images do not work. You
15189: get a data-relocatable image, if you use @file{gforthmi} with a
15190: Gforth binary that is not doubly indirect threaded (@pxref{Fully
15191: Relocatable Image Files}).
15192:
15193: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15194: @section Fully Relocatable Image Files
15195: @cindex fully relocatable image files
1.26 crook 15196: @cindex image file, fully relocatable
1.1 anton 15197:
15198: @cindex @file{kern*.fi}, relocatability
15199: @cindex @file{gforth.fi}, relocatability
15200: These image files have relocatable data addresses, and tokens for code
15201: addresses. They can be used with different binaries (e.g., with and
15202: without debugging) on the same machine, and even across machines with
15203: the same data formats (byte order, cell size, floating point
15204: format). However, they are usually specific to the version of Gforth
15205: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
15206: are fully relocatable.
15207:
15208: There are two ways to create a fully relocatable image file:
15209:
15210: @menu
1.29 crook 15211: * gforthmi:: The normal way
1.1 anton 15212: * cross.fs:: The hard way
15213: @end menu
15214:
15215: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15216: @subsection @file{gforthmi}
15217: @cindex @file{comp-i.fs}
15218: @cindex @file{gforthmi}
15219:
15220: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15221: image @i{file} that contains everything you would load by invoking
15222: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15223: @example
1.29 crook 15224: gforthmi @i{file} @i{options}
1.1 anton 15225: @end example
15226:
15227: E.g., if you want to create an image @file{asm.fi} that has the file
15228: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15229: like this:
15230:
15231: @example
15232: gforthmi asm.fi asm.fs
15233: @end example
15234:
1.27 crook 15235: @file{gforthmi} is implemented as a sh script and works like this: It
15236: produces two non-relocatable images for different addresses and then
15237: compares them. Its output reflects this: first you see the output (if
1.62 crook 15238: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15239: files, then you see the output of the comparing program: It displays the
15240: offset used for data addresses and the offset used for code addresses;
1.1 anton 15241: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15242: image files, it displays a line like this:
1.1 anton 15243:
15244: @example
15245: 78DC BFFFFA50 BFFFFA40
15246: @end example
15247:
15248: This means that at offset $78dc from @code{forthstart}, one input image
15249: contains $bffffa50, and the other contains $bffffa40. Since these cells
15250: cannot be represented correctly in the output image, you should examine
15251: these places in the dictionary and verify that these cells are dead
15252: (i.e., not read before they are written).
1.39 anton 15253:
15254: @cindex --application, @code{gforthmi} option
15255: If you insert the option @code{--application} in front of the image file
15256: name, you will get an image that uses the @code{--appl-image} option
15257: instead of the @code{--image-file} option (@pxref{Invoking
15258: Gforth}). When you execute such an image on Unix (by typing the image
15259: name as command), the Gforth engine will pass all options to the image
15260: instead of trying to interpret them as engine options.
1.1 anton 15261:
1.27 crook 15262: If you type @file{gforthmi} with no arguments, it prints some usage
15263: instructions.
15264:
1.1 anton 15265: @cindex @code{savesystem} during @file{gforthmi}
15266: @cindex @code{bye} during @file{gforthmi}
15267: @cindex doubly indirect threaded code
1.44 crook 15268: @cindex environment variables
15269: @cindex @code{GFORTHD} -- environment variable
15270: @cindex @code{GFORTH} -- environment variable
1.1 anton 15271: @cindex @code{gforth-ditc}
1.29 crook 15272: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 15273: words @code{savesystem} and @code{bye} must be visible. A special doubly
15274: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 15275: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 15276: this executable through the environment variable @code{GFORTHD}
15277: (default: @file{gforth-ditc}); if you pass a version that is not doubly
15278: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 15279: data-relocatable image (because there is no code address offset). The
15280: normal @file{gforth} executable is used for creating the relocatable
15281: image; you can pass the exact filename of this executable through the
15282: environment variable @code{GFORTH}.
1.1 anton 15283:
15284: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15285: @subsection @file{cross.fs}
15286: @cindex @file{cross.fs}
15287: @cindex cross-compiler
15288: @cindex metacompiler
1.47 crook 15289: @cindex target compiler
1.1 anton 15290:
15291: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15292: programming language (@pxref{Cross Compiler}).
1.1 anton 15293:
1.47 crook 15294: @code{cross} allows you to create image files for machines with
1.1 anton 15295: different data sizes and data formats than the one used for generating
15296: the image file. You can also use it to create an application image that
15297: does not contain a Forth compiler. These features are bought with
15298: restrictions and inconveniences in programming. E.g., addresses have to
15299: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15300: order to make the code relocatable.
15301:
15302:
15303: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15304: @section Stack and Dictionary Sizes
15305: @cindex image file, stack and dictionary sizes
15306: @cindex dictionary size default
15307: @cindex stack size default
15308:
15309: If you invoke Gforth with a command line flag for the size
15310: (@pxref{Invoking Gforth}), the size you specify is stored in the
15311: dictionary. If you save the dictionary with @code{savesystem} or create
15312: an image with @file{gforthmi}, this size will become the default
15313: for the resulting image file. E.g., the following will create a
1.21 crook 15314: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15315:
15316: @example
15317: gforthmi gforth.fi -m 1M
15318: @end example
15319:
15320: In other words, if you want to set the default size for the dictionary
15321: and the stacks of an image, just invoke @file{gforthmi} with the
15322: appropriate options when creating the image.
15323:
15324: @cindex stack size, cache-friendly
15325: Note: For cache-friendly behaviour (i.e., good performance), you should
15326: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15327: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15328: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15329:
15330: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15331: @section Running Image Files
15332: @cindex running image files
15333: @cindex invoking image files
15334: @cindex image file invocation
15335:
15336: @cindex -i, invoke image file
15337: @cindex --image file, invoke image file
1.29 crook 15338: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15339: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15340: @example
1.29 crook 15341: gforth -i @i{image}
1.1 anton 15342: @end example
15343:
15344: @cindex executable image file
1.26 crook 15345: @cindex image file, executable
1.1 anton 15346: If your operating system supports starting scripts with a line of the
15347: form @code{#! ...}, you just have to type the image file name to start
15348: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15349: just a convention). I.e., to run Gforth with the image file @i{image},
15350: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15351: This works because every @code{.fi} file starts with a line of this
15352: format:
15353:
15354: @example
15355: #! /usr/local/bin/gforth-0.4.0 -i
15356: @end example
15357:
15358: The file and pathname for the Gforth engine specified on this line is
15359: the specific Gforth executable that it was built against; i.e. the value
15360: of the environment variable @code{GFORTH} at the time that
15361: @file{gforthmi} was executed.
1.1 anton 15362:
1.27 crook 15363: You can make use of the same shell capability to make a Forth source
15364: file into an executable. For example, if you place this text in a file:
1.26 crook 15365:
15366: @example
15367: #! /usr/local/bin/gforth
15368:
15369: ." Hello, world" CR
15370: bye
15371: @end example
15372:
15373: @noindent
1.27 crook 15374: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15375: directly from the command line. The sequence @code{#!} is used in two
15376: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15377: system@footnote{The Unix kernel actually recognises two types of files:
15378: executable files and files of data, where the data is processed by an
15379: interpreter that is specified on the ``interpreter line'' -- the first
15380: line of the file, starting with the sequence #!. There may be a small
15381: limit (e.g., 32) on the number of characters that may be specified on
15382: the interpreter line.} secondly it is treated as a comment character by
15383: Gforth. Because of the second usage, a space is required between
1.80 anton 15384: @code{#!} and the path to the executable (moreover, some Unixes
15385: require the sequence @code{#! /}).
1.27 crook 15386:
15387: The disadvantage of this latter technique, compared with using
1.80 anton 15388: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15389: compiled on-the-fly, each time the program is invoked.
1.26 crook 15390:
1.1 anton 15391: doc-#!
15392:
1.44 crook 15393:
1.1 anton 15394: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15395: @section Modifying the Startup Sequence
15396: @cindex startup sequence for image file
15397: @cindex image file initialization sequence
15398: @cindex initialization sequence of image file
15399:
1.120 anton 15400: You can add your own initialization to the startup sequence of an image
15401: through the deferred word @code{'cold}. @code{'cold} is invoked just
15402: before the image-specific command line processing (i.e., loading files
15403: and evaluating (@code{-e}) strings) starts.
1.1 anton 15404:
15405: A sequence for adding your initialization usually looks like this:
15406:
15407: @example
15408: :noname
15409: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15410: ... \ your stuff
15411: ; IS 'cold
15412: @end example
15413:
1.157 anton 15414: After @code{'cold}, Gforth processes the image options
15415: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15416: another deferred word. This normally prints Gforth's startup message
15417: and does nothing else.
15418:
1.1 anton 15419: @cindex turnkey image files
1.26 crook 15420: @cindex image file, turnkey applications
1.157 anton 15421: So, if you want to make a turnkey image (i.e., an image for an
15422: application instead of an extended Forth system), you can do this in
15423: two ways:
15424:
15425: @itemize @bullet
15426:
15427: @item
15428: If you want to do your interpretation of the OS command-line
15429: arguments, hook into @code{'cold}. In that case you probably also
15430: want to build the image with @code{gforthmi --application}
15431: (@pxref{gforthmi}) to keep the engine from processing OS command line
15432: options. You can then do your own command-line processing with
15433: @code{next-arg}
15434:
15435: @item
15436: If you want to have the normal Gforth processing of OS command-line
15437: arguments, hook into @code{bootmessage}.
15438:
15439: @end itemize
15440:
15441: In either case, you probably do not want the word that you execute in
15442: these hooks to exit normally, but use @code{bye} or @code{throw}.
15443: Otherwise the Gforth startup process would continue and eventually
15444: present the Forth command line to the user.
1.26 crook 15445:
15446: doc-'cold
1.157 anton 15447: doc-bootmessage
1.44 crook 15448:
1.1 anton 15449: @c ******************************************************************
1.113 anton 15450: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15451: @chapter Engine
15452: @cindex engine
15453: @cindex virtual machine
15454:
1.26 crook 15455: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15456: may be helpful for finding your way in the Gforth sources.
15457:
1.109 anton 15458: The ideas in this section have also been published in the following
15459: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15460: Forth-Tagung '93; M. Anton Ertl,
15461: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15462: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15463: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15464: Threaded code variations and optimizations (extended version)}},
15465: Forth-Tagung '02.
1.1 anton 15466:
15467: @menu
15468: * Portability::
15469: * Threading::
15470: * Primitives::
15471: * Performance::
15472: @end menu
15473:
15474: @node Portability, Threading, Engine, Engine
15475: @section Portability
15476: @cindex engine portability
15477:
1.26 crook 15478: An important goal of the Gforth Project is availability across a wide
15479: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15480: achieved this goal by manually coding the engine in assembly language
15481: for several then-popular processors. This approach is very
15482: labor-intensive and the results are short-lived due to progress in
15483: computer architecture.
1.1 anton 15484:
15485: @cindex C, using C for the engine
15486: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15487: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15488: particularly popular for UNIX-based Forths due to the large variety of
15489: architectures of UNIX machines. Unfortunately an implementation in C
15490: does not mix well with the goals of efficiency and with using
15491: traditional techniques: Indirect or direct threading cannot be expressed
15492: in C, and switch threading, the fastest technique available in C, is
15493: significantly slower. Another problem with C is that it is very
15494: cumbersome to express double integer arithmetic.
15495:
15496: @cindex GNU C for the engine
15497: @cindex long long
15498: Fortunately, there is a portable language that does not have these
15499: limitations: GNU C, the version of C processed by the GNU C compiler
15500: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15501: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15502: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15503: threading possible, its @code{long long} type (@pxref{Long Long, ,
15504: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15505: double numbers on many systems. GNU C is freely available on all
1.1 anton 15506: important (and many unimportant) UNIX machines, VMS, 80386s running
15507: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15508: on all these machines.
15509:
15510: Writing in a portable language has the reputation of producing code that
15511: is slower than assembly. For our Forth engine we repeatedly looked at
15512: the code produced by the compiler and eliminated most compiler-induced
15513: inefficiencies by appropriate changes in the source code.
15514:
15515: @cindex explicit register declarations
15516: @cindex --enable-force-reg, configuration flag
15517: @cindex -DFORCE_REG
15518: However, register allocation cannot be portably influenced by the
15519: programmer, leading to some inefficiencies on register-starved
15520: machines. We use explicit register declarations (@pxref{Explicit Reg
15521: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15522: improve the speed on some machines. They are turned on by using the
15523: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15524: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15525: machine, but also on the compiler version: On some machines some
15526: compiler versions produce incorrect code when certain explicit register
15527: declarations are used. So by default @code{-DFORCE_REG} is not used.
15528:
15529: @node Threading, Primitives, Portability, Engine
15530: @section Threading
15531: @cindex inner interpreter implementation
15532: @cindex threaded code implementation
15533:
15534: @cindex labels as values
15535: GNU C's labels as values extension (available since @code{gcc-2.0},
15536: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15537: makes it possible to take the address of @i{label} by writing
15538: @code{&&@i{label}}. This address can then be used in a statement like
15539: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15540: @code{goto x}.
15541:
1.26 crook 15542: @cindex @code{NEXT}, indirect threaded
1.1 anton 15543: @cindex indirect threaded inner interpreter
15544: @cindex inner interpreter, indirect threaded
1.26 crook 15545: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15546: @example
15547: cfa = *ip++;
15548: ca = *cfa;
15549: goto *ca;
15550: @end example
15551: @cindex instruction pointer
15552: For those unfamiliar with the names: @code{ip} is the Forth instruction
15553: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15554: execution token and points to the code field of the next word to be
15555: executed; The @code{ca} (code address) fetched from there points to some
15556: executable code, e.g., a primitive or the colon definition handler
15557: @code{docol}.
15558:
1.26 crook 15559: @cindex @code{NEXT}, direct threaded
1.1 anton 15560: @cindex direct threaded inner interpreter
15561: @cindex inner interpreter, direct threaded
15562: Direct threading is even simpler:
15563: @example
15564: ca = *ip++;
15565: goto *ca;
15566: @end example
15567:
15568: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15569: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15570:
15571: @menu
15572: * Scheduling::
15573: * Direct or Indirect Threaded?::
1.109 anton 15574: * Dynamic Superinstructions::
1.1 anton 15575: * DOES>::
15576: @end menu
15577:
15578: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15579: @subsection Scheduling
15580: @cindex inner interpreter optimization
15581:
15582: There is a little complication: Pipelined and superscalar processors,
15583: i.e., RISC and some modern CISC machines can process independent
15584: instructions while waiting for the results of an instruction. The
15585: compiler usually reorders (schedules) the instructions in a way that
15586: achieves good usage of these delay slots. However, on our first tries
15587: the compiler did not do well on scheduling primitives. E.g., for
15588: @code{+} implemented as
15589: @example
15590: n=sp[0]+sp[1];
15591: sp++;
15592: sp[0]=n;
15593: NEXT;
15594: @end example
1.81 anton 15595: the @code{NEXT} comes strictly after the other code, i.e., there is
15596: nearly no scheduling. After a little thought the problem becomes clear:
15597: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15598: addresses (and the version of @code{gcc} we used would not know it even
15599: if it was possible), so it could not move the load of the cfa above the
15600: store to the TOS. Indeed the pointers could be the same, if code on or
15601: very near the top of stack were executed. In the interest of speed we
15602: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15603: in scheduling: @code{NEXT} is divided into several parts:
15604: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15605: like:
1.1 anton 15606: @example
1.81 anton 15607: NEXT_P0;
1.1 anton 15608: n=sp[0]+sp[1];
15609: sp++;
15610: NEXT_P1;
15611: sp[0]=n;
15612: NEXT_P2;
15613: @end example
15614:
1.81 anton 15615: There are various schemes that distribute the different operations of
15616: NEXT between these parts in several ways; in general, different schemes
15617: perform best on different processors. We use a scheme for most
15618: architectures that performs well for most processors of this
1.109 anton 15619: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15620: the scheme on installation time.
15621:
1.1 anton 15622:
1.109 anton 15623: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15624: @subsection Direct or Indirect Threaded?
15625: @cindex threading, direct or indirect?
15626:
1.109 anton 15627: Threaded forth code consists of references to primitives (simple machine
15628: code routines like @code{+}) and to non-primitives (e.g., colon
15629: definitions, variables, constants); for a specific class of
15630: non-primitives (e.g., variables) there is one code routine (e.g.,
15631: @code{dovar}), but each variable needs a separate reference to its data.
15632:
15633: Traditionally Forth has been implemented as indirect threaded code,
15634: because this allows to use only one cell to reference a non-primitive
15635: (basically you point to the data, and find the code address there).
15636:
15637: @cindex primitive-centric threaded code
15638: However, threaded code in Gforth (since 0.6.0) uses two cells for
15639: non-primitives, one for the code address, and one for the data address;
15640: the data pointer is an immediate argument for the virtual machine
15641: instruction represented by the code address. We call this
15642: @emph{primitive-centric} threaded code, because all code addresses point
15643: to simple primitives. E.g., for a variable, the code address is for
15644: @code{lit} (also used for integer literals like @code{99}).
15645:
15646: Primitive-centric threaded code allows us to use (faster) direct
15647: threading as dispatch method, completely portably (direct threaded code
15648: in Gforth before 0.6.0 required architecture-specific code). It also
15649: eliminates the performance problems related to I-cache consistency that
15650: 386 implementations have with direct threaded code, and allows
15651: additional optimizations.
15652:
15653: @cindex hybrid direct/indirect threaded code
15654: There is a catch, however: the @var{xt} parameter of @code{execute} can
15655: occupy only one cell, so how do we pass non-primitives with their code
15656: @emph{and} data addresses to them? Our answer is to use indirect
15657: threaded dispatch for @code{execute} and other words that use a
15658: single-cell xt. So, normal threaded code in colon definitions uses
15659: direct threading, and @code{execute} and similar words, which dispatch
15660: to xts on the data stack, use indirect threaded code. We call this
15661: @emph{hybrid direct/indirect} threaded code.
15662:
15663: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15664: @cindex gforth engine
15665: @cindex gforth-fast engine
15666: The engines @command{gforth} and @command{gforth-fast} use hybrid
15667: direct/indirect threaded code. This means that with these engines you
15668: cannot use @code{,} to compile an xt. Instead, you have to use
15669: @code{compile,}.
15670:
15671: @cindex gforth-itc engine
1.115 anton 15672: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15673: This engine uses plain old indirect threaded code. It still compiles in
15674: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15675: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15676: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15677: and execute @code{' , is compile,}. Your program can check if it is
15678: running on a hybrid direct/indirect threaded engine or a pure indirect
15679: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15680:
15681:
15682: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15683: @subsection Dynamic Superinstructions
15684: @cindex Dynamic superinstructions with replication
15685: @cindex Superinstructions
15686: @cindex Replication
15687:
15688: The engines @command{gforth} and @command{gforth-fast} use another
15689: optimization: Dynamic superinstructions with replication. As an
15690: example, consider the following colon definition:
15691:
15692: @example
15693: : squared ( n1 -- n2 )
15694: dup * ;
15695: @end example
15696:
15697: Gforth compiles this into the threaded code sequence
15698:
15699: @example
15700: dup
15701: *
15702: ;s
15703: @end example
15704:
15705: In normal direct threaded code there is a code address occupying one
15706: cell for each of these primitives. Each code address points to a
15707: machine code routine, and the interpreter jumps to this machine code in
15708: order to execute the primitive. The routines for these three
15709: primitives are (in @command{gforth-fast} on the 386):
15710:
15711: @example
15712: Code dup
15713: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15714: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15715: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15716: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15717: end-code
15718: Code *
15719: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15720: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15721: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15722: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15723: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15724: end-code
15725: Code ;s
15726: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15727: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15728: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15729: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15730: end-code
15731: @end example
15732:
15733: With dynamic superinstructions and replication the compiler does not
15734: just lay down the threaded code, but also copies the machine code
15735: fragments, usually without the jump at the end.
15736:
15737: @example
15738: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15739: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15740: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15741: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15742: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15743: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15744: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15745: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15746: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15747: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15748: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15749: @end example
15750:
15751: Only when a threaded-code control-flow change happens (e.g., in
15752: @code{;s}), the jump is appended. This optimization eliminates many of
15753: these jumps and makes the rest much more predictable. The speedup
15754: depends on the processor and the application; on the Athlon and Pentium
15755: III this optimization typically produces a speedup by a factor of 2.
15756:
15757: The code addresses in the direct-threaded code are set to point to the
15758: appropriate points in the copied machine code, in this example like
15759: this:
1.1 anton 15760:
1.109 anton 15761: @example
15762: primitive code address
15763: dup $4057D27D
15764: * $4057D286
15765: ;s $4057D292
15766: @end example
15767:
15768: Thus there can be threaded-code jumps to any place in this piece of
15769: code. This also simplifies decompilation quite a bit.
15770:
15771: @cindex --no-dynamic command-line option
15772: @cindex --no-super command-line option
15773: You can disable this optimization with @option{--no-dynamic}. You can
15774: use the copying without eliminating the jumps (i.e., dynamic
15775: replication, but without superinstructions) with @option{--no-super};
15776: this gives the branch prediction benefit alone; the effect on
1.110 anton 15777: performance depends on the CPU; on the Athlon and Pentium III the
15778: speedup is a little less than for dynamic superinstructions with
15779: replication.
15780:
15781: @cindex patching threaded code
15782: One use of these options is if you want to patch the threaded code.
15783: With superinstructions, many of the dispatch jumps are eliminated, so
15784: patching often has no effect. These options preserve all the dispatch
15785: jumps.
1.109 anton 15786:
15787: @cindex --dynamic command-line option
1.110 anton 15788: On some machines dynamic superinstructions are disabled by default,
15789: because it is unsafe on these machines. However, if you feel
15790: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15791:
15792: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15793: @subsection DOES>
15794: @cindex @code{DOES>} implementation
15795:
1.26 crook 15796: @cindex @code{dodoes} routine
15797: @cindex @code{DOES>}-code
1.1 anton 15798: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15799: the chunk of code executed by every word defined by a
1.109 anton 15800: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15801: this is only needed if the xt of the word is @code{execute}d. The main
15802: problem here is: How to find the Forth code to be executed, i.e. the
15803: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15804: solutions:
1.1 anton 15805:
1.21 crook 15806: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15807: @code{DOES>}-code address is stored in the cell after the code address
15808: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15809: illegal in the Forth-79 and all later standards, because in fig-Forth
15810: this address lies in the body (which is illegal in these
15811: standards). However, by making the code field larger for all words this
15812: solution becomes legal again. We use this approach. Leaving a cell
15813: unused in most words is a bit wasteful, but on the machines we are
15814: targeting this is hardly a problem.
15815:
1.1 anton 15816:
15817: @node Primitives, Performance, Threading, Engine
15818: @section Primitives
15819: @cindex primitives, implementation
15820: @cindex virtual machine instructions, implementation
15821:
15822: @menu
15823: * Automatic Generation::
15824: * TOS Optimization::
15825: * Produced code::
15826: @end menu
15827:
15828: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15829: @subsection Automatic Generation
15830: @cindex primitives, automatic generation
15831:
15832: @cindex @file{prims2x.fs}
1.109 anton 15833:
1.1 anton 15834: Since the primitives are implemented in a portable language, there is no
15835: longer any need to minimize the number of primitives. On the contrary,
15836: having many primitives has an advantage: speed. In order to reduce the
15837: number of errors in primitives and to make programming them easier, we
1.109 anton 15838: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15839: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15840: generates most (and sometimes all) of the C code for a primitive from
15841: the stack effect notation. The source for a primitive has the following
15842: form:
1.1 anton 15843:
15844: @cindex primitive source format
15845: @format
1.58 anton 15846: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15847: [@code{""}@i{glossary entry}@code{""}]
15848: @i{C code}
1.1 anton 15849: [@code{:}
1.29 crook 15850: @i{Forth code}]
1.1 anton 15851: @end format
15852:
15853: The items in brackets are optional. The category and glossary fields
15854: are there for generating the documentation, the Forth code is there
15855: for manual implementations on machines without GNU C. E.g., the source
15856: for the primitive @code{+} is:
15857: @example
1.58 anton 15858: + ( n1 n2 -- n ) core plus
1.1 anton 15859: n = n1+n2;
15860: @end example
15861:
15862: This looks like a specification, but in fact @code{n = n1+n2} is C
15863: code. Our primitive generation tool extracts a lot of information from
15864: the stack effect notations@footnote{We use a one-stack notation, even
15865: though we have separate data and floating-point stacks; The separate
15866: notation can be generated easily from the unified notation.}: The number
15867: of items popped from and pushed on the stack, their type, and by what
15868: name they are referred to in the C code. It then generates a C code
15869: prelude and postlude for each primitive. The final C code for @code{+}
15870: looks like this:
15871:
15872: @example
1.46 pazsan 15873: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15874: /* */ /* documentation */
1.81 anton 15875: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15876: @{
15877: DEF_CA /* definition of variable ca (indirect threading) */
15878: Cell n1; /* definitions of variables */
15879: Cell n2;
15880: Cell n;
1.81 anton 15881: NEXT_P0; /* NEXT part 0 */
1.1 anton 15882: n1 = (Cell) sp[1]; /* input */
15883: n2 = (Cell) TOS;
15884: sp += 1; /* stack adjustment */
15885: @{
15886: n = n1+n2; /* C code taken from the source */
15887: @}
15888: NEXT_P1; /* NEXT part 1 */
15889: TOS = (Cell)n; /* output */
15890: NEXT_P2; /* NEXT part 2 */
15891: @}
15892: @end example
15893:
15894: This looks long and inefficient, but the GNU C compiler optimizes quite
15895: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15896: HP RISC machines: Defining the @code{n}s does not produce any code, and
15897: using them as intermediate storage also adds no cost.
15898:
1.26 crook 15899: There are also other optimizations that are not illustrated by this
15900: example: assignments between simple variables are usually for free (copy
1.1 anton 15901: propagation). If one of the stack items is not used by the primitive
15902: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15903: (dead code elimination). On the other hand, there are some things that
15904: the compiler does not do, therefore they are performed by
15905: @file{prims2x.fs}: The compiler does not optimize code away that stores
15906: a stack item to the place where it just came from (e.g., @code{over}).
15907:
15908: While programming a primitive is usually easy, there are a few cases
15909: where the programmer has to take the actions of the generator into
15910: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15911: fall through to @code{NEXT}.
1.109 anton 15912:
15913: For more information
1.1 anton 15914:
15915: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15916: @subsection TOS Optimization
15917: @cindex TOS optimization for primitives
15918: @cindex primitives, keeping the TOS in a register
15919:
15920: An important optimization for stack machine emulators, e.g., Forth
15921: engines, is keeping one or more of the top stack items in
1.29 crook 15922: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15923: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15924: @itemize @bullet
15925: @item
1.29 crook 15926: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15927: due to fewer loads from and stores to the stack.
1.29 crook 15928: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15929: @i{y<n}, due to additional moves between registers.
1.1 anton 15930: @end itemize
15931:
15932: @cindex -DUSE_TOS
15933: @cindex -DUSE_NO_TOS
15934: In particular, keeping one item in a register is never a disadvantage,
15935: if there are enough registers. Keeping two items in registers is a
15936: disadvantage for frequent words like @code{?branch}, constants,
15937: variables, literals and @code{i}. Therefore our generator only produces
15938: code that keeps zero or one items in registers. The generated C code
15939: covers both cases; the selection between these alternatives is made at
15940: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15941: code for @code{+} is just a simple variable name in the one-item case,
15942: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15943: GNU C compiler tries to keep simple variables like @code{TOS} in
15944: registers, and it usually succeeds, if there are enough registers.
15945:
15946: @cindex -DUSE_FTOS
15947: @cindex -DUSE_NO_FTOS
15948: The primitive generator performs the TOS optimization for the
15949: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15950: operations the benefit of this optimization is even larger:
15951: floating-point operations take quite long on most processors, but can be
15952: performed in parallel with other operations as long as their results are
15953: not used. If the FP-TOS is kept in a register, this works. If
15954: it is kept on the stack, i.e., in memory, the store into memory has to
15955: wait for the result of the floating-point operation, lengthening the
15956: execution time of the primitive considerably.
15957:
15958: The TOS optimization makes the automatic generation of primitives a
15959: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15960: @code{TOS} is not sufficient. There are some special cases to
15961: consider:
15962: @itemize @bullet
15963: @item In the case of @code{dup ( w -- w w )} the generator must not
15964: eliminate the store to the original location of the item on the stack,
15965: if the TOS optimization is turned on.
15966: @item Primitives with stack effects of the form @code{--}
1.29 crook 15967: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15968: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15969: must load the TOS from the stack at the end. But for the null stack
15970: effect @code{--} no stores or loads should be generated.
15971: @end itemize
15972:
15973: @node Produced code, , TOS Optimization, Primitives
15974: @subsection Produced code
15975: @cindex primitives, assembly code listing
15976:
15977: @cindex @file{engine.s}
15978: To see what assembly code is produced for the primitives on your machine
15979: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15980: look at the resulting file @file{engine.s}. Alternatively, you can also
15981: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15982:
15983: @node Performance, , Primitives, Engine
15984: @section Performance
15985: @cindex performance of some Forth interpreters
15986: @cindex engine performance
15987: @cindex benchmarking Forth systems
15988: @cindex Gforth performance
15989:
15990: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15991: impossible to write a significantly faster threaded-code engine.
1.1 anton 15992:
15993: On register-starved machines like the 386 architecture processors
15994: improvements are possible, because @code{gcc} does not utilize the
15995: registers as well as a human, even with explicit register declarations;
15996: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15997: and hand-tuned it for the 486; this system is 1.19 times faster on the
15998: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15999: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
16000: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16001: registers fit in real registers (and we can even afford to use the TOS
16002: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 16003: earlier results. And dynamic superinstructions provide another speedup
16004: (but only around a factor 1.2 on the 486).
1.1 anton 16005:
16006: @cindex Win32Forth performance
16007: @cindex NT Forth performance
16008: @cindex eforth performance
16009: @cindex ThisForth performance
16010: @cindex PFE performance
16011: @cindex TILE performance
1.81 anton 16012: The potential advantage of assembly language implementations is not
1.112 anton 16013: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 16014: (direct threaded, compiled with @code{gcc-2.95.1} and
16015: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16016: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16017: (with and without peephole (aka pinhole) optimization of the threaded
16018: code); all these systems were written in assembly language. We also
16019: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16020: with @code{gcc-2.6.3} with the default configuration for Linux:
16021: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16022: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16023: employs peephole optimization of the threaded code) and TILE (compiled
16024: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16025: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16026: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16027: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16028: then extended it to run the benchmarks, added the peephole optimizer,
16029: ran the benchmarks and reported the results.
1.40 anton 16030:
1.1 anton 16031: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16032: matrix multiplication come from the Stanford integer benchmarks and have
16033: been translated into Forth by Martin Fraeman; we used the versions
16034: included in the TILE Forth package, but with bigger data set sizes; and
16035: a recursive Fibonacci number computation for benchmarking calling
16036: performance. The following table shows the time taken for the benchmarks
16037: scaled by the time taken by Gforth (in other words, it shows the speedup
16038: factor that Gforth achieved over the other systems).
16039:
16040: @example
1.112 anton 16041: relative Win32- NT eforth This-
16042: time Gforth Forth Forth eforth +opt PFE Forth TILE
16043: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
16044: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
16045: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
16046: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 16047: @end example
16048:
1.26 crook 16049: You may be quite surprised by the good performance of Gforth when
16050: compared with systems written in assembly language. One important reason
16051: for the disappointing performance of these other systems is probably
16052: that they are not written optimally for the 486 (e.g., they use the
16053: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16054: but costly method for relocating the Forth image: like @code{cforth}, it
16055: computes the actual addresses at run time, resulting in two address
16056: computations per @code{NEXT} (@pxref{Image File Background}).
16057:
1.1 anton 16058: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16059: explained with the self-imposed restriction of the latter systems to
16060: standard C, which makes efficient threading impossible (however, the
1.4 anton 16061: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 16062: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16063: Moreover, current C compilers have a hard time optimizing other aspects
16064: of the ThisForth and the TILE source.
16065:
1.26 crook 16066: The performance of Gforth on 386 architecture processors varies widely
16067: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16068: allocate any of the virtual machine registers into real machine
16069: registers by itself and would not work correctly with explicit register
1.112 anton 16070: declarations, giving a significantly slower engine (on a 486DX2/66
16071: running the Sieve) than the one measured above.
1.1 anton 16072:
1.26 crook 16073: Note that there have been several releases of Win32Forth since the
16074: release presented here, so the results presented above may have little
1.40 anton 16075: predictive value for the performance of Win32Forth today (results for
16076: the current release on an i486DX2/66 are welcome).
1.1 anton 16077:
16078: @cindex @file{Benchres}
1.66 anton 16079: In
16080: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16081: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 16082: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 16083: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16084: several native code systems; that version of Gforth is slower on a 486
1.112 anton 16085: than the version used here. You can find a newer version of these
16086: measurements at
1.47 crook 16087: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 16088: find numbers for Gforth on various machines in @file{Benchres}.
16089:
1.26 crook 16090: @c ******************************************************************
1.113 anton 16091: @c @node Binding to System Library, Cross Compiler, Engine, Top
16092: @c @chapter Binding to System Library
1.13 pazsan 16093:
1.113 anton 16094: @c ****************************************************************
16095: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 16096: @chapter Cross Compiler
1.47 crook 16097: @cindex @file{cross.fs}
16098: @cindex cross-compiler
16099: @cindex metacompiler
16100: @cindex target compiler
1.13 pazsan 16101:
1.46 pazsan 16102: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16103: mostly written in Forth, including crucial parts like the outer
16104: interpreter and compiler, it needs compiled Forth code to get
16105: started. The cross compiler allows to create new images for other
16106: architectures, even running under another Forth system.
1.13 pazsan 16107:
16108: @menu
1.67 anton 16109: * Using the Cross Compiler::
16110: * How the Cross Compiler Works::
1.13 pazsan 16111: @end menu
16112:
1.21 crook 16113: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 16114: @section Using the Cross Compiler
1.46 pazsan 16115:
16116: The cross compiler uses a language that resembles Forth, but isn't. The
16117: main difference is that you can execute Forth code after definition,
16118: while you usually can't execute the code compiled by cross, because the
16119: code you are compiling is typically for a different computer than the
16120: one you are compiling on.
16121:
1.81 anton 16122: @c anton: This chapter is somewhat different from waht I would expect: I
16123: @c would expect an explanation of the cross language and how to create an
16124: @c application image with it. The section explains some aspects of
16125: @c creating a Gforth kernel.
16126:
1.46 pazsan 16127: The Makefile is already set up to allow you to create kernels for new
16128: architectures with a simple make command. The generic kernels using the
16129: GCC compiled virtual machine are created in the normal build process
16130: with @code{make}. To create a embedded Gforth executable for e.g. the
16131: 8086 processor (running on a DOS machine), type
16132:
16133: @example
16134: make kernl-8086.fi
16135: @end example
16136:
16137: This will use the machine description from the @file{arch/8086}
16138: directory to create a new kernel. A machine file may look like that:
16139:
16140: @example
16141: \ Parameter for target systems 06oct92py
16142:
16143: 4 Constant cell \ cell size in bytes
16144: 2 Constant cell<< \ cell shift to bytes
16145: 5 Constant cell>bit \ cell shift to bits
16146: 8 Constant bits/char \ bits per character
16147: 8 Constant bits/byte \ bits per byte [default: 8]
16148: 8 Constant float \ bytes per float
16149: 8 Constant /maxalign \ maximum alignment in bytes
16150: false Constant bigendian \ byte order
16151: ( true=big, false=little )
16152:
16153: include machpc.fs \ feature list
16154: @end example
16155:
16156: This part is obligatory for the cross compiler itself, the feature list
16157: is used by the kernel to conditionally compile some features in and out,
16158: depending on whether the target supports these features.
16159:
16160: There are some optional features, if you define your own primitives,
16161: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 16162: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 16163: @code{prims-include} includes primitives, and @code{>boot} prepares for
16164: booting.
16165:
16166: @example
16167: : asm-include ." Include assembler" cr
16168: s" arch/8086/asm.fs" included ;
16169:
16170: : prims-include ." Include primitives" cr
16171: s" arch/8086/prim.fs" included ;
16172:
16173: : >boot ." Prepare booting" cr
16174: s" ' boot >body into-forth 1+ !" evaluate ;
16175: @end example
16176:
16177: These words are used as sort of macro during the cross compilation in
1.81 anton 16178: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 16179: be possible --- but more complicated --- to write a new kernel project
16180: file, too.
16181:
16182: @file{kernel/main.fs} expects the machine description file name on the
16183: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16184: @code{mach-file} leaves a counted string on the stack, or
16185: @code{machine-file} leaves an address, count pair of the filename on the
16186: stack.
16187:
16188: The feature list is typically controlled using @code{SetValue}, generic
16189: files that are used by several projects can use @code{DefaultValue}
16190: instead. Both functions work like @code{Value}, when the value isn't
16191: defined, but @code{SetValue} works like @code{to} if the value is
16192: defined, and @code{DefaultValue} doesn't set anything, if the value is
16193: defined.
16194:
16195: @example
16196: \ generic mach file for pc gforth 03sep97jaw
16197:
16198: true DefaultValue NIL \ relocating
16199:
16200: >ENVIRON
16201:
16202: true DefaultValue file \ controls the presence of the
16203: \ file access wordset
16204: true DefaultValue OS \ flag to indicate a operating system
16205:
16206: true DefaultValue prims \ true: primitives are c-code
16207:
16208: true DefaultValue floating \ floating point wordset is present
16209:
16210: true DefaultValue glocals \ gforth locals are present
16211: \ will be loaded
16212: true DefaultValue dcomps \ double number comparisons
16213:
16214: true DefaultValue hash \ hashing primitives are loaded/present
16215:
16216: true DefaultValue xconds \ used together with glocals,
16217: \ special conditionals supporting gforths'
16218: \ local variables
16219: true DefaultValue header \ save a header information
16220:
16221: true DefaultValue backtrace \ enables backtrace code
16222:
16223: false DefaultValue ec
16224: false DefaultValue crlf
16225:
16226: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16227:
16228: &16 KB DefaultValue stack-size
16229: &15 KB &512 + DefaultValue fstack-size
16230: &15 KB DefaultValue rstack-size
16231: &14 KB &512 + DefaultValue lstack-size
16232: @end example
1.13 pazsan 16233:
1.48 anton 16234: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16235: @section How the Cross Compiler Works
1.13 pazsan 16236:
16237: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16238: @appendix Bugs
1.1 anton 16239: @cindex bug reporting
16240:
1.21 crook 16241: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16242:
1.103 anton 16243: If you find a bug, please submit a bug report through
16244: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16245:
16246: @itemize @bullet
16247: @item
1.81 anton 16248: A program (or a sequence of keyboard commands) that reproduces the bug.
16249: @item
16250: A description of what you think constitutes the buggy behaviour.
16251: @item
1.21 crook 16252: The Gforth version used (it is announced at the start of an
16253: interactive Gforth session).
16254: @item
16255: The machine and operating system (on Unix
16256: systems @code{uname -a} will report this information).
16257: @item
1.81 anton 16258: The installation options (you can find the configure options at the
16259: start of @file{config.status}) and configuration (@code{configure}
16260: output or @file{config.cache}).
1.21 crook 16261: @item
16262: A complete list of changes (if any) you (or your installer) have made to the
16263: Gforth sources.
16264: @end itemize
1.1 anton 16265:
16266: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16267: to Report Bugs, gcc.info, GNU C Manual}.
16268:
16269:
1.21 crook 16270: @node Origin, Forth-related information, Bugs, Top
16271: @appendix Authors and Ancestors of Gforth
1.1 anton 16272:
16273: @section Authors and Contributors
16274: @cindex authors of Gforth
16275: @cindex contributors to Gforth
16276:
16277: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16278: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16279: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16280: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16281: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16282: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16283: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16284: working on automatic support for calling C libraries. Helpful comments
16285: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16286: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16287: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16288: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16289: comments from many others; thank you all, sorry for not listing you
16290: here (but digging through my mailbox to extract your names is on my
16291: to-do list).
1.1 anton 16292:
16293: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16294: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16295: was developed across the Internet, and its authors did not meet
1.20 pazsan 16296: physically for the first 4 years of development.
1.1 anton 16297:
16298: @section Pedigree
1.26 crook 16299: @cindex pedigree of Gforth
1.1 anton 16300:
1.81 anton 16301: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16302: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16303:
1.20 pazsan 16304: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16305: 32 bit native code version of VolksForth for the Atari ST, written
16306: mostly by Dietrich Weineck.
16307:
1.81 anton 16308: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16309: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16310: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16311:
1.147 anton 16312: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16313: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16314:
16315: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16316: 1979. Robert Selzer and Bill Ragsdale developed the original
16317: implementation of fig-Forth for the 6502 based on microForth.
16318:
16319: The principal architect of microForth was Dean Sanderson. microForth was
16320: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16321: the 1802, and subsequently implemented on the 8080, the 6800 and the
16322: Z80.
16323:
16324: All earlier Forth systems were custom-made, usually by Charles Moore,
16325: who discovered (as he puts it) Forth during the late 60s. The first full
16326: Forth existed in 1971.
16327:
1.81 anton 16328: A part of the information in this section comes from
16329: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16330: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16331: Charles H. Moore, presented at the HOPL-II conference and preprinted
16332: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16333: genealogical information about Forth there. For a more general (and
16334: graphical) Forth family tree look see
16335: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16336: Forth Family Tree and Timeline}.
1.1 anton 16337:
1.81 anton 16338: @c ------------------------------------------------------------------
1.113 anton 16339: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16340: @appendix Other Forth-related information
16341: @cindex Forth-related information
16342:
1.81 anton 16343: @c anton: I threw most of this stuff out, because it can be found through
16344: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16345:
16346: @cindex comp.lang.forth
16347: @cindex frequently asked questions
1.81 anton 16348: There is an active news group (comp.lang.forth) discussing Forth
16349: (including Gforth) and Forth-related issues. Its
16350: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16351: (frequently asked questions and their answers) contains a lot of
16352: information on Forth. You should read it before posting to
16353: comp.lang.forth.
1.21 crook 16354:
1.81 anton 16355: The ANS Forth standard is most usable in its
16356: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16357:
1.113 anton 16358: @c ---------------------------------------------------
16359: @node Licenses, Word Index, Forth-related information, Top
16360: @appendix Licenses
16361:
16362: @menu
16363: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 16364: * Copying:: GPL (for copying this software).
1.113 anton 16365: @end menu
16366:
1.192 anton 16367: @node GNU Free Documentation License, Copying, Licenses, Licenses
16368: @appendixsec GNU Free Documentation License
1.113 anton 16369: @include fdl.texi
16370:
1.192 anton 16371: @node Copying, , GNU Free Documentation License, Licenses
16372: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16373: @include gpl.texi
16374:
16375:
16376:
1.81 anton 16377: @c ------------------------------------------------------------------
1.113 anton 16378: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16379: @unnumbered Word Index
16380:
1.26 crook 16381: This index is a list of Forth words that have ``glossary'' entries
16382: within this manual. Each word is listed with its stack effect and
16383: wordset.
1.1 anton 16384:
16385: @printindex fn
16386:
1.81 anton 16387: @c anton: the name index seems superfluous given the word and concept indices.
16388:
16389: @c @node Name Index, Concept Index, Word Index, Top
16390: @c @unnumbered Name Index
1.41 anton 16391:
1.81 anton 16392: @c This index is a list of Forth words that have ``glossary'' entries
16393: @c within this manual.
1.41 anton 16394:
1.81 anton 16395: @c @printindex ky
1.41 anton 16396:
1.113 anton 16397: @c -------------------------------------------------------
1.81 anton 16398: @node Concept Index, , Word Index, Top
1.1 anton 16399: @unnumbered Concept and Word Index
16400:
1.26 crook 16401: Not all entries listed in this index are present verbatim in the
16402: text. This index also duplicates, in abbreviated form, all of the words
16403: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16404:
16405: @printindex cp
16406:
16407: @bye
1.81 anton 16408:
16409:
1.1 anton 16410:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>