Annotation of gforth/doc/gforth.ds, revision 1.177
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.169 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006 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.87 anton 177: * Files Tutorial::
1.48 anton 178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
1.29 crook 188:
1.24 anton 189: An Introduction to ANS Forth
190:
1.67 anton 191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
1.24 anton 199:
1.12 anton 200: Forth Words
201:
202: * Notation::
1.65 anton 203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
1.12 anton 206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
1.65 anton 211: * Interpretation and Compilation Semantics::
1.47 crook 212: * Tokens for Words::
1.81 anton 213: * Compiling words::
1.65 anton 214: * The Text Interpreter::
1.111 anton 215: * The Input Stream::
1.65 anton 216: * Word Lists::
217: * Environmental Queries::
1.12 anton 218: * Files::
219: * Blocks::
220: * Other I/O::
1.121 anton 221: * OS command line arguments::
1.78 anton 222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
1.12 anton 225: * Programming Tools::
1.150 anton 226: * C Interface::
1.12 anton 227: * Assembler and Code Words::
228: * Threading Words::
1.65 anton 229: * Passing Commands to the OS::
230: * Keeping track of Time::
231: * Miscellaneous Words::
1.12 anton 232:
233: Arithmetic
234:
235: * Single precision::
1.67 anton 236: * Double precision:: Double-cell integer arithmetic
1.12 anton 237: * Bitwise operations::
1.67 anton 238: * Numeric comparison::
1.32 anton 239: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 240: * Floating Point::
241:
242: Stack Manipulation
243:
244: * Data stack::
245: * Floating point stack::
246: * Return stack::
247: * Locals stack::
248: * Stack pointer manipulation::
249:
250: Memory
251:
1.32 anton 252: * Memory model::
253: * Dictionary allocation::
254: * Heap Allocation::
255: * Memory Access::
256: * Address arithmetic::
257: * Memory Blocks::
1.12 anton 258:
259: Control Structures
260:
1.41 anton 261: * Selection:: IF ... ELSE ... ENDIF
262: * Simple Loops:: BEGIN ...
1.32 anton 263: * Counted Loops:: DO
1.67 anton 264: * Arbitrary control structures::
265: * Calls and returns::
1.12 anton 266: * Exception Handling::
267:
268: Defining Words
269:
1.67 anton 270: * CREATE::
1.44 crook 271: * Variables:: Variables and user variables
1.67 anton 272: * Constants::
1.44 crook 273: * Values:: Initialised variables
1.67 anton 274: * Colon Definitions::
1.44 crook 275: * Anonymous Definitions:: Definitions without names
1.71 anton 276: * Supplying names:: Passing definition names as strings
1.67 anton 277: * User-defined Defining Words::
1.170 pazsan 278: * Deferred Words:: Allow forward references
1.67 anton 279: * Aliases::
1.47 crook 280:
1.63 anton 281: User-defined Defining Words
282:
283: * CREATE..DOES> applications::
284: * CREATE..DOES> details::
285: * Advanced does> usage example::
1.155 anton 286: * Const-does>::
1.63 anton 287:
1.47 crook 288: Interpretation and Compilation Semantics
289:
1.67 anton 290: * Combined words::
1.12 anton 291:
1.71 anton 292: Tokens for Words
293:
294: * Execution token:: represents execution/interpretation semantics
295: * Compilation token:: represents compilation semantics
296: * Name token:: represents named words
297:
1.82 anton 298: Compiling words
299:
300: * Literals:: Compiling data values
301: * Macros:: Compiling words
302:
1.21 crook 303: The Text Interpreter
304:
1.67 anton 305: * Input Sources::
306: * Number Conversion::
307: * Interpret/Compile states::
308: * Interpreter Directives::
1.21 crook 309:
1.26 crook 310: Word Lists
311:
1.75 anton 312: * Vocabularies::
1.67 anton 313: * Why use word lists?::
1.75 anton 314: * Word list example::
1.26 crook 315:
316: Files
317:
1.48 anton 318: * Forth source files::
319: * General files::
1.167 anton 320: * Redirection::
1.48 anton 321: * Search Paths::
322:
323: Search Paths
324:
1.75 anton 325: * Source Search Paths::
1.26 crook 326: * General Search Paths::
327:
328: Other I/O
329:
1.32 anton 330: * Simple numeric output:: Predefined formats
331: * Formatted numeric output:: Formatted (pictured) output
332: * String Formats:: How Forth stores strings in memory
1.67 anton 333: * Displaying characters and strings:: Other stuff
1.175 anton 334: * Terminal output::
1.32 anton 335: * Input:: Input
1.112 anton 336: * Pipes:: How to create your own pipes
1.149 pazsan 337: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 338:
339: Locals
340:
341: * Gforth locals::
342: * ANS Forth locals::
343:
344: Gforth locals
345:
346: * Where are locals visible by name?::
347: * How long do locals live?::
1.78 anton 348: * Locals programming style::
349: * Locals implementation::
1.26 crook 350:
1.12 anton 351: Structures
352:
353: * Why explicit structure support?::
354: * Structure Usage::
355: * Structure Naming Convention::
356: * Structure Implementation::
357: * Structure Glossary::
358:
359: Object-oriented Forth
360:
1.48 anton 361: * Why object-oriented programming?::
362: * Object-Oriented Terminology::
363: * Objects::
364: * OOF::
365: * Mini-OOF::
1.23 crook 366: * Comparison with other object models::
1.12 anton 367:
1.24 anton 368: The @file{objects.fs} model
1.12 anton 369:
370: * Properties of the Objects model::
371: * Basic Objects Usage::
1.41 anton 372: * The Objects base class::
1.12 anton 373: * Creating objects::
374: * Object-Oriented Programming Style::
375: * Class Binding::
376: * Method conveniences::
377: * Classes and Scoping::
1.41 anton 378: * Dividing classes::
1.12 anton 379: * Object Interfaces::
380: * Objects Implementation::
381: * Objects Glossary::
382:
1.24 anton 383: The @file{oof.fs} model
1.12 anton 384:
1.67 anton 385: * Properties of the OOF model::
386: * Basic OOF Usage::
387: * The OOF base class::
388: * Class Declaration::
389: * Class Implementation::
1.12 anton 390:
1.24 anton 391: The @file{mini-oof.fs} model
1.23 crook 392:
1.48 anton 393: * Basic Mini-OOF Usage::
394: * Mini-OOF Example::
395: * Mini-OOF Implementation::
1.23 crook 396:
1.78 anton 397: Programming Tools
398:
1.150 anton 399: * Examining:: Data and Code.
400: * Forgetting words:: Usually before reloading.
1.78 anton 401: * Debugging:: Simple and quick.
402: * Assertions:: Making your programs self-checking.
403: * Singlestep Debugger:: Executing your program word by word.
404:
1.155 anton 405: C Interface
406:
407: * Calling C Functions::
408: * Declaring C Functions::
409: * Callbacks::
410: * Low-Level C Interface Words::
411:
1.78 anton 412: Assembler and Code Words
413:
414: * Code and ;code::
415: * Common Assembler:: Assembler Syntax
416: * Common Disassembler::
417: * 386 Assembler:: Deviations and special cases
418: * Alpha Assembler:: Deviations and special cases
419: * MIPS assembler:: Deviations and special cases
1.167 anton 420: * PowerPC assembler:: Deviations and special cases
1.78 anton 421: * Other assemblers:: How to write them
422:
1.12 anton 423: Tools
424:
425: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 426: * Stack depth changes:: Where does this stack item come from?
1.12 anton 427:
428: ANS conformance
429:
430: * The Core Words::
431: * The optional Block word set::
432: * The optional Double Number word set::
433: * The optional Exception word set::
434: * The optional Facility word set::
435: * The optional File-Access word set::
436: * The optional Floating-Point word set::
437: * The optional Locals word set::
438: * The optional Memory-Allocation word set::
439: * The optional Programming-Tools word set::
440: * The optional Search-Order word set::
441:
442: The Core Words
443:
444: * core-idef:: Implementation Defined Options
445: * core-ambcond:: Ambiguous Conditions
446: * core-other:: Other System Documentation
447:
448: The optional Block word set
449:
450: * block-idef:: Implementation Defined Options
451: * block-ambcond:: Ambiguous Conditions
452: * block-other:: Other System Documentation
453:
454: The optional Double Number word set
455:
456: * double-ambcond:: Ambiguous Conditions
457:
458: The optional Exception word set
459:
460: * exception-idef:: Implementation Defined Options
461:
462: The optional Facility word set
463:
464: * facility-idef:: Implementation Defined Options
465: * facility-ambcond:: Ambiguous Conditions
466:
467: The optional File-Access word set
468:
469: * file-idef:: Implementation Defined Options
470: * file-ambcond:: Ambiguous Conditions
471:
472: The optional Floating-Point word set
473:
474: * floating-idef:: Implementation Defined Options
475: * floating-ambcond:: Ambiguous Conditions
476:
477: The optional Locals word set
478:
479: * locals-idef:: Implementation Defined Options
480: * locals-ambcond:: Ambiguous Conditions
481:
482: The optional Memory-Allocation word set
483:
484: * memory-idef:: Implementation Defined Options
485:
486: The optional Programming-Tools word set
487:
488: * programming-idef:: Implementation Defined Options
489: * programming-ambcond:: Ambiguous Conditions
490:
491: The optional Search-Order word set
492:
493: * search-idef:: Implementation Defined Options
494: * search-ambcond:: Ambiguous Conditions
495:
1.109 anton 496: Emacs and Gforth
497:
498: * Installing gforth.el:: Making Emacs aware of Forth.
499: * Emacs Tags:: Viewing the source of a word in Emacs.
500: * Hilighting:: Making Forth code look prettier.
501: * Auto-Indentation:: Customizing auto-indentation.
502: * Blocks Files:: Reading and writing blocks files.
503:
1.12 anton 504: Image Files
505:
1.24 anton 506: * Image Licensing Issues:: Distribution terms for images.
507: * Image File Background:: Why have image files?
1.67 anton 508: * Non-Relocatable Image Files:: don't always work.
1.24 anton 509: * Data-Relocatable Image Files:: are better.
1.67 anton 510: * Fully Relocatable Image Files:: better yet.
1.24 anton 511: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 512: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 513: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 514:
515: Fully Relocatable Image Files
516:
1.27 crook 517: * gforthmi:: The normal way
1.12 anton 518: * cross.fs:: The hard way
519:
520: Engine
521:
522: * Portability::
523: * Threading::
524: * Primitives::
525: * Performance::
526:
527: Threading
528:
529: * Scheduling::
530: * Direct or Indirect Threaded?::
1.109 anton 531: * Dynamic Superinstructions::
1.12 anton 532: * DOES>::
533:
534: Primitives
535:
536: * Automatic Generation::
537: * TOS Optimization::
538: * Produced code::
1.13 pazsan 539:
540: Cross Compiler
541:
1.67 anton 542: * Using the Cross Compiler::
543: * How the Cross Compiler Works::
1.13 pazsan 544:
1.113 anton 545: Licenses
546:
547: * GNU Free Documentation License:: License for copying this manual.
548: * Copying:: GPL (for copying this software).
549:
1.24 anton 550: @end detailmenu
1.1 anton 551: @end menu
552:
1.113 anton 553: @c ----------------------------------------------------------
1.1 anton 554: @iftex
555: @unnumbered Preface
556: @cindex Preface
1.21 crook 557: This manual documents Gforth. Some introductory material is provided for
558: readers who are unfamiliar with Forth or who are migrating to Gforth
559: from other Forth compilers. However, this manual is primarily a
560: reference manual.
1.1 anton 561: @end iftex
562:
1.28 crook 563: @comment TODO much more blurb here.
1.26 crook 564:
565: @c ******************************************************************
1.113 anton 566: @node Goals, Gforth Environment, Top, Top
1.26 crook 567: @comment node-name, next, previous, up
568: @chapter Goals of Gforth
569: @cindex goals of the Gforth project
570: The goal of the Gforth Project is to develop a standard model for
571: ANS Forth. This can be split into several subgoals:
572:
573: @itemize @bullet
574: @item
575: Gforth should conform to the ANS Forth Standard.
576: @item
577: It should be a model, i.e. it should define all the
578: implementation-dependent things.
579: @item
580: It should become standard, i.e. widely accepted and used. This goal
581: is the most difficult one.
582: @end itemize
583:
584: To achieve these goals Gforth should be
585: @itemize @bullet
586: @item
587: Similar to previous models (fig-Forth, F83)
588: @item
589: Powerful. It should provide for all the things that are considered
590: necessary today and even some that are not yet considered necessary.
591: @item
592: Efficient. It should not get the reputation of being exceptionally
593: slow.
594: @item
595: Free.
596: @item
597: Available on many machines/easy to port.
598: @end itemize
599:
600: Have we achieved these goals? Gforth conforms to the ANS Forth
601: standard. It may be considered a model, but we have not yet documented
602: which parts of the model are stable and which parts we are likely to
603: change. It certainly has not yet become a de facto standard, but it
604: appears to be quite popular. It has some similarities to and some
605: differences from previous models. It has some powerful features, but not
606: yet everything that we envisioned. We certainly have achieved our
1.65 anton 607: execution speed goals (@pxref{Performance})@footnote{However, in 1998
608: the bar was raised when the major commercial Forth vendors switched to
609: native code compilers.}. It is free and available on many machines.
1.29 crook 610:
1.26 crook 611: @c ******************************************************************
1.48 anton 612: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 613: @chapter Gforth Environment
614: @cindex Gforth environment
1.21 crook 615:
1.45 crook 616: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 617: material in this chapter.
1.21 crook 618:
619: @menu
1.29 crook 620: * Invoking Gforth:: Getting in
621: * Leaving Gforth:: Getting out
622: * Command-line editing::
1.48 anton 623: * Environment variables:: that affect how Gforth starts up
1.29 crook 624: * Gforth Files:: What gets installed and where
1.112 anton 625: * Gforth in pipes::
1.48 anton 626: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 627: @end menu
628:
1.49 anton 629: For related information about the creation of images see @ref{Image Files}.
1.29 crook 630:
1.21 crook 631: @comment ----------------------------------------------
1.48 anton 632: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 633: @section Invoking Gforth
634: @cindex invoking Gforth
635: @cindex running Gforth
636: @cindex command-line options
637: @cindex options on the command line
638: @cindex flags on the command line
1.21 crook 639:
1.30 anton 640: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 641: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 642: will usually just say @code{gforth} -- this automatically loads the
643: default image file @file{gforth.fi}. In many other cases the default
644: Gforth image will be invoked like this:
1.21 crook 645: @example
1.30 anton 646: gforth [file | -e forth-code] ...
1.21 crook 647: @end example
1.29 crook 648: @noindent
649: This interprets the contents of the files and the Forth code in the order they
650: are given.
1.21 crook 651:
1.109 anton 652: In addition to the @command{gforth} engine, there is also an engine
653: called @command{gforth-fast}, which is faster, but gives less
654: informative error messages (@pxref{Error messages}) and may catch some
1.166 anton 655: errors (in particular, stack underflows and integer division errors)
656: later or not at all. You should use it for debugged,
1.109 anton 657: performance-critical programs.
658:
659: Moreover, there is an engine called @command{gforth-itc}, which is
660: useful in some backwards-compatibility situations (@pxref{Direct or
661: Indirect Threaded?}).
1.30 anton 662:
1.29 crook 663: In general, the command line looks like this:
1.21 crook 664:
665: @example
1.30 anton 666: gforth[-fast] [engine options] [image options]
1.21 crook 667: @end example
668:
1.30 anton 669: The engine options must come before the rest of the command
1.29 crook 670: line. They are:
1.26 crook 671:
1.29 crook 672: @table @code
673: @cindex -i, command-line option
674: @cindex --image-file, command-line option
675: @item --image-file @i{file}
676: @itemx -i @i{file}
677: Loads the Forth image @i{file} instead of the default
678: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 679:
1.39 anton 680: @cindex --appl-image, command-line option
681: @item --appl-image @i{file}
682: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 683: to the image (instead of processing them as engine options). This is
684: useful for building executable application images on Unix, built with
1.39 anton 685: @code{gforthmi --application ...}.
686:
1.29 crook 687: @cindex --path, command-line option
688: @cindex -p, command-line option
689: @item --path @i{path}
690: @itemx -p @i{path}
691: Uses @i{path} for searching the image file and Forth source code files
692: instead of the default in the environment variable @code{GFORTHPATH} or
693: the path specified at installation time (e.g.,
694: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
695: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 696:
1.29 crook 697: @cindex --dictionary-size, command-line option
698: @cindex -m, command-line option
699: @cindex @i{size} parameters for command-line options
700: @cindex size of the dictionary and the stacks
701: @item --dictionary-size @i{size}
702: @itemx -m @i{size}
703: Allocate @i{size} space for the Forth dictionary space instead of
704: using the default specified in the image (typically 256K). The
705: @i{size} specification for this and subsequent options consists of
706: an integer and a unit (e.g.,
707: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
708: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
709: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
710: @code{e} is used.
1.21 crook 711:
1.29 crook 712: @cindex --data-stack-size, command-line option
713: @cindex -d, command-line option
714: @item --data-stack-size @i{size}
715: @itemx -d @i{size}
716: Allocate @i{size} space for the data stack instead of using the
717: default specified in the image (typically 16K).
1.21 crook 718:
1.29 crook 719: @cindex --return-stack-size, command-line option
720: @cindex -r, command-line option
721: @item --return-stack-size @i{size}
722: @itemx -r @i{size}
723: Allocate @i{size} space for the return stack instead of using the
724: default specified in the image (typically 15K).
1.21 crook 725:
1.29 crook 726: @cindex --fp-stack-size, command-line option
727: @cindex -f, command-line option
728: @item --fp-stack-size @i{size}
729: @itemx -f @i{size}
730: Allocate @i{size} space for the floating point stack instead of
731: using the default specified in the image (typically 15.5K). In this case
732: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 733:
1.48 anton 734: @cindex --locals-stack-size, command-line option
735: @cindex -l, command-line option
736: @item --locals-stack-size @i{size}
737: @itemx -l @i{size}
738: Allocate @i{size} space for the locals stack instead of using the
739: default specified in the image (typically 14.5K).
740:
1.176 anton 741: @cindex --vm-commit, command-line option
742: @cindex overcommit memory for dictionary and stacks
743: @cindex memory overcommit for dictionary and stacks
744: @item --vm-commit
745: Normally, Gforth tries to start up even if there is not enough virtual
746: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
747: on OSs that support it); so you can ask for a really big dictionary
748: and/or stacks, and as long as you don't use more virtual memory than
749: is available, everything will be fine (but if you use more, processes
750: get killed). With this option you just use the default allocation
751: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
752: means that you cannot and should not ask for as big dictionary and
753: stacks, but once Gforth successfully starts up, out-of-memory won't
754: kill it.
755:
1.48 anton 756: @cindex -h, command-line option
757: @cindex --help, command-line option
758: @item --help
759: @itemx -h
760: Print a message about the command-line options
761:
762: @cindex -v, command-line option
763: @cindex --version, command-line option
764: @item --version
765: @itemx -v
766: Print version and exit
767:
768: @cindex --debug, command-line option
769: @item --debug
770: Print some information useful for debugging on startup.
771:
772: @cindex --offset-image, command-line option
773: @item --offset-image
774: Start the dictionary at a slightly different position than would be used
775: otherwise (useful for creating data-relocatable images,
776: @pxref{Data-Relocatable Image Files}).
777:
778: @cindex --no-offset-im, command-line option
779: @item --no-offset-im
780: Start the dictionary at the normal position.
781:
782: @cindex --clear-dictionary, command-line option
783: @item --clear-dictionary
784: Initialize all bytes in the dictionary to 0 before loading the image
785: (@pxref{Data-Relocatable Image Files}).
786:
787: @cindex --die-on-signal, command-line-option
788: @item --die-on-signal
789: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
790: or the segmentation violation SIGSEGV) by translating it into a Forth
791: @code{THROW}. With this option, Gforth exits if it receives such a
792: signal. This option is useful when the engine and/or the image might be
793: severely broken (such that it causes another signal before recovering
794: from the first); this option avoids endless loops in such cases.
1.109 anton 795:
1.119 anton 796: @cindex --no-dynamic, command-line option
797: @cindex --dynamic, command-line option
1.109 anton 798: @item --no-dynamic
799: @item --dynamic
800: Disable or enable dynamic superinstructions with replication
801: (@pxref{Dynamic Superinstructions}).
802:
1.119 anton 803: @cindex --no-super, command-line option
1.109 anton 804: @item --no-super
1.110 anton 805: Disable dynamic superinstructions, use just dynamic replication; this is
806: useful if you want to patch threaded code (@pxref{Dynamic
807: Superinstructions}).
1.119 anton 808:
809: @cindex --ss-number, command-line option
810: @item --ss-number=@var{N}
811: Use only the first @var{N} static superinstructions compiled into the
812: engine (default: use them all; note that only @code{gforth-fast} has
813: any). This option is useful for measuring the performance impact of
814: static superinstructions.
815:
816: @cindex --ss-min-..., command-line options
817: @item --ss-min-codesize
818: @item --ss-min-ls
819: @item --ss-min-lsu
820: @item --ss-min-nexts
821: Use specified metric for determining the cost of a primitive or static
822: superinstruction for static superinstruction selection. @code{Codesize}
823: is the native code size of the primive or static superinstruction,
824: @code{ls} is the number of loads and stores, @code{lsu} is the number of
825: loads, stores, and updates, and @code{nexts} is the number of dispatches
826: (not taking dynamic superinstructions into account), i.e. every
827: primitive or static superinstruction has cost 1. Default:
828: @code{codesize} if you use dynamic code generation, otherwise
829: @code{nexts}.
830:
831: @cindex --ss-greedy, command-line option
832: @item --ss-greedy
833: This option is useful for measuring the performance impact of static
834: superinstructions. By default, an optimal shortest-path algorithm is
835: used for selecting static superinstructions. With @option{--ss-greedy}
836: this algorithm is modified to assume that anything after the static
837: superinstruction currently under consideration is not combined into
838: static superinstructions. With @option{--ss-min-nexts} this produces
839: the same result as a greedy algorithm that always selects the longest
840: superinstruction available at the moment. E.g., if there are
841: superinstructions AB and BCD, then for the sequence A B C D the optimal
842: algorithm will select A BCD and the greedy algorithm will select AB C D.
843:
844: @cindex --print-metrics, command-line option
845: @item --print-metrics
846: Prints some metrics used during static superinstruction selection:
847: @code{code size} is the actual size of the dynamically generated code.
848: @code{Metric codesize} is the sum of the codesize metrics as seen by
849: static superinstruction selection; there is a difference from @code{code
850: size}, because not all primitives and static superinstructions are
851: compiled into dynamically generated code, and because of markers. The
852: other metrics correspond to the @option{ss-min-...} options. This
853: option is useful for evaluating the effects of the @option{--ss-...}
854: options.
1.109 anton 855:
1.48 anton 856: @end table
857:
858: @cindex loading files at startup
859: @cindex executing code on startup
860: @cindex batch processing with Gforth
861: As explained above, the image-specific command-line arguments for the
862: default image @file{gforth.fi} consist of a sequence of filenames and
863: @code{-e @var{forth-code}} options that are interpreted in the sequence
864: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 865: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
866: option takes only one argument; if you want to evaluate more Forth
867: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 868: after processing the command line (instead of entering interactive mode)
1.121 anton 869: append @code{-e bye} to the command line. You can also process the
870: command-line arguments with a Forth program (@pxref{OS command line
871: arguments}).
1.48 anton 872:
873: @cindex versions, invoking other versions of Gforth
874: If you have several versions of Gforth installed, @code{gforth} will
875: invoke the version that was installed last. @code{gforth-@i{version}}
876: invokes a specific version. If your environment contains the variable
877: @code{GFORTHPATH}, you may want to override it by using the
878: @code{--path} option.
879:
880: Not yet implemented:
881: On startup the system first executes the system initialization file
882: (unless the option @code{--no-init-file} is given; note that the system
883: resulting from using this option may not be ANS Forth conformant). Then
884: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 885: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 886: then in @file{~}, then in the normal path (see above).
887:
888:
889:
890: @comment ----------------------------------------------
891: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
892: @section Leaving Gforth
893: @cindex Gforth - leaving
894: @cindex leaving Gforth
895:
896: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
897: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
898: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 899: data are discarded. For ways of saving the state of the system before
900: leaving Gforth see @ref{Image Files}.
1.48 anton 901:
902: doc-bye
903:
904:
905: @comment ----------------------------------------------
1.65 anton 906: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 907: @section Command-line editing
908: @cindex command-line editing
909:
910: Gforth maintains a history file that records every line that you type to
911: the text interpreter. This file is preserved between sessions, and is
912: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
913: repeatedly you can recall successively older commands from this (or
914: previous) session(s). The full list of command-line editing facilities is:
915:
916: @itemize @bullet
917: @item
918: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
919: commands from the history buffer.
920: @item
921: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
922: from the history buffer.
923: @item
924: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
925: @item
926: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
927: @item
928: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
929: closing up the line.
930: @item
931: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
932: @item
933: @kbd{Ctrl-a} to move the cursor to the start of the line.
934: @item
935: @kbd{Ctrl-e} to move the cursor to the end of the line.
936: @item
937: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
938: line.
939: @item
940: @key{TAB} to step through all possible full-word completions of the word
941: currently being typed.
942: @item
1.65 anton 943: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
944: using @code{bye}).
945: @item
946: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
947: character under the cursor.
1.48 anton 948: @end itemize
949:
950: When editing, displayable characters are inserted to the left of the
951: cursor position; the line is always in ``insert'' (as opposed to
952: ``overstrike'') mode.
953:
954: @cindex history file
955: @cindex @file{.gforth-history}
956: On Unix systems, the history file is @file{~/.gforth-history} by
957: default@footnote{i.e. it is stored in the user's home directory.}. You
958: can find out the name and location of your history file using:
959:
960: @example
961: history-file type \ Unix-class systems
962:
963: history-file type \ Other systems
964: history-dir type
965: @end example
966:
967: If you enter long definitions by hand, you can use a text editor to
968: paste them out of the history file into a Forth source file for reuse at
969: a later time.
970:
971: Gforth never trims the size of the history file, so you should do this
972: periodically, if necessary.
973:
974: @comment this is all defined in history.fs
975: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
976: @comment chosen?
977:
978:
979: @comment ----------------------------------------------
1.65 anton 980: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 981: @section Environment variables
982: @cindex environment variables
983:
984: Gforth uses these environment variables:
985:
986: @itemize @bullet
987: @item
988: @cindex @code{GFORTHHIST} -- environment variable
989: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
990: open/create the history file, @file{.gforth-history}. Default:
991: @code{$HOME}.
992:
993: @item
994: @cindex @code{GFORTHPATH} -- environment variable
995: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
996: for Forth source-code files.
997:
998: @item
1.147 anton 999: @cindex @code{LANG} -- environment variable
1000: @code{LANG} -- see @code{LC_CTYPE}
1001:
1002: @item
1003: @cindex @code{LC_ALL} -- environment variable
1004: @code{LC_ALL} -- see @code{LC_CTYPE}
1005:
1006: @item
1007: @cindex @code{LC_CTYPE} -- environment variable
1008: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1009: startup, Gforth uses the UTF-8 encoding for strings internally and
1010: expects its input and produces its output in UTF-8 encoding, otherwise
1011: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1012: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1013: that is unset, in @code{LANG}.
1014:
1015: @item
1.129 anton 1016: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1017:
1018: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1019: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1020: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1021: and the command are directly concatenated, so if a space between them is
1022: necessary, append it to the prefix.
1023:
1024: @item
1.48 anton 1025: @cindex @code{GFORTH} -- environment variable
1.49 anton 1026: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1027:
1028: @item
1029: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1030: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1031:
1032: @item
1033: @cindex @code{TMP}, @code{TEMP} - environment variable
1034: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1035: location for the history file.
1036: @end itemize
1037:
1038: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1039: @comment mentioning these.
1040:
1041: All the Gforth environment variables default to sensible values if they
1042: are not set.
1043:
1044:
1045: @comment ----------------------------------------------
1.112 anton 1046: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1047: @section Gforth files
1048: @cindex Gforth files
1049:
1050: When you install Gforth on a Unix system, it installs files in these
1051: locations by default:
1052:
1053: @itemize @bullet
1054: @item
1055: @file{/usr/local/bin/gforth}
1056: @item
1057: @file{/usr/local/bin/gforthmi}
1058: @item
1059: @file{/usr/local/man/man1/gforth.1} - man page.
1060: @item
1061: @file{/usr/local/info} - the Info version of this manual.
1062: @item
1063: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1064: @item
1065: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1066: @item
1067: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1068: @item
1069: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1070: @end itemize
1071:
1072: You can select different places for installation by using
1073: @code{configure} options (listed with @code{configure --help}).
1074:
1075: @comment ----------------------------------------------
1.112 anton 1076: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1077: @section Gforth in pipes
1078: @cindex pipes, Gforth as part of
1079:
1080: Gforth can be used in pipes created elsewhere (described here). It can
1081: also create pipes on its own (@pxref{Pipes}).
1082:
1083: @cindex input from pipes
1084: If you pipe into Gforth, your program should read with @code{read-file}
1085: or @code{read-line} from @code{stdin} (@pxref{General files}).
1086: @code{Key} does not recognize the end of input. Words like
1087: @code{accept} echo the input and are therefore usually not useful for
1088: reading from a pipe. You have to invoke the Forth program with an OS
1089: command-line option, as you have no chance to use the Forth command line
1090: (the text interpreter would try to interpret the pipe input).
1091:
1092: @cindex output in pipes
1093: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1094:
1095: @cindex silent exiting from Gforth
1096: When you write to a pipe that has been closed at the other end, Gforth
1097: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1098: into the exception @code{broken-pipe-error}. If your application does
1099: not catch that exception, the system catches it and exits, usually
1100: silently (unless you were working on the Forth command line; then it
1101: prints an error message and exits). This is usually the desired
1102: behaviour.
1103:
1104: If you do not like this behaviour, you have to catch the exception
1105: yourself, and react to it.
1106:
1107: Here's an example of an invocation of Gforth that is usable in a pipe:
1108:
1109: @example
1110: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1111: type repeat ; foo bye"
1112: @end example
1113:
1114: This example just copies the input verbatim to the output. A very
1115: simple pipe containing this example looks like this:
1116:
1117: @example
1118: cat startup.fs |
1119: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1120: type repeat ; foo bye"|
1121: head
1122: @end example
1123:
1124: @cindex stderr and pipes
1125: Pipes involving Gforth's @code{stderr} output do not work.
1126:
1127: @comment ----------------------------------------------
1128: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1129: @section Startup speed
1130: @cindex Startup speed
1131: @cindex speed, startup
1132:
1133: If Gforth is used for CGI scripts or in shell scripts, its startup
1134: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1135: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1136: system time.
1137:
1138: If startup speed is a problem, you may consider the following ways to
1139: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1140: (for example, by using Fast-CGI).
1.48 anton 1141:
1.112 anton 1142: An easy step that influences Gforth startup speed is the use of the
1143: @option{--no-dynamic} option; this decreases image loading speed, but
1144: increases compile-time and run-time.
1145:
1146: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1147: building it with @code{XLDFLAGS=-static}. This requires more memory for
1148: the code and will therefore slow down the first invocation, but
1149: subsequent invocations avoid the dynamic linking overhead. Another
1150: disadvantage is that Gforth won't profit from library upgrades. As a
1151: result, @code{gforth-static -e bye} takes about 17.1ms user and
1152: 8.2ms system time.
1153:
1154: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1155: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1156: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1157: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1158: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1159: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1160: address for the dictionary, for whatever reason; so you better provide a
1161: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1162: bye} takes about 15.3ms user and 7.5ms system time.
1163:
1164: The final step is to disable dictionary hashing in Gforth. Gforth
1165: builds the hash table on startup, which takes much of the startup
1166: overhead. You can do this by commenting out the @code{include hash.fs}
1167: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1168: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1169: The disadvantages are that functionality like @code{table} and
1170: @code{ekey} is missing and that text interpretation (e.g., compiling)
1171: now takes much longer. So, you should only use this method if there is
1172: no significant text interpretation to perform (the script should be
1.62 crook 1173: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1174: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1175:
1176: @c ******************************************************************
1177: @node Tutorial, Introduction, Gforth Environment, Top
1178: @chapter Forth Tutorial
1179: @cindex Tutorial
1180: @cindex Forth Tutorial
1181:
1.67 anton 1182: @c Topics from nac's Introduction that could be mentioned:
1183: @c press <ret> after each line
1184: @c Prompt
1185: @c numbers vs. words in dictionary on text interpretation
1186: @c what happens on redefinition
1187: @c parsing words (in particular, defining words)
1188:
1.83 anton 1189: The difference of this chapter from the Introduction
1190: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1191: be used while sitting in front of a computer, and covers much more
1192: material, but does not explain how the Forth system works.
1193:
1.62 crook 1194: This tutorial can be used with any ANS-compliant Forth; any
1195: Gforth-specific features are marked as such and you can skip them if you
1196: work with another Forth. This tutorial does not explain all features of
1197: Forth, just enough to get you started and give you some ideas about the
1198: facilities available in Forth. Read the rest of the manual and the
1199: standard when you are through this.
1.48 anton 1200:
1201: The intended way to use this tutorial is that you work through it while
1202: sitting in front of the console, take a look at the examples and predict
1203: what they will do, then try them out; if the outcome is not as expected,
1204: find out why (e.g., by trying out variations of the example), so you
1205: understand what's going on. There are also some assignments that you
1206: should solve.
1207:
1208: This tutorial assumes that you have programmed before and know what,
1209: e.g., a loop is.
1210:
1211: @c !! explain compat library
1212:
1213: @menu
1214: * Starting Gforth Tutorial::
1215: * Syntax Tutorial::
1216: * Crash Course Tutorial::
1217: * Stack Tutorial::
1218: * Arithmetics Tutorial::
1219: * Stack Manipulation Tutorial::
1220: * Using files for Forth code Tutorial::
1221: * Comments Tutorial::
1222: * Colon Definitions Tutorial::
1223: * Decompilation Tutorial::
1224: * Stack-Effect Comments Tutorial::
1225: * Types Tutorial::
1226: * Factoring Tutorial::
1227: * Designing the stack effect Tutorial::
1228: * Local Variables Tutorial::
1229: * Conditional execution Tutorial::
1230: * Flags and Comparisons Tutorial::
1231: * General Loops Tutorial::
1232: * Counted loops Tutorial::
1233: * Recursion Tutorial::
1234: * Leaving definitions or loops Tutorial::
1235: * Return Stack Tutorial::
1236: * Memory Tutorial::
1237: * Characters and Strings Tutorial::
1238: * Alignment Tutorial::
1.87 anton 1239: * Files Tutorial::
1.48 anton 1240: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1241: * Execution Tokens Tutorial::
1242: * Exceptions Tutorial::
1243: * Defining Words Tutorial::
1244: * Arrays and Records Tutorial::
1245: * POSTPONE Tutorial::
1246: * Literal Tutorial::
1247: * Advanced macros Tutorial::
1248: * Compilation Tokens Tutorial::
1249: * Wordlists and Search Order Tutorial::
1250: @end menu
1251:
1252: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1253: @section Starting Gforth
1.66 anton 1254: @cindex starting Gforth tutorial
1.48 anton 1255: You can start Gforth by typing its name:
1256:
1257: @example
1258: gforth
1259: @end example
1260:
1261: That puts you into interactive mode; you can leave Gforth by typing
1262: @code{bye}. While in Gforth, you can edit the command line and access
1263: the command line history with cursor keys, similar to bash.
1264:
1265:
1266: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1267: @section Syntax
1.66 anton 1268: @cindex syntax tutorial
1.48 anton 1269:
1.171 anton 1270: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1271: space). Words are separated by white space. E.g., each of the
1272: following lines contains exactly one word:
1273:
1274: @example
1275: word
1276: !@@#$%^&*()
1277: 1234567890
1278: 5!a
1279: @end example
1280:
1281: A frequent beginner's error is to leave away necessary white space,
1282: resulting in an error like @samp{Undefined word}; so if you see such an
1283: error, check if you have put spaces wherever necessary.
1284:
1285: @example
1286: ." hello, world" \ correct
1287: ."hello, world" \ gives an "Undefined word" error
1288: @end example
1289:
1.65 anton 1290: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1291: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1292: your system is case-sensitive, you may have to type all the examples
1293: given here in upper case.
1294:
1295:
1296: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1297: @section Crash Course
1298:
1299: Type
1300:
1301: @example
1302: 0 0 !
1303: here execute
1304: ' catch >body 20 erase abort
1305: ' (quit) >body 20 erase
1306: @end example
1307:
1308: The last two examples are guaranteed to destroy parts of Gforth (and
1309: most other systems), so you better leave Gforth afterwards (if it has
1310: not finished by itself). On some systems you may have to kill gforth
1311: from outside (e.g., in Unix with @code{kill}).
1312:
1313: Now that you know how to produce crashes (and that there's not much to
1314: them), let's learn how to produce meaningful programs.
1315:
1316:
1317: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1318: @section Stack
1.66 anton 1319: @cindex stack tutorial
1.48 anton 1320:
1321: The most obvious feature of Forth is the stack. When you type in a
1322: number, it is pushed on the stack. You can display the content of the
1323: stack with @code{.s}.
1324:
1325: @example
1326: 1 2 .s
1327: 3 .s
1328: @end example
1329:
1330: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1331: appear in @code{.s} output as they appeared in the input.
1332:
1333: You can print the top of stack element with @code{.}.
1334:
1335: @example
1336: 1 2 3 . . .
1337: @end example
1338:
1339: In general, words consume their stack arguments (@code{.s} is an
1340: exception).
1341:
1.141 anton 1342: @quotation Assignment
1.48 anton 1343: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1344: @end quotation
1.48 anton 1345:
1346:
1347: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1348: @section Arithmetics
1.66 anton 1349: @cindex arithmetics tutorial
1.48 anton 1350:
1351: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1352: operate on the top two stack items:
1353:
1354: @example
1.67 anton 1355: 2 2 .s
1356: + .s
1357: .
1.48 anton 1358: 2 1 - .
1359: 7 3 mod .
1360: @end example
1361:
1362: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1363: as in the corresponding infix expression (this is generally the case in
1364: Forth).
1365:
1366: Parentheses are superfluous (and not available), because the order of
1367: the words unambiguously determines the order of evaluation and the
1368: operands:
1369:
1370: @example
1371: 3 4 + 5 * .
1372: 3 4 5 * + .
1373: @end example
1374:
1.141 anton 1375: @quotation Assignment
1.48 anton 1376: What are the infix expressions corresponding to the Forth code above?
1377: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1378: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1379: @end quotation
1.48 anton 1380:
1381: To change the sign, use @code{negate}:
1382:
1383: @example
1384: 2 negate .
1385: @end example
1386:
1.141 anton 1387: @quotation Assignment
1.48 anton 1388: Convert -(-3)*4-5 to Forth.
1.141 anton 1389: @end quotation
1.48 anton 1390:
1391: @code{/mod} performs both @code{/} and @code{mod}.
1392:
1393: @example
1394: 7 3 /mod . .
1395: @end example
1396:
1.66 anton 1397: Reference: @ref{Arithmetic}.
1398:
1399:
1.48 anton 1400: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1401: @section Stack Manipulation
1.66 anton 1402: @cindex stack manipulation tutorial
1.48 anton 1403:
1404: Stack manipulation words rearrange the data on the stack.
1405:
1406: @example
1407: 1 .s drop .s
1408: 1 .s dup .s drop drop .s
1409: 1 2 .s over .s drop drop drop
1410: 1 2 .s swap .s drop drop
1411: 1 2 3 .s rot .s drop drop drop
1412: @end example
1413:
1414: These are the most important stack manipulation words. There are also
1415: variants that manipulate twice as many stack items:
1416:
1417: @example
1418: 1 2 3 4 .s 2swap .s 2drop 2drop
1419: @end example
1420:
1421: Two more stack manipulation words are:
1422:
1423: @example
1424: 1 2 .s nip .s drop
1425: 1 2 .s tuck .s 2drop drop
1426: @end example
1427:
1.141 anton 1428: @quotation Assignment
1.48 anton 1429: Replace @code{nip} and @code{tuck} with combinations of other stack
1430: manipulation words.
1431:
1432: @example
1433: Given: How do you get:
1434: 1 2 3 3 2 1
1435: 1 2 3 1 2 3 2
1436: 1 2 3 1 2 3 3
1437: 1 2 3 1 3 3
1438: 1 2 3 2 1 3
1439: 1 2 3 4 4 3 2 1
1440: 1 2 3 1 2 3 1 2 3
1441: 1 2 3 4 1 2 3 4 1 2
1442: 1 2 3
1443: 1 2 3 1 2 3 4
1444: 1 2 3 1 3
1445: @end example
1.141 anton 1446: @end quotation
1.48 anton 1447:
1448: @example
1449: 5 dup * .
1450: @end example
1451:
1.141 anton 1452: @quotation Assignment
1.48 anton 1453: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1454: Write a piece of Forth code that expects two numbers on the stack
1455: (@var{a} and @var{b}, with @var{b} on top) and computes
1456: @code{(a-b)(a+1)}.
1.141 anton 1457: @end quotation
1.48 anton 1458:
1.66 anton 1459: Reference: @ref{Stack Manipulation}.
1460:
1461:
1.48 anton 1462: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1463: @section Using files for Forth code
1.66 anton 1464: @cindex loading Forth code, tutorial
1465: @cindex files containing Forth code, tutorial
1.48 anton 1466:
1467: While working at the Forth command line is convenient for one-line
1468: examples and short one-off code, you probably want to store your source
1469: code in files for convenient editing and persistence. You can use your
1470: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1471: Gforth}) to create @var{file.fs} and use
1.48 anton 1472:
1473: @example
1.102 anton 1474: s" @var{file.fs}" included
1.48 anton 1475: @end example
1476:
1477: to load it into your Forth system. The file name extension I use for
1478: Forth files is @samp{.fs}.
1479:
1480: You can easily start Gforth with some files loaded like this:
1481:
1482: @example
1.102 anton 1483: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1484: @end example
1485:
1486: If an error occurs during loading these files, Gforth terminates,
1487: whereas an error during @code{INCLUDED} within Gforth usually gives you
1488: a Gforth command line. Starting the Forth system every time gives you a
1489: clean start every time, without interference from the results of earlier
1490: tries.
1491:
1492: I often put all the tests in a file, then load the code and run the
1493: tests with
1494:
1495: @example
1.102 anton 1496: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1497: @end example
1498:
1499: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1500: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1501: restart this command without ado.
1502:
1503: The advantage of this approach is that the tests can be repeated easily
1504: every time the program ist changed, making it easy to catch bugs
1505: introduced by the change.
1506:
1.66 anton 1507: Reference: @ref{Forth source files}.
1508:
1.48 anton 1509:
1510: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1511: @section Comments
1.66 anton 1512: @cindex comments tutorial
1.48 anton 1513:
1514: @example
1515: \ That's a comment; it ends at the end of the line
1516: ( Another comment; it ends here: ) .s
1517: @end example
1518:
1519: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1520: separated with white space from the following text.
1521:
1522: @example
1523: \This gives an "Undefined word" error
1524: @end example
1525:
1526: The first @code{)} ends a comment started with @code{(}, so you cannot
1527: nest @code{(}-comments; and you cannot comment out text containing a
1528: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1529: avoid @code{)} in word names.}.
1530:
1531: I use @code{\}-comments for descriptive text and for commenting out code
1532: of one or more line; I use @code{(}-comments for describing the stack
1533: effect, the stack contents, or for commenting out sub-line pieces of
1534: code.
1535:
1536: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1537: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1538: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1539: with @kbd{M-q}.
1540:
1.66 anton 1541: Reference: @ref{Comments}.
1542:
1.48 anton 1543:
1544: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1545: @section Colon Definitions
1.66 anton 1546: @cindex colon definitions, tutorial
1547: @cindex definitions, tutorial
1548: @cindex procedures, tutorial
1549: @cindex functions, tutorial
1.48 anton 1550:
1551: are similar to procedures and functions in other programming languages.
1552:
1553: @example
1554: : squared ( n -- n^2 )
1555: dup * ;
1556: 5 squared .
1557: 7 squared .
1558: @end example
1559:
1560: @code{:} starts the colon definition; its name is @code{squared}. The
1561: following comment describes its stack effect. The words @code{dup *}
1562: are not executed, but compiled into the definition. @code{;} ends the
1563: colon definition.
1564:
1565: The newly-defined word can be used like any other word, including using
1566: it in other definitions:
1567:
1568: @example
1569: : cubed ( n -- n^3 )
1570: dup squared * ;
1571: -5 cubed .
1572: : fourth-power ( n -- n^4 )
1573: squared squared ;
1574: 3 fourth-power .
1575: @end example
1576:
1.141 anton 1577: @quotation Assignment
1.48 anton 1578: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1579: @code{/mod} in terms of other Forth words, and check if they work (hint:
1580: test your tests on the originals first). Don't let the
1581: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1582: @end quotation
1.48 anton 1583:
1.66 anton 1584: Reference: @ref{Colon Definitions}.
1585:
1.48 anton 1586:
1587: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1588: @section Decompilation
1.66 anton 1589: @cindex decompilation tutorial
1590: @cindex see tutorial
1.48 anton 1591:
1592: You can decompile colon definitions with @code{see}:
1593:
1594: @example
1595: see squared
1596: see cubed
1597: @end example
1598:
1599: In Gforth @code{see} shows you a reconstruction of the source code from
1600: the executable code. Informations that were present in the source, but
1601: not in the executable code, are lost (e.g., comments).
1602:
1.65 anton 1603: You can also decompile the predefined words:
1604:
1605: @example
1606: see .
1607: see +
1608: @end example
1609:
1610:
1.48 anton 1611: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1612: @section Stack-Effect Comments
1.66 anton 1613: @cindex stack-effect comments, tutorial
1614: @cindex --, tutorial
1.48 anton 1615: By convention the comment after the name of a definition describes the
1.171 anton 1616: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1617: the stack before the execution of the definition, i.e., the parameters
1618: that are passed into the colon definition; the part behind the @samp{--}
1619: is the state of the stack after the execution of the definition, i.e.,
1620: the results of the definition. The stack comment only shows the top
1621: stack items that the definition accesses and/or changes.
1622:
1623: You should put a correct stack effect on every definition, even if it is
1624: just @code{( -- )}. You should also add some descriptive comment to
1625: more complicated words (I usually do this in the lines following
1626: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1627: you have to work through every definition before you can understand
1.48 anton 1628: any).
1629:
1.141 anton 1630: @quotation Assignment
1.48 anton 1631: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1632: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1633: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1634: are done, you can compare your stack effects to those in this manual
1.48 anton 1635: (@pxref{Word Index}).
1.141 anton 1636: @end quotation
1.48 anton 1637:
1638: Sometimes programmers put comments at various places in colon
1639: definitions that describe the contents of the stack at that place (stack
1640: comments); i.e., they are like the first part of a stack-effect
1641: comment. E.g.,
1642:
1643: @example
1644: : cubed ( n -- n^3 )
1645: dup squared ( n n^2 ) * ;
1646: @end example
1647:
1648: In this case the stack comment is pretty superfluous, because the word
1649: is simple enough. If you think it would be a good idea to add such a
1650: comment to increase readability, you should also consider factoring the
1651: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1652: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1653: however, if you decide not to refactor it, then having such a comment is
1654: better than not having it.
1655:
1656: The names of the stack items in stack-effect and stack comments in the
1657: standard, in this manual, and in many programs specify the type through
1658: a type prefix, similar to Fortran and Hungarian notation. The most
1659: frequent prefixes are:
1660:
1661: @table @code
1662: @item n
1663: signed integer
1664: @item u
1665: unsigned integer
1666: @item c
1667: character
1668: @item f
1669: Boolean flags, i.e. @code{false} or @code{true}.
1670: @item a-addr,a-
1671: Cell-aligned address
1672: @item c-addr,c-
1673: Char-aligned address (note that a Char may have two bytes in Windows NT)
1674: @item xt
1675: Execution token, same size as Cell
1676: @item w,x
1677: Cell, can contain an integer or an address. It usually takes 32, 64 or
1678: 16 bits (depending on your platform and Forth system). A cell is more
1679: commonly known as machine word, but the term @emph{word} already means
1680: something different in Forth.
1681: @item d
1682: signed double-cell integer
1683: @item ud
1684: unsigned double-cell integer
1685: @item r
1686: Float (on the FP stack)
1687: @end table
1688:
1689: You can find a more complete list in @ref{Notation}.
1690:
1.141 anton 1691: @quotation Assignment
1.48 anton 1692: Write stack-effect comments for all definitions you have written up to
1693: now.
1.141 anton 1694: @end quotation
1.48 anton 1695:
1696:
1697: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1698: @section Types
1.66 anton 1699: @cindex types tutorial
1.48 anton 1700:
1701: In Forth the names of the operations are not overloaded; so similar
1702: operations on different types need different names; e.g., @code{+} adds
1703: integers, and you have to use @code{f+} to add floating-point numbers.
1704: The following prefixes are often used for related operations on
1705: different types:
1706:
1707: @table @code
1708: @item (none)
1709: signed integer
1710: @item u
1711: unsigned integer
1712: @item c
1713: character
1714: @item d
1715: signed double-cell integer
1716: @item ud, du
1717: unsigned double-cell integer
1718: @item 2
1719: two cells (not-necessarily double-cell numbers)
1720: @item m, um
1721: mixed single-cell and double-cell operations
1722: @item f
1723: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1724: and @samp{r} represents FP numbers).
1.48 anton 1725: @end table
1726:
1727: If there are no differences between the signed and the unsigned variant
1728: (e.g., for @code{+}), there is only the prefix-less variant.
1729:
1730: Forth does not perform type checking, neither at compile time, nor at
1731: run time. If you use the wrong oeration, the data are interpreted
1732: incorrectly:
1733:
1734: @example
1735: -1 u.
1736: @end example
1737:
1738: If you have only experience with type-checked languages until now, and
1739: have heard how important type-checking is, don't panic! In my
1740: experience (and that of other Forthers), type errors in Forth code are
1741: usually easy to find (once you get used to it), the increased vigilance
1742: of the programmer tends to catch some harder errors in addition to most
1743: type errors, and you never have to work around the type system, so in
1744: most situations the lack of type-checking seems to be a win (projects to
1745: add type checking to Forth have not caught on).
1746:
1747:
1748: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1749: @section Factoring
1.66 anton 1750: @cindex factoring tutorial
1.48 anton 1751:
1752: If you try to write longer definitions, you will soon find it hard to
1753: keep track of the stack contents. Therefore, good Forth programmers
1754: tend to write only short definitions (e.g., three lines). The art of
1755: finding meaningful short definitions is known as factoring (as in
1756: factoring polynomials).
1757:
1758: Well-factored programs offer additional advantages: smaller, more
1759: general words, are easier to test and debug and can be reused more and
1760: better than larger, specialized words.
1761:
1762: So, if you run into difficulties with stack management, when writing
1763: code, try to define meaningful factors for the word, and define the word
1764: in terms of those. Even if a factor contains only two words, it is
1765: often helpful.
1766:
1.65 anton 1767: Good factoring is not easy, and it takes some practice to get the knack
1768: for it; but even experienced Forth programmers often don't find the
1769: right solution right away, but only when rewriting the program. So, if
1770: you don't come up with a good solution immediately, keep trying, don't
1771: despair.
1.48 anton 1772:
1773: @c example !!
1774:
1775:
1776: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1777: @section Designing the stack effect
1.66 anton 1778: @cindex Stack effect design, tutorial
1779: @cindex design of stack effects, tutorial
1.48 anton 1780:
1781: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1782: function; and since there is only one result, you don't have to deal with
1.48 anton 1783: the order of results, either.
1784:
1.117 anton 1785: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1786: parameter and result order of a definition is important and should be
1787: designed well. The general guideline is to design the stack effect such
1788: that the word is simple to use in most cases, even if that complicates
1789: the implementation of the word. Some concrete rules are:
1790:
1791: @itemize @bullet
1792:
1793: @item
1794: Words consume all of their parameters (e.g., @code{.}).
1795:
1796: @item
1797: If there is a convention on the order of parameters (e.g., from
1798: mathematics or another programming language), stick with it (e.g.,
1799: @code{-}).
1800:
1801: @item
1802: If one parameter usually requires only a short computation (e.g., it is
1803: a constant), pass it on the top of the stack. Conversely, parameters
1804: that usually require a long sequence of code to compute should be passed
1805: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1806: read, because the reader does not need to keep track of the bottom item
1.48 anton 1807: through a long sequence of code (or, alternatively, through stack
1.49 anton 1808: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1809: address on top of the stack because it is usually simpler to compute
1810: than the stored value (often the address is just a variable).
1811:
1812: @item
1813: Similarly, results that are usually consumed quickly should be returned
1814: on the top of stack, whereas a result that is often used in long
1815: computations should be passed as bottom result. E.g., the file words
1816: like @code{open-file} return the error code on the top of stack, because
1817: it is usually consumed quickly by @code{throw}; moreover, the error code
1818: has to be checked before doing anything with the other results.
1819:
1820: @end itemize
1821:
1822: These rules are just general guidelines, don't lose sight of the overall
1823: goal to make the words easy to use. E.g., if the convention rule
1824: conflicts with the computation-length rule, you might decide in favour
1825: of the convention if the word will be used rarely, and in favour of the
1826: computation-length rule if the word will be used frequently (because
1827: with frequent use the cost of breaking the computation-length rule would
1828: be quite high, and frequent use makes it easier to remember an
1829: unconventional order).
1830:
1831: @c example !! structure package
1832:
1.65 anton 1833:
1.48 anton 1834: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1835: @section Local Variables
1.66 anton 1836: @cindex local variables, tutorial
1.48 anton 1837:
1838: You can define local variables (@emph{locals}) in a colon definition:
1839:
1840: @example
1841: : swap @{ a b -- b a @}
1842: b a ;
1843: 1 2 swap .s 2drop
1844: @end example
1845:
1846: (If your Forth system does not support this syntax, include
1847: @file{compat/anslocals.fs} first).
1848:
1849: In this example @code{@{ a b -- b a @}} is the locals definition; it
1850: takes two cells from the stack, puts the top of stack in @code{b} and
1851: the next stack element in @code{a}. @code{--} starts a comment ending
1852: with @code{@}}. After the locals definition, using the name of the
1853: local will push its value on the stack. You can leave the comment
1854: part (@code{-- b a}) away:
1855:
1856: @example
1857: : swap ( x1 x2 -- x2 x1 )
1858: @{ a b @} b a ;
1859: @end example
1860:
1861: In Gforth you can have several locals definitions, anywhere in a colon
1862: definition; in contrast, in a standard program you can have only one
1863: locals definition per colon definition, and that locals definition must
1.163 anton 1864: be outside any control structure.
1.48 anton 1865:
1866: With locals you can write slightly longer definitions without running
1867: into stack trouble. However, I recommend trying to write colon
1868: definitions without locals for exercise purposes to help you gain the
1869: essential factoring skills.
1870:
1.141 anton 1871: @quotation Assignment
1.48 anton 1872: Rewrite your definitions until now with locals
1.141 anton 1873: @end quotation
1.48 anton 1874:
1.66 anton 1875: Reference: @ref{Locals}.
1876:
1.48 anton 1877:
1878: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1879: @section Conditional execution
1.66 anton 1880: @cindex conditionals, tutorial
1881: @cindex if, tutorial
1.48 anton 1882:
1883: In Forth you can use control structures only inside colon definitions.
1884: An @code{if}-structure looks like this:
1885:
1886: @example
1887: : abs ( n1 -- +n2 )
1888: dup 0 < if
1889: negate
1890: endif ;
1891: 5 abs .
1892: -5 abs .
1893: @end example
1894:
1895: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1896: the following code is performed, otherwise execution continues after the
1.51 pazsan 1897: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1898: elements and produces a flag:
1.48 anton 1899:
1900: @example
1901: 1 2 < .
1902: 2 1 < .
1903: 1 1 < .
1904: @end example
1905:
1906: Actually the standard name for @code{endif} is @code{then}. This
1907: tutorial presents the examples using @code{endif}, because this is often
1908: less confusing for people familiar with other programming languages
1909: where @code{then} has a different meaning. If your system does not have
1910: @code{endif}, define it with
1911:
1912: @example
1913: : endif postpone then ; immediate
1914: @end example
1915:
1916: You can optionally use an @code{else}-part:
1917:
1918: @example
1919: : min ( n1 n2 -- n )
1920: 2dup < if
1921: drop
1922: else
1923: nip
1924: endif ;
1925: 2 3 min .
1926: 3 2 min .
1927: @end example
1928:
1.141 anton 1929: @quotation Assignment
1.48 anton 1930: Write @code{min} without @code{else}-part (hint: what's the definition
1931: of @code{nip}?).
1.141 anton 1932: @end quotation
1.48 anton 1933:
1.66 anton 1934: Reference: @ref{Selection}.
1935:
1.48 anton 1936:
1937: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1938: @section Flags and Comparisons
1.66 anton 1939: @cindex flags tutorial
1940: @cindex comparison tutorial
1.48 anton 1941:
1942: In a false-flag all bits are clear (0 when interpreted as integer). In
1943: a canonical true-flag all bits are set (-1 as a twos-complement signed
1944: integer); in many contexts (e.g., @code{if}) any non-zero value is
1945: treated as true flag.
1946:
1947: @example
1948: false .
1949: true .
1950: true hex u. decimal
1951: @end example
1952:
1953: Comparison words produce canonical flags:
1954:
1955: @example
1956: 1 1 = .
1957: 1 0= .
1958: 0 1 < .
1959: 0 0 < .
1960: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1961: -1 1 < .
1962: @end example
1963:
1.66 anton 1964: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1965: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1966: these combinations are standard (for details see the standard,
1967: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1968:
1.171 anton 1969: You can use @code{and or xor invert} as operations on canonical flags.
1970: Actually they are bitwise operations:
1.48 anton 1971:
1972: @example
1973: 1 2 and .
1974: 1 2 or .
1975: 1 3 xor .
1976: 1 invert .
1977: @end example
1978:
1979: You can convert a zero/non-zero flag into a canonical flag with
1980: @code{0<>} (and complement it on the way with @code{0=}).
1981:
1982: @example
1983: 1 0= .
1984: 1 0<> .
1985: @end example
1986:
1.65 anton 1987: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1988: operation of the Boolean operations to avoid @code{if}s:
1989:
1990: @example
1991: : foo ( n1 -- n2 )
1992: 0= if
1993: 14
1994: else
1995: 0
1996: endif ;
1997: 0 foo .
1998: 1 foo .
1999:
2000: : foo ( n1 -- n2 )
2001: 0= 14 and ;
2002: 0 foo .
2003: 1 foo .
2004: @end example
2005:
1.141 anton 2006: @quotation Assignment
1.48 anton 2007: Write @code{min} without @code{if}.
1.141 anton 2008: @end quotation
1.48 anton 2009:
1.66 anton 2010: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2011: @ref{Bitwise operations}.
2012:
1.48 anton 2013:
2014: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2015: @section General Loops
1.66 anton 2016: @cindex loops, indefinite, tutorial
1.48 anton 2017:
2018: The endless loop is the most simple one:
2019:
2020: @example
2021: : endless ( -- )
2022: 0 begin
2023: dup . 1+
2024: again ;
2025: endless
2026: @end example
2027:
2028: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2029: does nothing at run-time, @code{again} jumps back to @code{begin}.
2030:
2031: A loop with one exit at any place looks like this:
2032:
2033: @example
2034: : log2 ( +n1 -- n2 )
2035: \ logarithmus dualis of n1>0, rounded down to the next integer
2036: assert( dup 0> )
2037: 2/ 0 begin
2038: over 0> while
2039: 1+ swap 2/ swap
2040: repeat
2041: nip ;
2042: 7 log2 .
2043: 8 log2 .
2044: @end example
2045:
2046: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2047: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2048: continues behind the @code{while}. @code{Repeat} jumps back to
2049: @code{begin}, just like @code{again}.
2050:
2051: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2052: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2053: one bit (arithmetic shift right):
2054:
2055: @example
2056: -5 2 / .
2057: -5 2/ .
2058: @end example
2059:
2060: @code{assert(} is no standard word, but you can get it on systems other
2061: then Gforth by including @file{compat/assert.fs}. You can see what it
2062: does by trying
2063:
2064: @example
2065: 0 log2 .
2066: @end example
2067:
2068: Here's a loop with an exit at the end:
2069:
2070: @example
2071: : log2 ( +n1 -- n2 )
2072: \ logarithmus dualis of n1>0, rounded down to the next integer
2073: assert( dup 0 > )
2074: -1 begin
2075: 1+ swap 2/ swap
2076: over 0 <=
2077: until
2078: nip ;
2079: @end example
2080:
2081: @code{Until} consumes a flag; if it is non-zero, execution continues at
2082: the @code{begin}, otherwise after the @code{until}.
2083:
1.141 anton 2084: @quotation Assignment
1.48 anton 2085: Write a definition for computing the greatest common divisor.
1.141 anton 2086: @end quotation
1.48 anton 2087:
1.66 anton 2088: Reference: @ref{Simple Loops}.
2089:
1.48 anton 2090:
2091: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2092: @section Counted loops
1.66 anton 2093: @cindex loops, counted, tutorial
1.48 anton 2094:
2095: @example
2096: : ^ ( n1 u -- n )
1.171 anton 2097: \ n = the uth power of n1
1.48 anton 2098: 1 swap 0 u+do
2099: over *
2100: loop
2101: nip ;
2102: 3 2 ^ .
2103: 4 3 ^ .
2104: @end example
2105:
2106: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2107: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2108: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2109: times (or not at all, if @code{u3-u4<0}).
2110:
2111: You can see the stack effect design rules at work in the stack effect of
2112: the loop start words: Since the start value of the loop is more
2113: frequently constant than the end value, the start value is passed on
2114: the top-of-stack.
2115:
2116: You can access the counter of a counted loop with @code{i}:
2117:
2118: @example
2119: : fac ( u -- u! )
2120: 1 swap 1+ 1 u+do
2121: i *
2122: loop ;
2123: 5 fac .
2124: 7 fac .
2125: @end example
2126:
2127: There is also @code{+do}, which expects signed numbers (important for
2128: deciding whether to enter the loop).
2129:
1.141 anton 2130: @quotation Assignment
1.48 anton 2131: Write a definition for computing the nth Fibonacci number.
1.141 anton 2132: @end quotation
1.48 anton 2133:
1.65 anton 2134: You can also use increments other than 1:
2135:
2136: @example
2137: : up2 ( n1 n2 -- )
2138: +do
2139: i .
2140: 2 +loop ;
2141: 10 0 up2
2142:
2143: : down2 ( n1 n2 -- )
2144: -do
2145: i .
2146: 2 -loop ;
2147: 0 10 down2
2148: @end example
1.48 anton 2149:
1.66 anton 2150: Reference: @ref{Counted Loops}.
2151:
1.48 anton 2152:
2153: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2154: @section Recursion
1.66 anton 2155: @cindex recursion tutorial
1.48 anton 2156:
2157: Usually the name of a definition is not visible in the definition; but
2158: earlier definitions are usually visible:
2159:
2160: @example
1.166 anton 2161: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2162: : / ( n1 n2 -- n )
2163: dup 0= if
2164: -10 throw \ report division by zero
2165: endif
2166: / \ old version
2167: ;
2168: 1 0 /
2169: @end example
2170:
2171: For recursive definitions you can use @code{recursive} (non-standard) or
2172: @code{recurse}:
2173:
2174: @example
2175: : fac1 ( n -- n! ) recursive
2176: dup 0> if
2177: dup 1- fac1 *
2178: else
2179: drop 1
2180: endif ;
2181: 7 fac1 .
2182:
2183: : fac2 ( n -- n! )
2184: dup 0> if
2185: dup 1- recurse *
2186: else
2187: drop 1
2188: endif ;
2189: 8 fac2 .
2190: @end example
2191:
1.141 anton 2192: @quotation Assignment
1.48 anton 2193: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2194: @end quotation
1.48 anton 2195:
1.66 anton 2196: Reference (including indirect recursion): @xref{Calls and returns}.
2197:
1.48 anton 2198:
2199: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2200: @section Leaving definitions or loops
1.66 anton 2201: @cindex leaving definitions, tutorial
2202: @cindex leaving loops, tutorial
1.48 anton 2203:
2204: @code{EXIT} exits the current definition right away. For every counted
2205: loop that is left in this way, an @code{UNLOOP} has to be performed
2206: before the @code{EXIT}:
2207:
2208: @c !! real examples
2209: @example
2210: : ...
2211: ... u+do
2212: ... if
2213: ... unloop exit
2214: endif
2215: ...
2216: loop
2217: ... ;
2218: @end example
2219:
2220: @code{LEAVE} leaves the innermost counted loop right away:
2221:
2222: @example
2223: : ...
2224: ... u+do
2225: ... if
2226: ... leave
2227: endif
2228: ...
2229: loop
2230: ... ;
2231: @end example
2232:
1.65 anton 2233: @c !! example
1.48 anton 2234:
1.66 anton 2235: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2236:
2237:
1.48 anton 2238: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2239: @section Return Stack
1.66 anton 2240: @cindex return stack tutorial
1.48 anton 2241:
2242: In addition to the data stack Forth also has a second stack, the return
2243: stack; most Forth systems store the return addresses of procedure calls
2244: there (thus its name). Programmers can also use this stack:
2245:
2246: @example
2247: : foo ( n1 n2 -- )
2248: .s
2249: >r .s
1.50 anton 2250: r@@ .
1.48 anton 2251: >r .s
1.50 anton 2252: r@@ .
1.48 anton 2253: r> .
1.50 anton 2254: r@@ .
1.48 anton 2255: r> . ;
2256: 1 2 foo
2257: @end example
2258:
2259: @code{>r} takes an element from the data stack and pushes it onto the
2260: return stack; conversely, @code{r>} moves an elementm from the return to
2261: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2262: on the data stack.
1.48 anton 2263:
2264: Forth programmers usually use the return stack for storing data
2265: temporarily, if using the data stack alone would be too complex, and
2266: factoring and locals are not an option:
2267:
2268: @example
2269: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2270: rot >r rot r> ;
2271: @end example
2272:
2273: The return address of the definition and the loop control parameters of
2274: counted loops usually reside on the return stack, so you have to take
2275: all items, that you have pushed on the return stack in a colon
2276: definition or counted loop, from the return stack before the definition
2277: or loop ends. You cannot access items that you pushed on the return
2278: stack outside some definition or loop within the definition of loop.
2279:
2280: If you miscount the return stack items, this usually ends in a crash:
2281:
2282: @example
2283: : crash ( n -- )
2284: >r ;
2285: 5 crash
2286: @end example
2287:
2288: You cannot mix using locals and using the return stack (according to the
2289: standard; Gforth has no problem). However, they solve the same
2290: problems, so this shouldn't be an issue.
2291:
1.141 anton 2292: @quotation Assignment
1.48 anton 2293: Can you rewrite any of the definitions you wrote until now in a better
2294: way using the return stack?
1.141 anton 2295: @end quotation
1.48 anton 2296:
1.66 anton 2297: Reference: @ref{Return stack}.
2298:
1.48 anton 2299:
2300: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2301: @section Memory
1.66 anton 2302: @cindex memory access/allocation tutorial
1.48 anton 2303:
2304: You can create a global variable @code{v} with
2305:
2306: @example
2307: variable v ( -- addr )
2308: @end example
2309:
2310: @code{v} pushes the address of a cell in memory on the stack. This cell
2311: was reserved by @code{variable}. You can use @code{!} (store) to store
2312: values into this cell and @code{@@} (fetch) to load the value from the
2313: stack into memory:
2314:
2315: @example
2316: v .
2317: 5 v ! .s
1.50 anton 2318: v @@ .
1.48 anton 2319: @end example
2320:
1.65 anton 2321: You can see a raw dump of memory with @code{dump}:
2322:
2323: @example
2324: v 1 cells .s dump
2325: @end example
2326:
2327: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2328: generally, address units (aus)) that @code{n1 cells} occupy. You can
2329: also reserve more memory:
1.48 anton 2330:
2331: @example
2332: create v2 20 cells allot
1.65 anton 2333: v2 20 cells dump
1.48 anton 2334: @end example
2335:
1.65 anton 2336: creates a word @code{v2} and reserves 20 uninitialized cells; the
2337: address pushed by @code{v2} points to the start of these 20 cells. You
2338: can use address arithmetic to access these cells:
1.48 anton 2339:
2340: @example
2341: 3 v2 5 cells + !
1.65 anton 2342: v2 20 cells dump
1.48 anton 2343: @end example
2344:
2345: You can reserve and initialize memory with @code{,}:
2346:
2347: @example
2348: create v3
2349: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2350: v3 @@ .
2351: v3 cell+ @@ .
2352: v3 2 cells + @@ .
1.65 anton 2353: v3 5 cells dump
1.48 anton 2354: @end example
2355:
1.141 anton 2356: @quotation Assignment
1.48 anton 2357: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2358: @code{u} cells, with the first of these cells at @code{addr}, the next
2359: one at @code{addr cell+} etc.
1.141 anton 2360: @end quotation
1.48 anton 2361:
2362: You can also reserve memory without creating a new word:
2363:
2364: @example
1.60 anton 2365: here 10 cells allot .
2366: here .
1.48 anton 2367: @end example
2368:
2369: @code{Here} pushes the start address of the memory area. You should
2370: store it somewhere, or you will have a hard time finding the memory area
2371: again.
2372:
2373: @code{Allot} manages dictionary memory. The dictionary memory contains
2374: the system's data structures for words etc. on Gforth and most other
2375: Forth systems. It is managed like a stack: You can free the memory that
2376: you have just @code{allot}ed with
2377:
2378: @example
2379: -10 cells allot
1.60 anton 2380: here .
1.48 anton 2381: @end example
2382:
2383: Note that you cannot do this if you have created a new word in the
2384: meantime (because then your @code{allot}ed memory is no longer on the
2385: top of the dictionary ``stack'').
2386:
2387: Alternatively, you can use @code{allocate} and @code{free} which allow
2388: freeing memory in any order:
2389:
2390: @example
2391: 10 cells allocate throw .s
2392: 20 cells allocate throw .s
2393: swap
2394: free throw
2395: free throw
2396: @end example
2397:
2398: The @code{throw}s deal with errors (e.g., out of memory).
2399:
1.65 anton 2400: And there is also a
2401: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2402: garbage collector}, which eliminates the need to @code{free} memory
2403: explicitly.
1.48 anton 2404:
1.66 anton 2405: Reference: @ref{Memory}.
2406:
1.48 anton 2407:
2408: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2409: @section Characters and Strings
1.66 anton 2410: @cindex strings tutorial
2411: @cindex characters tutorial
1.48 anton 2412:
2413: On the stack characters take up a cell, like numbers. In memory they
2414: have their own size (one 8-bit byte on most systems), and therefore
2415: require their own words for memory access:
2416:
2417: @example
2418: create v4
2419: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2420: v4 4 chars + c@@ .
1.65 anton 2421: v4 5 chars dump
1.48 anton 2422: @end example
2423:
2424: The preferred representation of strings on the stack is @code{addr
2425: u-count}, where @code{addr} is the address of the first character and
2426: @code{u-count} is the number of characters in the string.
2427:
2428: @example
2429: v4 5 type
2430: @end example
2431:
2432: You get a string constant with
2433:
2434: @example
2435: s" hello, world" .s
2436: type
2437: @end example
2438:
2439: Make sure you have a space between @code{s"} and the string; @code{s"}
2440: is a normal Forth word and must be delimited with white space (try what
2441: happens when you remove the space).
2442:
2443: However, this interpretive use of @code{s"} is quite restricted: the
2444: string exists only until the next call of @code{s"} (some Forth systems
2445: keep more than one of these strings, but usually they still have a
1.62 crook 2446: limited lifetime).
1.48 anton 2447:
2448: @example
2449: s" hello," s" world" .s
2450: type
2451: type
2452: @end example
2453:
1.62 crook 2454: You can also use @code{s"} in a definition, and the resulting
2455: strings then live forever (well, for as long as the definition):
1.48 anton 2456:
2457: @example
2458: : foo s" hello," s" world" ;
2459: foo .s
2460: type
2461: type
2462: @end example
2463:
1.141 anton 2464: @quotation Assignment
1.48 anton 2465: @code{Emit ( c -- )} types @code{c} as character (not a number).
2466: Implement @code{type ( addr u -- )}.
1.141 anton 2467: @end quotation
1.48 anton 2468:
1.66 anton 2469: Reference: @ref{Memory Blocks}.
2470:
2471:
1.84 pazsan 2472: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2473: @section Alignment
1.66 anton 2474: @cindex alignment tutorial
2475: @cindex memory alignment tutorial
1.48 anton 2476:
2477: On many processors cells have to be aligned in memory, if you want to
2478: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2479: not require alignment, access to aligned cells is faster).
1.48 anton 2480:
2481: @code{Create} aligns @code{here} (i.e., the place where the next
2482: allocation will occur, and that the @code{create}d word points to).
2483: Likewise, the memory produced by @code{allocate} starts at an aligned
2484: address. Adding a number of @code{cells} to an aligned address produces
2485: another aligned address.
2486:
2487: However, address arithmetic involving @code{char+} and @code{chars} can
2488: create an address that is not cell-aligned. @code{Aligned ( addr --
2489: a-addr )} produces the next aligned address:
2490:
2491: @example
1.50 anton 2492: v3 char+ aligned .s @@ .
2493: v3 char+ .s @@ .
1.48 anton 2494: @end example
2495:
2496: Similarly, @code{align} advances @code{here} to the next aligned
2497: address:
2498:
2499: @example
2500: create v5 97 c,
2501: here .
2502: align here .
2503: 1000 ,
2504: @end example
2505:
2506: Note that you should use aligned addresses even if your processor does
2507: not require them, if you want your program to be portable.
2508:
1.66 anton 2509: Reference: @ref{Address arithmetic}.
2510:
1.48 anton 2511:
1.84 pazsan 2512: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2513: @section Files
2514: @cindex files tutorial
2515:
2516: This section gives a short introduction into how to use files inside
2517: Forth. It's broken up into five easy steps:
2518:
2519: @enumerate 1
2520: @item Opened an ASCII text file for input
2521: @item Opened a file for output
2522: @item Read input file until string matched (or some other condition matched)
2523: @item Wrote some lines from input ( modified or not) to output
2524: @item Closed the files.
2525: @end enumerate
2526:
1.153 anton 2527: Reference: @ref{General files}.
2528:
1.84 pazsan 2529: @subsection Open file for input
2530:
2531: @example
2532: s" foo.in" r/o open-file throw Value fd-in
2533: @end example
2534:
2535: @subsection Create file for output
2536:
2537: @example
2538: s" foo.out" w/o create-file throw Value fd-out
2539: @end example
2540:
2541: The available file modes are r/o for read-only access, r/w for
2542: read-write access, and w/o for write-only access. You could open both
2543: files with r/w, too, if you like. All file words return error codes; for
2544: most applications, it's best to pass there error codes with @code{throw}
2545: to the outer error handler.
2546:
2547: If you want words for opening and assigning, define them as follows:
2548:
2549: @example
2550: 0 Value fd-in
2551: 0 Value fd-out
2552: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2553: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2554: @end example
2555:
2556: Usage example:
2557:
2558: @example
2559: s" foo.in" open-input
2560: s" foo.out" open-output
2561: @end example
2562:
2563: @subsection Scan file for a particular line
2564:
2565: @example
2566: 256 Constant max-line
2567: Create line-buffer max-line 2 + allot
2568:
2569: : scan-file ( addr u -- )
2570: begin
2571: line-buffer max-line fd-in read-line throw
2572: while
2573: >r 2dup line-buffer r> compare 0=
2574: until
2575: else
2576: drop
2577: then
2578: 2drop ;
2579: @end example
2580:
2581: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2582: the buffer at addr, and returns the number of bytes read, a flag that is
2583: false when the end of file is reached, and an error code.
1.84 pazsan 2584:
2585: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2586: returns zero if both strings are equal. It returns a positive number if
2587: the first string is lexically greater, a negative if the second string
2588: is lexically greater.
2589:
2590: We haven't seen this loop here; it has two exits. Since the @code{while}
2591: exits with the number of bytes read on the stack, we have to clean up
2592: that separately; that's after the @code{else}.
2593:
2594: Usage example:
2595:
2596: @example
2597: s" The text I search is here" scan-file
2598: @end example
2599:
2600: @subsection Copy input to output
2601:
2602: @example
2603: : copy-file ( -- )
2604: begin
2605: line-buffer max-line fd-in read-line throw
2606: while
2607: line-buffer swap fd-out write-file throw
2608: repeat ;
2609: @end example
2610:
2611: @subsection Close files
2612:
2613: @example
2614: fd-in close-file throw
2615: fd-out close-file throw
2616: @end example
2617:
2618: Likewise, you can put that into definitions, too:
2619:
2620: @example
2621: : close-input ( -- ) fd-in close-file throw ;
2622: : close-output ( -- ) fd-out close-file throw ;
2623: @end example
2624:
1.141 anton 2625: @quotation Assignment
1.84 pazsan 2626: How could you modify @code{copy-file} so that it copies until a second line is
2627: matched? Can you write a program that extracts a section of a text file,
2628: given the line that starts and the line that terminates that section?
1.141 anton 2629: @end quotation
1.84 pazsan 2630:
2631: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2632: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2633: @cindex semantics tutorial
2634: @cindex interpretation semantics tutorial
2635: @cindex compilation semantics tutorial
2636: @cindex immediate, tutorial
1.48 anton 2637:
2638: When a word is compiled, it behaves differently from being interpreted.
2639: E.g., consider @code{+}:
2640:
2641: @example
2642: 1 2 + .
2643: : foo + ;
2644: @end example
2645:
2646: These two behaviours are known as compilation and interpretation
2647: semantics. For normal words (e.g., @code{+}), the compilation semantics
2648: is to append the interpretation semantics to the currently defined word
2649: (@code{foo} in the example above). I.e., when @code{foo} is executed
2650: later, the interpretation semantics of @code{+} (i.e., adding two
2651: numbers) will be performed.
2652:
2653: However, there are words with non-default compilation semantics, e.g.,
2654: the control-flow words like @code{if}. You can use @code{immediate} to
2655: change the compilation semantics of the last defined word to be equal to
2656: the interpretation semantics:
2657:
2658: @example
2659: : [FOO] ( -- )
2660: 5 . ; immediate
2661:
2662: [FOO]
2663: : bar ( -- )
2664: [FOO] ;
2665: bar
2666: see bar
2667: @end example
2668:
2669: Two conventions to mark words with non-default compilation semnatics are
2670: names with brackets (more frequently used) and to write them all in
2671: upper case (less frequently used).
2672:
2673: In Gforth (and many other systems) you can also remove the
2674: interpretation semantics with @code{compile-only} (the compilation
2675: semantics is derived from the original interpretation semantics):
2676:
2677: @example
2678: : flip ( -- )
2679: 6 . ; compile-only \ but not immediate
2680: flip
2681:
2682: : flop ( -- )
2683: flip ;
2684: flop
2685: @end example
2686:
2687: In this example the interpretation semantics of @code{flop} is equal to
2688: the original interpretation semantics of @code{flip}.
2689:
2690: The text interpreter has two states: in interpret state, it performs the
2691: interpretation semantics of words it encounters; in compile state, it
2692: performs the compilation semantics of these words.
2693:
2694: Among other things, @code{:} switches into compile state, and @code{;}
2695: switches back to interpret state. They contain the factors @code{]}
2696: (switch to compile state) and @code{[} (switch to interpret state), that
2697: do nothing but switch the state.
2698:
2699: @example
2700: : xxx ( -- )
2701: [ 5 . ]
2702: ;
2703:
2704: xxx
2705: see xxx
2706: @end example
2707:
2708: These brackets are also the source of the naming convention mentioned
2709: above.
2710:
1.66 anton 2711: Reference: @ref{Interpretation and Compilation Semantics}.
2712:
1.48 anton 2713:
2714: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2715: @section Execution Tokens
1.66 anton 2716: @cindex execution tokens tutorial
2717: @cindex XT tutorial
1.48 anton 2718:
2719: @code{' word} gives you the execution token (XT) of a word. The XT is a
2720: cell representing the interpretation semantics of a word. You can
2721: execute this semantics with @code{execute}:
2722:
2723: @example
2724: ' + .s
2725: 1 2 rot execute .
2726: @end example
2727:
2728: The XT is similar to a function pointer in C. However, parameter
2729: passing through the stack makes it a little more flexible:
2730:
2731: @example
2732: : map-array ( ... addr u xt -- ... )
1.50 anton 2733: \ executes xt ( ... x -- ... ) for every element of the array starting
2734: \ at addr and containing u elements
1.48 anton 2735: @{ xt @}
2736: cells over + swap ?do
1.50 anton 2737: i @@ xt execute
1.48 anton 2738: 1 cells +loop ;
2739:
2740: create a 3 , 4 , 2 , -1 , 4 ,
2741: a 5 ' . map-array .s
2742: 0 a 5 ' + map-array .
2743: s" max-n" environment? drop .s
2744: a 5 ' min map-array .
2745: @end example
2746:
2747: You can use map-array with the XTs of words that consume one element
2748: more than they produce. In theory you can also use it with other XTs,
2749: but the stack effect then depends on the size of the array, which is
2750: hard to understand.
2751:
1.51 pazsan 2752: Since XTs are cell-sized, you can store them in memory and manipulate
2753: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2754: word with @code{compile,}:
2755:
2756: @example
2757: : foo1 ( n1 n2 -- n )
2758: [ ' + compile, ] ;
2759: see foo
2760: @end example
2761:
2762: This is non-standard, because @code{compile,} has no compilation
2763: semantics in the standard, but it works in good Forth systems. For the
2764: broken ones, use
2765:
2766: @example
2767: : [compile,] compile, ; immediate
2768:
2769: : foo1 ( n1 n2 -- n )
2770: [ ' + ] [compile,] ;
2771: see foo
2772: @end example
2773:
2774: @code{'} is a word with default compilation semantics; it parses the
2775: next word when its interpretation semantics are executed, not during
2776: compilation:
2777:
2778: @example
2779: : foo ( -- xt )
2780: ' ;
2781: see foo
2782: : bar ( ... "word" -- ... )
2783: ' execute ;
2784: see bar
1.60 anton 2785: 1 2 bar + .
1.48 anton 2786: @end example
2787:
2788: You often want to parse a word during compilation and compile its XT so
2789: it will be pushed on the stack at run-time. @code{[']} does this:
2790:
2791: @example
2792: : xt-+ ( -- xt )
2793: ['] + ;
2794: see xt-+
2795: 1 2 xt-+ execute .
2796: @end example
2797:
2798: Many programmers tend to see @code{'} and the word it parses as one
2799: unit, and expect it to behave like @code{[']} when compiled, and are
2800: confused by the actual behaviour. If you are, just remember that the
2801: Forth system just takes @code{'} as one unit and has no idea that it is
2802: a parsing word (attempts to convenience programmers in this issue have
2803: usually resulted in even worse pitfalls, see
1.66 anton 2804: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2805: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2806:
2807: Note that the state of the interpreter does not come into play when
1.51 pazsan 2808: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2809: compile state, it still gives you the interpretation semantics. And
2810: whatever that state is, @code{execute} performs the semantics
1.66 anton 2811: represented by the XT (i.e., for XTs produced with @code{'} the
2812: interpretation semantics).
2813:
2814: Reference: @ref{Tokens for Words}.
1.48 anton 2815:
2816:
2817: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2818: @section Exceptions
1.66 anton 2819: @cindex exceptions tutorial
1.48 anton 2820:
2821: @code{throw ( n -- )} causes an exception unless n is zero.
2822:
2823: @example
2824: 100 throw .s
2825: 0 throw .s
2826: @end example
2827:
2828: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2829: it catches exceptions and pushes the number of the exception on the
2830: stack (or 0, if the xt executed without exception). If there was an
2831: exception, the stacks have the same depth as when entering @code{catch}:
2832:
2833: @example
2834: .s
2835: 3 0 ' / catch .s
2836: 3 2 ' / catch .s
2837: @end example
2838:
1.141 anton 2839: @quotation Assignment
1.48 anton 2840: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2841: @end quotation
1.48 anton 2842:
2843: @code{Throw} always jumps to the dynamically next enclosing
2844: @code{catch}, even if it has to leave several call levels to achieve
2845: this:
2846:
2847: @example
2848: : foo 100 throw ;
2849: : foo1 foo ." after foo" ;
1.51 pazsan 2850: : bar ['] foo1 catch ;
1.60 anton 2851: bar .
1.48 anton 2852: @end example
2853:
2854: It is often important to restore a value upon leaving a definition, even
2855: if the definition is left through an exception. You can ensure this
2856: like this:
2857:
2858: @example
2859: : ...
2860: save-x
1.51 pazsan 2861: ['] word-changing-x catch ( ... n )
1.48 anton 2862: restore-x
2863: ( ... n ) throw ;
2864: @end example
2865:
1.172 anton 2866: However, this is still not safe against, e.g., the user pressing
2867: @kbd{Ctrl-C} when execution is between the @code{catch} and
2868: @code{restore-x}.
2869:
2870: Gforth provides an alternative exception handling syntax that is safe
2871: against such cases: @code{try ... restore ... endtry}. If the code
2872: between @code{try} and @code{endtry} has an exception, the stack
2873: depths are restored, the exception number is pushed on the stack, and
2874: the execution continues right after @code{restore}.
1.48 anton 2875:
1.172 anton 2876: The safer equivalent to the restoration code above is
1.48 anton 2877:
2878: @example
2879: : ...
2880: save-x
2881: try
1.92 anton 2882: word-changing-x 0
1.172 anton 2883: restore
2884: restore-x
2885: endtry
1.48 anton 2886: throw ;
2887: @end example
2888:
1.66 anton 2889: Reference: @ref{Exception Handling}.
2890:
1.48 anton 2891:
2892: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2893: @section Defining Words
1.66 anton 2894: @cindex defining words tutorial
2895: @cindex does> tutorial
2896: @cindex create...does> tutorial
2897:
2898: @c before semantics?
1.48 anton 2899:
2900: @code{:}, @code{create}, and @code{variable} are definition words: They
2901: define other words. @code{Constant} is another definition word:
2902:
2903: @example
2904: 5 constant foo
2905: foo .
2906: @end example
2907:
2908: You can also use the prefixes @code{2} (double-cell) and @code{f}
2909: (floating point) with @code{variable} and @code{constant}.
2910:
2911: You can also define your own defining words. E.g.:
2912:
2913: @example
2914: : variable ( "name" -- )
2915: create 0 , ;
2916: @end example
2917:
2918: You can also define defining words that create words that do something
2919: other than just producing their address:
2920:
2921: @example
2922: : constant ( n "name" -- )
2923: create ,
2924: does> ( -- n )
1.50 anton 2925: ( addr ) @@ ;
1.48 anton 2926:
2927: 5 constant foo
2928: foo .
2929: @end example
2930:
2931: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2932: @code{does>} replaces @code{;}, but it also does something else: It
2933: changes the last defined word such that it pushes the address of the
2934: body of the word and then performs the code after the @code{does>}
2935: whenever it is called.
2936:
2937: In the example above, @code{constant} uses @code{,} to store 5 into the
2938: body of @code{foo}. When @code{foo} executes, it pushes the address of
2939: the body onto the stack, then (in the code after the @code{does>})
2940: fetches the 5 from there.
2941:
2942: The stack comment near the @code{does>} reflects the stack effect of the
2943: defined word, not the stack effect of the code after the @code{does>}
2944: (the difference is that the code expects the address of the body that
2945: the stack comment does not show).
2946:
2947: You can use these definition words to do factoring in cases that involve
2948: (other) definition words. E.g., a field offset is always added to an
2949: address. Instead of defining
2950:
2951: @example
2952: 2 cells constant offset-field1
2953: @end example
2954:
2955: and using this like
2956:
2957: @example
2958: ( addr ) offset-field1 +
2959: @end example
2960:
2961: you can define a definition word
2962:
2963: @example
2964: : simple-field ( n "name" -- )
2965: create ,
2966: does> ( n1 -- n1+n )
1.50 anton 2967: ( addr ) @@ + ;
1.48 anton 2968: @end example
1.21 crook 2969:
1.48 anton 2970: Definition and use of field offsets now look like this:
1.21 crook 2971:
1.48 anton 2972: @example
2973: 2 cells simple-field field1
1.60 anton 2974: create mystruct 4 cells allot
2975: mystruct .s field1 .s drop
1.48 anton 2976: @end example
1.21 crook 2977:
1.48 anton 2978: If you want to do something with the word without performing the code
2979: after the @code{does>}, you can access the body of a @code{create}d word
2980: with @code{>body ( xt -- addr )}:
1.21 crook 2981:
1.48 anton 2982: @example
2983: : value ( n "name" -- )
2984: create ,
2985: does> ( -- n1 )
1.50 anton 2986: @@ ;
1.48 anton 2987: : to ( n "name" -- )
2988: ' >body ! ;
1.21 crook 2989:
1.48 anton 2990: 5 value foo
2991: foo .
2992: 7 to foo
2993: foo .
2994: @end example
1.21 crook 2995:
1.141 anton 2996: @quotation Assignment
1.48 anton 2997: Define @code{defer ( "name" -- )}, which creates a word that stores an
2998: XT (at the start the XT of @code{abort}), and upon execution
2999: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3000: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3001: recursion is one application of @code{defer}.
1.141 anton 3002: @end quotation
1.29 crook 3003:
1.66 anton 3004: Reference: @ref{User-defined Defining Words}.
3005:
3006:
1.48 anton 3007: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3008: @section Arrays and Records
1.66 anton 3009: @cindex arrays tutorial
3010: @cindex records tutorial
3011: @cindex structs tutorial
1.29 crook 3012:
1.48 anton 3013: Forth has no standard words for defining data structures such as arrays
3014: and records (structs in C terminology), but you can build them yourself
3015: based on address arithmetic. You can also define words for defining
3016: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3017:
1.48 anton 3018: One of the first projects a Forth newcomer sets out upon when learning
3019: about defining words is an array defining word (possibly for
3020: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3021: learn something from it. However, don't be disappointed when you later
3022: learn that you have little use for these words (inappropriate use would
3023: be even worse). I have not yet found a set of useful array words yet;
3024: the needs are just too diverse, and named, global arrays (the result of
3025: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3026: consider how to pass them as parameters). Another such project is a set
3027: of words to help dealing with strings.
1.29 crook 3028:
1.48 anton 3029: On the other hand, there is a useful set of record words, and it has
3030: been defined in @file{compat/struct.fs}; these words are predefined in
3031: Gforth. They are explained in depth elsewhere in this manual (see
3032: @pxref{Structures}). The @code{simple-field} example above is
3033: simplified variant of fields in this package.
1.21 crook 3034:
3035:
1.48 anton 3036: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3037: @section @code{POSTPONE}
1.66 anton 3038: @cindex postpone tutorial
1.21 crook 3039:
1.48 anton 3040: You can compile the compilation semantics (instead of compiling the
3041: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3042:
1.48 anton 3043: @example
3044: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3045: POSTPONE + ; immediate
1.48 anton 3046: : foo ( n1 n2 -- n )
3047: MY-+ ;
3048: 1 2 foo .
3049: see foo
3050: @end example
1.21 crook 3051:
1.48 anton 3052: During the definition of @code{foo} the text interpreter performs the
3053: compilation semantics of @code{MY-+}, which performs the compilation
3054: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3055:
3056: This example also displays separate stack comments for the compilation
3057: semantics and for the stack effect of the compiled code. For words with
3058: default compilation semantics these stack effects are usually not
3059: displayed; the stack effect of the compilation semantics is always
3060: @code{( -- )} for these words, the stack effect for the compiled code is
3061: the stack effect of the interpretation semantics.
3062:
3063: Note that the state of the interpreter does not come into play when
3064: performing the compilation semantics in this way. You can also perform
3065: it interpretively, e.g.:
3066:
3067: @example
3068: : foo2 ( n1 n2 -- n )
3069: [ MY-+ ] ;
3070: 1 2 foo .
3071: see foo
3072: @end example
1.21 crook 3073:
1.48 anton 3074: However, there are some broken Forth systems where this does not always
1.62 crook 3075: work, and therefore this practice was been declared non-standard in
1.48 anton 3076: 1999.
3077: @c !! repair.fs
3078:
3079: Here is another example for using @code{POSTPONE}:
1.44 crook 3080:
1.48 anton 3081: @example
3082: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3083: POSTPONE negate POSTPONE + ; immediate compile-only
3084: : bar ( n1 n2 -- n )
3085: MY-- ;
3086: 2 1 bar .
3087: see bar
3088: @end example
1.21 crook 3089:
1.48 anton 3090: You can define @code{ENDIF} in this way:
1.21 crook 3091:
1.48 anton 3092: @example
3093: : ENDIF ( Compilation: orig -- )
3094: POSTPONE then ; immediate
3095: @end example
1.21 crook 3096:
1.141 anton 3097: @quotation Assignment
1.48 anton 3098: Write @code{MY-2DUP} that has compilation semantics equivalent to
3099: @code{2dup}, but compiles @code{over over}.
1.141 anton 3100: @end quotation
1.29 crook 3101:
1.66 anton 3102: @c !! @xref{Macros} for reference
3103:
3104:
1.48 anton 3105: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3106: @section @code{Literal}
1.66 anton 3107: @cindex literal tutorial
1.29 crook 3108:
1.48 anton 3109: You cannot @code{POSTPONE} numbers:
1.21 crook 3110:
1.48 anton 3111: @example
3112: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3113: @end example
3114:
1.48 anton 3115: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3116:
1.48 anton 3117: @example
3118: : [FOO] ( compilation: --; run-time: -- n )
3119: 500 POSTPONE literal ; immediate
1.29 crook 3120:
1.60 anton 3121: : flip [FOO] ;
1.48 anton 3122: flip .
3123: see flip
3124: @end example
1.29 crook 3125:
1.48 anton 3126: @code{LITERAL} consumes a number at compile-time (when it's compilation
3127: semantics are executed) and pushes it at run-time (when the code it
3128: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3129: number computed at compile time into the current word:
1.29 crook 3130:
1.48 anton 3131: @example
3132: : bar ( -- n )
3133: [ 2 2 + ] literal ;
3134: see bar
3135: @end example
1.29 crook 3136:
1.141 anton 3137: @quotation Assignment
1.48 anton 3138: Write @code{]L} which allows writing the example above as @code{: bar (
3139: -- n ) [ 2 2 + ]L ;}
1.141 anton 3140: @end quotation
1.48 anton 3141:
1.66 anton 3142: @c !! @xref{Macros} for reference
3143:
1.48 anton 3144:
3145: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3146: @section Advanced macros
1.66 anton 3147: @cindex macros, advanced tutorial
3148: @cindex run-time code generation, tutorial
1.48 anton 3149:
1.66 anton 3150: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3151: Execution Tokens}. It frequently performs @code{execute}, a relatively
3152: expensive operation in some Forth implementations. You can use
1.48 anton 3153: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3154: and produce a word that contains the word to be performed directly:
3155:
3156: @c use ]] ... [[
3157: @example
3158: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3159: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3160: \ array beginning at addr and containing u elements
3161: @{ xt @}
3162: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3163: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3164: 1 cells POSTPONE literal POSTPONE +loop ;
3165:
3166: : sum-array ( addr u -- n )
3167: 0 rot rot [ ' + compile-map-array ] ;
3168: see sum-array
3169: a 5 sum-array .
3170: @end example
3171:
3172: You can use the full power of Forth for generating the code; here's an
3173: example where the code is generated in a loop:
3174:
3175: @example
3176: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3177: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3178: POSTPONE tuck POSTPONE @@
1.48 anton 3179: POSTPONE literal POSTPONE * POSTPONE +
3180: POSTPONE swap POSTPONE cell+ ;
3181:
3182: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3183: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3184: 0 postpone literal postpone swap
3185: [ ' compile-vmul-step compile-map-array ]
3186: postpone drop ;
3187: see compile-vmul
3188:
3189: : a-vmul ( addr -- n )
1.51 pazsan 3190: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3191: [ a 5 compile-vmul ] ;
3192: see a-vmul
3193: a a-vmul .
3194: @end example
3195:
3196: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3197: also use @code{map-array} instead (try it now!).
1.48 anton 3198:
3199: You can use this technique for efficient multiplication of large
3200: matrices. In matrix multiplication, you multiply every line of one
3201: matrix with every column of the other matrix. You can generate the code
3202: for one line once, and use it for every column. The only downside of
3203: this technique is that it is cumbersome to recover the memory consumed
3204: by the generated code when you are done (and in more complicated cases
3205: it is not possible portably).
3206:
1.66 anton 3207: @c !! @xref{Macros} for reference
3208:
3209:
1.48 anton 3210: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3211: @section Compilation Tokens
1.66 anton 3212: @cindex compilation tokens, tutorial
3213: @cindex CT, tutorial
1.48 anton 3214:
3215: This section is Gforth-specific. You can skip it.
3216:
3217: @code{' word compile,} compiles the interpretation semantics. For words
3218: with default compilation semantics this is the same as performing the
3219: compilation semantics. To represent the compilation semantics of other
3220: words (e.g., words like @code{if} that have no interpretation
3221: semantics), Gforth has the concept of a compilation token (CT,
3222: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3223: You can perform the compilation semantics represented by a CT with
3224: @code{execute}:
1.29 crook 3225:
1.48 anton 3226: @example
3227: : foo2 ( n1 n2 -- n )
3228: [ comp' + execute ] ;
3229: see foo
3230: @end example
1.29 crook 3231:
1.48 anton 3232: You can compile the compilation semantics represented by a CT with
3233: @code{postpone,}:
1.30 anton 3234:
1.48 anton 3235: @example
3236: : foo3 ( -- )
3237: [ comp' + postpone, ] ;
3238: see foo3
3239: @end example
1.30 anton 3240:
1.51 pazsan 3241: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3242: @code{comp'} is particularly useful for words that have no
3243: interpretation semantics:
1.29 crook 3244:
1.30 anton 3245: @example
1.48 anton 3246: ' if
1.60 anton 3247: comp' if .s 2drop
1.30 anton 3248: @end example
3249:
1.66 anton 3250: Reference: @ref{Tokens for Words}.
3251:
1.29 crook 3252:
1.48 anton 3253: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3254: @section Wordlists and Search Order
1.66 anton 3255: @cindex wordlists tutorial
3256: @cindex search order, tutorial
1.48 anton 3257:
3258: The dictionary is not just a memory area that allows you to allocate
3259: memory with @code{allot}, it also contains the Forth words, arranged in
3260: several wordlists. When searching for a word in a wordlist,
3261: conceptually you start searching at the youngest and proceed towards
3262: older words (in reality most systems nowadays use hash-tables); i.e., if
3263: you define a word with the same name as an older word, the new word
3264: shadows the older word.
3265:
3266: Which wordlists are searched in which order is determined by the search
3267: order. You can display the search order with @code{order}. It displays
3268: first the search order, starting with the wordlist searched first, then
3269: it displays the wordlist that will contain newly defined words.
1.21 crook 3270:
1.48 anton 3271: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3272:
1.48 anton 3273: @example
3274: wordlist constant mywords
3275: @end example
1.21 crook 3276:
1.48 anton 3277: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3278: defined words (the @emph{current} wordlist):
1.21 crook 3279:
1.48 anton 3280: @example
3281: mywords set-current
3282: order
3283: @end example
1.26 crook 3284:
1.48 anton 3285: Gforth does not display a name for the wordlist in @code{mywords}
3286: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3287:
1.48 anton 3288: You can get the current wordlist with @code{get-current ( -- wid)}. If
3289: you want to put something into a specific wordlist without overall
3290: effect on the current wordlist, this typically looks like this:
1.21 crook 3291:
1.48 anton 3292: @example
3293: get-current mywords set-current ( wid )
3294: create someword
3295: ( wid ) set-current
3296: @end example
1.21 crook 3297:
1.48 anton 3298: You can write the search order with @code{set-order ( wid1 .. widn n --
3299: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3300: searched wordlist is topmost.
1.21 crook 3301:
1.48 anton 3302: @example
3303: get-order mywords swap 1+ set-order
3304: order
3305: @end example
1.21 crook 3306:
1.48 anton 3307: Yes, the order of wordlists in the output of @code{order} is reversed
3308: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3309:
1.141 anton 3310: @quotation Assignment
1.48 anton 3311: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3312: wordlist to the search order. Define @code{previous ( -- )}, which
3313: removes the first searched wordlist from the search order. Experiment
3314: with boundary conditions (you will see some crashes or situations that
3315: are hard or impossible to leave).
1.141 anton 3316: @end quotation
1.21 crook 3317:
1.48 anton 3318: The search order is a powerful foundation for providing features similar
3319: to Modula-2 modules and C++ namespaces. However, trying to modularize
3320: programs in this way has disadvantages for debugging and reuse/factoring
3321: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3322: though). These disadvantages are not so clear in other
1.82 anton 3323: languages/programming environments, because these languages are not so
1.48 anton 3324: strong in debugging and reuse.
1.21 crook 3325:
1.66 anton 3326: @c !! example
3327:
3328: Reference: @ref{Word Lists}.
1.21 crook 3329:
1.29 crook 3330: @c ******************************************************************
1.48 anton 3331: @node Introduction, Words, Tutorial, Top
1.29 crook 3332: @comment node-name, next, previous, up
3333: @chapter An Introduction to ANS Forth
3334: @cindex Forth - an introduction
1.21 crook 3335:
1.83 anton 3336: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3337: that it is slower-paced in its examples, but uses them to dive deep into
3338: explaining Forth internals (not covered by the Tutorial). Apart from
3339: that, this chapter covers far less material. It is suitable for reading
3340: without using a computer.
3341:
1.29 crook 3342: The primary purpose of this manual is to document Gforth. However, since
3343: Forth is not a widely-known language and there is a lack of up-to-date
3344: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3345: material. For other sources of Forth-related
3346: information, see @ref{Forth-related information}.
1.21 crook 3347:
1.29 crook 3348: The examples in this section should work on any ANS Forth; the
3349: output shown was produced using Gforth. Each example attempts to
3350: reproduce the exact output that Gforth produces. If you try out the
3351: examples (and you should), what you should type is shown @kbd{like this}
3352: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3353: that, where the example shows @key{RET} it means that you should
1.29 crook 3354: press the ``carriage return'' key. Unfortunately, some output formats for
3355: this manual cannot show the difference between @kbd{this} and
3356: @code{this} which will make trying out the examples harder (but not
3357: impossible).
1.21 crook 3358:
1.29 crook 3359: Forth is an unusual language. It provides an interactive development
3360: environment which includes both an interpreter and compiler. Forth
3361: programming style encourages you to break a problem down into many
3362: @cindex factoring
3363: small fragments (@dfn{factoring}), and then to develop and test each
3364: fragment interactively. Forth advocates assert that breaking the
3365: edit-compile-test cycle used by conventional programming languages can
3366: lead to great productivity improvements.
1.21 crook 3367:
1.29 crook 3368: @menu
1.67 anton 3369: * Introducing the Text Interpreter::
3370: * Stacks and Postfix notation::
3371: * Your first definition::
3372: * How does that work?::
3373: * Forth is written in Forth::
3374: * Review - elements of a Forth system::
3375: * Where to go next::
3376: * Exercises::
1.29 crook 3377: @end menu
1.21 crook 3378:
1.29 crook 3379: @comment ----------------------------------------------
3380: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3381: @section Introducing the Text Interpreter
3382: @cindex text interpreter
3383: @cindex outer interpreter
1.21 crook 3384:
1.30 anton 3385: @c IMO this is too detailed and the pace is too slow for
3386: @c an introduction. If you know German, take a look at
3387: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3388: @c to see how I do it - anton
3389:
1.44 crook 3390: @c nac-> Where I have accepted your comments 100% and modified the text
3391: @c accordingly, I have deleted your comments. Elsewhere I have added a
3392: @c response like this to attempt to rationalise what I have done. Of
3393: @c course, this is a very clumsy mechanism for something that would be
3394: @c done far more efficiently over a beer. Please delete any dialogue
3395: @c you consider closed.
3396:
1.29 crook 3397: When you invoke the Forth image, you will see a startup banner printed
3398: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3399: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3400: its command line interpreter, which is called the @dfn{Text Interpreter}
3401: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3402: about the text interpreter as you read through this chapter, for more
3403: detail @pxref{The Text Interpreter}).
1.21 crook 3404:
1.29 crook 3405: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3406: input. Type a number and press the @key{RET} key:
1.21 crook 3407:
1.26 crook 3408: @example
1.30 anton 3409: @kbd{45@key{RET}} ok
1.26 crook 3410: @end example
1.21 crook 3411:
1.29 crook 3412: Rather than give you a prompt to invite you to input something, the text
3413: interpreter prints a status message @i{after} it has processed a line
3414: of input. The status message in this case (``@code{ ok}'' followed by
3415: carriage-return) indicates that the text interpreter was able to process
3416: all of your input successfully. Now type something illegal:
3417:
3418: @example
1.30 anton 3419: @kbd{qwer341@key{RET}}
1.134 anton 3420: *the terminal*:2: Undefined word
3421: >>>qwer341<<<
3422: Backtrace:
3423: $2A95B42A20 throw
3424: $2A95B57FB8 no.extensions
1.29 crook 3425: @end example
1.23 crook 3426:
1.134 anton 3427: The exact text, other than the ``Undefined word'' may differ slightly
3428: on your system, but the effect is the same; when the text interpreter
1.29 crook 3429: detects an error, it discards any remaining text on a line, resets
1.134 anton 3430: certain internal state and prints an error message. For a detailed
3431: description of error messages see @ref{Error messages}.
1.23 crook 3432:
1.29 crook 3433: The text interpreter waits for you to press carriage-return, and then
3434: processes your input line. Starting at the beginning of the line, it
3435: breaks the line into groups of characters separated by spaces. For each
3436: group of characters in turn, it makes two attempts to do something:
1.23 crook 3437:
1.29 crook 3438: @itemize @bullet
3439: @item
1.44 crook 3440: @cindex name dictionary
1.29 crook 3441: It tries to treat it as a command. It does this by searching a @dfn{name
3442: dictionary}. If the group of characters matches an entry in the name
3443: dictionary, the name dictionary provides the text interpreter with
3444: information that allows the text interpreter perform some actions. In
3445: Forth jargon, we say that the group
3446: @cindex word
3447: @cindex definition
3448: @cindex execution token
3449: @cindex xt
3450: of characters names a @dfn{word}, that the dictionary search returns an
3451: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3452: word, and that the text interpreter executes the xt. Often, the terms
3453: @dfn{word} and @dfn{definition} are used interchangeably.
3454: @item
3455: If the text interpreter fails to find a match in the name dictionary, it
3456: tries to treat the group of characters as a number in the current number
3457: base (when you start up Forth, the current number base is base 10). If
3458: the group of characters legitimately represents a number, the text
3459: interpreter pushes the number onto a stack (we'll learn more about that
3460: in the next section).
3461: @end itemize
1.23 crook 3462:
1.29 crook 3463: If the text interpreter is unable to do either of these things with any
3464: group of characters, it discards the group of characters and the rest of
3465: the line, then prints an error message. If the text interpreter reaches
3466: the end of the line without error, it prints the status message ``@code{ ok}''
3467: followed by carriage-return.
1.21 crook 3468:
1.29 crook 3469: This is the simplest command we can give to the text interpreter:
1.23 crook 3470:
3471: @example
1.30 anton 3472: @key{RET} ok
1.23 crook 3473: @end example
1.21 crook 3474:
1.29 crook 3475: The text interpreter did everything we asked it to do (nothing) without
3476: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3477: command:
1.21 crook 3478:
1.23 crook 3479: @example
1.30 anton 3480: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3481: *the terminal*:3: Undefined word
3482: 12 dup >>>fred<<< dup
3483: Backtrace:
3484: $2A95B42A20 throw
3485: $2A95B57FB8 no.extensions
1.23 crook 3486: @end example
1.21 crook 3487:
1.29 crook 3488: When you press the carriage-return key, the text interpreter starts to
3489: work its way along the line:
1.21 crook 3490:
1.29 crook 3491: @itemize @bullet
3492: @item
3493: When it gets to the space after the @code{2}, it takes the group of
3494: characters @code{12} and looks them up in the name
3495: dictionary@footnote{We can't tell if it found them or not, but assume
3496: for now that it did not}. There is no match for this group of characters
3497: in the name dictionary, so it tries to treat them as a number. It is
3498: able to do this successfully, so it puts the number, 12, ``on the stack''
3499: (whatever that means).
3500: @item
3501: The text interpreter resumes scanning the line and gets the next group
3502: of characters, @code{dup}. It looks it up in the name dictionary and
3503: (you'll have to take my word for this) finds it, and executes the word
3504: @code{dup} (whatever that means).
3505: @item
3506: Once again, the text interpreter resumes scanning the line and gets the
3507: group of characters @code{fred}. It looks them up in the name
3508: dictionary, but can't find them. It tries to treat them as a number, but
3509: they don't represent any legal number.
3510: @end itemize
1.21 crook 3511:
1.29 crook 3512: At this point, the text interpreter gives up and prints an error
3513: message. The error message shows exactly how far the text interpreter
3514: got in processing the line. In particular, it shows that the text
3515: interpreter made no attempt to do anything with the final character
3516: group, @code{dup}, even though we have good reason to believe that the
3517: text interpreter would have no problem looking that word up and
3518: executing it a second time.
1.21 crook 3519:
3520:
1.29 crook 3521: @comment ----------------------------------------------
3522: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3523: @section Stacks, postfix notation and parameter passing
3524: @cindex text interpreter
3525: @cindex outer interpreter
1.21 crook 3526:
1.29 crook 3527: In procedural programming languages (like C and Pascal), the
3528: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3529: functions or procedures are called with @dfn{explicit parameters}. For
3530: example, in C we might write:
1.21 crook 3531:
1.23 crook 3532: @example
1.29 crook 3533: total = total + new_volume(length,height,depth);
1.23 crook 3534: @end example
1.21 crook 3535:
1.23 crook 3536: @noindent
1.29 crook 3537: where new_volume is a function-call to another piece of code, and total,
3538: length, height and depth are all variables. length, height and depth are
3539: parameters to the function-call.
1.21 crook 3540:
1.29 crook 3541: In Forth, the equivalent of the function or procedure is the
3542: @dfn{definition} and parameters are implicitly passed between
3543: definitions using a shared stack that is visible to the
3544: programmer. Although Forth does support variables, the existence of the
3545: stack means that they are used far less often than in most other
3546: programming languages. When the text interpreter encounters a number, it
3547: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3548: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3549: used for any operation is implied unambiguously by the operation being
3550: performed. The stack used for all integer operations is called the @dfn{data
3551: stack} and, since this is the stack used most commonly, references to
3552: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3553:
1.29 crook 3554: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3555:
1.23 crook 3556: @example
1.30 anton 3557: @kbd{1 2 3@key{RET}} ok
1.23 crook 3558: @end example
1.21 crook 3559:
1.29 crook 3560: Then this instructs the text interpreter to placed three numbers on the
3561: (data) stack. An analogy for the behaviour of the stack is to take a
3562: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3563: the table. The 3 was the last card onto the pile (``last-in'') and if
3564: you take a card off the pile then, unless you're prepared to fiddle a
3565: bit, the card that you take off will be the 3 (``first-out''). The
3566: number that will be first-out of the stack is called the @dfn{top of
3567: stack}, which
3568: @cindex TOS definition
3569: is often abbreviated to @dfn{TOS}.
1.21 crook 3570:
1.29 crook 3571: To understand how parameters are passed in Forth, consider the
3572: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3573: be surprised to learn that this definition performs addition. More
3574: precisely, it adds two number together and produces a result. Where does
3575: it get the two numbers from? It takes the top two numbers off the
3576: stack. Where does it place the result? On the stack. You can act-out the
3577: behaviour of @code{+} with your playing cards like this:
1.21 crook 3578:
3579: @itemize @bullet
3580: @item
1.29 crook 3581: Pick up two cards from the stack on the table
1.21 crook 3582: @item
1.29 crook 3583: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3584: numbers''
1.21 crook 3585: @item
1.29 crook 3586: Decide that the answer is 5
1.21 crook 3587: @item
1.29 crook 3588: Shuffle the two cards back into the pack and find a 5
1.21 crook 3589: @item
1.29 crook 3590: Put a 5 on the remaining ace that's on the table.
1.21 crook 3591: @end itemize
3592:
1.29 crook 3593: If you don't have a pack of cards handy but you do have Forth running,
3594: you can use the definition @code{.s} to show the current state of the stack,
3595: without affecting the stack. Type:
1.21 crook 3596:
3597: @example
1.124 anton 3598: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3599: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3600: @end example
3601:
1.124 anton 3602: The text interpreter looks up the word @code{clearstacks} and executes
3603: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3604: left on it by earlier examples. The text interpreter pushes each of the
3605: three numbers in turn onto the stack. Finally, the text interpreter
3606: looks up the word @code{.s} and executes it. The effect of executing
3607: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3608: followed by a list of all the items on the stack; the item on the far
3609: right-hand side is the TOS.
1.21 crook 3610:
1.29 crook 3611: You can now type:
1.21 crook 3612:
1.29 crook 3613: @example
1.30 anton 3614: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3615: @end example
1.21 crook 3616:
1.29 crook 3617: @noindent
3618: which is correct; there are now 2 items on the stack and the result of
3619: the addition is 5.
1.23 crook 3620:
1.29 crook 3621: If you're playing with cards, try doing a second addition: pick up the
3622: two cards, work out that their sum is 6, shuffle them into the pack,
3623: look for a 6 and place that on the table. You now have just one item on
3624: the stack. What happens if you try to do a third addition? Pick up the
3625: first card, pick up the second card -- ah! There is no second card. This
3626: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3627: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3628: Underflow or an Invalid Memory Address error).
1.23 crook 3629:
1.29 crook 3630: The opposite situation to a stack underflow is a @dfn{stack overflow},
3631: which simply accepts that there is a finite amount of storage space
3632: reserved for the stack. To stretch the playing card analogy, if you had
3633: enough packs of cards and you piled the cards up on the table, you would
3634: eventually be unable to add another card; you'd hit the ceiling. Gforth
3635: allows you to set the maximum size of the stacks. In general, the only
3636: time that you will get a stack overflow is because a definition has a
3637: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3638:
1.29 crook 3639: There's one final use for the playing card analogy. If you model your
3640: stack using a pack of playing cards, the maximum number of items on
3641: your stack will be 52 (I assume you didn't use the Joker). The maximum
3642: @i{value} of any item on the stack is 13 (the King). In fact, the only
3643: possible numbers are positive integer numbers 1 through 13; you can't
3644: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3645: think about some of the cards, you can accommodate different
3646: numbers. For example, you could think of the Jack as representing 0,
3647: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3648: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3649: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3650:
1.29 crook 3651: In that analogy, the limit was the amount of information that a single
3652: stack entry could hold, and Forth has a similar limit. In Forth, the
3653: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3654: implementation dependent and affects the maximum value that a stack
3655: entry can hold. A Standard Forth provides a cell size of at least
3656: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3657:
1.29 crook 3658: Forth does not do any type checking for you, so you are free to
3659: manipulate and combine stack items in any way you wish. A convenient way
3660: of treating stack items is as 2's complement signed integers, and that
3661: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3662:
1.29 crook 3663: @example
1.30 anton 3664: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3665: @end example
1.21 crook 3666:
1.29 crook 3667: If you use numbers and definitions like @code{+} in order to turn Forth
3668: into a great big pocket calculator, you will realise that it's rather
3669: different from a normal calculator. Rather than typing 2 + 3 = you had
3670: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3671: result). The terminology used to describe this difference is to say that
3672: your calculator uses @dfn{Infix Notation} (parameters and operators are
3673: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3674: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3675:
1.29 crook 3676: Whilst postfix notation might look confusing to begin with, it has
3677: several important advantages:
1.21 crook 3678:
1.23 crook 3679: @itemize @bullet
3680: @item
1.29 crook 3681: it is unambiguous
1.23 crook 3682: @item
1.29 crook 3683: it is more concise
1.23 crook 3684: @item
1.29 crook 3685: it fits naturally with a stack-based system
1.23 crook 3686: @end itemize
1.21 crook 3687:
1.29 crook 3688: To examine these claims in more detail, consider these sums:
1.21 crook 3689:
1.29 crook 3690: @example
3691: 6 + 5 * 4 =
3692: 4 * 5 + 6 =
3693: @end example
1.21 crook 3694:
1.29 crook 3695: If you're just learning maths or your maths is very rusty, you will
3696: probably come up with the answer 44 for the first and 26 for the
3697: second. If you are a bit of a whizz at maths you will remember the
3698: @i{convention} that multiplication takes precendence over addition, and
3699: you'd come up with the answer 26 both times. To explain the answer 26
3700: to someone who got the answer 44, you'd probably rewrite the first sum
3701: like this:
1.21 crook 3702:
1.29 crook 3703: @example
3704: 6 + (5 * 4) =
3705: @end example
1.21 crook 3706:
1.29 crook 3707: If what you really wanted was to perform the addition before the
3708: multiplication, you would have to use parentheses to force it.
1.21 crook 3709:
1.29 crook 3710: If you did the first two sums on a pocket calculator you would probably
3711: get the right answers, unless you were very cautious and entered them using
3712: these keystroke sequences:
1.21 crook 3713:
1.29 crook 3714: 6 + 5 = * 4 =
3715: 4 * 5 = + 6 =
1.21 crook 3716:
1.29 crook 3717: Postfix notation is unambiguous because the order that the operators
3718: are applied is always explicit; that also means that parentheses are
3719: never required. The operators are @i{active} (the act of quoting the
3720: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3721:
1.29 crook 3722: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3723: equivalent ways:
1.26 crook 3724:
3725: @example
1.29 crook 3726: 6 5 4 * + or:
3727: 5 4 * 6 +
1.26 crook 3728: @end example
1.23 crook 3729:
1.29 crook 3730: An important thing that you should notice about this notation is that
3731: the @i{order} of the numbers does not change; if you want to subtract
3732: 2 from 10 you type @code{10 2 -}.
1.1 anton 3733:
1.29 crook 3734: The reason that Forth uses postfix notation is very simple to explain: it
3735: makes the implementation extremely simple, and it follows naturally from
3736: using the stack as a mechanism for passing parameters. Another way of
3737: thinking about this is to realise that all Forth definitions are
3738: @i{active}; they execute as they are encountered by the text
3739: interpreter. The result of this is that the syntax of Forth is trivially
3740: simple.
1.1 anton 3741:
3742:
3743:
1.29 crook 3744: @comment ----------------------------------------------
3745: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3746: @section Your first Forth definition
3747: @cindex first definition
1.1 anton 3748:
1.29 crook 3749: Until now, the examples we've seen have been trivial; we've just been
3750: using Forth as a bigger-than-pocket calculator. Also, each calculation
3751: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3752: again@footnote{That's not quite true. If you press the up-arrow key on
3753: your keyboard you should be able to scroll back to any earlier command,
3754: edit it and re-enter it.} In this section we'll see how to add new
3755: words to Forth's vocabulary.
1.1 anton 3756:
1.29 crook 3757: The easiest way to create a new word is to use a @dfn{colon
3758: definition}. We'll define a few and try them out before worrying too
3759: much about how they work. Try typing in these examples; be careful to
3760: copy the spaces accurately:
1.1 anton 3761:
1.29 crook 3762: @example
3763: : add-two 2 + . ;
3764: : greet ." Hello and welcome" ;
3765: : demo 5 add-two ;
3766: @end example
1.1 anton 3767:
1.29 crook 3768: @noindent
3769: Now try them out:
1.1 anton 3770:
1.29 crook 3771: @example
1.30 anton 3772: @kbd{greet@key{RET}} Hello and welcome ok
3773: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3774: @kbd{4 add-two@key{RET}} 6 ok
3775: @kbd{demo@key{RET}} 7 ok
3776: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3777: @end example
1.1 anton 3778:
1.29 crook 3779: The first new thing that we've introduced here is the pair of words
3780: @code{:} and @code{;}. These are used to start and terminate a new
3781: definition, respectively. The first word after the @code{:} is the name
3782: for the new definition.
1.1 anton 3783:
1.29 crook 3784: As you can see from the examples, a definition is built up of words that
3785: have already been defined; Forth makes no distinction between
3786: definitions that existed when you started the system up, and those that
3787: you define yourself.
1.1 anton 3788:
1.29 crook 3789: The examples also introduce the words @code{.} (dot), @code{."}
3790: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3791: the stack and displays it. It's like @code{.s} except that it only
3792: displays the top item of the stack and it is destructive; after it has
3793: executed, the number is no longer on the stack. There is always one
3794: space printed after the number, and no spaces before it. Dot-quote
3795: defines a string (a sequence of characters) that will be printed when
3796: the word is executed. The string can contain any printable characters
3797: except @code{"}. A @code{"} has a special function; it is not a Forth
3798: word but it acts as a delimiter (the way that delimiters work is
3799: described in the next section). Finally, @code{dup} duplicates the value
3800: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3801:
1.29 crook 3802: We already know that the text interpreter searches through the
3803: dictionary to locate names. If you've followed the examples earlier, you
3804: will already have a definition called @code{add-two}. Lets try modifying
3805: it by typing in a new definition:
1.1 anton 3806:
1.29 crook 3807: @example
1.30 anton 3808: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3809: @end example
1.5 anton 3810:
1.29 crook 3811: Forth recognised that we were defining a word that already exists, and
3812: printed a message to warn us of that fact. Let's try out the new
3813: definition:
1.5 anton 3814:
1.29 crook 3815: @example
1.30 anton 3816: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3817: @end example
1.1 anton 3818:
1.29 crook 3819: @noindent
3820: All that we've actually done here, though, is to create a new
3821: definition, with a particular name. The fact that there was already a
3822: definition with the same name did not make any difference to the way
3823: that the new definition was created (except that Forth printed a warning
3824: message). The old definition of add-two still exists (try @code{demo}
3825: again to see that this is true). Any new definition will use the new
3826: definition of @code{add-two}, but old definitions continue to use the
3827: version that already existed at the time that they were @code{compiled}.
1.1 anton 3828:
1.29 crook 3829: Before you go on to the next section, try defining and redefining some
3830: words of your own.
1.1 anton 3831:
1.29 crook 3832: @comment ----------------------------------------------
3833: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3834: @section How does that work?
3835: @cindex parsing words
1.1 anton 3836:
1.30 anton 3837: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3838:
3839: @c Is it a good idea to talk about the interpretation semantics of a
3840: @c number? We don't have an xt to go along with it. - anton
3841:
3842: @c Now that I have eliminated execution semantics, I wonder if it would not
3843: @c be better to keep them (or add run-time semantics), to make it easier to
3844: @c explain what compilation semantics usually does. - anton
3845:
1.44 crook 3846: @c nac-> I removed the term ``default compilation sematics'' from the
3847: @c introductory chapter. Removing ``execution semantics'' was making
3848: @c everything simpler to explain, then I think the use of this term made
3849: @c everything more complex again. I replaced it with ``default
3850: @c semantics'' (which is used elsewhere in the manual) by which I mean
3851: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3852: @c flag set''.
3853:
3854: @c anton: I have eliminated default semantics (except in one place where it
3855: @c means "default interpretation and compilation semantics"), because it
3856: @c makes no sense in the presence of combined words. I reverted to
3857: @c "execution semantics" where necessary.
3858:
3859: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3860: @c section (and, unusually for me, I think I even made it shorter!). See
3861: @c what you think -- I know I have not addressed your primary concern
3862: @c that it is too heavy-going for an introduction. From what I understood
3863: @c of your course notes it looks as though they might be a good framework.
3864: @c Things that I've tried to capture here are some things that came as a
3865: @c great revelation here when I first understood them. Also, I like the
3866: @c fact that a very simple code example shows up almost all of the issues
3867: @c that you need to understand to see how Forth works. That's unique and
3868: @c worthwhile to emphasise.
3869:
1.83 anton 3870: @c anton: I think it's a good idea to present the details, especially those
3871: @c that you found to be a revelation, and probably the tutorial tries to be
3872: @c too superficial and does not get some of the things across that make
3873: @c Forth special. I do believe that most of the time these things should
3874: @c be discussed at the end of a section or in separate sections instead of
3875: @c in the middle of a section (e.g., the stuff you added in "User-defined
3876: @c defining words" leads in a completely different direction from the rest
3877: @c of the section).
3878:
1.29 crook 3879: Now we're going to take another look at the definition of @code{add-two}
3880: from the previous section. From our knowledge of the way that the text
3881: interpreter works, we would have expected this result when we tried to
3882: define @code{add-two}:
1.21 crook 3883:
1.29 crook 3884: @example
1.44 crook 3885: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3886: *the terminal*:4: Undefined word
3887: : >>>add-two<<< 2 + . ;
1.29 crook 3888: @end example
1.28 crook 3889:
1.29 crook 3890: The reason that this didn't happen is bound up in the way that @code{:}
3891: works. The word @code{:} does two special things. The first special
3892: thing that it does prevents the text interpreter from ever seeing the
3893: characters @code{add-two}. The text interpreter uses a variable called
3894: @cindex modifying >IN
1.44 crook 3895: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3896: input line. When it encounters the word @code{:} it behaves in exactly
3897: the same way as it does for any other word; it looks it up in the name
3898: dictionary, finds its xt and executes it. When @code{:} executes, it
3899: looks at the input buffer, finds the word @code{add-two} and advances the
3900: value of @code{>IN} to point past it. It then does some other stuff
3901: associated with creating the new definition (including creating an entry
3902: for @code{add-two} in the name dictionary). When the execution of @code{:}
3903: completes, control returns to the text interpreter, which is oblivious
3904: to the fact that it has been tricked into ignoring part of the input
3905: line.
1.21 crook 3906:
1.29 crook 3907: @cindex parsing words
3908: Words like @code{:} -- words that advance the value of @code{>IN} and so
3909: prevent the text interpreter from acting on the whole of the input line
3910: -- are called @dfn{parsing words}.
1.21 crook 3911:
1.29 crook 3912: @cindex @code{state} - effect on the text interpreter
3913: @cindex text interpreter - effect of state
3914: The second special thing that @code{:} does is change the value of a
3915: variable called @code{state}, which affects the way that the text
3916: interpreter behaves. When Gforth starts up, @code{state} has the value
3917: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3918: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3919: the text interpreter is said to be @dfn{compiling}.
3920:
3921: In this example, the text interpreter is compiling when it processes the
3922: string ``@code{2 + . ;}''. It still breaks the string down into
3923: character sequences in the same way. However, instead of pushing the
3924: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3925: into the definition of @code{add-two} that will make the number @code{2} get
3926: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3927: the behaviours of @code{+} and @code{.} are also compiled into the
3928: definition.
3929:
3930: One category of words don't get compiled. These so-called @dfn{immediate
3931: words} get executed (performed @i{now}) regardless of whether the text
3932: interpreter is interpreting or compiling. The word @code{;} is an
3933: immediate word. Rather than being compiled into the definition, it
3934: executes. Its effect is to terminate the current definition, which
3935: includes changing the value of @code{state} back to 0.
3936:
3937: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3938: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3939: definition.
1.28 crook 3940:
1.30 anton 3941: In Forth, every word or number can be described in terms of two
1.29 crook 3942: properties:
1.28 crook 3943:
3944: @itemize @bullet
3945: @item
1.29 crook 3946: @cindex interpretation semantics
1.44 crook 3947: Its @dfn{interpretation semantics} describe how it will behave when the
3948: text interpreter encounters it in @dfn{interpret} state. The
3949: interpretation semantics of a word are represented by an @dfn{execution
3950: token}.
1.28 crook 3951: @item
1.29 crook 3952: @cindex compilation semantics
1.44 crook 3953: Its @dfn{compilation semantics} describe how it will behave when the
3954: text interpreter encounters it in @dfn{compile} state. The compilation
3955: semantics of a word are represented in an implementation-dependent way;
3956: Gforth uses a @dfn{compilation token}.
1.29 crook 3957: @end itemize
3958:
3959: @noindent
3960: Numbers are always treated in a fixed way:
3961:
3962: @itemize @bullet
1.28 crook 3963: @item
1.44 crook 3964: When the number is @dfn{interpreted}, its behaviour is to push the
3965: number onto the stack.
1.28 crook 3966: @item
1.30 anton 3967: When the number is @dfn{compiled}, a piece of code is appended to the
3968: current definition that pushes the number when it runs. (In other words,
3969: the compilation semantics of a number are to postpone its interpretation
3970: semantics until the run-time of the definition that it is being compiled
3971: into.)
1.29 crook 3972: @end itemize
3973:
1.44 crook 3974: Words don't behave in such a regular way, but most have @i{default
3975: semantics} which means that they behave like this:
1.29 crook 3976:
3977: @itemize @bullet
1.28 crook 3978: @item
1.30 anton 3979: The @dfn{interpretation semantics} of the word are to do something useful.
3980: @item
1.29 crook 3981: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3982: @dfn{interpretation semantics} to the current definition (so that its
3983: run-time behaviour is to do something useful).
1.28 crook 3984: @end itemize
3985:
1.30 anton 3986: @cindex immediate words
1.44 crook 3987: The actual behaviour of any particular word can be controlled by using
3988: the words @code{immediate} and @code{compile-only} when the word is
3989: defined. These words set flags in the name dictionary entry of the most
3990: recently defined word, and these flags are retrieved by the text
3991: interpreter when it finds the word in the name dictionary.
3992:
3993: A word that is marked as @dfn{immediate} has compilation semantics that
3994: are identical to its interpretation semantics. In other words, it
3995: behaves like this:
1.29 crook 3996:
3997: @itemize @bullet
3998: @item
1.30 anton 3999: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4000: @item
1.30 anton 4001: The @dfn{compilation semantics} of the word are to do something useful
4002: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4003: @end itemize
1.28 crook 4004:
1.44 crook 4005: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4006: performing the interpretation semantics of the word directly; an attempt
4007: to do so will generate an error. It is never necessary to use
4008: @code{compile-only} (and it is not even part of ANS Forth, though it is
4009: provided by many implementations) but it is good etiquette to apply it
4010: to a word that will not behave correctly (and might have unexpected
4011: side-effects) in interpret state. For example, it is only legal to use
4012: the conditional word @code{IF} within a definition. If you forget this
4013: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4014: @code{compile-only} allows the text interpreter to generate a helpful
4015: error message rather than subjecting you to the consequences of your
4016: folly.
4017:
1.29 crook 4018: This example shows the difference between an immediate and a
4019: non-immediate word:
1.28 crook 4020:
1.29 crook 4021: @example
4022: : show-state state @@ . ;
4023: : show-state-now show-state ; immediate
4024: : word1 show-state ;
4025: : word2 show-state-now ;
1.28 crook 4026: @end example
1.23 crook 4027:
1.29 crook 4028: The word @code{immediate} after the definition of @code{show-state-now}
4029: makes that word an immediate word. These definitions introduce a new
4030: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4031: variable, and leaves it on the stack. Therefore, the behaviour of
4032: @code{show-state} is to print a number that represents the current value
4033: of @code{state}.
1.28 crook 4034:
1.29 crook 4035: When you execute @code{word1}, it prints the number 0, indicating that
4036: the system is interpreting. When the text interpreter compiled the
4037: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4038: compilation semantics are to append its interpretation semantics to the
1.29 crook 4039: current definition. When you execute @code{word1}, it performs the
1.30 anton 4040: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4041: (and therefore @code{show-state}) are executed, the system is
4042: interpreting.
1.28 crook 4043:
1.30 anton 4044: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4045: you should have seen the number -1 printed, followed by ``@code{
4046: ok}''. When the text interpreter compiled the definition of
4047: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4048: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4049: semantics. It is executed straight away (even before the text
4050: interpreter has moved on to process another group of characters; the
4051: @code{;} in this example). The effect of executing it are to display the
4052: value of @code{state} @i{at the time that the definition of}
4053: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4054: system is compiling at this time. If you execute @code{word2} it does
4055: nothing at all.
1.28 crook 4056:
1.29 crook 4057: @cindex @code{."}, how it works
4058: Before leaving the subject of immediate words, consider the behaviour of
4059: @code{."} in the definition of @code{greet}, in the previous
4060: section. This word is both a parsing word and an immediate word. Notice
4061: that there is a space between @code{."} and the start of the text
4062: @code{Hello and welcome}, but that there is no space between the last
4063: letter of @code{welcome} and the @code{"} character. The reason for this
4064: is that @code{."} is a Forth word; it must have a space after it so that
4065: the text interpreter can identify it. The @code{"} is not a Forth word;
4066: it is a @dfn{delimiter}. The examples earlier show that, when the string
4067: is displayed, there is neither a space before the @code{H} nor after the
4068: @code{e}. Since @code{."} is an immediate word, it executes at the time
4069: that @code{greet} is defined. When it executes, its behaviour is to
4070: search forward in the input line looking for the delimiter. When it
4071: finds the delimiter, it updates @code{>IN} to point past the
4072: delimiter. It also compiles some magic code into the definition of
4073: @code{greet}; the xt of a run-time routine that prints a text string. It
4074: compiles the string @code{Hello and welcome} into memory so that it is
4075: available to be printed later. When the text interpreter gains control,
4076: the next word it finds in the input stream is @code{;} and so it
4077: terminates the definition of @code{greet}.
1.28 crook 4078:
4079:
4080: @comment ----------------------------------------------
1.29 crook 4081: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4082: @section Forth is written in Forth
4083: @cindex structure of Forth programs
4084:
4085: When you start up a Forth compiler, a large number of definitions
4086: already exist. In Forth, you develop a new application using bottom-up
4087: programming techniques to create new definitions that are defined in
4088: terms of existing definitions. As you create each definition you can
4089: test and debug it interactively.
4090:
4091: If you have tried out the examples in this section, you will probably
4092: have typed them in by hand; when you leave Gforth, your definitions will
4093: be lost. You can avoid this by using a text editor to enter Forth source
4094: code into a file, and then loading code from the file using
1.49 anton 4095: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4096: processed by the text interpreter, just as though you had typed it in by
4097: hand@footnote{Actually, there are some subtle differences -- see
4098: @ref{The Text Interpreter}.}.
4099:
4100: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4101: files for program entry (@pxref{Blocks}).
1.28 crook 4102:
1.29 crook 4103: In common with many, if not most, Forth compilers, most of Gforth is
4104: actually written in Forth. All of the @file{.fs} files in the
4105: installation directory@footnote{For example,
1.30 anton 4106: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4107: study to see examples of Forth programming.
1.28 crook 4108:
1.29 crook 4109: Gforth maintains a history file that records every line that you type to
4110: the text interpreter. This file is preserved between sessions, and is
4111: used to provide a command-line recall facility. If you enter long
4112: definitions by hand, you can use a text editor to paste them out of the
4113: history file into a Forth source file for reuse at a later time
1.49 anton 4114: (for more information @pxref{Command-line editing}).
1.28 crook 4115:
4116:
4117: @comment ----------------------------------------------
1.29 crook 4118: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4119: @section Review - elements of a Forth system
4120: @cindex elements of a Forth system
1.28 crook 4121:
1.29 crook 4122: To summarise this chapter:
1.28 crook 4123:
4124: @itemize @bullet
4125: @item
1.29 crook 4126: Forth programs use @dfn{factoring} to break a problem down into small
4127: fragments called @dfn{words} or @dfn{definitions}.
4128: @item
4129: Forth program development is an interactive process.
4130: @item
4131: The main command loop that accepts input, and controls both
4132: interpretation and compilation, is called the @dfn{text interpreter}
4133: (also known as the @dfn{outer interpreter}).
4134: @item
4135: Forth has a very simple syntax, consisting of words and numbers
4136: separated by spaces or carriage-return characters. Any additional syntax
4137: is imposed by @dfn{parsing words}.
4138: @item
4139: Forth uses a stack to pass parameters between words. As a result, it
4140: uses postfix notation.
4141: @item
4142: To use a word that has previously been defined, the text interpreter
4143: searches for the word in the @dfn{name dictionary}.
4144: @item
1.30 anton 4145: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4146: @item
1.29 crook 4147: The text interpreter uses the value of @code{state} to select between
4148: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4149: semantics} of a word that it encounters.
1.28 crook 4150: @item
1.30 anton 4151: The relationship between the @dfn{interpretation semantics} and
4152: @dfn{compilation semantics} for a word
1.29 crook 4153: depend upon the way in which the word was defined (for example, whether
4154: it is an @dfn{immediate} word).
1.28 crook 4155: @item
1.29 crook 4156: Forth definitions can be implemented in Forth (called @dfn{high-level
4157: definitions}) or in some other way (usually a lower-level language and
4158: as a result often called @dfn{low-level definitions}, @dfn{code
4159: definitions} or @dfn{primitives}).
1.28 crook 4160: @item
1.29 crook 4161: Many Forth systems are implemented mainly in Forth.
1.28 crook 4162: @end itemize
4163:
4164:
1.29 crook 4165: @comment ----------------------------------------------
1.48 anton 4166: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4167: @section Where To Go Next
4168: @cindex where to go next
1.28 crook 4169:
1.29 crook 4170: Amazing as it may seem, if you have read (and understood) this far, you
4171: know almost all the fundamentals about the inner workings of a Forth
4172: system. You certainly know enough to be able to read and understand the
4173: rest of this manual and the ANS Forth document, to learn more about the
4174: facilities that Forth in general and Gforth in particular provide. Even
4175: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4176: However, that's not a good idea just yet... better to try writing some
1.29 crook 4177: programs in Gforth.
1.28 crook 4178:
1.29 crook 4179: Forth has such a rich vocabulary that it can be hard to know where to
4180: start in learning it. This section suggests a few sets of words that are
4181: enough to write small but useful programs. Use the word index in this
4182: document to learn more about each word, then try it out and try to write
4183: small definitions using it. Start by experimenting with these words:
1.28 crook 4184:
4185: @itemize @bullet
4186: @item
1.29 crook 4187: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4188: @item
4189: Comparison: @code{MIN MAX =}
4190: @item
4191: Logic: @code{AND OR XOR NOT}
4192: @item
4193: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4194: @item
1.29 crook 4195: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4196: @item
1.29 crook 4197: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4198: @item
1.29 crook 4199: Defining words: @code{: ; CREATE}
1.28 crook 4200: @item
1.29 crook 4201: Memory allocation words: @code{ALLOT ,}
1.28 crook 4202: @item
1.29 crook 4203: Tools: @code{SEE WORDS .S MARKER}
4204: @end itemize
4205:
4206: When you have mastered those, go on to:
4207:
4208: @itemize @bullet
1.28 crook 4209: @item
1.29 crook 4210: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4211: @item
1.29 crook 4212: Memory access: @code{@@ !}
1.28 crook 4213: @end itemize
1.23 crook 4214:
1.29 crook 4215: When you have mastered these, there's nothing for it but to read through
4216: the whole of this manual and find out what you've missed.
4217:
4218: @comment ----------------------------------------------
1.48 anton 4219: @node Exercises, , Where to go next, Introduction
1.29 crook 4220: @section Exercises
4221: @cindex exercises
4222:
4223: TODO: provide a set of programming excercises linked into the stuff done
4224: already and into other sections of the manual. Provide solutions to all
4225: the exercises in a .fs file in the distribution.
4226:
4227: @c Get some inspiration from Starting Forth and Kelly&Spies.
4228:
4229: @c excercises:
4230: @c 1. take inches and convert to feet and inches.
4231: @c 2. take temperature and convert from fahrenheight to celcius;
4232: @c may need to care about symmetric vs floored??
4233: @c 3. take input line and do character substitution
4234: @c to encipher or decipher
4235: @c 4. as above but work on a file for in and out
4236: @c 5. take input line and convert to pig-latin
4237: @c
4238: @c thing of sets of things to exercise then come up with
4239: @c problems that need those things.
4240:
4241:
1.26 crook 4242: @c ******************************************************************
1.29 crook 4243: @node Words, Error messages, Introduction, Top
1.1 anton 4244: @chapter Forth Words
1.26 crook 4245: @cindex words
1.1 anton 4246:
4247: @menu
4248: * Notation::
1.65 anton 4249: * Case insensitivity::
4250: * Comments::
4251: * Boolean Flags::
1.1 anton 4252: * Arithmetic::
4253: * Stack Manipulation::
1.5 anton 4254: * Memory::
1.1 anton 4255: * Control Structures::
4256: * Defining Words::
1.65 anton 4257: * Interpretation and Compilation Semantics::
1.47 crook 4258: * Tokens for Words::
1.81 anton 4259: * Compiling words::
1.65 anton 4260: * The Text Interpreter::
1.111 anton 4261: * The Input Stream::
1.65 anton 4262: * Word Lists::
4263: * Environmental Queries::
1.12 anton 4264: * Files::
4265: * Blocks::
4266: * Other I/O::
1.121 anton 4267: * OS command line arguments::
1.78 anton 4268: * Locals::
4269: * Structures::
4270: * Object-oriented Forth::
1.12 anton 4271: * Programming Tools::
1.150 anton 4272: * C Interface::
1.12 anton 4273: * Assembler and Code Words::
4274: * Threading Words::
1.65 anton 4275: * Passing Commands to the OS::
4276: * Keeping track of Time::
4277: * Miscellaneous Words::
1.1 anton 4278: @end menu
4279:
1.65 anton 4280: @node Notation, Case insensitivity, Words, Words
1.1 anton 4281: @section Notation
4282: @cindex notation of glossary entries
4283: @cindex format of glossary entries
4284: @cindex glossary notation format
4285: @cindex word glossary entry format
4286:
4287: The Forth words are described in this section in the glossary notation
1.67 anton 4288: that has become a de-facto standard for Forth texts:
1.1 anton 4289:
4290: @format
1.29 crook 4291: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4292: @end format
1.29 crook 4293: @i{Description}
1.1 anton 4294:
4295: @table @var
4296: @item word
1.28 crook 4297: The name of the word.
1.1 anton 4298:
4299: @item Stack effect
4300: @cindex stack effect
1.29 crook 4301: The stack effect is written in the notation @code{@i{before} --
4302: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4303: stack entries before and after the execution of the word. The rest of
4304: the stack is not touched by the word. The top of stack is rightmost,
4305: i.e., a stack sequence is written as it is typed in. Note that Gforth
4306: uses a separate floating point stack, but a unified stack
1.29 crook 4307: notation. Also, return stack effects are not shown in @i{stack
4308: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4309: the type and/or the function of the item. See below for a discussion of
4310: the types.
4311:
4312: All words have two stack effects: A compile-time stack effect and a
4313: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4314: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4315: this standard behaviour, or the word does other unusual things at
4316: compile time, both stack effects are shown; otherwise only the run-time
4317: stack effect is shown.
4318:
4319: @cindex pronounciation of words
4320: @item pronunciation
4321: How the word is pronounced.
4322:
4323: @cindex wordset
1.67 anton 4324: @cindex environment wordset
1.1 anton 4325: @item wordset
1.21 crook 4326: The ANS Forth standard is divided into several word sets. A standard
4327: system need not support all of them. Therefore, in theory, the fewer
4328: word sets your program uses the more portable it will be. However, we
4329: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4330: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4331: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4332: describes words that will work in future releases of Gforth;
4333: @code{gforth-internal} words are more volatile. Environmental query
4334: strings are also displayed like words; you can recognize them by the
1.21 crook 4335: @code{environment} in the word set field.
1.1 anton 4336:
4337: @item Description
4338: A description of the behaviour of the word.
4339: @end table
4340:
4341: @cindex types of stack items
4342: @cindex stack item types
4343: The type of a stack item is specified by the character(s) the name
4344: starts with:
4345:
4346: @table @code
4347: @item f
4348: @cindex @code{f}, stack item type
4349: Boolean flags, i.e. @code{false} or @code{true}.
4350: @item c
4351: @cindex @code{c}, stack item type
4352: Char
4353: @item w
4354: @cindex @code{w}, stack item type
4355: Cell, can contain an integer or an address
4356: @item n
4357: @cindex @code{n}, stack item type
4358: signed integer
4359: @item u
4360: @cindex @code{u}, stack item type
4361: unsigned integer
4362: @item d
4363: @cindex @code{d}, stack item type
4364: double sized signed integer
4365: @item ud
4366: @cindex @code{ud}, stack item type
4367: double sized unsigned integer
4368: @item r
4369: @cindex @code{r}, stack item type
4370: Float (on the FP stack)
1.21 crook 4371: @item a-
1.1 anton 4372: @cindex @code{a_}, stack item type
4373: Cell-aligned address
1.21 crook 4374: @item c-
1.1 anton 4375: @cindex @code{c_}, stack item type
4376: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4377: @item f-
1.1 anton 4378: @cindex @code{f_}, stack item type
4379: Float-aligned address
1.21 crook 4380: @item df-
1.1 anton 4381: @cindex @code{df_}, stack item type
4382: Address aligned for IEEE double precision float
1.21 crook 4383: @item sf-
1.1 anton 4384: @cindex @code{sf_}, stack item type
4385: Address aligned for IEEE single precision float
4386: @item xt
4387: @cindex @code{xt}, stack item type
4388: Execution token, same size as Cell
4389: @item wid
4390: @cindex @code{wid}, stack item type
1.21 crook 4391: Word list ID, same size as Cell
1.68 anton 4392: @item ior, wior
4393: @cindex ior type description
4394: @cindex wior type description
4395: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4396: @item f83name
4397: @cindex @code{f83name}, stack item type
4398: Pointer to a name structure
4399: @item "
4400: @cindex @code{"}, stack item type
1.12 anton 4401: string in the input stream (not on the stack). The terminating character
4402: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4403: quotes.
4404: @end table
4405:
1.65 anton 4406: @comment ----------------------------------------------
4407: @node Case insensitivity, Comments, Notation, Words
4408: @section Case insensitivity
4409: @cindex case sensitivity
4410: @cindex upper and lower case
4411:
4412: Gforth is case-insensitive; you can enter definitions and invoke
4413: Standard words using upper, lower or mixed case (however,
4414: @pxref{core-idef, Implementation-defined options, Implementation-defined
4415: options}).
4416:
4417: ANS Forth only @i{requires} implementations to recognise Standard words
4418: when they are typed entirely in upper case. Therefore, a Standard
4419: program must use upper case for all Standard words. You can use whatever
4420: case you like for words that you define, but in a Standard program you
4421: have to use the words in the same case that you defined them.
4422:
4423: Gforth supports case sensitivity through @code{table}s (case-sensitive
4424: wordlists, @pxref{Word Lists}).
4425:
4426: Two people have asked how to convert Gforth to be case-sensitive; while
4427: we think this is a bad idea, you can change all wordlists into tables
4428: like this:
4429:
4430: @example
4431: ' table-find forth-wordlist wordlist-map @ !
4432: @end example
4433:
4434: Note that you now have to type the predefined words in the same case
4435: that we defined them, which are varying. You may want to convert them
4436: to your favourite case before doing this operation (I won't explain how,
4437: because if you are even contemplating doing this, you'd better have
4438: enough knowledge of Forth systems to know this already).
4439:
4440: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4441: @section Comments
1.26 crook 4442: @cindex comments
1.21 crook 4443:
1.29 crook 4444: Forth supports two styles of comment; the traditional @i{in-line} comment,
4445: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4446:
1.44 crook 4447:
1.23 crook 4448: doc-(
1.21 crook 4449: doc-\
1.23 crook 4450: doc-\G
1.21 crook 4451:
1.44 crook 4452:
1.21 crook 4453: @node Boolean Flags, Arithmetic, Comments, Words
4454: @section Boolean Flags
1.26 crook 4455: @cindex Boolean flags
1.21 crook 4456:
4457: A Boolean flag is cell-sized. A cell with all bits clear represents the
4458: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4459: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4460: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4461: @c on and off to Memory?
4462: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4463:
1.21 crook 4464: doc-true
4465: doc-false
1.29 crook 4466: doc-on
4467: doc-off
1.21 crook 4468:
1.44 crook 4469:
1.21 crook 4470: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4471: @section Arithmetic
4472: @cindex arithmetic words
4473:
4474: @cindex division with potentially negative operands
4475: Forth arithmetic is not checked, i.e., you will not hear about integer
4476: overflow on addition or multiplication, you may hear about division by
4477: zero if you are lucky. The operator is written after the operands, but
4478: the operands are still in the original order. I.e., the infix @code{2-1}
4479: corresponds to @code{2 1 -}. Forth offers a variety of division
4480: operators. If you perform division with potentially negative operands,
4481: you do not want to use @code{/} or @code{/mod} with its undefined
4482: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4483: former, @pxref{Mixed precision}).
1.26 crook 4484: @comment TODO discuss the different division forms and the std approach
1.1 anton 4485:
4486: @menu
4487: * Single precision::
1.67 anton 4488: * Double precision:: Double-cell integer arithmetic
1.1 anton 4489: * Bitwise operations::
1.67 anton 4490: * Numeric comparison::
1.29 crook 4491: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4492: * Floating Point::
4493: @end menu
4494:
1.67 anton 4495: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4496: @subsection Single precision
4497: @cindex single precision arithmetic words
4498:
1.67 anton 4499: @c !! cell undefined
4500:
4501: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4502: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4503: treat them. For the rules used by the text interpreter for recognising
4504: single-precision integers see @ref{Number Conversion}.
1.21 crook 4505:
1.67 anton 4506: These words are all defined for signed operands, but some of them also
4507: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4508: @code{*}.
1.44 crook 4509:
1.1 anton 4510: doc-+
1.21 crook 4511: doc-1+
1.128 anton 4512: doc-under+
1.1 anton 4513: doc--
1.21 crook 4514: doc-1-
1.1 anton 4515: doc-*
4516: doc-/
4517: doc-mod
4518: doc-/mod
4519: doc-negate
4520: doc-abs
4521: doc-min
4522: doc-max
1.27 crook 4523: doc-floored
1.1 anton 4524:
1.44 crook 4525:
1.67 anton 4526: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4527: @subsection Double precision
4528: @cindex double precision arithmetic words
4529:
1.49 anton 4530: For the rules used by the text interpreter for
4531: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4532:
4533: A double precision number is represented by a cell pair, with the most
1.67 anton 4534: significant cell at the TOS. It is trivial to convert an unsigned single
4535: to a double: simply push a @code{0} onto the TOS. Since numbers are
4536: represented by Gforth using 2's complement arithmetic, converting a
4537: signed single to a (signed) double requires sign-extension across the
4538: most significant cell. This can be achieved using @code{s>d}. The moral
4539: of the story is that you cannot convert a number without knowing whether
4540: it represents an unsigned or a signed number.
1.21 crook 4541:
1.67 anton 4542: These words are all defined for signed operands, but some of them also
4543: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4544:
1.21 crook 4545: doc-s>d
1.67 anton 4546: doc-d>s
1.21 crook 4547: doc-d+
4548: doc-d-
4549: doc-dnegate
4550: doc-dabs
4551: doc-dmin
4552: doc-dmax
4553:
1.44 crook 4554:
1.67 anton 4555: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4556: @subsection Bitwise operations
4557: @cindex bitwise operation words
4558:
4559:
4560: doc-and
4561: doc-or
4562: doc-xor
4563: doc-invert
4564: doc-lshift
4565: doc-rshift
4566: doc-2*
4567: doc-d2*
4568: doc-2/
4569: doc-d2/
4570:
4571:
4572: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4573: @subsection Numeric comparison
4574: @cindex numeric comparison words
4575:
1.67 anton 4576: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4577: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4578:
1.28 crook 4579: doc-<
4580: doc-<=
4581: doc-<>
4582: doc-=
4583: doc->
4584: doc->=
4585:
1.21 crook 4586: doc-0<
1.23 crook 4587: doc-0<=
1.21 crook 4588: doc-0<>
4589: doc-0=
1.23 crook 4590: doc-0>
4591: doc-0>=
1.28 crook 4592:
4593: doc-u<
4594: doc-u<=
1.44 crook 4595: @c u<> and u= exist but are the same as <> and =
1.31 anton 4596: @c doc-u<>
4597: @c doc-u=
1.28 crook 4598: doc-u>
4599: doc-u>=
4600:
4601: doc-within
4602:
4603: doc-d<
4604: doc-d<=
4605: doc-d<>
4606: doc-d=
4607: doc-d>
4608: doc-d>=
1.23 crook 4609:
1.21 crook 4610: doc-d0<
1.23 crook 4611: doc-d0<=
4612: doc-d0<>
1.21 crook 4613: doc-d0=
1.23 crook 4614: doc-d0>
4615: doc-d0>=
4616:
1.21 crook 4617: doc-du<
1.28 crook 4618: doc-du<=
1.44 crook 4619: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4620: @c doc-du<>
4621: @c doc-du=
1.28 crook 4622: doc-du>
4623: doc-du>=
1.1 anton 4624:
1.44 crook 4625:
1.21 crook 4626: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4627: @subsection Mixed precision
4628: @cindex mixed precision arithmetic words
4629:
1.44 crook 4630:
1.1 anton 4631: doc-m+
4632: doc-*/
4633: doc-*/mod
4634: doc-m*
4635: doc-um*
4636: doc-m*/
4637: doc-um/mod
4638: doc-fm/mod
4639: doc-sm/rem
4640:
1.44 crook 4641:
1.21 crook 4642: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4643: @subsection Floating Point
4644: @cindex floating point arithmetic words
4645:
1.49 anton 4646: For the rules used by the text interpreter for
4647: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4648:
1.67 anton 4649: Gforth has a separate floating point stack, but the documentation uses
4650: the unified notation.@footnote{It's easy to generate the separate
4651: notation from that by just separating the floating-point numbers out:
4652: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4653: r3 )}.}
1.1 anton 4654:
4655: @cindex floating-point arithmetic, pitfalls
4656: Floating point numbers have a number of unpleasant surprises for the
4657: unwary (e.g., floating point addition is not associative) and even a few
4658: for the wary. You should not use them unless you know what you are doing
4659: or you don't care that the results you get are totally bogus. If you
4660: want to learn about the problems of floating point numbers (and how to
1.66 anton 4661: avoid them), you might start with @cite{David Goldberg,
4662: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4663: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4664: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4665:
1.44 crook 4666:
1.21 crook 4667: doc-d>f
4668: doc-f>d
1.1 anton 4669: doc-f+
4670: doc-f-
4671: doc-f*
4672: doc-f/
4673: doc-fnegate
4674: doc-fabs
4675: doc-fmax
4676: doc-fmin
4677: doc-floor
4678: doc-fround
4679: doc-f**
4680: doc-fsqrt
4681: doc-fexp
4682: doc-fexpm1
4683: doc-fln
4684: doc-flnp1
4685: doc-flog
4686: doc-falog
1.32 anton 4687: doc-f2*
4688: doc-f2/
4689: doc-1/f
4690: doc-precision
4691: doc-set-precision
4692:
4693: @cindex angles in trigonometric operations
4694: @cindex trigonometric operations
4695: Angles in floating point operations are given in radians (a full circle
4696: has 2 pi radians).
4697:
1.1 anton 4698: doc-fsin
4699: doc-fcos
4700: doc-fsincos
4701: doc-ftan
4702: doc-fasin
4703: doc-facos
4704: doc-fatan
4705: doc-fatan2
4706: doc-fsinh
4707: doc-fcosh
4708: doc-ftanh
4709: doc-fasinh
4710: doc-facosh
4711: doc-fatanh
1.21 crook 4712: doc-pi
1.28 crook 4713:
1.32 anton 4714: @cindex equality of floats
4715: @cindex floating-point comparisons
1.31 anton 4716: One particular problem with floating-point arithmetic is that comparison
4717: for equality often fails when you would expect it to succeed. For this
4718: reason approximate equality is often preferred (but you still have to
1.67 anton 4719: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4720: differently from what you might expect. The comparison words are:
1.31 anton 4721:
4722: doc-f~rel
4723: doc-f~abs
1.68 anton 4724: doc-f~
1.31 anton 4725: doc-f=
4726: doc-f<>
4727:
4728: doc-f<
4729: doc-f<=
4730: doc-f>
4731: doc-f>=
4732:
1.21 crook 4733: doc-f0<
1.28 crook 4734: doc-f0<=
4735: doc-f0<>
1.21 crook 4736: doc-f0=
1.28 crook 4737: doc-f0>
4738: doc-f0>=
4739:
1.1 anton 4740:
4741: @node Stack Manipulation, Memory, Arithmetic, Words
4742: @section Stack Manipulation
4743: @cindex stack manipulation words
4744:
4745: @cindex floating-point stack in the standard
1.21 crook 4746: Gforth maintains a number of separate stacks:
4747:
1.29 crook 4748: @cindex data stack
4749: @cindex parameter stack
1.21 crook 4750: @itemize @bullet
4751: @item
1.29 crook 4752: A data stack (also known as the @dfn{parameter stack}) -- for
4753: characters, cells, addresses, and double cells.
1.21 crook 4754:
1.29 crook 4755: @cindex floating-point stack
1.21 crook 4756: @item
1.44 crook 4757: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4758:
1.29 crook 4759: @cindex return stack
1.21 crook 4760: @item
1.44 crook 4761: A return stack -- for holding the return addresses of colon
1.32 anton 4762: definitions and other (non-FP) data.
1.21 crook 4763:
1.29 crook 4764: @cindex locals stack
1.21 crook 4765: @item
1.44 crook 4766: A locals stack -- for holding local variables.
1.21 crook 4767: @end itemize
4768:
1.1 anton 4769: @menu
4770: * Data stack::
4771: * Floating point stack::
4772: * Return stack::
4773: * Locals stack::
4774: * Stack pointer manipulation::
4775: @end menu
4776:
4777: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4778: @subsection Data stack
4779: @cindex data stack manipulation words
4780: @cindex stack manipulations words, data stack
4781:
1.44 crook 4782:
1.1 anton 4783: doc-drop
4784: doc-nip
4785: doc-dup
4786: doc-over
4787: doc-tuck
4788: doc-swap
1.21 crook 4789: doc-pick
1.1 anton 4790: doc-rot
4791: doc--rot
4792: doc-?dup
4793: doc-roll
4794: doc-2drop
4795: doc-2nip
4796: doc-2dup
4797: doc-2over
4798: doc-2tuck
4799: doc-2swap
4800: doc-2rot
4801:
1.44 crook 4802:
1.1 anton 4803: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4804: @subsection Floating point stack
4805: @cindex floating-point stack manipulation words
4806: @cindex stack manipulation words, floating-point stack
4807:
1.32 anton 4808: Whilst every sane Forth has a separate floating-point stack, it is not
4809: strictly required; an ANS Forth system could theoretically keep
4810: floating-point numbers on the data stack. As an additional difficulty,
4811: you don't know how many cells a floating-point number takes. It is
4812: reportedly possible to write words in a way that they work also for a
4813: unified stack model, but we do not recommend trying it. Instead, just
4814: say that your program has an environmental dependency on a separate
4815: floating-point stack.
4816:
4817: doc-floating-stack
4818:
1.1 anton 4819: doc-fdrop
4820: doc-fnip
4821: doc-fdup
4822: doc-fover
4823: doc-ftuck
4824: doc-fswap
1.21 crook 4825: doc-fpick
1.1 anton 4826: doc-frot
4827:
1.44 crook 4828:
1.1 anton 4829: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4830: @subsection Return stack
4831: @cindex return stack manipulation words
4832: @cindex stack manipulation words, return stack
4833:
1.32 anton 4834: @cindex return stack and locals
4835: @cindex locals and return stack
4836: A Forth system is allowed to keep local variables on the
4837: return stack. This is reasonable, as local variables usually eliminate
4838: the need to use the return stack explicitly. So, if you want to produce
4839: a standard compliant program and you are using local variables in a
4840: word, forget about return stack manipulations in that word (refer to the
4841: standard document for the exact rules).
4842:
1.1 anton 4843: doc->r
4844: doc-r>
4845: doc-r@
4846: doc-rdrop
4847: doc-2>r
4848: doc-2r>
4849: doc-2r@
4850: doc-2rdrop
4851:
1.44 crook 4852:
1.1 anton 4853: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4854: @subsection Locals stack
4855:
1.78 anton 4856: Gforth uses an extra locals stack. It is described, along with the
4857: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4858:
1.1 anton 4859: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4860: @subsection Stack pointer manipulation
4861: @cindex stack pointer manipulation words
4862:
1.44 crook 4863: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4864: doc-sp0
1.1 anton 4865: doc-sp@
4866: doc-sp!
1.21 crook 4867: doc-fp0
1.1 anton 4868: doc-fp@
4869: doc-fp!
1.21 crook 4870: doc-rp0
1.1 anton 4871: doc-rp@
4872: doc-rp!
1.21 crook 4873: doc-lp0
1.1 anton 4874: doc-lp@
4875: doc-lp!
4876:
1.44 crook 4877:
1.1 anton 4878: @node Memory, Control Structures, Stack Manipulation, Words
4879: @section Memory
1.26 crook 4880: @cindex memory words
1.1 anton 4881:
1.32 anton 4882: @menu
4883: * Memory model::
4884: * Dictionary allocation::
4885: * Heap Allocation::
4886: * Memory Access::
4887: * Address arithmetic::
4888: * Memory Blocks::
4889: @end menu
4890:
1.67 anton 4891: In addition to the standard Forth memory allocation words, there is also
4892: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4893: garbage collector}.
4894:
1.32 anton 4895: @node Memory model, Dictionary allocation, Memory, Memory
4896: @subsection ANS Forth and Gforth memory models
4897:
4898: @c The ANS Forth description is a mess (e.g., is the heap part of
4899: @c the dictionary?), so let's not stick to closely with it.
4900:
1.67 anton 4901: ANS Forth considers a Forth system as consisting of several address
4902: spaces, of which only @dfn{data space} is managed and accessible with
4903: the memory words. Memory not necessarily in data space includes the
4904: stacks, the code (called code space) and the headers (called name
4905: space). In Gforth everything is in data space, but the code for the
4906: primitives is usually read-only.
1.32 anton 4907:
4908: Data space is divided into a number of areas: The (data space portion of
4909: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4910: refer to the search data structure embodied in word lists and headers,
4911: because it is used for looking up names, just as you would in a
4912: conventional dictionary.}, the heap, and a number of system-allocated
4913: buffers.
4914:
1.68 anton 4915: @cindex address arithmetic restrictions, ANS vs. Gforth
4916: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4917: In ANS Forth data space is also divided into contiguous regions. You
4918: can only use address arithmetic within a contiguous region, not between
4919: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4920: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4921: allocation}).
4922:
4923: Gforth provides one big address space, and address arithmetic can be
4924: performed between any addresses. However, in the dictionary headers or
4925: code are interleaved with data, so almost the only contiguous data space
4926: regions there are those described by ANS Forth as contiguous; but you
4927: can be sure that the dictionary is allocated towards increasing
4928: addresses even between contiguous regions. The memory order of
4929: allocations in the heap is platform-dependent (and possibly different
4930: from one run to the next).
4931:
1.27 crook 4932:
1.32 anton 4933: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4934: @subsection Dictionary allocation
1.27 crook 4935: @cindex reserving data space
4936: @cindex data space - reserving some
4937:
1.32 anton 4938: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4939: you want to deallocate X, you also deallocate everything
4940: allocated after X.
4941:
1.68 anton 4942: @cindex contiguous regions in dictionary allocation
1.32 anton 4943: The allocations using the words below are contiguous and grow the region
4944: towards increasing addresses. Other words that allocate dictionary
4945: memory of any kind (i.e., defining words including @code{:noname}) end
4946: the contiguous region and start a new one.
4947:
4948: In ANS Forth only @code{create}d words are guaranteed to produce an
4949: address that is the start of the following contiguous region. In
4950: particular, the cell allocated by @code{variable} is not guaranteed to
4951: be contiguous with following @code{allot}ed memory.
4952:
4953: You can deallocate memory by using @code{allot} with a negative argument
4954: (with some restrictions, see @code{allot}). For larger deallocations use
4955: @code{marker}.
1.27 crook 4956:
1.29 crook 4957:
1.27 crook 4958: doc-here
4959: doc-unused
4960: doc-allot
4961: doc-c,
1.29 crook 4962: doc-f,
1.27 crook 4963: doc-,
4964: doc-2,
4965:
1.32 anton 4966: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4967: course you should allocate memory in an aligned way, too. I.e., before
4968: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4969: The words below align @code{here} if it is not already. Basically it is
4970: only already aligned for a type, if the last allocation was a multiple
4971: of the size of this type and if @code{here} was aligned for this type
4972: before.
4973:
4974: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4975: ANS Forth (@code{maxalign}ed in Gforth).
4976:
4977: doc-align
4978: doc-falign
4979: doc-sfalign
4980: doc-dfalign
4981: doc-maxalign
4982: doc-cfalign
4983:
4984:
4985: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4986: @subsection Heap allocation
4987: @cindex heap allocation
4988: @cindex dynamic allocation of memory
4989: @cindex memory-allocation word set
4990:
1.68 anton 4991: @cindex contiguous regions and heap allocation
1.32 anton 4992: Heap allocation supports deallocation of allocated memory in any
4993: order. Dictionary allocation is not affected by it (i.e., it does not
4994: end a contiguous region). In Gforth, these words are implemented using
4995: the standard C library calls malloc(), free() and resize().
4996:
1.68 anton 4997: The memory region produced by one invocation of @code{allocate} or
4998: @code{resize} is internally contiguous. There is no contiguity between
4999: such a region and any other region (including others allocated from the
5000: heap).
5001:
1.32 anton 5002: doc-allocate
5003: doc-free
5004: doc-resize
5005:
1.27 crook 5006:
1.32 anton 5007: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5008: @subsection Memory Access
5009: @cindex memory access words
5010:
5011: doc-@
5012: doc-!
5013: doc-+!
5014: doc-c@
5015: doc-c!
5016: doc-2@
5017: doc-2!
5018: doc-f@
5019: doc-f!
5020: doc-sf@
5021: doc-sf!
5022: doc-df@
5023: doc-df!
1.144 anton 5024: doc-sw@
5025: doc-uw@
5026: doc-w!
5027: doc-sl@
5028: doc-ul@
5029: doc-l!
1.68 anton 5030:
1.32 anton 5031: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5032: @subsection Address arithmetic
1.1 anton 5033: @cindex address arithmetic words
5034:
1.67 anton 5035: Address arithmetic is the foundation on which you can build data
5036: structures like arrays, records (@pxref{Structures}) and objects
5037: (@pxref{Object-oriented Forth}).
1.32 anton 5038:
1.68 anton 5039: @cindex address unit
5040: @cindex au (address unit)
1.1 anton 5041: ANS Forth does not specify the sizes of the data types. Instead, it
5042: offers a number of words for computing sizes and doing address
1.29 crook 5043: arithmetic. Address arithmetic is performed in terms of address units
5044: (aus); on most systems the address unit is one byte. Note that a
5045: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5046: platforms where it is a noop, it compiles to nothing).
1.1 anton 5047:
1.67 anton 5048: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5049: you have the address of a cell, perform @code{1 cells +}, and you will
5050: have the address of the next cell.
5051:
1.68 anton 5052: @cindex contiguous regions and address arithmetic
1.67 anton 5053: In ANS Forth you can perform address arithmetic only within a contiguous
5054: region, i.e., if you have an address into one region, you can only add
5055: and subtract such that the result is still within the region; you can
5056: only subtract or compare addresses from within the same contiguous
5057: region. Reasons: several contiguous regions can be arranged in memory
5058: in any way; on segmented systems addresses may have unusual
5059: representations, such that address arithmetic only works within a
5060: region. Gforth provides a few more guarantees (linear address space,
5061: dictionary grows upwards), but in general I have found it easy to stay
5062: within contiguous regions (exception: computing and comparing to the
5063: address just beyond the end of an array).
5064:
1.1 anton 5065: @cindex alignment of addresses for types
5066: ANS Forth also defines words for aligning addresses for specific
5067: types. Many computers require that accesses to specific data types
5068: must only occur at specific addresses; e.g., that cells may only be
5069: accessed at addresses divisible by 4. Even if a machine allows unaligned
5070: accesses, it can usually perform aligned accesses faster.
5071:
5072: For the performance-conscious: alignment operations are usually only
5073: necessary during the definition of a data structure, not during the
5074: (more frequent) accesses to it.
5075:
5076: ANS Forth defines no words for character-aligning addresses. This is not
5077: an oversight, but reflects the fact that addresses that are not
5078: char-aligned have no use in the standard and therefore will not be
5079: created.
5080:
5081: @cindex @code{CREATE} and alignment
1.29 crook 5082: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5083: are cell-aligned; in addition, Gforth guarantees that these addresses
5084: are aligned for all purposes.
5085:
1.26 crook 5086: Note that the ANS Forth word @code{char} has nothing to do with address
5087: arithmetic.
1.1 anton 5088:
1.44 crook 5089:
1.1 anton 5090: doc-chars
5091: doc-char+
5092: doc-cells
5093: doc-cell+
5094: doc-cell
5095: doc-aligned
5096: doc-floats
5097: doc-float+
5098: doc-float
5099: doc-faligned
5100: doc-sfloats
5101: doc-sfloat+
5102: doc-sfaligned
5103: doc-dfloats
5104: doc-dfloat+
5105: doc-dfaligned
5106: doc-maxaligned
5107: doc-cfaligned
5108: doc-address-unit-bits
1.145 anton 5109: doc-/w
5110: doc-/l
1.44 crook 5111:
1.32 anton 5112: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5113: @subsection Memory Blocks
5114: @cindex memory block words
1.27 crook 5115: @cindex character strings - moving and copying
5116:
1.49 anton 5117: Memory blocks often represent character strings; For ways of storing
5118: character strings in memory see @ref{String Formats}. For other
5119: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5120:
1.67 anton 5121: A few of these words work on address unit blocks. In that case, you
5122: usually have to insert @code{CHARS} before the word when working on
5123: character strings. Most words work on character blocks, and expect a
5124: char-aligned address.
5125:
5126: When copying characters between overlapping memory regions, use
5127: @code{chars move} or choose carefully between @code{cmove} and
5128: @code{cmove>}.
1.44 crook 5129:
1.1 anton 5130: doc-move
5131: doc-erase
5132: doc-cmove
5133: doc-cmove>
5134: doc-fill
5135: doc-blank
1.21 crook 5136: doc-compare
1.111 anton 5137: doc-str=
5138: doc-str<
5139: doc-string-prefix?
1.21 crook 5140: doc-search
1.27 crook 5141: doc--trailing
5142: doc-/string
1.82 anton 5143: doc-bounds
1.141 anton 5144: doc-pad
1.111 anton 5145:
1.27 crook 5146: @comment TODO examples
5147:
1.1 anton 5148:
1.26 crook 5149: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5150: @section Control Structures
5151: @cindex control structures
5152:
1.33 anton 5153: Control structures in Forth cannot be used interpretively, only in a
5154: colon definition@footnote{To be precise, they have no interpretation
5155: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5156: not like this limitation, but have not seen a satisfying way around it
5157: yet, although many schemes have been proposed.
1.1 anton 5158:
5159: @menu
1.33 anton 5160: * Selection:: IF ... ELSE ... ENDIF
5161: * Simple Loops:: BEGIN ...
1.29 crook 5162: * Counted Loops:: DO
1.67 anton 5163: * Arbitrary control structures::
5164: * Calls and returns::
1.1 anton 5165: * Exception Handling::
5166: @end menu
5167:
5168: @node Selection, Simple Loops, Control Structures, Control Structures
5169: @subsection Selection
5170: @cindex selection control structures
5171: @cindex control structures for selection
5172:
5173: @cindex @code{IF} control structure
5174: @example
1.29 crook 5175: @i{flag}
1.1 anton 5176: IF
1.29 crook 5177: @i{code}
1.1 anton 5178: ENDIF
5179: @end example
1.21 crook 5180: @noindent
1.33 anton 5181:
1.44 crook 5182: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5183: with any bit set represents truth) @i{code} is executed.
1.33 anton 5184:
1.1 anton 5185: @example
1.29 crook 5186: @i{flag}
1.1 anton 5187: IF
1.29 crook 5188: @i{code1}
1.1 anton 5189: ELSE
1.29 crook 5190: @i{code2}
1.1 anton 5191: ENDIF
5192: @end example
5193:
1.44 crook 5194: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5195: executed.
1.33 anton 5196:
1.1 anton 5197: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5198: standard, and @code{ENDIF} is not, although it is quite popular. We
5199: recommend using @code{ENDIF}, because it is less confusing for people
5200: who also know other languages (and is not prone to reinforcing negative
5201: prejudices against Forth in these people). Adding @code{ENDIF} to a
5202: system that only supplies @code{THEN} is simple:
5203: @example
1.82 anton 5204: : ENDIF POSTPONE then ; immediate
1.1 anton 5205: @end example
5206:
5207: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5208: (adv.)} has the following meanings:
5209: @quotation
5210: ... 2b: following next after in order ... 3d: as a necessary consequence
5211: (if you were there, then you saw them).
5212: @end quotation
5213: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5214: and many other programming languages has the meaning 3d.]
5215:
1.21 crook 5216: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5217: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5218: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5219: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5220: @file{compat/control.fs}.
5221:
5222: @cindex @code{CASE} control structure
5223: @example
1.29 crook 5224: @i{n}
1.1 anton 5225: CASE
1.29 crook 5226: @i{n1} OF @i{code1} ENDOF
5227: @i{n2} OF @i{code2} ENDOF
1.1 anton 5228: @dots{}
1.68 anton 5229: ( n ) @i{default-code} ( n )
1.131 anton 5230: ENDCASE ( )
1.1 anton 5231: @end example
5232:
1.131 anton 5233: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5234: no @i{ni} matches, the optional @i{default-code} is executed. The
5235: optional default case can be added by simply writing the code after
5236: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5237: but must not consume it. The value @i{n} is consumed by this
5238: construction (either by a OF that matches, or by the ENDCASE, if no OF
5239: matches).
1.1 anton 5240:
1.69 anton 5241: @progstyle
1.131 anton 5242: To keep the code understandable, you should ensure that you change the
5243: stack in the same way (wrt. number and types of stack items consumed
5244: and pushed) on all paths through a selection construct.
1.69 anton 5245:
1.1 anton 5246: @node Simple Loops, Counted Loops, Selection, Control Structures
5247: @subsection Simple Loops
5248: @cindex simple loops
5249: @cindex loops without count
5250:
5251: @cindex @code{WHILE} loop
5252: @example
5253: BEGIN
1.29 crook 5254: @i{code1}
5255: @i{flag}
1.1 anton 5256: WHILE
1.29 crook 5257: @i{code2}
1.1 anton 5258: REPEAT
5259: @end example
5260:
1.29 crook 5261: @i{code1} is executed and @i{flag} is computed. If it is true,
5262: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5263: false, execution continues after the @code{REPEAT}.
5264:
5265: @cindex @code{UNTIL} loop
5266: @example
5267: BEGIN
1.29 crook 5268: @i{code}
5269: @i{flag}
1.1 anton 5270: UNTIL
5271: @end example
5272:
1.29 crook 5273: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5274:
1.69 anton 5275: @progstyle
5276: To keep the code understandable, a complete iteration of the loop should
5277: not change the number and types of the items on the stacks.
5278:
1.1 anton 5279: @cindex endless loop
5280: @cindex loops, endless
5281: @example
5282: BEGIN
1.29 crook 5283: @i{code}
1.1 anton 5284: AGAIN
5285: @end example
5286:
5287: This is an endless loop.
5288:
5289: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5290: @subsection Counted Loops
5291: @cindex counted loops
5292: @cindex loops, counted
5293: @cindex @code{DO} loops
5294:
5295: The basic counted loop is:
5296: @example
1.29 crook 5297: @i{limit} @i{start}
1.1 anton 5298: ?DO
1.29 crook 5299: @i{body}
1.1 anton 5300: LOOP
5301: @end example
5302:
1.29 crook 5303: This performs one iteration for every integer, starting from @i{start}
5304: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5305: accessed with @code{i}. For example, the loop:
1.1 anton 5306: @example
5307: 10 0 ?DO
5308: i .
5309: LOOP
5310: @end example
1.21 crook 5311: @noindent
5312: prints @code{0 1 2 3 4 5 6 7 8 9}
5313:
1.1 anton 5314: The index of the innermost loop can be accessed with @code{i}, the index
5315: of the next loop with @code{j}, and the index of the third loop with
5316: @code{k}.
5317:
1.44 crook 5318:
1.1 anton 5319: doc-i
5320: doc-j
5321: doc-k
5322:
1.44 crook 5323:
1.1 anton 5324: The loop control data are kept on the return stack, so there are some
1.21 crook 5325: restrictions on mixing return stack accesses and counted loop words. In
5326: particuler, if you put values on the return stack outside the loop, you
5327: cannot read them inside the loop@footnote{well, not in a way that is
5328: portable.}. If you put values on the return stack within a loop, you
5329: have to remove them before the end of the loop and before accessing the
5330: index of the loop.
1.1 anton 5331:
5332: There are several variations on the counted loop:
5333:
1.21 crook 5334: @itemize @bullet
5335: @item
5336: @code{LEAVE} leaves the innermost counted loop immediately; execution
5337: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5338:
5339: @example
5340: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5341: @end example
5342: prints @code{0 1 2 3}
5343:
1.1 anton 5344:
1.21 crook 5345: @item
5346: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5347: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5348: return stack so @code{EXIT} can get to its return address. For example:
5349:
5350: @example
5351: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5352: @end example
5353: prints @code{0 1 2 3}
5354:
5355:
5356: @item
1.29 crook 5357: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5358: (and @code{LOOP} iterates until they become equal by wrap-around
5359: arithmetic). This behaviour is usually not what you want. Therefore,
5360: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5361: @code{?DO}), which do not enter the loop if @i{start} is greater than
5362: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5363: unsigned loop parameters.
5364:
1.21 crook 5365: @item
5366: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5367: the loop, independent of the loop parameters. Do not use @code{DO}, even
5368: if you know that the loop is entered in any case. Such knowledge tends
5369: to become invalid during maintenance of a program, and then the
5370: @code{DO} will make trouble.
5371:
5372: @item
1.29 crook 5373: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5374: index by @i{n} instead of by 1. The loop is terminated when the border
5375: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5376:
1.21 crook 5377: @example
5378: 4 0 +DO i . 2 +LOOP
5379: @end example
5380: @noindent
5381: prints @code{0 2}
5382:
5383: @example
5384: 4 1 +DO i . 2 +LOOP
5385: @end example
5386: @noindent
5387: prints @code{1 3}
1.1 anton 5388:
1.68 anton 5389: @item
1.1 anton 5390: @cindex negative increment for counted loops
5391: @cindex counted loops with negative increment
1.29 crook 5392: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5393:
1.21 crook 5394: @example
5395: -1 0 ?DO i . -1 +LOOP
5396: @end example
5397: @noindent
5398: prints @code{0 -1}
1.1 anton 5399:
1.21 crook 5400: @example
5401: 0 0 ?DO i . -1 +LOOP
5402: @end example
5403: prints nothing.
1.1 anton 5404:
1.29 crook 5405: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5406: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5407: index by @i{u} each iteration. The loop is terminated when the border
5408: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5409: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5410:
1.21 crook 5411: @example
5412: -2 0 -DO i . 1 -LOOP
5413: @end example
5414: @noindent
5415: prints @code{0 -1}
1.1 anton 5416:
1.21 crook 5417: @example
5418: -1 0 -DO i . 1 -LOOP
5419: @end example
5420: @noindent
5421: prints @code{0}
5422:
5423: @example
5424: 0 0 -DO i . 1 -LOOP
5425: @end example
5426: @noindent
5427: prints nothing.
1.1 anton 5428:
1.21 crook 5429: @end itemize
1.1 anton 5430:
5431: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5432: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5433: for these words that uses only standard words is provided in
5434: @file{compat/loops.fs}.
1.1 anton 5435:
5436:
5437: @cindex @code{FOR} loops
1.26 crook 5438: Another counted loop is:
1.1 anton 5439: @example
1.29 crook 5440: @i{n}
1.1 anton 5441: FOR
1.29 crook 5442: @i{body}
1.1 anton 5443: NEXT
5444: @end example
5445: This is the preferred loop of native code compiler writers who are too
1.26 crook 5446: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5447: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5448: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5449: Forth systems may behave differently, even if they support @code{FOR}
5450: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5451:
5452: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5453: @subsection Arbitrary control structures
5454: @cindex control structures, user-defined
5455:
5456: @cindex control-flow stack
5457: ANS Forth permits and supports using control structures in a non-nested
5458: way. Information about incomplete control structures is stored on the
5459: control-flow stack. This stack may be implemented on the Forth data
5460: stack, and this is what we have done in Gforth.
5461:
5462: @cindex @code{orig}, control-flow stack item
5463: @cindex @code{dest}, control-flow stack item
5464: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5465: entry represents a backward branch target. A few words are the basis for
5466: building any control structure possible (except control structures that
5467: need storage, like calls, coroutines, and backtracking).
5468:
1.44 crook 5469:
1.1 anton 5470: doc-if
5471: doc-ahead
5472: doc-then
5473: doc-begin
5474: doc-until
5475: doc-again
5476: doc-cs-pick
5477: doc-cs-roll
5478:
1.44 crook 5479:
1.21 crook 5480: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5481: manipulate the control-flow stack in a portable way. Without them, you
5482: would need to know how many stack items are occupied by a control-flow
5483: entry (many systems use one cell. In Gforth they currently take three,
5484: but this may change in the future).
5485:
1.1 anton 5486: Some standard control structure words are built from these words:
5487:
1.44 crook 5488:
1.1 anton 5489: doc-else
5490: doc-while
5491: doc-repeat
5492:
1.44 crook 5493:
5494: @noindent
1.1 anton 5495: Gforth adds some more control-structure words:
5496:
1.44 crook 5497:
1.1 anton 5498: doc-endif
5499: doc-?dup-if
5500: doc-?dup-0=-if
5501:
1.44 crook 5502:
5503: @noindent
1.1 anton 5504: Counted loop words constitute a separate group of words:
5505:
1.44 crook 5506:
1.1 anton 5507: doc-?do
5508: doc-+do
5509: doc-u+do
5510: doc--do
5511: doc-u-do
5512: doc-do
5513: doc-for
5514: doc-loop
5515: doc-+loop
5516: doc--loop
5517: doc-next
5518: doc-leave
5519: doc-?leave
5520: doc-unloop
5521: doc-done
5522:
1.44 crook 5523:
1.21 crook 5524: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5525: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5526: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5527: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5528: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5529: resolved (by using one of the loop-ending words or @code{DONE}).
5530:
1.44 crook 5531: @noindent
1.26 crook 5532: Another group of control structure words are:
1.1 anton 5533:
1.44 crook 5534:
1.1 anton 5535: doc-case
5536: doc-endcase
5537: doc-of
5538: doc-endof
5539:
1.44 crook 5540:
1.21 crook 5541: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5542: @code{CS-ROLL}.
1.1 anton 5543:
5544: @subsubsection Programming Style
1.47 crook 5545: @cindex control structures programming style
5546: @cindex programming style, arbitrary control structures
1.1 anton 5547:
5548: In order to ensure readability we recommend that you do not create
5549: arbitrary control structures directly, but define new control structure
5550: words for the control structure you want and use these words in your
1.26 crook 5551: program. For example, instead of writing:
1.1 anton 5552:
5553: @example
1.26 crook 5554: BEGIN
1.1 anton 5555: ...
1.26 crook 5556: IF [ 1 CS-ROLL ]
1.1 anton 5557: ...
1.26 crook 5558: AGAIN THEN
1.1 anton 5559: @end example
5560:
1.21 crook 5561: @noindent
1.1 anton 5562: we recommend defining control structure words, e.g.,
5563:
5564: @example
1.26 crook 5565: : WHILE ( DEST -- ORIG DEST )
5566: POSTPONE IF
5567: 1 CS-ROLL ; immediate
5568:
5569: : REPEAT ( orig dest -- )
5570: POSTPONE AGAIN
5571: POSTPONE THEN ; immediate
1.1 anton 5572: @end example
5573:
1.21 crook 5574: @noindent
1.1 anton 5575: and then using these to create the control structure:
5576:
5577: @example
1.26 crook 5578: BEGIN
1.1 anton 5579: ...
1.26 crook 5580: WHILE
1.1 anton 5581: ...
1.26 crook 5582: REPEAT
1.1 anton 5583: @end example
5584:
5585: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5586: @code{WHILE} are predefined, so in this example it would not be
5587: necessary to define them.
5588:
5589: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5590: @subsection Calls and returns
5591: @cindex calling a definition
5592: @cindex returning from a definition
5593:
1.3 anton 5594: @cindex recursive definitions
5595: A definition can be called simply be writing the name of the definition
1.26 crook 5596: to be called. Normally a definition is invisible during its own
1.3 anton 5597: definition. If you want to write a directly recursive definition, you
1.26 crook 5598: can use @code{recursive} to make the current definition visible, or
5599: @code{recurse} to call the current definition directly.
1.3 anton 5600:
1.44 crook 5601:
1.3 anton 5602: doc-recursive
5603: doc-recurse
5604:
1.44 crook 5605:
1.21 crook 5606: @comment TODO add example of the two recursion methods
1.12 anton 5607: @quotation
5608: @progstyle
5609: I prefer using @code{recursive} to @code{recurse}, because calling the
5610: definition by name is more descriptive (if the name is well-chosen) than
5611: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5612: implementation, it is much better to read (and think) ``now sort the
5613: partitions'' than to read ``now do a recursive call''.
5614: @end quotation
1.3 anton 5615:
1.29 crook 5616: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5617:
5618: @example
1.28 crook 5619: Defer foo
1.3 anton 5620:
5621: : bar ( ... -- ... )
5622: ... foo ... ;
5623:
5624: :noname ( ... -- ... )
5625: ... bar ... ;
5626: IS foo
5627: @end example
5628:
1.170 pazsan 5629: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5630:
1.26 crook 5631: The current definition returns control to the calling definition when
1.33 anton 5632: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5633:
5634: doc-exit
5635: doc-;s
5636:
1.44 crook 5637:
1.1 anton 5638: @node Exception Handling, , Calls and returns, Control Structures
5639: @subsection Exception Handling
1.26 crook 5640: @cindex exceptions
1.1 anton 5641:
1.68 anton 5642: @c quit is a very bad idea for error handling,
5643: @c because it does not translate into a THROW
5644: @c it also does not belong into this chapter
5645:
5646: If a word detects an error condition that it cannot handle, it can
5647: @code{throw} an exception. In the simplest case, this will terminate
5648: your program, and report an appropriate error.
1.21 crook 5649:
1.68 anton 5650: doc-throw
1.1 anton 5651:
1.69 anton 5652: @code{Throw} consumes a cell-sized error number on the stack. There are
5653: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5654: Gforth (and most other systems) you can use the iors produced by various
5655: words as error numbers (e.g., a typical use of @code{allocate} is
5656: @code{allocate throw}). Gforth also provides the word @code{exception}
5657: to define your own error numbers (with decent error reporting); an ANS
5658: Forth version of this word (but without the error messages) is available
5659: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5660: numbers (anything outside the range -4095..0), but won't get nice error
5661: messages, only numbers. For example, try:
5662:
5663: @example
1.69 anton 5664: -10 throw \ ANS defined
5665: -267 throw \ system defined
5666: s" my error" exception throw \ user defined
5667: 7 throw \ arbitrary number
1.68 anton 5668: @end example
5669:
5670: doc---exception-exception
1.1 anton 5671:
1.69 anton 5672: A common idiom to @code{THROW} a specific error if a flag is true is
5673: this:
5674:
5675: @example
5676: @code{( flag ) 0<> @i{errno} and throw}
5677: @end example
5678:
5679: Your program can provide exception handlers to catch exceptions. An
5680: exception handler can be used to correct the problem, or to clean up
5681: some data structures and just throw the exception to the next exception
5682: handler. Note that @code{throw} jumps to the dynamically innermost
5683: exception handler. The system's exception handler is outermost, and just
5684: prints an error and restarts command-line interpretation (or, in batch
5685: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5686:
1.68 anton 5687: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5688:
1.68 anton 5689: doc-catch
1.160 anton 5690: doc-nothrow
1.68 anton 5691:
5692: The most common use of exception handlers is to clean up the state when
5693: an error happens. E.g.,
1.1 anton 5694:
1.26 crook 5695: @example
1.68 anton 5696: base @ >r hex \ actually the hex should be inside foo, or we h
5697: ['] foo catch ( nerror|0 )
5698: r> base !
1.69 anton 5699: ( nerror|0 ) throw \ pass it on
1.26 crook 5700: @end example
1.1 anton 5701:
1.69 anton 5702: A use of @code{catch} for handling the error @code{myerror} might look
5703: like this:
1.44 crook 5704:
1.68 anton 5705: @example
1.69 anton 5706: ['] foo catch
5707: CASE
1.160 anton 5708: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5709: dup throw \ default: pass other errors on, do nothing on non-errors
5710: ENDCASE
1.68 anton 5711: @end example
1.44 crook 5712:
1.68 anton 5713: Having to wrap the code into a separate word is often cumbersome,
5714: therefore Gforth provides an alternative syntax:
1.1 anton 5715:
5716: @example
1.69 anton 5717: TRY
1.68 anton 5718: @i{code1}
1.172 anton 5719: IFERROR
5720: @i{code2}
5721: THEN
5722: @i{code3}
1.69 anton 5723: ENDTRY
1.1 anton 5724: @end example
5725:
1.172 anton 5726: This performs @i{code1}. If @i{code1} completes normally, execution
5727: continues with @i{code3}. If @i{code1} or there is an exception
5728: before @code{endtry}, the stacks are reset to the state during
5729: @code{try}, the throw value is pushed on the data stack, and execution
5730: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26 crook 5731:
1.68 anton 5732: doc-try
5733: doc-endtry
1.172 anton 5734: doc-iferror
5735:
5736: If you don't need @i{code2}, you can write @code{restore} instead of
5737: @code{iferror then}:
5738:
5739: @example
5740: TRY
5741: @i{code1}
5742: RESTORE
5743: @i{code3}
5744: ENDTRY
5745: @end example
1.26 crook 5746:
1.172 anton 5747: @cindex unwind-protect
1.69 anton 5748: The cleanup example from above in this syntax:
1.26 crook 5749:
1.68 anton 5750: @example
1.174 anton 5751: base @@ @{ oldbase @}
1.172 anton 5752: TRY
1.68 anton 5753: hex foo \ now the hex is placed correctly
1.69 anton 5754: 0 \ value for throw
1.172 anton 5755: RESTORE
5756: oldbase base !
5757: ENDTRY
5758: throw
1.1 anton 5759: @end example
5760:
1.172 anton 5761: An additional advantage of this variant is that an exception between
5762: @code{restore} and @code{endtry} (e.g., from the user pressing
5763: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5764: so the base will be restored under all circumstances.
5765:
5766: However, you have to ensure that this code does not cause an exception
5767: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5768: Moreover, you should also make sure that the stack contents needed by
5769: the @code{iferror}/@code{restore} code exist everywhere between
5770: @code{try} and @code{endtry}; in our example this is achived by
5771: putting the data in a local before the @code{try} (you cannot use the
5772: return stack because the exception frame (@i{sys1}) is in the way
5773: there).
5774:
5775: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5776:
5777: @cindex @code{recover} (old Gforth versions)
5778: If you do not want this exception-restarting behaviour, you achieve
5779: this as follows:
5780:
5781: @example
5782: TRY
5783: @i{code1}
5784: ENDTRY-IFERROR
5785: @i{code2}
5786: THEN
5787: @end example
5788:
5789: If there is an exception in @i{code1}, then @i{code2} is executed,
5790: otherwise execution continues behind the @code{then} (or in a possible
5791: @code{else} branch). This corresponds to the construct
5792:
5793: @example
5794: TRY
5795: @i{code1}
5796: RECOVER
5797: @i{code2}
5798: ENDTRY
5799: @end example
5800:
5801: in Gforth before version 0.7. So you can directly replace
5802: @code{recover}-using code; however, we recommend that you check if it
5803: would not be better to use one of the other @code{try} variants while
5804: you are at it.
5805:
1.173 anton 5806: To ease the transition, Gforth provides two compatibility files:
5807: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5808: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5809: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5810: ... endtry} syntax on new systems, so you can use that file as a
5811: stopgap to run old programs. Both files work on any system (they just
5812: do nothing if the system already has the syntax it implements), so you
5813: can unconditionally @code{require} one of these files, even if you use
5814: a mix old and new systems.
5815:
1.172 anton 5816: doc-restore
5817: doc-endtry-iferror
5818:
5819: Here's the error handling example:
1.1 anton 5820:
1.68 anton 5821: @example
1.69 anton 5822: TRY
1.68 anton 5823: foo
1.172 anton 5824: ENDTRY-IFERROR
1.69 anton 5825: CASE
1.160 anton 5826: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5827: throw \ pass other errors on
5828: ENDCASE
1.172 anton 5829: THEN
1.68 anton 5830: @end example
1.1 anton 5831:
1.69 anton 5832: @progstyle
5833: As usual, you should ensure that the stack depth is statically known at
5834: the end: either after the @code{throw} for passing on errors, or after
5835: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5836: selection construct for handling the error).
5837:
1.68 anton 5838: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5839: and you can provide an error message. @code{Abort} just produces an
5840: ``Aborted'' error.
1.1 anton 5841:
1.68 anton 5842: The problem with these words is that exception handlers cannot
5843: differentiate between different @code{abort"}s; they just look like
5844: @code{-2 throw} to them (the error message cannot be accessed by
5845: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5846: exception handlers.
1.44 crook 5847:
1.68 anton 5848: doc-abort"
1.26 crook 5849: doc-abort
1.29 crook 5850:
5851:
1.44 crook 5852:
1.29 crook 5853: @c -------------------------------------------------------------
1.47 crook 5854: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5855: @section Defining Words
5856: @cindex defining words
5857:
1.47 crook 5858: Defining words are used to extend Forth by creating new entries in the dictionary.
5859:
1.29 crook 5860: @menu
1.67 anton 5861: * CREATE::
1.44 crook 5862: * Variables:: Variables and user variables
1.67 anton 5863: * Constants::
1.44 crook 5864: * Values:: Initialised variables
1.67 anton 5865: * Colon Definitions::
1.44 crook 5866: * Anonymous Definitions:: Definitions without names
1.69 anton 5867: * Supplying names:: Passing definition names as strings
1.67 anton 5868: * User-defined Defining Words::
1.170 pazsan 5869: * Deferred Words:: Allow forward references
1.67 anton 5870: * Aliases::
1.29 crook 5871: @end menu
5872:
1.44 crook 5873: @node CREATE, Variables, Defining Words, Defining Words
5874: @subsection @code{CREATE}
1.29 crook 5875: @cindex simple defining words
5876: @cindex defining words, simple
5877:
5878: Defining words are used to create new entries in the dictionary. The
5879: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5880: this:
5881:
5882: @example
5883: CREATE new-word1
5884: @end example
5885:
1.69 anton 5886: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5887: input stream (@code{new-word1} in our example). It generates a
5888: dictionary entry for @code{new-word1}. When @code{new-word1} is
5889: executed, all that it does is leave an address on the stack. The address
5890: represents the value of the data space pointer (@code{HERE}) at the time
5891: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5892: associating a name with the address of a region of memory.
1.29 crook 5893:
1.34 anton 5894: doc-create
5895:
1.69 anton 5896: Note that in ANS Forth guarantees only for @code{create} that its body
5897: is in dictionary data space (i.e., where @code{here}, @code{allot}
5898: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5899: @code{create}d words can be modified with @code{does>}
5900: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5901: can only be applied to @code{create}d words.
5902:
1.29 crook 5903: By extending this example to reserve some memory in data space, we end
1.69 anton 5904: up with something like a @i{variable}. Here are two different ways to do
5905: it:
1.29 crook 5906:
5907: @example
5908: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5909: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5910: @end example
5911:
5912: The variable can be examined and modified using @code{@@} (``fetch'') and
5913: @code{!} (``store'') like this:
5914:
5915: @example
5916: new-word2 @@ . \ get address, fetch from it and display
5917: 1234 new-word2 ! \ new value, get address, store to it
5918: @end example
5919:
1.44 crook 5920: @cindex arrays
5921: A similar mechanism can be used to create arrays. For example, an
5922: 80-character text input buffer:
1.29 crook 5923:
5924: @example
1.44 crook 5925: CREATE text-buf 80 chars allot
5926:
1.168 anton 5927: text-buf 0 chars + c@@ \ the 1st character (offset 0)
5928: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 5929: @end example
1.29 crook 5930:
1.44 crook 5931: You can build arbitrarily complex data structures by allocating
1.49 anton 5932: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5933: learn about some Gforth tools that make it easier,
1.49 anton 5934: @xref{Structures}.
1.44 crook 5935:
5936:
5937: @node Variables, Constants, CREATE, Defining Words
5938: @subsection Variables
5939: @cindex variables
5940:
5941: The previous section showed how a sequence of commands could be used to
5942: generate a variable. As a final refinement, the whole code sequence can
5943: be wrapped up in a defining word (pre-empting the subject of the next
5944: section), making it easier to create new variables:
5945:
5946: @example
5947: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5948: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5949:
5950: myvariableX foo \ variable foo starts off with an unknown value
5951: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5952:
5953: 45 3 * foo ! \ set foo to 135
5954: 1234 joe ! \ set joe to 1234
5955: 3 joe +! \ increment joe by 3.. to 1237
5956: @end example
5957:
5958: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5959: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5960: guarantee that a @code{Variable} is initialised when it is created
5961: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5962: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5963: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5964: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5965: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5966: store a boolean, you can use @code{on} and @code{off} to toggle its
5967: state.
1.29 crook 5968:
1.34 anton 5969: doc-variable
5970: doc-2variable
5971: doc-fvariable
5972:
1.29 crook 5973: @cindex user variables
5974: @cindex user space
5975: The defining word @code{User} behaves in the same way as @code{Variable}.
5976: The difference is that it reserves space in @i{user (data) space} rather
5977: than normal data space. In a Forth system that has a multi-tasker, each
5978: task has its own set of user variables.
5979:
1.34 anton 5980: doc-user
1.67 anton 5981: @c doc-udp
5982: @c doc-uallot
1.34 anton 5983:
1.29 crook 5984: @comment TODO is that stuff about user variables strictly correct? Is it
5985: @comment just terminal tasks that have user variables?
5986: @comment should document tasker.fs (with some examples) elsewhere
5987: @comment in this manual, then expand on user space and user variables.
5988:
1.44 crook 5989: @node Constants, Values, Variables, Defining Words
5990: @subsection Constants
5991: @cindex constants
5992:
5993: @code{Constant} allows you to declare a fixed value and refer to it by
5994: name. For example:
1.29 crook 5995:
5996: @example
5997: 12 Constant INCHES-PER-FOOT
5998: 3E+08 fconstant SPEED-O-LIGHT
5999: @end example
6000:
6001: A @code{Variable} can be both read and written, so its run-time
6002: behaviour is to supply an address through which its current value can be
6003: manipulated. In contrast, the value of a @code{Constant} cannot be
6004: changed once it has been declared@footnote{Well, often it can be -- but
6005: not in a Standard, portable way. It's safer to use a @code{Value} (read
6006: on).} so it's not necessary to supply the address -- it is more
6007: efficient to return the value of the constant directly. That's exactly
6008: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6009: the top of the stack (You can find one
6010: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6011:
1.69 anton 6012: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6013: double and floating-point constants, respectively.
6014:
1.34 anton 6015: doc-constant
6016: doc-2constant
6017: doc-fconstant
6018:
6019: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6020: @c nac-> How could that not be true in an ANS Forth? You can't define a
6021: @c constant, use it and then delete the definition of the constant..
1.69 anton 6022:
6023: @c anton->An ANS Forth system can compile a constant to a literal; On
6024: @c decompilation you would see only the number, just as if it had been used
6025: @c in the first place. The word will stay, of course, but it will only be
6026: @c used by the text interpreter (no run-time duties, except when it is
6027: @c POSTPONEd or somesuch).
6028:
6029: @c nac:
1.44 crook 6030: @c I agree that it's rather deep, but IMO it is an important difference
6031: @c relative to other programming languages.. often it's annoying: it
6032: @c certainly changes my programming style relative to C.
6033:
1.69 anton 6034: @c anton: In what way?
6035:
1.29 crook 6036: Constants in Forth behave differently from their equivalents in other
6037: programming languages. In other languages, a constant (such as an EQU in
6038: assembler or a #define in C) only exists at compile-time; in the
6039: executable program the constant has been translated into an absolute
6040: number and, unless you are using a symbolic debugger, it's impossible to
6041: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6042: an entry in the header space and remains there after the code that uses
6043: it has been defined. In fact, it must remain in the dictionary since it
6044: has run-time duties to perform. For example:
1.29 crook 6045:
6046: @example
6047: 12 Constant INCHES-PER-FOOT
6048: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6049: @end example
6050:
6051: @cindex in-lining of constants
6052: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6053: associated with the constant @code{INCHES-PER-FOOT}. If you use
6054: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6055: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6056: attempt to optimise constants by in-lining them where they are used. You
6057: can force Gforth to in-line a constant like this:
6058:
6059: @example
6060: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6061: @end example
6062:
6063: If you use @code{see} to decompile @i{this} version of
6064: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6065: longer present. To understand how this works, read
6066: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6067:
6068: In-lining constants in this way might improve execution time
6069: fractionally, and can ensure that a constant is now only referenced at
6070: compile-time. However, the definition of the constant still remains in
6071: the dictionary. Some Forth compilers provide a mechanism for controlling
6072: a second dictionary for holding transient words such that this second
6073: dictionary can be deleted later in order to recover memory
6074: space. However, there is no standard way of doing this.
6075:
6076:
1.44 crook 6077: @node Values, Colon Definitions, Constants, Defining Words
6078: @subsection Values
6079: @cindex values
1.34 anton 6080:
1.69 anton 6081: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6082: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6083: (not in ANS Forth) you can access (and change) a @code{value} also with
6084: @code{>body}.
6085:
6086: Here are some
6087: examples:
1.29 crook 6088:
6089: @example
1.69 anton 6090: 12 Value APPLES \ Define APPLES with an initial value of 12
6091: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6092: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6093: APPLES \ puts 35 on the top of the stack.
1.29 crook 6094: @end example
6095:
1.44 crook 6096: doc-value
6097: doc-to
1.29 crook 6098:
1.35 anton 6099:
1.69 anton 6100:
1.44 crook 6101: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6102: @subsection Colon Definitions
6103: @cindex colon definitions
1.35 anton 6104:
6105: @example
1.44 crook 6106: : name ( ... -- ... )
6107: word1 word2 word3 ;
1.29 crook 6108: @end example
6109:
1.44 crook 6110: @noindent
6111: Creates a word called @code{name} that, upon execution, executes
6112: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6113:
1.49 anton 6114: The explanation above is somewhat superficial. For simple examples of
6115: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6116: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6117: Compilation Semantics}.
1.29 crook 6118:
1.44 crook 6119: doc-:
6120: doc-;
1.1 anton 6121:
1.34 anton 6122:
1.69 anton 6123: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6124: @subsection Anonymous Definitions
6125: @cindex colon definitions
6126: @cindex defining words without name
1.34 anton 6127:
1.44 crook 6128: Sometimes you want to define an @dfn{anonymous word}; a word without a
6129: name. You can do this with:
1.1 anton 6130:
1.44 crook 6131: doc-:noname
1.1 anton 6132:
1.44 crook 6133: This leaves the execution token for the word on the stack after the
6134: closing @code{;}. Here's an example in which a deferred word is
6135: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6136:
1.29 crook 6137: @example
1.44 crook 6138: Defer deferred
6139: :noname ( ... -- ... )
6140: ... ;
6141: IS deferred
1.29 crook 6142: @end example
1.26 crook 6143:
1.44 crook 6144: @noindent
6145: Gforth provides an alternative way of doing this, using two separate
6146: words:
1.27 crook 6147:
1.44 crook 6148: doc-noname
6149: @cindex execution token of last defined word
1.116 anton 6150: doc-latestxt
1.1 anton 6151:
1.44 crook 6152: @noindent
6153: The previous example can be rewritten using @code{noname} and
1.116 anton 6154: @code{latestxt}:
1.1 anton 6155:
1.26 crook 6156: @example
1.44 crook 6157: Defer deferred
6158: noname : ( ... -- ... )
6159: ... ;
1.116 anton 6160: latestxt IS deferred
1.26 crook 6161: @end example
1.1 anton 6162:
1.29 crook 6163: @noindent
1.44 crook 6164: @code{noname} works with any defining word, not just @code{:}.
6165:
1.116 anton 6166: @code{latestxt} also works when the last word was not defined as
1.71 anton 6167: @code{noname}. It does not work for combined words, though. It also has
6168: the useful property that is is valid as soon as the header for a
6169: definition has been built. Thus:
1.44 crook 6170:
6171: @example
1.116 anton 6172: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6173: @end example
1.1 anton 6174:
1.44 crook 6175: @noindent
6176: prints 3 numbers; the last two are the same.
1.26 crook 6177:
1.69 anton 6178: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6179: @subsection Supplying the name of a defined word
6180: @cindex names for defined words
6181: @cindex defining words, name given in a string
6182:
6183: By default, a defining word takes the name for the defined word from the
6184: input stream. Sometimes you want to supply the name from a string. You
6185: can do this with:
6186:
6187: doc-nextname
6188:
6189: For example:
6190:
6191: @example
6192: s" foo" nextname create
6193: @end example
6194:
6195: @noindent
6196: is equivalent to:
6197:
6198: @example
6199: create foo
6200: @end example
6201:
6202: @noindent
6203: @code{nextname} works with any defining word.
6204:
1.1 anton 6205:
1.170 pazsan 6206: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6207: @subsection User-defined Defining Words
6208: @cindex user-defined defining words
6209: @cindex defining words, user-defined
1.1 anton 6210:
1.29 crook 6211: You can create a new defining word by wrapping defining-time code around
6212: an existing defining word and putting the sequence in a colon
1.69 anton 6213: definition.
6214:
6215: @c anton: This example is very complex and leads in a quite different
6216: @c direction from the CREATE-DOES> stuff that follows. It should probably
6217: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6218: @c subsection of Defining Words)
6219:
6220: For example, suppose that you have a word @code{stats} that
1.29 crook 6221: gathers statistics about colon definitions given the @i{xt} of the
6222: definition, and you want every colon definition in your application to
6223: make a call to @code{stats}. You can define and use a new version of
6224: @code{:} like this:
6225:
6226: @example
6227: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6228: ... ; \ other code
6229:
1.116 anton 6230: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6231:
6232: my: foo + - ;
6233: @end example
6234:
6235: When @code{foo} is defined using @code{my:} these steps occur:
6236:
6237: @itemize @bullet
6238: @item
6239: @code{my:} is executed.
6240: @item
6241: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6242: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6243: the input stream for a name, builds a dictionary header for the name
6244: @code{foo} and switches @code{state} from interpret to compile.
6245: @item
1.116 anton 6246: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6247: being defined -- @code{foo} -- onto the stack.
6248: @item
6249: The code that was produced by @code{postpone literal} is executed; this
6250: causes the value on the stack to be compiled as a literal in the code
6251: area of @code{foo}.
6252: @item
6253: The code @code{['] stats} compiles a literal into the definition of
6254: @code{my:}. When @code{compile,} is executed, that literal -- the
6255: execution token for @code{stats} -- is layed down in the code area of
6256: @code{foo} , following the literal@footnote{Strictly speaking, the
6257: mechanism that @code{compile,} uses to convert an @i{xt} into something
6258: in the code area is implementation-dependent. A threaded implementation
6259: might spit out the execution token directly whilst another
6260: implementation might spit out a native code sequence.}.
6261: @item
6262: At this point, the execution of @code{my:} is complete, and control
6263: returns to the text interpreter. The text interpreter is in compile
6264: state, so subsequent text @code{+ -} is compiled into the definition of
6265: @code{foo} and the @code{;} terminates the definition as always.
6266: @end itemize
6267:
6268: You can use @code{see} to decompile a word that was defined using
6269: @code{my:} and see how it is different from a normal @code{:}
6270: definition. For example:
6271:
6272: @example
6273: : bar + - ; \ like foo but using : rather than my:
6274: see bar
6275: : bar
6276: + - ;
6277: see foo
6278: : foo
6279: 107645672 stats + - ;
6280:
1.140 anton 6281: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6282: @end example
6283:
6284: You can use techniques like this to make new defining words in terms of
6285: @i{any} existing defining word.
1.1 anton 6286:
6287:
1.29 crook 6288: @cindex defining defining words
1.26 crook 6289: @cindex @code{CREATE} ... @code{DOES>}
6290: If you want the words defined with your defining words to behave
6291: differently from words defined with standard defining words, you can
6292: write your defining word like this:
1.1 anton 6293:
6294: @example
1.26 crook 6295: : def-word ( "name" -- )
1.29 crook 6296: CREATE @i{code1}
1.26 crook 6297: DOES> ( ... -- ... )
1.29 crook 6298: @i{code2} ;
1.26 crook 6299:
6300: def-word name
1.1 anton 6301: @end example
6302:
1.29 crook 6303: @cindex child words
6304: This fragment defines a @dfn{defining word} @code{def-word} and then
6305: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6306: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6307: is not executed at this time. The word @code{name} is sometimes called a
6308: @dfn{child} of @code{def-word}.
6309:
6310: When you execute @code{name}, the address of the body of @code{name} is
6311: put on the data stack and @i{code2} is executed (the address of the body
6312: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6313: @code{CREATE}, i.e., the address a @code{create}d word returns by
6314: default).
6315:
6316: @c anton:
6317: @c www.dictionary.com says:
6318: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6319: @c several generations of absence, usually caused by the chance
6320: @c recombination of genes. 2.An individual or a part that exhibits
6321: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6322: @c of previous behavior after a period of absence.
6323: @c
6324: @c Doesn't seem to fit.
1.29 crook 6325:
1.69 anton 6326: @c @cindex atavism in child words
1.33 anton 6327: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6328: similarly; they all have a common run-time behaviour determined by
6329: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6330: body of the child word. The structure of the data is common to all
6331: children of @code{def-word}, but the data values are specific -- and
6332: private -- to each child word. When a child word is executed, the
6333: address of its private data area is passed as a parameter on TOS to be
6334: used and manipulated@footnote{It is legitimate both to read and write to
6335: this data area.} by @i{code2}.
1.29 crook 6336:
6337: The two fragments of code that make up the defining words act (are
6338: executed) at two completely separate times:
1.1 anton 6339:
1.29 crook 6340: @itemize @bullet
6341: @item
6342: At @i{define time}, the defining word executes @i{code1} to generate a
6343: child word
6344: @item
6345: At @i{child execution time}, when a child word is invoked, @i{code2}
6346: is executed, using parameters (data) that are private and specific to
6347: the child word.
6348: @end itemize
6349:
1.44 crook 6350: Another way of understanding the behaviour of @code{def-word} and
6351: @code{name} is to say that, if you make the following definitions:
1.33 anton 6352: @example
6353: : def-word1 ( "name" -- )
6354: CREATE @i{code1} ;
6355:
6356: : action1 ( ... -- ... )
6357: @i{code2} ;
6358:
6359: def-word1 name1
6360: @end example
6361:
1.44 crook 6362: @noindent
6363: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6364:
1.29 crook 6365: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6366:
1.1 anton 6367: @example
1.29 crook 6368: : CONSTANT ( w "name" -- )
6369: CREATE ,
1.26 crook 6370: DOES> ( -- w )
6371: @@ ;
1.1 anton 6372: @end example
6373:
1.29 crook 6374: @comment There is a beautiful description of how this works and what
6375: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6376: @comment commentary on the Counting Fruits problem.
6377:
6378: When you create a constant with @code{5 CONSTANT five}, a set of
6379: define-time actions take place; first a new word @code{five} is created,
6380: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6381: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6382: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6383: no code of its own; it simply contains a data field and a pointer to the
6384: code that follows @code{DOES>} in its defining word. That makes words
6385: created in this way very compact.
6386:
6387: The final example in this section is intended to remind you that space
6388: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6389: both read and written by a Standard program@footnote{Exercise: use this
6390: example as a starting point for your own implementation of @code{Value}
6391: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6392: @code{[']}.}:
6393:
6394: @example
6395: : foo ( "name" -- )
6396: CREATE -1 ,
6397: DOES> ( -- )
1.33 anton 6398: @@ . ;
1.29 crook 6399:
6400: foo first-word
6401: foo second-word
6402:
6403: 123 ' first-word >BODY !
6404: @end example
6405:
6406: If @code{first-word} had been a @code{CREATE}d word, we could simply
6407: have executed it to get the address of its data field. However, since it
6408: was defined to have @code{DOES>} actions, its execution semantics are to
6409: perform those @code{DOES>} actions. To get the address of its data field
6410: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6411: translate the xt into the address of the data field. When you execute
6412: @code{first-word}, it will display @code{123}. When you execute
6413: @code{second-word} it will display @code{-1}.
1.26 crook 6414:
6415: @cindex stack effect of @code{DOES>}-parts
6416: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6417: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6418: the stack effect of the defined words, not the stack effect of the
6419: following code (the following code expects the address of the body on
6420: the top of stack, which is not reflected in the stack comment). This is
6421: the convention that I use and recommend (it clashes a bit with using
6422: locals declarations for stack effect specification, though).
1.1 anton 6423:
1.53 anton 6424: @menu
6425: * CREATE..DOES> applications::
6426: * CREATE..DOES> details::
1.63 anton 6427: * Advanced does> usage example::
1.155 anton 6428: * Const-does>::
1.53 anton 6429: @end menu
6430:
6431: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6432: @subsubsection Applications of @code{CREATE..DOES>}
6433: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6434:
1.26 crook 6435: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6436:
1.26 crook 6437: @cindex factoring similar colon definitions
6438: When you see a sequence of code occurring several times, and you can
6439: identify a meaning, you will factor it out as a colon definition. When
6440: you see similar colon definitions, you can factor them using
6441: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6442: that look very similar:
1.1 anton 6443: @example
1.26 crook 6444: : ori, ( reg-target reg-source n -- )
6445: 0 asm-reg-reg-imm ;
6446: : andi, ( reg-target reg-source n -- )
6447: 1 asm-reg-reg-imm ;
1.1 anton 6448: @end example
6449:
1.26 crook 6450: @noindent
6451: This could be factored with:
6452: @example
6453: : reg-reg-imm ( op-code -- )
6454: CREATE ,
6455: DOES> ( reg-target reg-source n -- )
6456: @@ asm-reg-reg-imm ;
6457:
6458: 0 reg-reg-imm ori,
6459: 1 reg-reg-imm andi,
6460: @end example
1.1 anton 6461:
1.26 crook 6462: @cindex currying
6463: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6464: supply a part of the parameters for a word (known as @dfn{currying} in
6465: the functional language community). E.g., @code{+} needs two
6466: parameters. Creating versions of @code{+} with one parameter fixed can
6467: be done like this:
1.82 anton 6468:
1.1 anton 6469: @example
1.82 anton 6470: : curry+ ( n1 "name" -- )
1.26 crook 6471: CREATE ,
6472: DOES> ( n2 -- n1+n2 )
6473: @@ + ;
6474:
6475: 3 curry+ 3+
6476: -2 curry+ 2-
1.1 anton 6477: @end example
6478:
1.91 anton 6479:
1.63 anton 6480: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6481: @subsubsection The gory details of @code{CREATE..DOES>}
6482: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6483:
1.26 crook 6484: doc-does>
1.1 anton 6485:
1.26 crook 6486: @cindex @code{DOES>} in a separate definition
6487: This means that you need not use @code{CREATE} and @code{DOES>} in the
6488: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6489: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6490: @example
6491: : does1
6492: DOES> ( ... -- ... )
1.44 crook 6493: ... ;
6494:
6495: : does2
6496: DOES> ( ... -- ... )
6497: ... ;
6498:
6499: : def-word ( ... -- ... )
6500: create ...
6501: IF
6502: does1
6503: ELSE
6504: does2
6505: ENDIF ;
6506: @end example
6507:
6508: In this example, the selection of whether to use @code{does1} or
1.69 anton 6509: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6510: @code{CREATE}d.
6511:
6512: @cindex @code{DOES>} in interpretation state
6513: In a standard program you can apply a @code{DOES>}-part only if the last
6514: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6515: will override the behaviour of the last word defined in any case. In a
6516: standard program, you can use @code{DOES>} only in a colon
6517: definition. In Gforth, you can also use it in interpretation state, in a
6518: kind of one-shot mode; for example:
6519: @example
6520: CREATE name ( ... -- ... )
6521: @i{initialization}
6522: DOES>
6523: @i{code} ;
6524: @end example
6525:
6526: @noindent
6527: is equivalent to the standard:
6528: @example
6529: :noname
6530: DOES>
6531: @i{code} ;
6532: CREATE name EXECUTE ( ... -- ... )
6533: @i{initialization}
6534: @end example
6535:
1.53 anton 6536: doc->body
6537:
1.152 pazsan 6538: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6539: @subsubsection Advanced does> usage example
6540:
6541: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6542: for disassembling instructions, that follow a very repetetive scheme:
6543:
6544: @example
6545: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6546: @var{entry-num} cells @var{table} + !
6547: @end example
6548:
6549: Of course, this inspires the idea to factor out the commonalities to
6550: allow a definition like
6551:
6552: @example
6553: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6554: @end example
6555:
6556: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6557: correlated. Moreover, before I wrote the disassembler, there already
6558: existed code that defines instructions like this:
1.63 anton 6559:
6560: @example
6561: @var{entry-num} @var{inst-format} @var{inst-name}
6562: @end example
6563:
6564: This code comes from the assembler and resides in
6565: @file{arch/mips/insts.fs}.
6566:
6567: So I had to define the @var{inst-format} words that performed the scheme
6568: above when executed. At first I chose to use run-time code-generation:
6569:
6570: @example
6571: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6572: :noname Postpone @var{disasm-operands}
6573: name Postpone sliteral Postpone type Postpone ;
6574: swap cells @var{table} + ! ;
6575: @end example
6576:
6577: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6578:
1.63 anton 6579: An alternative would have been to write this using
6580: @code{create}/@code{does>}:
6581:
6582: @example
6583: : @var{inst-format} ( entry-num "name" -- )
6584: here name string, ( entry-num c-addr ) \ parse and save "name"
6585: noname create , ( entry-num )
1.116 anton 6586: latestxt swap cells @var{table} + !
1.63 anton 6587: does> ( addr w -- )
6588: \ disassemble instruction w at addr
6589: @@ >r
6590: @var{disasm-operands}
6591: r> count type ;
6592: @end example
6593:
6594: Somehow the first solution is simpler, mainly because it's simpler to
6595: shift a string from definition-time to use-time with @code{sliteral}
6596: than with @code{string,} and friends.
6597:
6598: I wrote a lot of words following this scheme and soon thought about
6599: factoring out the commonalities among them. Note that this uses a
6600: two-level defining word, i.e., a word that defines ordinary defining
6601: words.
6602:
6603: This time a solution involving @code{postpone} and friends seemed more
6604: difficult (try it as an exercise), so I decided to use a
6605: @code{create}/@code{does>} word; since I was already at it, I also used
6606: @code{create}/@code{does>} for the lower level (try using
6607: @code{postpone} etc. as an exercise), resulting in the following
6608: definition:
6609:
6610: @example
6611: : define-format ( disasm-xt table-xt -- )
6612: \ define an instruction format that uses disasm-xt for
6613: \ disassembling and enters the defined instructions into table
6614: \ table-xt
6615: create 2,
6616: does> ( u "inst" -- )
6617: \ defines an anonymous word for disassembling instruction inst,
6618: \ and enters it as u-th entry into table-xt
6619: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6620: noname create 2, \ define anonymous word
1.116 anton 6621: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6622: does> ( addr w -- )
6623: \ disassemble instruction w at addr
6624: 2@@ >r ( addr w disasm-xt R: c-addr )
6625: execute ( R: c-addr ) \ disassemble operands
6626: r> count type ; \ print name
6627: @end example
6628:
6629: Note that the tables here (in contrast to above) do the @code{cells +}
6630: by themselves (that's why you have to pass an xt). This word is used in
6631: the following way:
6632:
6633: @example
6634: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6635: @end example
6636:
1.71 anton 6637: As shown above, the defined instruction format is then used like this:
6638:
6639: @example
6640: @var{entry-num} @var{inst-format} @var{inst-name}
6641: @end example
6642:
1.63 anton 6643: In terms of currying, this kind of two-level defining word provides the
6644: parameters in three stages: first @var{disasm-operands} and @var{table},
6645: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6646: the instruction to be disassembled.
6647:
6648: Of course this did not quite fit all the instruction format names used
6649: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6650: the parameters into the right form.
6651:
6652: If you have trouble following this section, don't worry. First, this is
6653: involved and takes time (and probably some playing around) to
6654: understand; second, this is the first two-level
6655: @code{create}/@code{does>} word I have written in seventeen years of
6656: Forth; and if I did not have @file{insts.fs} to start with, I may well
6657: have elected to use just a one-level defining word (with some repeating
6658: of parameters when using the defining word). So it is not necessary to
6659: understand this, but it may improve your understanding of Forth.
1.44 crook 6660:
6661:
1.152 pazsan 6662: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6663: @subsubsection @code{Const-does>}
6664:
6665: A frequent use of @code{create}...@code{does>} is for transferring some
6666: values from definition-time to run-time. Gforth supports this use with
6667:
6668: doc-const-does>
6669:
6670: A typical use of this word is:
6671:
6672: @example
6673: : curry+ ( n1 "name" -- )
6674: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6675: + ;
6676:
6677: 3 curry+ 3+
6678: @end example
6679:
6680: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6681: definition to run-time.
6682:
6683: The advantages of using @code{const-does>} are:
6684:
6685: @itemize
6686:
6687: @item
6688: You don't have to deal with storing and retrieving the values, i.e.,
6689: your program becomes more writable and readable.
6690:
6691: @item
6692: When using @code{does>}, you have to introduce a @code{@@} that cannot
6693: be optimized away (because you could change the data using
6694: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6695:
6696: @end itemize
6697:
6698: An ANS Forth implementation of @code{const-does>} is available in
6699: @file{compat/const-does.fs}.
6700:
6701:
1.170 pazsan 6702: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6703: @subsection Deferred Words
1.44 crook 6704: @cindex deferred words
6705:
6706: The defining word @code{Defer} allows you to define a word by name
6707: without defining its behaviour; the definition of its behaviour is
6708: deferred. Here are two situation where this can be useful:
6709:
6710: @itemize @bullet
6711: @item
6712: Where you want to allow the behaviour of a word to be altered later, and
6713: for all precompiled references to the word to change when its behaviour
6714: is changed.
6715: @item
6716: For mutual recursion; @xref{Calls and returns}.
6717: @end itemize
6718:
6719: In the following example, @code{foo} always invokes the version of
6720: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6721: always invokes the version that prints ``@code{Hello}''. There is no way
6722: of getting @code{foo} to use the later version without re-ordering the
6723: source code and recompiling it.
6724:
6725: @example
6726: : greet ." Good morning" ;
6727: : foo ... greet ... ;
6728: : greet ." Hello" ;
6729: : bar ... greet ... ;
6730: @end example
6731:
6732: This problem can be solved by defining @code{greet} as a @code{Defer}red
6733: word. The behaviour of a @code{Defer}red word can be defined and
6734: redefined at any time by using @code{IS} to associate the xt of a
6735: previously-defined word with it. The previous example becomes:
6736:
6737: @example
1.69 anton 6738: Defer greet ( -- )
1.44 crook 6739: : foo ... greet ... ;
6740: : bar ... greet ... ;
1.69 anton 6741: : greet1 ( -- ) ." Good morning" ;
6742: : greet2 ( -- ) ." Hello" ;
1.132 anton 6743: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6744: @end example
6745:
1.69 anton 6746: @progstyle
6747: You should write a stack comment for every deferred word, and put only
6748: XTs into deferred words that conform to this stack effect. Otherwise
6749: it's too difficult to use the deferred word.
6750:
1.44 crook 6751: A deferred word can be used to improve the statistics-gathering example
6752: from @ref{User-defined Defining Words}; rather than edit the
6753: application's source code to change every @code{:} to a @code{my:}, do
6754: this:
6755:
6756: @example
6757: : real: : ; \ retain access to the original
6758: defer : \ redefine as a deferred word
1.132 anton 6759: ' my: IS : \ use special version of :
1.44 crook 6760: \
6761: \ load application here
6762: \
1.132 anton 6763: ' real: IS : \ go back to the original
1.44 crook 6764: @end example
6765:
6766:
1.132 anton 6767: One thing to note is that @code{IS} has special compilation semantics,
6768: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6769:
6770: @example
6771: : set-greet ( xt -- )
1.132 anton 6772: IS greet ;
1.44 crook 6773:
6774: ' greet1 set-greet
6775: @end example
6776:
1.132 anton 6777: In situations where @code{IS} does not fit, use @code{defer!} instead.
6778:
1.69 anton 6779: A deferred word can only inherit execution semantics from the xt
6780: (because that is all that an xt can represent -- for more discussion of
6781: this @pxref{Tokens for Words}); by default it will have default
6782: interpretation and compilation semantics deriving from this execution
6783: semantics. However, you can change the interpretation and compilation
6784: semantics of the deferred word in the usual ways:
1.44 crook 6785:
6786: @example
1.132 anton 6787: : bar .... ; immediate
1.44 crook 6788: Defer fred immediate
6789: Defer jim
6790:
1.132 anton 6791: ' bar IS jim \ jim has default semantics
6792: ' bar IS fred \ fred is immediate
1.44 crook 6793: @end example
6794:
6795: doc-defer
1.132 anton 6796: doc-defer!
1.44 crook 6797: doc-is
1.132 anton 6798: doc-defer@
6799: doc-action-of
1.44 crook 6800: @comment TODO document these: what's defers [is]
6801: doc-defers
6802:
6803: @c Use @code{words-deferred} to see a list of deferred words.
6804:
1.132 anton 6805: Definitions of these words (except @code{defers}) in ANS Forth are
6806: provided in @file{compat/defer.fs}.
1.44 crook 6807:
6808:
1.170 pazsan 6809: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6810: @subsection Aliases
6811: @cindex aliases
1.1 anton 6812:
1.44 crook 6813: The defining word @code{Alias} allows you to define a word by name that
6814: has the same behaviour as some other word. Here are two situation where
6815: this can be useful:
1.1 anton 6816:
1.44 crook 6817: @itemize @bullet
6818: @item
6819: When you want access to a word's definition from a different word list
6820: (for an example of this, see the definition of the @code{Root} word list
6821: in the Gforth source).
6822: @item
6823: When you want to create a synonym; a definition that can be known by
6824: either of two names (for example, @code{THEN} and @code{ENDIF} are
6825: aliases).
6826: @end itemize
1.1 anton 6827:
1.69 anton 6828: Like deferred words, an alias has default compilation and interpretation
6829: semantics at the beginning (not the modifications of the other word),
6830: but you can change them in the usual ways (@code{immediate},
6831: @code{compile-only}). For example:
1.1 anton 6832:
6833: @example
1.44 crook 6834: : foo ... ; immediate
6835:
6836: ' foo Alias bar \ bar is not an immediate word
6837: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6838: @end example
6839:
1.44 crook 6840: Words that are aliases have the same xt, different headers in the
6841: dictionary, and consequently different name tokens (@pxref{Tokens for
6842: Words}) and possibly different immediate flags. An alias can only have
6843: default or immediate compilation semantics; you can define aliases for
6844: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6845:
1.44 crook 6846: doc-alias
1.1 anton 6847:
6848:
1.47 crook 6849: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6850: @section Interpretation and Compilation Semantics
1.26 crook 6851: @cindex semantics, interpretation and compilation
1.1 anton 6852:
1.71 anton 6853: @c !! state and ' are used without explanation
6854: @c example for immediate/compile-only? or is the tutorial enough
6855:
1.26 crook 6856: @cindex interpretation semantics
1.71 anton 6857: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6858: interpreter does when it encounters the word in interpret state. It also
6859: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6860: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6861: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6862: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6863:
1.26 crook 6864: @cindex compilation semantics
1.71 anton 6865: The @dfn{compilation semantics} of a (named) word are what the text
6866: interpreter does when it encounters the word in compile state. It also
6867: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6868: compiles@footnote{In standard terminology, ``appends to the current
6869: definition''.} the compilation semantics of @i{word}.
1.1 anton 6870:
1.26 crook 6871: @cindex execution semantics
6872: The standard also talks about @dfn{execution semantics}. They are used
6873: only for defining the interpretation and compilation semantics of many
6874: words. By default, the interpretation semantics of a word are to
6875: @code{execute} its execution semantics, and the compilation semantics of
6876: a word are to @code{compile,} its execution semantics.@footnote{In
6877: standard terminology: The default interpretation semantics are its
6878: execution semantics; the default compilation semantics are to append its
6879: execution semantics to the execution semantics of the current
6880: definition.}
6881:
1.71 anton 6882: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6883: the text interpreter, ticked, or @code{postpone}d, so they have no
6884: interpretation or compilation semantics. Their behaviour is represented
6885: by their XT (@pxref{Tokens for Words}), and we call it execution
6886: semantics, too.
6887:
1.26 crook 6888: @comment TODO expand, make it co-operate with new sections on text interpreter.
6889:
6890: @cindex immediate words
6891: @cindex compile-only words
6892: You can change the semantics of the most-recently defined word:
6893:
1.44 crook 6894:
1.26 crook 6895: doc-immediate
6896: doc-compile-only
6897: doc-restrict
6898:
1.82 anton 6899: By convention, words with non-default compilation semantics (e.g.,
6900: immediate words) often have names surrounded with brackets (e.g.,
6901: @code{[']}, @pxref{Execution token}).
1.44 crook 6902:
1.26 crook 6903: Note that ticking (@code{'}) a compile-only word gives an error
6904: (``Interpreting a compile-only word'').
1.1 anton 6905:
1.47 crook 6906: @menu
1.67 anton 6907: * Combined words::
1.47 crook 6908: @end menu
1.44 crook 6909:
1.71 anton 6910:
1.48 anton 6911: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6912: @subsection Combined Words
6913: @cindex combined words
6914:
6915: Gforth allows you to define @dfn{combined words} -- words that have an
6916: arbitrary combination of interpretation and compilation semantics.
6917:
1.26 crook 6918: doc-interpret/compile:
1.1 anton 6919:
1.26 crook 6920: This feature was introduced for implementing @code{TO} and @code{S"}. I
6921: recommend that you do not define such words, as cute as they may be:
6922: they make it hard to get at both parts of the word in some contexts.
6923: E.g., assume you want to get an execution token for the compilation
6924: part. Instead, define two words, one that embodies the interpretation
6925: part, and one that embodies the compilation part. Once you have done
6926: that, you can define a combined word with @code{interpret/compile:} for
6927: the convenience of your users.
1.1 anton 6928:
1.26 crook 6929: You might try to use this feature to provide an optimizing
6930: implementation of the default compilation semantics of a word. For
6931: example, by defining:
1.1 anton 6932: @example
1.26 crook 6933: :noname
6934: foo bar ;
6935: :noname
6936: POSTPONE foo POSTPONE bar ;
1.29 crook 6937: interpret/compile: opti-foobar
1.1 anton 6938: @end example
1.26 crook 6939:
1.23 crook 6940: @noindent
1.26 crook 6941: as an optimizing version of:
6942:
1.1 anton 6943: @example
1.26 crook 6944: : foobar
6945: foo bar ;
1.1 anton 6946: @end example
6947:
1.26 crook 6948: Unfortunately, this does not work correctly with @code{[compile]},
6949: because @code{[compile]} assumes that the compilation semantics of all
6950: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6951: opti-foobar} would compile compilation semantics, whereas
6952: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6953:
1.26 crook 6954: @cindex state-smart words (are a bad idea)
1.82 anton 6955: @anchor{state-smartness}
1.29 crook 6956: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6957: by @code{interpret/compile:} (words are state-smart if they check
6958: @code{STATE} during execution). E.g., they would try to code
6959: @code{foobar} like this:
1.1 anton 6960:
1.26 crook 6961: @example
6962: : foobar
6963: STATE @@
6964: IF ( compilation state )
6965: POSTPONE foo POSTPONE bar
6966: ELSE
6967: foo bar
6968: ENDIF ; immediate
6969: @end example
1.1 anton 6970:
1.26 crook 6971: Although this works if @code{foobar} is only processed by the text
6972: interpreter, it does not work in other contexts (like @code{'} or
6973: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6974: for a state-smart word, not for the interpretation semantics of the
6975: original @code{foobar}; when you execute this execution token (directly
6976: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6977: state, the result will not be what you expected (i.e., it will not
6978: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6979: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6980: M. Anton Ertl,
6981: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6982: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6983:
1.26 crook 6984: @cindex defining words with arbitrary semantics combinations
6985: It is also possible to write defining words that define words with
6986: arbitrary combinations of interpretation and compilation semantics. In
6987: general, they look like this:
1.1 anton 6988:
1.26 crook 6989: @example
6990: : def-word
6991: create-interpret/compile
1.29 crook 6992: @i{code1}
1.26 crook 6993: interpretation>
1.29 crook 6994: @i{code2}
1.26 crook 6995: <interpretation
6996: compilation>
1.29 crook 6997: @i{code3}
1.26 crook 6998: <compilation ;
6999: @end example
1.1 anton 7000:
1.29 crook 7001: For a @i{word} defined with @code{def-word}, the interpretation
7002: semantics are to push the address of the body of @i{word} and perform
7003: @i{code2}, and the compilation semantics are to push the address of
7004: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7005: can also be defined like this (except that the defined constants don't
7006: behave correctly when @code{[compile]}d):
1.1 anton 7007:
1.26 crook 7008: @example
7009: : constant ( n "name" -- )
7010: create-interpret/compile
7011: ,
7012: interpretation> ( -- n )
7013: @@
7014: <interpretation
7015: compilation> ( compilation. -- ; run-time. -- n )
7016: @@ postpone literal
7017: <compilation ;
7018: @end example
1.1 anton 7019:
1.44 crook 7020:
1.26 crook 7021: doc-create-interpret/compile
7022: doc-interpretation>
7023: doc-<interpretation
7024: doc-compilation>
7025: doc-<compilation
1.1 anton 7026:
1.44 crook 7027:
1.29 crook 7028: Words defined with @code{interpret/compile:} and
1.26 crook 7029: @code{create-interpret/compile} have an extended header structure that
7030: differs from other words; however, unless you try to access them with
7031: plain address arithmetic, you should not notice this. Words for
7032: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7033: @code{'} @i{word} @code{>body} also gives you the body of a word created
7034: with @code{create-interpret/compile}.
1.1 anton 7035:
1.44 crook 7036:
1.47 crook 7037: @c -------------------------------------------------------------
1.81 anton 7038: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7039: @section Tokens for Words
7040: @cindex tokens for words
7041:
7042: This section describes the creation and use of tokens that represent
7043: words.
7044:
1.71 anton 7045: @menu
7046: * Execution token:: represents execution/interpretation semantics
7047: * Compilation token:: represents compilation semantics
7048: * Name token:: represents named words
7049: @end menu
1.47 crook 7050:
1.71 anton 7051: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7052: @subsection Execution token
1.47 crook 7053:
7054: @cindex xt
7055: @cindex execution token
1.71 anton 7056: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7057: You can use @code{execute} to invoke this behaviour.
1.47 crook 7058:
1.71 anton 7059: @cindex tick (')
7060: You can use @code{'} to get an execution token that represents the
7061: interpretation semantics of a named word:
1.47 crook 7062:
7063: @example
1.97 anton 7064: 5 ' . ( n xt )
7065: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7066: @end example
1.47 crook 7067:
1.71 anton 7068: doc-'
7069:
7070: @code{'} parses at run-time; there is also a word @code{[']} that parses
7071: when it is compiled, and compiles the resulting XT:
7072:
7073: @example
7074: : foo ['] . execute ;
7075: 5 foo
7076: : bar ' execute ; \ by contrast,
7077: 5 bar . \ ' parses "." when bar executes
7078: @end example
7079:
7080: doc-[']
7081:
7082: If you want the execution token of @i{word}, write @code{['] @i{word}}
7083: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7084: @code{'} and @code{[']} behave somewhat unusually by complaining about
7085: compile-only words (because these words have no interpretation
7086: semantics). You might get what you want by using @code{COMP' @i{word}
7087: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7088: token}).
7089:
1.116 anton 7090: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7091: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7092: for the only behaviour the word has (the execution semantics). For
1.116 anton 7093: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7094: would produce if the word was defined anonymously.
7095:
7096: @example
7097: :noname ." hello" ;
7098: execute
1.47 crook 7099: @end example
7100:
1.71 anton 7101: An XT occupies one cell and can be manipulated like any other cell.
7102:
1.47 crook 7103: @cindex code field address
7104: @cindex CFA
1.71 anton 7105: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7106: operations that produce or consume it). For old hands: In Gforth, the
7107: XT is implemented as a code field address (CFA).
7108:
7109: doc-execute
7110: doc-perform
7111:
7112: @node Compilation token, Name token, Execution token, Tokens for Words
7113: @subsection Compilation token
1.47 crook 7114:
7115: @cindex compilation token
1.71 anton 7116: @cindex CT (compilation token)
7117: Gforth represents the compilation semantics of a named word by a
1.47 crook 7118: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7119: @i{xt} is an execution token. The compilation semantics represented by
7120: the compilation token can be performed with @code{execute}, which
7121: consumes the whole compilation token, with an additional stack effect
7122: determined by the represented compilation semantics.
7123:
7124: At present, the @i{w} part of a compilation token is an execution token,
7125: and the @i{xt} part represents either @code{execute} or
7126: @code{compile,}@footnote{Depending upon the compilation semantics of the
7127: word. If the word has default compilation semantics, the @i{xt} will
7128: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7129: @i{xt} will represent @code{execute}.}. However, don't rely on that
7130: knowledge, unless necessary; future versions of Gforth may introduce
7131: unusual compilation tokens (e.g., a compilation token that represents
7132: the compilation semantics of a literal).
7133:
1.71 anton 7134: You can perform the compilation semantics represented by the compilation
7135: token with @code{execute}. You can compile the compilation semantics
7136: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7137: equivalent to @code{postpone @i{word}}.
7138:
7139: doc-[comp']
7140: doc-comp'
7141: doc-postpone,
7142:
7143: @node Name token, , Compilation token, Tokens for Words
7144: @subsection Name token
1.47 crook 7145:
7146: @cindex name token
1.116 anton 7147: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7148: token is an abstract data type that occurs as argument or result of the
7149: words below.
7150:
7151: @c !! put this elswhere?
1.47 crook 7152: @cindex name field address
7153: @cindex NFA
1.116 anton 7154: The closest thing to the nt in older Forth systems is the name field
7155: address (NFA), but there are significant differences: in older Forth
7156: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7157: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7158: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7159: is a link field in the structure identified by the name token, but
7160: searching usually uses a hash table external to these structures; the
7161: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7162: implemented as the address of that count field.
1.47 crook 7163:
7164: doc-find-name
1.116 anton 7165: doc-latest
7166: doc->name
1.47 crook 7167: doc-name>int
7168: doc-name?int
7169: doc-name>comp
7170: doc-name>string
1.109 anton 7171: doc-id.
7172: doc-.name
7173: doc-.id
1.47 crook 7174:
1.81 anton 7175: @c ----------------------------------------------------------
7176: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7177: @section Compiling words
7178: @cindex compiling words
7179: @cindex macros
7180:
7181: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7182: between compilation and run-time. E.g., you can run arbitrary code
7183: between defining words (or for computing data used by defining words
7184: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7185: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7186: running arbitrary code while compiling a colon definition (exception:
7187: you must not allot dictionary space).
7188:
7189: @menu
7190: * Literals:: Compiling data values
7191: * Macros:: Compiling words
7192: @end menu
7193:
7194: @node Literals, Macros, Compiling words, Compiling words
7195: @subsection Literals
7196: @cindex Literals
7197:
7198: The simplest and most frequent example is to compute a literal during
7199: compilation. E.g., the following definition prints an array of strings,
7200: one string per line:
7201:
7202: @example
7203: : .strings ( addr u -- ) \ gforth
7204: 2* cells bounds U+DO
7205: cr i 2@@ type
7206: 2 cells +LOOP ;
7207: @end example
1.81 anton 7208:
1.82 anton 7209: With a simple-minded compiler like Gforth's, this computes @code{2
7210: cells} on every loop iteration. You can compute this value once and for
7211: all at compile time and compile it into the definition like this:
7212:
7213: @example
7214: : .strings ( addr u -- ) \ gforth
7215: 2* cells bounds U+DO
7216: cr i 2@@ type
7217: [ 2 cells ] literal +LOOP ;
7218: @end example
7219:
7220: @code{[} switches the text interpreter to interpret state (you will get
7221: an @code{ok} prompt if you type this example interactively and insert a
7222: newline between @code{[} and @code{]}), so it performs the
7223: interpretation semantics of @code{2 cells}; this computes a number.
7224: @code{]} switches the text interpreter back into compile state. It then
7225: performs @code{Literal}'s compilation semantics, which are to compile
7226: this number into the current word. You can decompile the word with
7227: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7228:
1.82 anton 7229: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7230: *} in this way.
1.81 anton 7231:
1.82 anton 7232: doc-[
7233: doc-]
1.81 anton 7234: doc-literal
7235: doc-]L
1.82 anton 7236:
7237: There are also words for compiling other data types than single cells as
7238: literals:
7239:
1.81 anton 7240: doc-2literal
7241: doc-fliteral
1.82 anton 7242: doc-sliteral
7243:
7244: @cindex colon-sys, passing data across @code{:}
7245: @cindex @code{:}, passing data across
7246: You might be tempted to pass data from outside a colon definition to the
7247: inside on the data stack. This does not work, because @code{:} puhes a
7248: colon-sys, making stuff below unaccessible. E.g., this does not work:
7249:
7250: @example
7251: 5 : foo literal ; \ error: "unstructured"
7252: @end example
7253:
7254: Instead, you have to pass the value in some other way, e.g., through a
7255: variable:
7256:
7257: @example
7258: variable temp
7259: 5 temp !
7260: : foo [ temp @@ ] literal ;
7261: @end example
7262:
7263:
7264: @node Macros, , Literals, Compiling words
7265: @subsection Macros
7266: @cindex Macros
7267: @cindex compiling compilation semantics
7268:
7269: @code{Literal} and friends compile data values into the current
7270: definition. You can also write words that compile other words into the
7271: current definition. E.g.,
7272:
7273: @example
7274: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7275: POSTPONE + ;
7276:
7277: : foo ( n1 n2 -- n )
7278: [ compile-+ ] ;
7279: 1 2 foo .
7280: @end example
7281:
7282: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7283: What happens in this example? @code{Postpone} compiles the compilation
7284: semantics of @code{+} into @code{compile-+}; later the text interpreter
7285: executes @code{compile-+} and thus the compilation semantics of +, which
7286: compile (the execution semantics of) @code{+} into
7287: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7288: should only be executed in compile state, so this example is not
7289: guaranteed to work on all standard systems, but on any decent system it
7290: will work.}
7291:
7292: doc-postpone
7293: doc-[compile]
7294:
7295: Compiling words like @code{compile-+} are usually immediate (or similar)
7296: so you do not have to switch to interpret state to execute them;
7297: mopifying the last example accordingly produces:
7298:
7299: @example
7300: : [compile-+] ( compilation: --; interpretation: -- )
7301: \ compiled code: ( n1 n2 -- n )
7302: POSTPONE + ; immediate
7303:
7304: : foo ( n1 n2 -- n )
7305: [compile-+] ;
7306: 1 2 foo .
7307: @end example
7308:
7309: Immediate compiling words are similar to macros in other languages (in
7310: particular, Lisp). The important differences to macros in, e.g., C are:
7311:
7312: @itemize @bullet
7313:
7314: @item
7315: You use the same language for defining and processing macros, not a
7316: separate preprocessing language and processor.
7317:
7318: @item
7319: Consequently, the full power of Forth is available in macro definitions.
7320: E.g., you can perform arbitrarily complex computations, or generate
7321: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7322: Tutorial}). This power is very useful when writing a parser generators
7323: or other code-generating software.
7324:
7325: @item
7326: Macros defined using @code{postpone} etc. deal with the language at a
7327: higher level than strings; name binding happens at macro definition
7328: time, so you can avoid the pitfalls of name collisions that can happen
7329: in C macros. Of course, Forth is a liberal language and also allows to
7330: shoot yourself in the foot with text-interpreted macros like
7331:
7332: @example
7333: : [compile-+] s" +" evaluate ; immediate
7334: @end example
7335:
7336: Apart from binding the name at macro use time, using @code{evaluate}
7337: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7338: @end itemize
7339:
7340: You may want the macro to compile a number into a word. The word to do
7341: it is @code{literal}, but you have to @code{postpone} it, so its
7342: compilation semantics take effect when the macro is executed, not when
7343: it is compiled:
7344:
7345: @example
7346: : [compile-5] ( -- ) \ compiled code: ( -- n )
7347: 5 POSTPONE literal ; immediate
7348:
7349: : foo [compile-5] ;
7350: foo .
7351: @end example
7352:
7353: You may want to pass parameters to a macro, that the macro should
7354: compile into the current definition. If the parameter is a number, then
7355: you can use @code{postpone literal} (similar for other values).
7356:
7357: If you want to pass a word that is to be compiled, the usual way is to
7358: pass an execution token and @code{compile,} it:
7359:
7360: @example
7361: : twice1 ( xt -- ) \ compiled code: ... -- ...
7362: dup compile, compile, ;
7363:
7364: : 2+ ( n1 -- n2 )
7365: [ ' 1+ twice1 ] ;
7366: @end example
7367:
7368: doc-compile,
7369:
7370: An alternative available in Gforth, that allows you to pass compile-only
7371: words as parameters is to use the compilation token (@pxref{Compilation
7372: token}). The same example in this technique:
7373:
7374: @example
7375: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7376: 2dup 2>r execute 2r> execute ;
7377:
7378: : 2+ ( n1 -- n2 )
7379: [ comp' 1+ twice ] ;
7380: @end example
7381:
7382: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7383: works even if the executed compilation semantics has an effect on the
7384: data stack.
7385:
7386: You can also define complete definitions with these words; this provides
7387: an alternative to using @code{does>} (@pxref{User-defined Defining
7388: Words}). E.g., instead of
7389:
7390: @example
7391: : curry+ ( n1 "name" -- )
7392: CREATE ,
7393: DOES> ( n2 -- n1+n2 )
7394: @@ + ;
7395: @end example
7396:
7397: you could define
7398:
7399: @example
7400: : curry+ ( n1 "name" -- )
7401: \ name execution: ( n2 -- n1+n2 )
7402: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7403:
1.82 anton 7404: -3 curry+ 3-
7405: see 3-
7406: @end example
1.81 anton 7407:
1.82 anton 7408: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7409: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7410:
1.82 anton 7411: This way of writing defining words is sometimes more, sometimes less
7412: convenient than using @code{does>} (@pxref{Advanced does> usage
7413: example}). One advantage of this method is that it can be optimized
7414: better, because the compiler knows that the value compiled with
7415: @code{literal} is fixed, whereas the data associated with a
7416: @code{create}d word can be changed.
1.47 crook 7417:
1.26 crook 7418: @c ----------------------------------------------------------
1.111 anton 7419: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7420: @section The Text Interpreter
7421: @cindex interpreter - outer
7422: @cindex text interpreter
7423: @cindex outer interpreter
1.1 anton 7424:
1.34 anton 7425: @c Should we really describe all these ugly details? IMO the text
7426: @c interpreter should be much cleaner, but that may not be possible within
7427: @c ANS Forth. - anton
1.44 crook 7428: @c nac-> I wanted to explain how it works to show how you can exploit
7429: @c it in your own programs. When I was writing a cross-compiler, figuring out
7430: @c some of these gory details was very helpful to me. None of the textbooks
7431: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7432: @c seems to positively avoid going into too much detail for some of
7433: @c the internals.
1.34 anton 7434:
1.71 anton 7435: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7436: @c it is; for the ugly details, I would prefer another place. I wonder
7437: @c whether we should have a chapter before "Words" that describes some
7438: @c basic concepts referred to in words, and a chapter after "Words" that
7439: @c describes implementation details.
7440:
1.29 crook 7441: The text interpreter@footnote{This is an expanded version of the
7442: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7443: that processes input from the current input device. It is also called
7444: the outer interpreter, in contrast to the inner interpreter
7445: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7446: implementations.
1.27 crook 7447:
1.29 crook 7448: @cindex interpret state
7449: @cindex compile state
7450: The text interpreter operates in one of two states: @dfn{interpret
7451: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7452: aptly-named variable @code{state}.
1.29 crook 7453:
7454: This section starts by describing how the text interpreter behaves when
7455: it is in interpret state, processing input from the user input device --
7456: the keyboard. This is the mode that a Forth system is in after it starts
7457: up.
7458:
7459: @cindex input buffer
7460: @cindex terminal input buffer
7461: The text interpreter works from an area of memory called the @dfn{input
7462: buffer}@footnote{When the text interpreter is processing input from the
7463: keyboard, this area of memory is called the @dfn{terminal input buffer}
7464: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7465: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7466: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7467: leading spaces (called @dfn{delimiters}) then parses a string (a
7468: sequence of non-space characters) until it reaches either a space
7469: character or the end of the buffer. Having parsed a string, it makes two
7470: attempts to process it:
1.27 crook 7471:
1.29 crook 7472: @cindex dictionary
1.27 crook 7473: @itemize @bullet
7474: @item
1.29 crook 7475: It looks for the string in a @dfn{dictionary} of definitions. If the
7476: string is found, the string names a @dfn{definition} (also known as a
7477: @dfn{word}) and the dictionary search returns information that allows
7478: the text interpreter to perform the word's @dfn{interpretation
7479: semantics}. In most cases, this simply means that the word will be
7480: executed.
1.27 crook 7481: @item
7482: If the string is not found in the dictionary, the text interpreter
1.29 crook 7483: attempts to treat it as a number, using the rules described in
7484: @ref{Number Conversion}. If the string represents a legal number in the
7485: current radix, the number is pushed onto a parameter stack (the data
7486: stack for integers, the floating-point stack for floating-point
7487: numbers).
7488: @end itemize
7489:
7490: If both attempts fail, or if the word is found in the dictionary but has
7491: no interpretation semantics@footnote{This happens if the word was
7492: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7493: remainder of the input buffer, issues an error message and waits for
7494: more input. If one of the attempts succeeds, the text interpreter
7495: repeats the parsing process until the whole of the input buffer has been
7496: processed, at which point it prints the status message ``@code{ ok}''
7497: and waits for more input.
7498:
1.71 anton 7499: @c anton: this should be in the input stream subsection (or below it)
7500:
1.29 crook 7501: @cindex parse area
7502: The text interpreter keeps track of its position in the input buffer by
7503: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7504: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7505: of the input buffer. The region from offset @code{>IN @@} to the end of
7506: the input buffer is called the @dfn{parse area}@footnote{In other words,
7507: the text interpreter processes the contents of the input buffer by
7508: parsing strings from the parse area until the parse area is empty.}.
7509: This example shows how @code{>IN} changes as the text interpreter parses
7510: the input buffer:
7511:
7512: @example
7513: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7514: CR ." ->" TYPE ." <-" ; IMMEDIATE
7515:
7516: 1 2 3 remaining + remaining .
7517:
7518: : foo 1 2 3 remaining SWAP remaining ;
7519: @end example
7520:
7521: @noindent
7522: The result is:
7523:
7524: @example
7525: ->+ remaining .<-
7526: ->.<-5 ok
7527:
7528: ->SWAP remaining ;-<
7529: ->;<- ok
7530: @end example
7531:
7532: @cindex parsing words
7533: The value of @code{>IN} can also be modified by a word in the input
7534: buffer that is executed by the text interpreter. This means that a word
7535: can ``trick'' the text interpreter into either skipping a section of the
7536: input buffer@footnote{This is how parsing words work.} or into parsing a
7537: section twice. For example:
1.27 crook 7538:
1.29 crook 7539: @example
1.71 anton 7540: : lat ." <<foo>>" ;
7541: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7542: @end example
7543:
7544: @noindent
7545: When @code{flat} is executed, this output is produced@footnote{Exercise
7546: for the reader: what would happen if the @code{3} were replaced with
7547: @code{4}?}:
7548:
7549: @example
1.71 anton 7550: <<bar>><<foo>>
1.29 crook 7551: @end example
7552:
1.71 anton 7553: This technique can be used to work around some of the interoperability
7554: problems of parsing words. Of course, it's better to avoid parsing
7555: words where possible.
7556:
1.29 crook 7557: @noindent
7558: Two important notes about the behaviour of the text interpreter:
1.27 crook 7559:
7560: @itemize @bullet
7561: @item
7562: It processes each input string to completion before parsing additional
1.29 crook 7563: characters from the input buffer.
7564: @item
7565: It treats the input buffer as a read-only region (and so must your code).
7566: @end itemize
7567:
7568: @noindent
7569: When the text interpreter is in compile state, its behaviour changes in
7570: these ways:
7571:
7572: @itemize @bullet
7573: @item
7574: If a parsed string is found in the dictionary, the text interpreter will
7575: perform the word's @dfn{compilation semantics}. In most cases, this
7576: simply means that the execution semantics of the word will be appended
7577: to the current definition.
1.27 crook 7578: @item
1.29 crook 7579: When a number is encountered, it is compiled into the current definition
7580: (as a literal) rather than being pushed onto a parameter stack.
7581: @item
7582: If an error occurs, @code{state} is modified to put the text interpreter
7583: back into interpret state.
7584: @item
7585: Each time a line is entered from the keyboard, Gforth prints
7586: ``@code{ compiled}'' rather than `` @code{ok}''.
7587: @end itemize
7588:
7589: @cindex text interpreter - input sources
7590: When the text interpreter is using an input device other than the
7591: keyboard, its behaviour changes in these ways:
7592:
7593: @itemize @bullet
7594: @item
7595: When the parse area is empty, the text interpreter attempts to refill
7596: the input buffer from the input source. When the input source is
1.71 anton 7597: exhausted, the input source is set back to the previous input source.
1.29 crook 7598: @item
7599: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7600: time the parse area is emptied.
7601: @item
7602: If an error occurs, the input source is set back to the user input
7603: device.
1.27 crook 7604: @end itemize
1.21 crook 7605:
1.49 anton 7606: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7607:
1.26 crook 7608: doc->in
1.27 crook 7609: doc-source
7610:
1.26 crook 7611: doc-tib
7612: doc-#tib
1.1 anton 7613:
1.44 crook 7614:
1.26 crook 7615: @menu
1.67 anton 7616: * Input Sources::
7617: * Number Conversion::
7618: * Interpret/Compile states::
7619: * Interpreter Directives::
1.26 crook 7620: @end menu
1.1 anton 7621:
1.29 crook 7622: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7623: @subsection Input Sources
7624: @cindex input sources
7625: @cindex text interpreter - input sources
7626:
1.44 crook 7627: By default, the text interpreter processes input from the user input
1.29 crook 7628: device (the keyboard) when Forth starts up. The text interpreter can
7629: process input from any of these sources:
7630:
7631: @itemize @bullet
7632: @item
7633: The user input device -- the keyboard.
7634: @item
7635: A file, using the words described in @ref{Forth source files}.
7636: @item
7637: A block, using the words described in @ref{Blocks}.
7638: @item
7639: A text string, using @code{evaluate}.
7640: @end itemize
7641:
7642: A program can identify the current input device from the values of
7643: @code{source-id} and @code{blk}.
7644:
1.44 crook 7645:
1.29 crook 7646: doc-source-id
7647: doc-blk
7648:
7649: doc-save-input
7650: doc-restore-input
7651:
7652: doc-evaluate
1.111 anton 7653: doc-query
1.1 anton 7654:
1.29 crook 7655:
1.44 crook 7656:
1.29 crook 7657: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7658: @subsection Number Conversion
7659: @cindex number conversion
7660: @cindex double-cell numbers, input format
7661: @cindex input format for double-cell numbers
7662: @cindex single-cell numbers, input format
7663: @cindex input format for single-cell numbers
7664: @cindex floating-point numbers, input format
7665: @cindex input format for floating-point numbers
1.1 anton 7666:
1.29 crook 7667: This section describes the rules that the text interpreter uses when it
7668: tries to convert a string into a number.
1.1 anton 7669:
1.26 crook 7670: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7671: number base@footnote{For example, 0-9 when the number base is decimal or
7672: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7673:
1.26 crook 7674: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7675:
1.29 crook 7676: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7677: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7678:
1.26 crook 7679: Let * represent any number of instances of the previous character
7680: (including none).
1.1 anton 7681:
1.26 crook 7682: Let any other character represent itself.
1.1 anton 7683:
1.29 crook 7684: @noindent
1.26 crook 7685: Now, the conversion rules are:
1.21 crook 7686:
1.26 crook 7687: @itemize @bullet
7688: @item
7689: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7690: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7691: @item
7692: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7693: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7694: arithmetic. Examples are -45 -5681 -0
7695: @item
7696: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7697: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7698: (all three of these represent the same number).
1.26 crook 7699: @item
7700: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7701: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7702: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7703: -34.65 (all three of these represent the same number).
1.26 crook 7704: @item
1.29 crook 7705: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7706: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7707: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7708: number) +12.E-4
1.26 crook 7709: @end itemize
1.1 anton 7710:
1.174 anton 7711: By default, the number base used for integer number conversion is
7712: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7713: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7714: change @code{base} anywhere, make sure to save the old value and
7715: restore it afterwards; better yet, use @code{base-execute}, which does
7716: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7717: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7718:
1.29 crook 7719: doc-dpl
1.174 anton 7720: doc-base-execute
1.26 crook 7721: doc-base
7722: doc-hex
7723: doc-decimal
1.1 anton 7724:
1.26 crook 7725: @cindex '-prefix for character strings
7726: @cindex &-prefix for decimal numbers
1.133 anton 7727: @cindex #-prefix for decimal numbers
1.26 crook 7728: @cindex %-prefix for binary numbers
7729: @cindex $-prefix for hexadecimal numbers
1.133 anton 7730: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7731: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7732: prefix@footnote{Some Forth implementations provide a similar scheme by
7733: implementing @code{$} etc. as parsing words that process the subsequent
7734: number in the input stream and push it onto the stack. For example, see
7735: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7736: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7737: is required between the prefix and the number.} before the first digit
1.133 anton 7738: of an (integer) number. The following prefixes are supported:
1.1 anton 7739:
1.26 crook 7740: @itemize @bullet
7741: @item
1.35 anton 7742: @code{&} -- decimal
1.26 crook 7743: @item
1.133 anton 7744: @code{#} -- decimal
7745: @item
1.35 anton 7746: @code{%} -- binary
1.26 crook 7747: @item
1.35 anton 7748: @code{$} -- hexadecimal
1.26 crook 7749: @item
1.133 anton 7750: @code{0x} -- hexadecimal, if base<33.
7751: @item
7752: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7753: optional @code{'} may be present after the character.
1.26 crook 7754: @end itemize
1.1 anton 7755:
1.26 crook 7756: Here are some examples, with the equivalent decimal number shown after
7757: in braces:
1.1 anton 7758:
1.26 crook 7759: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7760: 'A (65),
7761: -'a' (-97),
1.26 crook 7762: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7763:
1.26 crook 7764: @cindex number conversion - traps for the unwary
1.29 crook 7765: @noindent
1.26 crook 7766: Number conversion has a number of traps for the unwary:
1.1 anton 7767:
1.26 crook 7768: @itemize @bullet
7769: @item
7770: You cannot determine the current number base using the code sequence
1.35 anton 7771: @code{base @@ .} -- the number base is always 10 in the current number
7772: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7773: @item
7774: If the number base is set to a value greater than 14 (for example,
7775: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7776: it to be intepreted as either a single-precision integer or a
7777: floating-point number (Gforth treats it as an integer). The ambiguity
7778: can be resolved by explicitly stating the sign of the mantissa and/or
7779: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7780: ambiguity arises; either representation will be treated as a
7781: floating-point number.
7782: @item
1.29 crook 7783: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7784: It is used to specify file types.
7785: @item
1.72 anton 7786: ANS Forth requires the @code{.} of a double-precision number to be the
7787: final character in the string. Gforth allows the @code{.} to be
7788: anywhere after the first digit.
1.26 crook 7789: @item
7790: The number conversion process does not check for overflow.
7791: @item
1.72 anton 7792: In an ANS Forth program @code{base} is required to be decimal when
7793: converting floating-point numbers. In Gforth, number conversion to
7794: floating-point numbers always uses base &10, irrespective of the value
7795: of @code{base}.
1.26 crook 7796: @end itemize
1.1 anton 7797:
1.49 anton 7798: You can read numbers into your programs with the words described in
7799: @ref{Input}.
1.1 anton 7800:
1.82 anton 7801: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7802: @subsection Interpret/Compile states
7803: @cindex Interpret/Compile states
1.1 anton 7804:
1.29 crook 7805: A standard program is not permitted to change @code{state}
7806: explicitly. However, it can change @code{state} implicitly, using the
7807: words @code{[} and @code{]}. When @code{[} is executed it switches
7808: @code{state} to interpret state, and therefore the text interpreter
7809: starts interpreting. When @code{]} is executed it switches @code{state}
7810: to compile state and therefore the text interpreter starts
1.44 crook 7811: compiling. The most common usage for these words is for switching into
7812: interpret state and back from within a colon definition; this technique
1.49 anton 7813: can be used to compile a literal (for an example, @pxref{Literals}) or
7814: for conditional compilation (for an example, @pxref{Interpreter
7815: Directives}).
1.44 crook 7816:
1.35 anton 7817:
7818: @c This is a bad example: It's non-standard, and it's not necessary.
7819: @c However, I can't think of a good example for switching into compile
7820: @c state when there is no current word (@code{state}-smart words are not a
7821: @c good reason). So maybe we should use an example for switching into
7822: @c interpret @code{state} in a colon def. - anton
1.44 crook 7823: @c nac-> I agree. I started out by putting in the example, then realised
7824: @c that it was non-ANS, so wrote more words around it. I hope this
7825: @c re-written version is acceptable to you. I do want to keep the example
7826: @c as it is helpful for showing what is and what is not portable, particularly
7827: @c where it outlaws a style in common use.
7828:
1.72 anton 7829: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7830: @c that, we can also show what's not. In any case, I have written a
7831: @c section Compiling Words which also deals with [ ].
1.35 anton 7832:
1.95 anton 7833: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7834:
1.95 anton 7835: @c @code{[} and @code{]} also give you the ability to switch into compile
7836: @c state and back, but we cannot think of any useful Standard application
7837: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7838:
7839: @c @example
7840: @c : AA ." this is A" ;
7841: @c : BB ." this is B" ;
7842: @c : CC ." this is C" ;
7843:
7844: @c create table ] aa bb cc [
7845:
7846: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7847: @c cells table + @@ execute ;
7848: @c @end example
7849:
7850: @c This example builds a jump table; @code{0 go} will display ``@code{this
7851: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7852: @c defining @code{table} like this:
7853:
7854: @c @example
7855: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7856: @c @end example
7857:
7858: @c The problem with this code is that the definition of @code{table} is not
7859: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7860: @c @i{may} work on systems where code space and data space co-incide, the
7861: @c Standard only allows data space to be assigned for a @code{CREATE}d
7862: @c word. In addition, the Standard only allows @code{@@} to access data
7863: @c space, whilst this example is using it to access code space. The only
7864: @c portable, Standard way to build this table is to build it in data space,
7865: @c like this:
7866:
7867: @c @example
7868: @c create table ' aa , ' bb , ' cc ,
7869: @c @end example
1.29 crook 7870:
1.95 anton 7871: @c doc-state
1.44 crook 7872:
1.29 crook 7873:
1.82 anton 7874: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7875: @subsection Interpreter Directives
7876: @cindex interpreter directives
1.72 anton 7877: @cindex conditional compilation
1.1 anton 7878:
1.29 crook 7879: These words are usually used in interpret state; typically to control
7880: which parts of a source file are processed by the text
1.26 crook 7881: interpreter. There are only a few ANS Forth Standard words, but Gforth
7882: supplements these with a rich set of immediate control structure words
7883: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7884: used in compile state (@pxref{Control Structures}). Typical usages:
7885:
7886: @example
1.72 anton 7887: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7888: .
7889: .
1.72 anton 7890: HAVE-ASSEMBLER [IF]
1.29 crook 7891: : ASSEMBLER-FEATURE
7892: ...
7893: ;
7894: [ENDIF]
7895: .
7896: .
7897: : SEE
7898: ... \ general-purpose SEE code
1.72 anton 7899: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7900: ... \ assembler-specific SEE code
7901: [ [ENDIF] ]
7902: ;
7903: @end example
1.1 anton 7904:
1.44 crook 7905:
1.26 crook 7906: doc-[IF]
7907: doc-[ELSE]
7908: doc-[THEN]
7909: doc-[ENDIF]
1.1 anton 7910:
1.26 crook 7911: doc-[IFDEF]
7912: doc-[IFUNDEF]
1.1 anton 7913:
1.26 crook 7914: doc-[?DO]
7915: doc-[DO]
7916: doc-[FOR]
7917: doc-[LOOP]
7918: doc-[+LOOP]
7919: doc-[NEXT]
1.1 anton 7920:
1.26 crook 7921: doc-[BEGIN]
7922: doc-[UNTIL]
7923: doc-[AGAIN]
7924: doc-[WHILE]
7925: doc-[REPEAT]
1.1 anton 7926:
1.27 crook 7927:
1.26 crook 7928: @c -------------------------------------------------------------
1.111 anton 7929: @node The Input Stream, Word Lists, The Text Interpreter, Words
7930: @section The Input Stream
7931: @cindex input stream
7932:
7933: @c !! integrate this better with the "Text Interpreter" section
7934: The text interpreter reads from the input stream, which can come from
7935: several sources (@pxref{Input Sources}). Some words, in particular
7936: defining words, but also words like @code{'}, read parameters from the
7937: input stream instead of from the stack.
7938:
7939: Such words are called parsing words, because they parse the input
7940: stream. Parsing words are hard to use in other words, because it is
7941: hard to pass program-generated parameters through the input stream.
7942: They also usually have an unintuitive combination of interpretation and
7943: compilation semantics when implemented naively, leading to various
7944: approaches that try to produce a more intuitive behaviour
7945: (@pxref{Combined words}).
7946:
7947: It should be obvious by now that parsing words are a bad idea. If you
7948: want to implement a parsing word for convenience, also provide a factor
7949: of the word that does not parse, but takes the parameters on the stack.
7950: To implement the parsing word on top if it, you can use the following
7951: words:
7952:
7953: @c anton: these belong in the input stream section
7954: doc-parse
1.138 anton 7955: doc-parse-name
1.111 anton 7956: doc-parse-word
7957: doc-name
7958: doc-word
7959: doc-\"-parse
7960: doc-refill
7961:
7962: Conversely, if you have the bad luck (or lack of foresight) to have to
7963: deal with parsing words without having such factors, how do you pass a
7964: string that is not in the input stream to it?
7965:
7966: doc-execute-parsing
7967:
1.146 anton 7968: A definition of this word in ANS Forth is provided in
7969: @file{compat/execute-parsing.fs}.
7970:
1.111 anton 7971: If you want to run a parsing word on a file, the following word should
7972: help:
7973:
7974: doc-execute-parsing-file
7975:
7976: @c -------------------------------------------------------------
7977: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7978: @section Word Lists
7979: @cindex word lists
1.32 anton 7980: @cindex header space
1.1 anton 7981:
1.36 anton 7982: A wordlist is a list of named words; you can add new words and look up
7983: words by name (and you can remove words in a restricted way with
7984: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7985:
7986: @cindex search order stack
7987: The text interpreter searches the wordlists present in the search order
7988: (a stack of wordlists), from the top to the bottom. Within each
7989: wordlist, the search starts conceptually at the newest word; i.e., if
7990: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7991:
1.26 crook 7992: @cindex compilation word list
1.36 anton 7993: New words are added to the @dfn{compilation wordlist} (aka current
7994: wordlist).
1.1 anton 7995:
1.36 anton 7996: @cindex wid
7997: A word list is identified by a cell-sized word list identifier (@i{wid})
7998: in much the same way as a file is identified by a file handle. The
7999: numerical value of the wid has no (portable) meaning, and might change
8000: from session to session.
1.1 anton 8001:
1.29 crook 8002: The ANS Forth ``Search order'' word set is intended to provide a set of
8003: low-level tools that allow various different schemes to be
1.74 anton 8004: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8005: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8006: Forth.
1.1 anton 8007:
1.27 crook 8008: @comment TODO: locals section refers to here, saying that every word list (aka
8009: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8010: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8011:
1.45 crook 8012: @comment TODO: document markers, reveal, tables, mappedwordlist
8013:
8014: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8015: @comment word from the source files, rather than some alias.
1.44 crook 8016:
1.26 crook 8017: doc-forth-wordlist
8018: doc-definitions
8019: doc-get-current
8020: doc-set-current
8021: doc-get-order
1.45 crook 8022: doc---gforthman-set-order
1.26 crook 8023: doc-wordlist
1.30 anton 8024: doc-table
1.79 anton 8025: doc->order
1.36 anton 8026: doc-previous
1.26 crook 8027: doc-also
1.45 crook 8028: doc---gforthman-forth
1.26 crook 8029: doc-only
1.45 crook 8030: doc---gforthman-order
1.15 anton 8031:
1.26 crook 8032: doc-find
8033: doc-search-wordlist
1.15 anton 8034:
1.26 crook 8035: doc-words
8036: doc-vlist
1.44 crook 8037: @c doc-words-deferred
1.1 anton 8038:
1.74 anton 8039: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8040: doc-root
8041: doc-vocabulary
8042: doc-seal
8043: doc-vocs
8044: doc-current
8045: doc-context
1.1 anton 8046:
1.44 crook 8047:
1.26 crook 8048: @menu
1.75 anton 8049: * Vocabularies::
1.67 anton 8050: * Why use word lists?::
1.75 anton 8051: * Word list example::
1.26 crook 8052: @end menu
8053:
1.75 anton 8054: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8055: @subsection Vocabularies
8056: @cindex Vocabularies, detailed explanation
8057:
8058: Here is an example of creating and using a new wordlist using ANS
8059: Forth words:
8060:
8061: @example
8062: wordlist constant my-new-words-wordlist
8063: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8064:
8065: \ add it to the search order
8066: also my-new-words
8067:
8068: \ alternatively, add it to the search order and make it
8069: \ the compilation word list
8070: also my-new-words definitions
8071: \ type "order" to see the problem
8072: @end example
8073:
8074: The problem with this example is that @code{order} has no way to
8075: associate the name @code{my-new-words} with the wid of the word list (in
8076: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8077: that has no associated name). There is no Standard way of associating a
8078: name with a wid.
8079:
8080: In Gforth, this example can be re-coded using @code{vocabulary}, which
8081: associates a name with a wid:
8082:
8083: @example
8084: vocabulary my-new-words
8085:
8086: \ add it to the search order
8087: also my-new-words
8088:
8089: \ alternatively, add it to the search order and make it
8090: \ the compilation word list
8091: my-new-words definitions
8092: \ type "order" to see that the problem is solved
8093: @end example
8094:
8095:
8096: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8097: @subsection Why use word lists?
8098: @cindex word lists - why use them?
8099:
1.74 anton 8100: Here are some reasons why people use wordlists:
1.26 crook 8101:
8102: @itemize @bullet
1.74 anton 8103:
8104: @c anton: Gforth's hashing implementation makes the search speed
8105: @c independent from the number of words. But it is linear with the number
8106: @c of wordlists that have to be searched, so in effect using more wordlists
8107: @c actually slows down compilation.
8108:
8109: @c @item
8110: @c To improve compilation speed by reducing the number of header space
8111: @c entries that must be searched. This is achieved by creating a new
8112: @c word list that contains all of the definitions that are used in the
8113: @c definition of a Forth system but which would not usually be used by
8114: @c programs running on that system. That word list would be on the search
8115: @c list when the Forth system was compiled but would be removed from the
8116: @c search list for normal operation. This can be a useful technique for
8117: @c low-performance systems (for example, 8-bit processors in embedded
8118: @c systems) but is unlikely to be necessary in high-performance desktop
8119: @c systems.
8120:
1.26 crook 8121: @item
8122: To prevent a set of words from being used outside the context in which
8123: they are valid. Two classic examples of this are an integrated editor
8124: (all of the edit commands are defined in a separate word list; the
8125: search order is set to the editor word list when the editor is invoked;
8126: the old search order is restored when the editor is terminated) and an
8127: integrated assembler (the op-codes for the machine are defined in a
8128: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8129:
8130: @item
8131: To organize the words of an application or library into a user-visible
8132: set (in @code{forth-wordlist} or some other common wordlist) and a set
8133: of helper words used just for the implementation (hidden in a separate
1.75 anton 8134: wordlist). This keeps @code{words}' output smaller, separates
8135: implementation and interface, and reduces the chance of name conflicts
8136: within the common wordlist.
1.74 anton 8137:
1.26 crook 8138: @item
8139: To prevent a name-space clash between multiple definitions with the same
8140: name. For example, when building a cross-compiler you might have a word
8141: @code{IF} that generates conditional code for your target system. By
8142: placing this definition in a different word list you can control whether
8143: the host system's @code{IF} or the target system's @code{IF} get used in
8144: any particular context by controlling the order of the word lists on the
8145: search order stack.
1.74 anton 8146:
1.26 crook 8147: @end itemize
1.1 anton 8148:
1.74 anton 8149: The downsides of using wordlists are:
8150:
8151: @itemize
8152:
8153: @item
8154: Debugging becomes more cumbersome.
8155:
8156: @item
8157: Name conflicts worked around with wordlists are still there, and you
8158: have to arrange the search order carefully to get the desired results;
8159: if you forget to do that, you get hard-to-find errors (as in any case
8160: where you read the code differently from the compiler; @code{see} can
1.75 anton 8161: help seeing which of several possible words the name resolves to in such
8162: cases). @code{See} displays just the name of the words, not what
8163: wordlist they belong to, so it might be misleading. Using unique names
8164: is a better approach to avoid name conflicts.
1.74 anton 8165:
8166: @item
8167: You have to explicitly undo any changes to the search order. In many
8168: cases it would be more convenient if this happened implicitly. Gforth
8169: currently does not provide such a feature, but it may do so in the
8170: future.
8171: @end itemize
8172:
8173:
1.75 anton 8174: @node Word list example, , Why use word lists?, Word Lists
8175: @subsection Word list example
8176: @cindex word lists - example
1.1 anton 8177:
1.74 anton 8178: The following example is from the
8179: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8180: garbage collector} and uses wordlists to separate public words from
8181: helper words:
8182:
8183: @example
8184: get-current ( wid )
8185: vocabulary garbage-collector also garbage-collector definitions
8186: ... \ define helper words
8187: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8188: ... \ define the public (i.e., API) words
8189: \ they can refer to the helper words
8190: previous \ restore original search order (helper words become invisible)
8191: @end example
8192:
1.26 crook 8193: @c -------------------------------------------------------------
8194: @node Environmental Queries, Files, Word Lists, Words
8195: @section Environmental Queries
8196: @cindex environmental queries
1.21 crook 8197:
1.26 crook 8198: ANS Forth introduced the idea of ``environmental queries'' as a way
8199: for a program running on a system to determine certain characteristics of the system.
8200: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8201:
1.32 anton 8202: The Standard requires that the header space used for environmental queries
8203: be distinct from the header space used for definitions.
1.21 crook 8204:
1.26 crook 8205: Typically, environmental queries are supported by creating a set of
1.29 crook 8206: definitions in a word list that is @i{only} used during environmental
1.26 crook 8207: queries; that is what Gforth does. There is no Standard way of adding
8208: definitions to the set of recognised environmental queries, but any
8209: implementation that supports the loading of optional word sets must have
8210: some mechanism for doing this (after loading the word set, the
8211: associated environmental query string must return @code{true}). In
8212: Gforth, the word list used to honour environmental queries can be
8213: manipulated just like any other word list.
1.21 crook 8214:
1.44 crook 8215:
1.26 crook 8216: doc-environment?
8217: doc-environment-wordlist
1.21 crook 8218:
1.26 crook 8219: doc-gforth
8220: doc-os-class
1.21 crook 8221:
1.44 crook 8222:
1.26 crook 8223: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8224: returning two items on the stack, querying it using @code{environment?}
8225: will return an additional item; the @code{true} flag that shows that the
8226: string was recognised.
1.21 crook 8227:
1.26 crook 8228: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8229:
1.26 crook 8230: Here are some examples of using environmental queries:
1.21 crook 8231:
1.26 crook 8232: @example
8233: s" address-unit-bits" environment? 0=
8234: [IF]
8235: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8236: [ELSE]
8237: drop \ ensure balanced stack effect
1.26 crook 8238: [THEN]
1.21 crook 8239:
1.75 anton 8240: \ this might occur in the prelude of a standard program that uses THROW
8241: s" exception" environment? [IF]
8242: 0= [IF]
8243: : throw abort" exception thrown" ;
8244: [THEN]
8245: [ELSE] \ we don't know, so make sure
8246: : throw abort" exception thrown" ;
8247: [THEN]
1.21 crook 8248:
1.26 crook 8249: s" gforth" environment? [IF] .( Gforth version ) TYPE
8250: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8251:
8252: \ a program using v*
8253: s" gforth" environment? [IF]
8254: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8255: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8256: >r swap 2swap swap 0e r> 0 ?DO
8257: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8258: LOOP
8259: 2drop 2drop ;
8260: [THEN]
8261: [ELSE] \
8262: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8263: ...
8264: [THEN]
1.26 crook 8265: @end example
1.21 crook 8266:
1.26 crook 8267: Here is an example of adding a definition to the environment word list:
1.21 crook 8268:
1.26 crook 8269: @example
8270: get-current environment-wordlist set-current
8271: true constant block
8272: true constant block-ext
8273: set-current
8274: @end example
1.21 crook 8275:
1.26 crook 8276: You can see what definitions are in the environment word list like this:
1.21 crook 8277:
1.26 crook 8278: @example
1.79 anton 8279: environment-wordlist >order words previous
1.26 crook 8280: @end example
1.21 crook 8281:
8282:
1.26 crook 8283: @c -------------------------------------------------------------
8284: @node Files, Blocks, Environmental Queries, Words
8285: @section Files
1.28 crook 8286: @cindex files
8287: @cindex I/O - file-handling
1.21 crook 8288:
1.26 crook 8289: Gforth provides facilities for accessing files that are stored in the
8290: host operating system's file-system. Files that are processed by Gforth
8291: can be divided into two categories:
1.21 crook 8292:
1.23 crook 8293: @itemize @bullet
8294: @item
1.29 crook 8295: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8296: @item
1.29 crook 8297: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8298: @end itemize
8299:
8300: @menu
1.48 anton 8301: * Forth source files::
8302: * General files::
1.167 anton 8303: * Redirection::
1.48 anton 8304: * Search Paths::
1.26 crook 8305: @end menu
8306:
8307: @c -------------------------------------------------------------
8308: @node Forth source files, General files, Files, Files
8309: @subsection Forth source files
8310: @cindex including files
8311: @cindex Forth source files
1.21 crook 8312:
1.26 crook 8313: The simplest way to interpret the contents of a file is to use one of
8314: these two formats:
1.21 crook 8315:
1.26 crook 8316: @example
8317: include mysource.fs
8318: s" mysource.fs" included
8319: @end example
1.21 crook 8320:
1.75 anton 8321: You usually want to include a file only if it is not included already
1.26 crook 8322: (by, say, another source file). In that case, you can use one of these
1.45 crook 8323: three formats:
1.21 crook 8324:
1.26 crook 8325: @example
8326: require mysource.fs
8327: needs mysource.fs
8328: s" mysource.fs" required
8329: @end example
1.21 crook 8330:
1.26 crook 8331: @cindex stack effect of included files
8332: @cindex including files, stack effect
1.45 crook 8333: It is good practice to write your source files such that interpreting them
8334: does not change the stack. Source files designed in this way can be used with
1.26 crook 8335: @code{required} and friends without complications. For example:
1.21 crook 8336:
1.26 crook 8337: @example
1.75 anton 8338: 1024 require foo.fs drop
1.26 crook 8339: @end example
1.21 crook 8340:
1.75 anton 8341: Here you want to pass the argument 1024 (e.g., a buffer size) to
8342: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8343: ), which allows its use with @code{require}. Of course with such
8344: parameters to required files, you have to ensure that the first
8345: @code{require} fits for all uses (i.e., @code{require} it early in the
8346: master load file).
1.44 crook 8347:
1.26 crook 8348: doc-include-file
8349: doc-included
1.28 crook 8350: doc-included?
1.26 crook 8351: doc-include
8352: doc-required
8353: doc-require
8354: doc-needs
1.75 anton 8355: @c doc-init-included-files @c internal
8356: doc-sourcefilename
8357: doc-sourceline#
1.44 crook 8358:
1.26 crook 8359: A definition in ANS Forth for @code{required} is provided in
8360: @file{compat/required.fs}.
1.21 crook 8361:
1.26 crook 8362: @c -------------------------------------------------------------
1.167 anton 8363: @node General files, Redirection, Forth source files, Files
1.26 crook 8364: @subsection General files
8365: @cindex general files
8366: @cindex file-handling
1.21 crook 8367:
1.75 anton 8368: Files are opened/created by name and type. The following file access
8369: methods (FAMs) are recognised:
1.44 crook 8370:
1.75 anton 8371: @cindex fam (file access method)
1.26 crook 8372: doc-r/o
8373: doc-r/w
8374: doc-w/o
8375: doc-bin
1.1 anton 8376:
1.44 crook 8377:
1.26 crook 8378: When a file is opened/created, it returns a file identifier,
1.29 crook 8379: @i{wfileid} that is used for all other file commands. All file
8380: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8381: successful operation and an implementation-defined non-zero value in the
8382: case of an error.
1.21 crook 8383:
1.44 crook 8384:
1.26 crook 8385: doc-open-file
8386: doc-create-file
1.21 crook 8387:
1.26 crook 8388: doc-close-file
8389: doc-delete-file
8390: doc-rename-file
8391: doc-read-file
8392: doc-read-line
1.154 anton 8393: doc-key-file
8394: doc-key?-file
1.26 crook 8395: doc-write-file
8396: doc-write-line
8397: doc-emit-file
8398: doc-flush-file
1.21 crook 8399:
1.26 crook 8400: doc-file-status
8401: doc-file-position
8402: doc-reposition-file
8403: doc-file-size
8404: doc-resize-file
1.21 crook 8405:
1.93 anton 8406: doc-slurp-file
8407: doc-slurp-fid
1.112 anton 8408: doc-stdin
8409: doc-stdout
8410: doc-stderr
1.44 crook 8411:
1.26 crook 8412: @c ---------------------------------------------------------
1.167 anton 8413: @node Redirection, Search Paths, General files, Files
8414: @subsection Redirection
8415: @cindex Redirection
8416: @cindex Input Redirection
8417: @cindex Output Redirection
8418:
8419: You can redirect the output of @code{type} and @code{emit} and all the
8420: words that use them (all output words that don't have an explicit
1.174 anton 8421: target file) to an arbitrary file with the @code{outfile-execute},
8422: used like this:
1.167 anton 8423:
8424: @example
1.174 anton 8425: : some-warning ( n -- )
8426: cr ." warning# " . ;
8427:
1.167 anton 8428: : print-some-warning ( n -- )
1.174 anton 8429: ['] some-warning stderr outfile-execute ;
1.167 anton 8430: @end example
8431:
1.174 anton 8432: After @code{some-warning} is executed, the original output direction
8433: is restored; this construct is safe against exceptions. Similarly,
8434: there is @code{infile-execute} for redirecting the input of @code{key}
8435: and its users (any input word that does not take a file explicitly).
8436:
8437: doc-outfile-execute
8438: doc-infile-execute
1.167 anton 8439:
8440: If you do not want to redirect the input or output to a file, you can
8441: also make use of the fact that @code{key}, @code{emit} and @code{type}
8442: are deferred words (@pxref{Deferred Words}). However, in that case
8443: you have to worry about the restoration and the protection against
8444: exceptions yourself; also, note that for redirecting the output in
8445: this way, you have to redirect both @code{emit} and @code{type}.
8446:
8447: @c ---------------------------------------------------------
8448: @node Search Paths, , Redirection, Files
1.26 crook 8449: @subsection Search Paths
8450: @cindex path for @code{included}
8451: @cindex file search path
8452: @cindex @code{include} search path
8453: @cindex search path for files
1.21 crook 8454:
1.26 crook 8455: If you specify an absolute filename (i.e., a filename starting with
8456: @file{/} or @file{~}, or with @file{:} in the second position (as in
8457: @samp{C:...})) for @code{included} and friends, that file is included
8458: just as you would expect.
1.21 crook 8459:
1.75 anton 8460: If the filename starts with @file{./}, this refers to the directory that
8461: the present file was @code{included} from. This allows files to include
8462: other files relative to their own position (irrespective of the current
8463: working directory or the absolute position). This feature is essential
8464: for libraries consisting of several files, where a file may include
8465: other files from the library. It corresponds to @code{#include "..."}
8466: in C. If the current input source is not a file, @file{.} refers to the
8467: directory of the innermost file being included, or, if there is no file
8468: being included, to the current working directory.
8469:
8470: For relative filenames (not starting with @file{./}), Gforth uses a
8471: search path similar to Forth's search order (@pxref{Word Lists}). It
8472: tries to find the given filename in the directories present in the path,
8473: and includes the first one it finds. There are separate search paths for
8474: Forth source files and general files. If the search path contains the
8475: directory @file{.}, this refers to the directory of the current file, or
8476: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8477:
1.26 crook 8478: Use @file{~+} to refer to the current working directory (as in the
8479: @code{bash}).
1.1 anton 8480:
1.75 anton 8481: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8482:
1.48 anton 8483: @menu
1.75 anton 8484: * Source Search Paths::
1.48 anton 8485: * General Search Paths::
8486: @end menu
8487:
1.26 crook 8488: @c ---------------------------------------------------------
1.75 anton 8489: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8490: @subsubsection Source Search Paths
8491: @cindex search path control, source files
1.5 anton 8492:
1.26 crook 8493: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8494: Gforth}). You can display it and change it using @code{fpath} in
8495: combination with the general path handling words.
1.5 anton 8496:
1.75 anton 8497: doc-fpath
8498: @c the functionality of the following words is easily available through
8499: @c fpath and the general path words. The may go away.
8500: @c doc-.fpath
8501: @c doc-fpath+
8502: @c doc-fpath=
8503: @c doc-open-fpath-file
1.44 crook 8504:
8505: @noindent
1.26 crook 8506: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8507:
1.26 crook 8508: @example
1.75 anton 8509: fpath path= /usr/lib/forth/|./
1.26 crook 8510: require timer.fs
8511: @end example
1.5 anton 8512:
1.75 anton 8513:
1.26 crook 8514: @c ---------------------------------------------------------
1.75 anton 8515: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8516: @subsubsection General Search Paths
1.75 anton 8517: @cindex search path control, source files
1.5 anton 8518:
1.26 crook 8519: Your application may need to search files in several directories, like
8520: @code{included} does. To facilitate this, Gforth allows you to define
8521: and use your own search paths, by providing generic equivalents of the
8522: Forth search path words:
1.5 anton 8523:
1.75 anton 8524: doc-open-path-file
8525: doc-path-allot
8526: doc-clear-path
8527: doc-also-path
1.26 crook 8528: doc-.path
8529: doc-path+
8530: doc-path=
1.5 anton 8531:
1.75 anton 8532: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8533:
1.75 anton 8534: Here's an example of creating an empty search path:
8535: @c
1.26 crook 8536: @example
1.75 anton 8537: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8538: @end example
1.5 anton 8539:
1.26 crook 8540: @c -------------------------------------------------------------
8541: @node Blocks, Other I/O, Files, Words
8542: @section Blocks
1.28 crook 8543: @cindex I/O - blocks
8544: @cindex blocks
8545:
8546: When you run Gforth on a modern desk-top computer, it runs under the
8547: control of an operating system which provides certain services. One of
8548: these services is @var{file services}, which allows Forth source code
8549: and data to be stored in files and read into Gforth (@pxref{Files}).
8550:
8551: Traditionally, Forth has been an important programming language on
8552: systems where it has interfaced directly to the underlying hardware with
8553: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8554: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8555:
8556: A block is a 1024-byte data area, which can be used to hold data or
8557: Forth source code. No structure is imposed on the contents of the
8558: block. A block is identified by its number; blocks are numbered
8559: contiguously from 1 to an implementation-defined maximum.
8560:
8561: A typical system that used blocks but no operating system might use a
8562: single floppy-disk drive for mass storage, with the disks formatted to
8563: provide 256-byte sectors. Blocks would be implemented by assigning the
8564: first four sectors of the disk to block 1, the second four sectors to
8565: block 2 and so on, up to the limit of the capacity of the disk. The disk
8566: would not contain any file system information, just the set of blocks.
8567:
1.29 crook 8568: @cindex blocks file
1.28 crook 8569: On systems that do provide file services, blocks are typically
1.29 crook 8570: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8571: file}. The size of the blocks file will be an exact multiple of 1024
8572: bytes, corresponding to the number of blocks it contains. This is the
8573: mechanism that Gforth uses.
8574:
1.29 crook 8575: @cindex @file{blocks.fb}
1.75 anton 8576: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8577: having specified a blocks file, Gforth defaults to the blocks file
8578: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8579: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8580:
1.29 crook 8581: @cindex block buffers
1.28 crook 8582: When you read and write blocks under program control, Gforth uses a
1.29 crook 8583: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8584: not used when you use @code{load} to interpret the contents of a block.
8585:
1.75 anton 8586: The behaviour of the block buffers is analagous to that of a cache.
8587: Each block buffer has three states:
1.28 crook 8588:
8589: @itemize @bullet
8590: @item
8591: Unassigned
8592: @item
8593: Assigned-clean
8594: @item
8595: Assigned-dirty
8596: @end itemize
8597:
1.29 crook 8598: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8599: block, the block (specified by its block number) must be assigned to a
8600: block buffer.
8601:
8602: The assignment of a block to a block buffer is performed by @code{block}
8603: or @code{buffer}. Use @code{block} when you wish to modify the existing
8604: contents of a block. Use @code{buffer} when you don't care about the
8605: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8606: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8607: with the particular block is already stored in a block buffer due to an
8608: earlier @code{block} command, @code{buffer} will return that block
8609: buffer and the existing contents of the block will be
8610: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8611: block buffer for the block.}.
1.28 crook 8612:
1.47 crook 8613: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8614: @code{buffer}, that block buffer becomes the @i{current block
8615: buffer}. Data may only be manipulated (read or written) within the
8616: current block buffer.
1.47 crook 8617:
8618: When the contents of the current block buffer has been modified it is
1.48 anton 8619: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8620: either abandon the changes (by doing nothing) or mark the block as
8621: changed (assigned-dirty), using @code{update}. Using @code{update} does
8622: not change the blocks file; it simply changes a block buffer's state to
8623: @i{assigned-dirty}. The block will be written implicitly when it's
8624: buffer is needed for another block, or explicitly by @code{flush} or
8625: @code{save-buffers}.
8626:
8627: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8628: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8629: @code{flush}.
1.28 crook 8630:
1.29 crook 8631: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8632: algorithm to assign a block buffer to a block. That means that any
8633: particular block can only be assigned to one specific block buffer,
1.29 crook 8634: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8635: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8636: the new block immediately. If it is @i{assigned-dirty} its current
8637: contents are written back to the blocks file on disk before it is
1.28 crook 8638: allocated to the new block.
8639:
8640: Although no structure is imposed on the contents of a block, it is
8641: traditional to display the contents as 16 lines each of 64 characters. A
8642: block provides a single, continuous stream of input (for example, it
8643: acts as a single parse area) -- there are no end-of-line characters
8644: within a block, and no end-of-file character at the end of a
8645: block. There are two consequences of this:
1.26 crook 8646:
1.28 crook 8647: @itemize @bullet
8648: @item
8649: The last character of one line wraps straight into the first character
8650: of the following line
8651: @item
8652: The word @code{\} -- comment to end of line -- requires special
8653: treatment; in the context of a block it causes all characters until the
8654: end of the current 64-character ``line'' to be ignored.
8655: @end itemize
8656:
8657: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8658: the current blocks file will be extended to the appropriate size and the
1.28 crook 8659: block buffer will be initialised with spaces.
8660:
1.47 crook 8661: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8662: for details) but doesn't encourage the use of blocks; the mechanism is
8663: only provided for backward compatibility -- ANS Forth requires blocks to
8664: be available when files are.
1.28 crook 8665:
8666: Common techniques that are used when working with blocks include:
8667:
8668: @itemize @bullet
8669: @item
8670: A screen editor that allows you to edit blocks without leaving the Forth
8671: environment.
8672: @item
8673: Shadow screens; where every code block has an associated block
8674: containing comments (for example: code in odd block numbers, comments in
8675: even block numbers). Typically, the block editor provides a convenient
8676: mechanism to toggle between code and comments.
8677: @item
8678: Load blocks; a single block (typically block 1) contains a number of
8679: @code{thru} commands which @code{load} the whole of the application.
8680: @end itemize
1.26 crook 8681:
1.29 crook 8682: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8683: integrated into a Forth programming environment.
1.26 crook 8684:
8685: @comment TODO what about errors on open-blocks?
1.44 crook 8686:
1.26 crook 8687: doc-open-blocks
8688: doc-use
1.75 anton 8689: doc-block-offset
1.26 crook 8690: doc-get-block-fid
8691: doc-block-position
1.28 crook 8692:
1.75 anton 8693: doc-list
1.28 crook 8694: doc-scr
8695:
1.45 crook 8696: doc---gforthman-block
1.28 crook 8697: doc-buffer
8698:
1.75 anton 8699: doc-empty-buffers
8700: doc-empty-buffer
1.26 crook 8701: doc-update
1.28 crook 8702: doc-updated?
1.26 crook 8703: doc-save-buffers
1.75 anton 8704: doc-save-buffer
1.26 crook 8705: doc-flush
1.28 crook 8706:
1.26 crook 8707: doc-load
8708: doc-thru
8709: doc-+load
8710: doc-+thru
1.45 crook 8711: doc---gforthman--->
1.26 crook 8712: doc-block-included
8713:
1.44 crook 8714:
1.26 crook 8715: @c -------------------------------------------------------------
1.126 pazsan 8716: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8717: @section Other I/O
1.28 crook 8718: @cindex I/O - keyboard and display
1.26 crook 8719:
8720: @menu
8721: * Simple numeric output:: Predefined formats
8722: * Formatted numeric output:: Formatted (pictured) output
8723: * String Formats:: How Forth stores strings in memory
1.67 anton 8724: * Displaying characters and strings:: Other stuff
1.175 anton 8725: * Terminal output:: Cursor positioning etc.
1.26 crook 8726: * Input:: Input
1.112 anton 8727: * Pipes:: How to create your own pipes
1.149 pazsan 8728: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8729: @end menu
8730:
8731: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8732: @subsection Simple numeric output
1.28 crook 8733: @cindex numeric output - simple/free-format
1.5 anton 8734:
1.26 crook 8735: The simplest output functions are those that display numbers from the
8736: data or floating-point stacks. Floating-point output is always displayed
8737: using base 10. Numbers displayed from the data stack use the value stored
8738: in @code{base}.
1.5 anton 8739:
1.44 crook 8740:
1.26 crook 8741: doc-.
8742: doc-dec.
8743: doc-hex.
8744: doc-u.
8745: doc-.r
8746: doc-u.r
8747: doc-d.
8748: doc-ud.
8749: doc-d.r
8750: doc-ud.r
8751: doc-f.
8752: doc-fe.
8753: doc-fs.
1.111 anton 8754: doc-f.rdp
1.44 crook 8755:
1.26 crook 8756: Examples of printing the number 1234.5678E23 in the different floating-point output
8757: formats are shown below:
1.5 anton 8758:
8759: @example
1.26 crook 8760: f. 123456779999999000000000000.
8761: fe. 123.456779999999E24
8762: fs. 1.23456779999999E26
1.5 anton 8763: @end example
8764:
8765:
1.26 crook 8766: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8767: @subsection Formatted numeric output
1.28 crook 8768: @cindex formatted numeric output
1.26 crook 8769: @cindex pictured numeric output
1.28 crook 8770: @cindex numeric output - formatted
1.26 crook 8771:
1.29 crook 8772: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8773: output} for formatted printing of integers. In this technique, digits
8774: are extracted from the number (using the current output radix defined by
8775: @code{base}), converted to ASCII codes and appended to a string that is
8776: built in a scratch-pad area of memory (@pxref{core-idef,
8777: Implementation-defined options, Implementation-defined
8778: options}). Arbitrary characters can be appended to the string during the
8779: extraction process. The completed string is specified by an address
8780: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8781: under program control.
1.5 anton 8782:
1.75 anton 8783: All of the integer output words described in the previous section
8784: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8785: numeric output.
1.5 anton 8786:
1.47 crook 8787: Three important things to remember about pictured numeric output:
1.5 anton 8788:
1.26 crook 8789: @itemize @bullet
8790: @item
1.28 crook 8791: It always operates on double-precision numbers; to display a
1.49 anton 8792: single-precision number, convert it first (for ways of doing this
8793: @pxref{Double precision}).
1.26 crook 8794: @item
1.28 crook 8795: It always treats the double-precision number as though it were
8796: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8797: @item
8798: The string is built up from right to left; least significant digit first.
8799: @end itemize
1.5 anton 8800:
1.44 crook 8801:
1.26 crook 8802: doc-<#
1.47 crook 8803: doc-<<#
1.26 crook 8804: doc-#
8805: doc-#s
8806: doc-hold
8807: doc-sign
8808: doc-#>
1.47 crook 8809: doc-#>>
1.5 anton 8810:
1.26 crook 8811: doc-represent
1.111 anton 8812: doc-f>str-rdp
8813: doc-f>buf-rdp
1.5 anton 8814:
1.44 crook 8815:
8816: @noindent
1.26 crook 8817: Here are some examples of using pictured numeric output:
1.5 anton 8818:
8819: @example
1.26 crook 8820: : my-u. ( u -- )
8821: \ Simplest use of pns.. behaves like Standard u.
8822: 0 \ convert to unsigned double
1.75 anton 8823: <<# \ start conversion
1.26 crook 8824: #s \ convert all digits
8825: #> \ complete conversion
1.75 anton 8826: TYPE SPACE \ display, with trailing space
8827: #>> ; \ release hold area
1.5 anton 8828:
1.26 crook 8829: : cents-only ( u -- )
8830: 0 \ convert to unsigned double
1.75 anton 8831: <<# \ start conversion
1.26 crook 8832: # # \ convert two least-significant digits
8833: #> \ complete conversion, discard other digits
1.75 anton 8834: TYPE SPACE \ display, with trailing space
8835: #>> ; \ release hold area
1.5 anton 8836:
1.26 crook 8837: : dollars-and-cents ( u -- )
8838: 0 \ convert to unsigned double
1.75 anton 8839: <<# \ start conversion
1.26 crook 8840: # # \ convert two least-significant digits
8841: [char] . hold \ insert decimal point
8842: #s \ convert remaining digits
8843: [char] $ hold \ append currency symbol
8844: #> \ complete conversion
1.75 anton 8845: TYPE SPACE \ display, with trailing space
8846: #>> ; \ release hold area
1.5 anton 8847:
1.26 crook 8848: : my-. ( n -- )
8849: \ handling negatives.. behaves like Standard .
8850: s>d \ convert to signed double
8851: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8852: <<# \ start conversion
1.26 crook 8853: #s \ convert all digits
8854: rot sign \ get at sign byte, append "-" if needed
8855: #> \ complete conversion
1.75 anton 8856: TYPE SPACE \ display, with trailing space
8857: #>> ; \ release hold area
1.5 anton 8858:
1.26 crook 8859: : account. ( n -- )
1.75 anton 8860: \ accountants don't like minus signs, they use parentheses
1.26 crook 8861: \ for negative numbers
8862: s>d \ convert to signed double
8863: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8864: <<# \ start conversion
1.26 crook 8865: 2 pick \ get copy of sign byte
8866: 0< IF [char] ) hold THEN \ right-most character of output
8867: #s \ convert all digits
8868: rot \ get at sign byte
8869: 0< IF [char] ( hold THEN
8870: #> \ complete conversion
1.75 anton 8871: TYPE SPACE \ display, with trailing space
8872: #>> ; \ release hold area
8873:
1.5 anton 8874: @end example
8875:
1.26 crook 8876: Here are some examples of using these words:
1.5 anton 8877:
8878: @example
1.26 crook 8879: 1 my-u. 1
8880: hex -1 my-u. decimal FFFFFFFF
8881: 1 cents-only 01
8882: 1234 cents-only 34
8883: 2 dollars-and-cents $0.02
8884: 1234 dollars-and-cents $12.34
8885: 123 my-. 123
8886: -123 my. -123
8887: 123 account. 123
8888: -456 account. (456)
1.5 anton 8889: @end example
8890:
8891:
1.26 crook 8892: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8893: @subsection String Formats
1.27 crook 8894: @cindex strings - see character strings
8895: @cindex character strings - formats
1.28 crook 8896: @cindex I/O - see character strings
1.75 anton 8897: @cindex counted strings
8898:
8899: @c anton: this does not really belong here; maybe the memory section,
8900: @c or the principles chapter
1.26 crook 8901:
1.27 crook 8902: Forth commonly uses two different methods for representing character
8903: strings:
1.26 crook 8904:
8905: @itemize @bullet
8906: @item
8907: @cindex address of counted string
1.45 crook 8908: @cindex counted string
1.29 crook 8909: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8910: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8911: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8912: memory.
8913: @item
1.29 crook 8914: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8915: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8916: first byte of the string.
8917: @end itemize
8918:
8919: ANS Forth encourages the use of the second format when representing
1.75 anton 8920: strings.
1.26 crook 8921:
1.44 crook 8922:
1.26 crook 8923: doc-count
8924:
1.44 crook 8925:
1.49 anton 8926: For words that move, copy and search for strings see @ref{Memory
8927: Blocks}. For words that display characters and strings see
8928: @ref{Displaying characters and strings}.
1.26 crook 8929:
1.175 anton 8930: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 8931: @subsection Displaying characters and strings
1.27 crook 8932: @cindex characters - compiling and displaying
8933: @cindex character strings - compiling and displaying
1.26 crook 8934:
8935: This section starts with a glossary of Forth words and ends with a set
8936: of examples.
8937:
8938: doc-bl
8939: doc-space
8940: doc-spaces
8941: doc-emit
8942: doc-toupper
8943: doc-."
8944: doc-.(
1.98 anton 8945: doc-.\"
1.26 crook 8946: doc-type
1.44 crook 8947: doc-typewhite
1.26 crook 8948: doc-cr
1.27 crook 8949: @cindex cursor control
1.26 crook 8950: doc-s"
1.98 anton 8951: doc-s\"
1.26 crook 8952: doc-c"
8953: doc-char
8954: doc-[char]
8955:
1.44 crook 8956:
8957: @noindent
1.26 crook 8958: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8959:
8960: @example
1.26 crook 8961: .( text-1)
8962: : my-word
8963: ." text-2" cr
8964: .( text-3)
8965: ;
8966:
8967: ." text-4"
8968:
8969: : my-char
8970: [char] ALPHABET emit
8971: char emit
8972: ;
1.5 anton 8973: @end example
8974:
1.26 crook 8975: When you load this code into Gforth, the following output is generated:
1.5 anton 8976:
1.26 crook 8977: @example
1.30 anton 8978: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8979: @end example
1.5 anton 8980:
1.26 crook 8981: @itemize @bullet
8982: @item
8983: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8984: is an immediate word; it behaves in the same way whether it is used inside
8985: or outside a colon definition.
8986: @item
8987: Message @code{text-4} is displayed because of Gforth's added interpretation
8988: semantics for @code{."}.
8989: @item
1.29 crook 8990: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8991: performs the compilation semantics for @code{."} within the definition of
8992: @code{my-word}.
8993: @end itemize
1.5 anton 8994:
1.26 crook 8995: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8996:
1.26 crook 8997: @example
1.30 anton 8998: @kbd{my-word @key{RET}} text-2
1.26 crook 8999: ok
1.30 anton 9000: @kbd{my-char fred @key{RET}} Af ok
9001: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9002: @end example
1.5 anton 9003:
9004: @itemize @bullet
9005: @item
1.26 crook 9006: Message @code{text-2} is displayed because of the run-time behaviour of
9007: @code{."}.
9008: @item
9009: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9010: on the stack at run-time. @code{emit} always displays the character
9011: when @code{my-char} is executed.
9012: @item
9013: @code{char} parses a string at run-time and the second @code{emit} displays
9014: the first character of the string.
1.5 anton 9015: @item
1.26 crook 9016: If you type @code{see my-char} you can see that @code{[char]} discarded
9017: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9018: definition of @code{my-char}.
1.5 anton 9019: @end itemize
9020:
9021:
1.175 anton 9022: @node Terminal output, Input, Displaying characters and strings, Other I/O
9023: @subsection Terminal output
9024: @cindex output to terminal
9025: @cindex terminal output
9026:
9027: If you are outputting to a terminal, you may want to control the
9028: positioning of the cursor:
9029: @cindex cursor positioning
9030:
9031: doc-at-xy
9032:
9033: In order to know where to position the cursor, it is often helpful to
9034: know the size of the screen:
9035: @cindex terminal size
9036:
9037: doc-form
9038:
9039: And sometimes you want to use:
9040: @cindex clear screen
9041:
9042: doc-page
9043:
9044: Note that on non-terminals you should use @code{12 emit}, not
9045: @code{page}, to get a form feed.
9046:
1.5 anton 9047:
1.175 anton 9048: @node Input, Pipes, Terminal output, Other I/O
1.26 crook 9049: @subsection Input
9050: @cindex input
1.28 crook 9051: @cindex I/O - see input
9052: @cindex parsing a string
1.5 anton 9053:
1.49 anton 9054: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 9055:
1.27 crook 9056: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 9057: @comment then index them
1.27 crook 9058:
1.44 crook 9059:
1.27 crook 9060: doc-key
9061: doc-key?
1.45 crook 9062: doc-ekey
1.141 anton 9063: doc-ekey>char
1.45 crook 9064: doc-ekey?
1.141 anton 9065:
9066: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9067: you need the ANSI.SYS driver to get that behaviour). These are the
9068: keyboard events produced by various common keys:
9069:
9070: doc-k-left
9071: doc-k-right
9072: doc-k-up
9073: doc-k-down
9074: doc-k-home
9075: doc-k-end
9076: doc-k-prior
9077: doc-k-next
9078: doc-k-insert
9079: doc-k-delete
9080:
9081: The function keys (aka keypad keys) are:
9082:
9083: doc-k1
9084: doc-k2
9085: doc-k3
9086: doc-k4
9087: doc-k5
9088: doc-k6
9089: doc-k7
9090: doc-k8
9091: doc-k9
9092: doc-k10
9093: doc-k11
9094: doc-k12
9095:
9096: Note that K11 and K12 are not as widely available. The shifted
9097: function keys are also not very widely available:
9098:
9099: doc-s-k1
9100: doc-s-k2
9101: doc-s-k3
9102: doc-s-k4
9103: doc-s-k5
9104: doc-s-k6
9105: doc-s-k7
9106: doc-s-k8
9107: doc-s-k9
9108: doc-s-k10
9109: doc-s-k11
9110: doc-s-k12
9111:
9112: Words for inputting one line from the keyboard:
9113:
9114: doc-accept
9115: doc-edit-line
9116:
9117: Conversion words:
9118:
1.143 anton 9119: doc-s>number?
9120: doc-s>unumber?
1.26 crook 9121: doc->number
9122: doc->float
1.143 anton 9123:
1.141 anton 9124:
1.27 crook 9125: @comment obsolescent words..
1.141 anton 9126: Obsolescent input and conversion words:
9127:
1.27 crook 9128: doc-convert
1.26 crook 9129: doc-expect
1.27 crook 9130: doc-span
1.5 anton 9131:
9132:
1.149 pazsan 9133: @node Pipes, Xchars and Unicode, Input, Other I/O
1.112 anton 9134: @subsection Pipes
9135: @cindex pipes, creating your own
9136:
9137: In addition to using Gforth in pipes created by other processes
9138: (@pxref{Gforth in pipes}), you can create your own pipe with
9139: @code{open-pipe}, and read from or write to it.
9140:
9141: doc-open-pipe
9142: doc-close-pipe
9143:
9144: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9145: you don't catch this exception, Gforth will catch it and exit, usually
9146: silently (@pxref{Gforth in pipes}). Since you probably do not want
9147: this, you should wrap a @code{catch} or @code{try} block around the code
9148: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9149: problem yourself, and then return to regular processing.
9150:
9151: doc-broken-pipe-error
9152:
1.155 anton 9153: @node Xchars and Unicode, , Pipes, Other I/O
9154: @subsection Xchars and Unicode
1.149 pazsan 9155:
9156: This chapter needs completion
1.112 anton 9157:
1.121 anton 9158: @node OS command line arguments, Locals, Other I/O, Words
9159: @section OS command line arguments
9160: @cindex OS command line arguments
9161: @cindex command line arguments, OS
9162: @cindex arguments, OS command line
9163:
9164: The usual way to pass arguments to Gforth programs on the command line
9165: is via the @option{-e} option, e.g.
9166:
9167: @example
9168: gforth -e "123 456" foo.fs -e bye
9169: @end example
9170:
9171: However, you may want to interpret the command-line arguments directly.
9172: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9173: through @code{next-arg}:
1.121 anton 9174:
1.123 anton 9175: doc-next-arg
1.121 anton 9176:
1.123 anton 9177: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9178:
9179: @example
9180: : echo ( -- )
1.122 anton 9181: begin
1.123 anton 9182: next-arg 2dup 0 0 d<> while
9183: type space
9184: repeat
9185: 2drop ;
1.121 anton 9186:
9187: echo cr bye
9188: @end example
9189:
9190: This can be invoked with
9191:
9192: @example
9193: gforth echo.fs hello world
9194: @end example
1.123 anton 9195:
9196: and it will print
9197:
9198: @example
9199: hello world
9200: @end example
9201:
9202: The next lower level of dealing with the OS command line are the
9203: following words:
9204:
9205: doc-arg
9206: doc-shift-args
9207:
9208: Finally, at the lowest level Gforth provides the following words:
9209:
9210: doc-argc
9211: doc-argv
1.121 anton 9212:
1.78 anton 9213: @c -------------------------------------------------------------
1.126 pazsan 9214: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9215: @section Locals
9216: @cindex locals
9217:
9218: Local variables can make Forth programming more enjoyable and Forth
9219: programs easier to read. Unfortunately, the locals of ANS Forth are
9220: laden with restrictions. Therefore, we provide not only the ANS Forth
9221: locals wordset, but also our own, more powerful locals wordset (we
9222: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9223:
1.78 anton 9224: The ideas in this section have also been published in M. Anton Ertl,
9225: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9226: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9227:
9228: @menu
1.78 anton 9229: * Gforth locals::
9230: * ANS Forth locals::
1.5 anton 9231: @end menu
9232:
1.78 anton 9233: @node Gforth locals, ANS Forth locals, Locals, Locals
9234: @subsection Gforth locals
9235: @cindex Gforth locals
9236: @cindex locals, Gforth style
1.5 anton 9237:
1.78 anton 9238: Locals can be defined with
1.44 crook 9239:
1.78 anton 9240: @example
9241: @{ local1 local2 ... -- comment @}
9242: @end example
9243: or
9244: @example
9245: @{ local1 local2 ... @}
9246: @end example
1.5 anton 9247:
1.78 anton 9248: E.g.,
9249: @example
9250: : max @{ n1 n2 -- n3 @}
9251: n1 n2 > if
9252: n1
9253: else
9254: n2
9255: endif ;
9256: @end example
1.44 crook 9257:
1.78 anton 9258: The similarity of locals definitions with stack comments is intended. A
9259: locals definition often replaces the stack comment of a word. The order
9260: of the locals corresponds to the order in a stack comment and everything
9261: after the @code{--} is really a comment.
1.77 anton 9262:
1.78 anton 9263: This similarity has one disadvantage: It is too easy to confuse locals
9264: declarations with stack comments, causing bugs and making them hard to
9265: find. However, this problem can be avoided by appropriate coding
9266: conventions: Do not use both notations in the same program. If you do,
9267: they should be distinguished using additional means, e.g. by position.
1.77 anton 9268:
1.78 anton 9269: @cindex types of locals
9270: @cindex locals types
9271: The name of the local may be preceded by a type specifier, e.g.,
9272: @code{F:} for a floating point value:
1.5 anton 9273:
1.78 anton 9274: @example
9275: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9276: \ complex multiplication
9277: Ar Br f* Ai Bi f* f-
9278: Ar Bi f* Ai Br f* f+ ;
9279: @end example
1.44 crook 9280:
1.78 anton 9281: @cindex flavours of locals
9282: @cindex locals flavours
9283: @cindex value-flavoured locals
9284: @cindex variable-flavoured locals
9285: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9286: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9287: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9288: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9289: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9290: produces its address (which becomes invalid when the variable's scope is
9291: left). E.g., the standard word @code{emit} can be defined in terms of
9292: @code{type} like this:
1.5 anton 9293:
1.78 anton 9294: @example
9295: : emit @{ C^ char* -- @}
9296: char* 1 type ;
9297: @end example
1.5 anton 9298:
1.78 anton 9299: @cindex default type of locals
9300: @cindex locals, default type
9301: A local without type specifier is a @code{W:} local. Both flavours of
9302: locals are initialized with values from the data or FP stack.
1.44 crook 9303:
1.78 anton 9304: Currently there is no way to define locals with user-defined data
9305: structures, but we are working on it.
1.5 anton 9306:
1.78 anton 9307: Gforth allows defining locals everywhere in a colon definition. This
9308: poses the following questions:
1.5 anton 9309:
1.78 anton 9310: @menu
9311: * Where are locals visible by name?::
9312: * How long do locals live?::
9313: * Locals programming style::
9314: * Locals implementation::
9315: @end menu
1.44 crook 9316:
1.78 anton 9317: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9318: @subsubsection Where are locals visible by name?
9319: @cindex locals visibility
9320: @cindex visibility of locals
9321: @cindex scope of locals
1.5 anton 9322:
1.78 anton 9323: Basically, the answer is that locals are visible where you would expect
9324: it in block-structured languages, and sometimes a little longer. If you
9325: want to restrict the scope of a local, enclose its definition in
9326: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9327:
9328:
1.78 anton 9329: doc-scope
9330: doc-endscope
1.5 anton 9331:
9332:
1.78 anton 9333: These words behave like control structure words, so you can use them
9334: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9335: arbitrary ways.
1.77 anton 9336:
1.78 anton 9337: If you want a more exact answer to the visibility question, here's the
9338: basic principle: A local is visible in all places that can only be
9339: reached through the definition of the local@footnote{In compiler
9340: construction terminology, all places dominated by the definition of the
9341: local.}. In other words, it is not visible in places that can be reached
9342: without going through the definition of the local. E.g., locals defined
9343: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9344: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9345: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9346:
1.78 anton 9347: The reasoning behind this solution is: We want to have the locals
9348: visible as long as it is meaningful. The user can always make the
9349: visibility shorter by using explicit scoping. In a place that can
9350: only be reached through the definition of a local, the meaning of a
9351: local name is clear. In other places it is not: How is the local
9352: initialized at the control flow path that does not contain the
9353: definition? Which local is meant, if the same name is defined twice in
9354: two independent control flow paths?
1.77 anton 9355:
1.78 anton 9356: This should be enough detail for nearly all users, so you can skip the
9357: rest of this section. If you really must know all the gory details and
9358: options, read on.
1.77 anton 9359:
1.78 anton 9360: In order to implement this rule, the compiler has to know which places
9361: are unreachable. It knows this automatically after @code{AHEAD},
9362: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9363: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9364: compiler that the control flow never reaches that place. If
9365: @code{UNREACHABLE} is not used where it could, the only consequence is
9366: that the visibility of some locals is more limited than the rule above
9367: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9368: lie to the compiler), buggy code will be produced.
1.77 anton 9369:
1.5 anton 9370:
1.78 anton 9371: doc-unreachable
1.5 anton 9372:
1.23 crook 9373:
1.78 anton 9374: Another problem with this rule is that at @code{BEGIN}, the compiler
9375: does not know which locals will be visible on the incoming
9376: back-edge. All problems discussed in the following are due to this
9377: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9378: loops as examples; the discussion also applies to @code{?DO} and other
9379: loops). Perhaps the most insidious example is:
1.26 crook 9380: @example
1.78 anton 9381: AHEAD
9382: BEGIN
9383: x
9384: [ 1 CS-ROLL ] THEN
9385: @{ x @}
9386: ...
9387: UNTIL
1.26 crook 9388: @end example
1.23 crook 9389:
1.78 anton 9390: This should be legal according to the visibility rule. The use of
9391: @code{x} can only be reached through the definition; but that appears
9392: textually below the use.
9393:
9394: From this example it is clear that the visibility rules cannot be fully
9395: implemented without major headaches. Our implementation treats common
9396: cases as advertised and the exceptions are treated in a safe way: The
9397: compiler makes a reasonable guess about the locals visible after a
9398: @code{BEGIN}; if it is too pessimistic, the
9399: user will get a spurious error about the local not being defined; if the
9400: compiler is too optimistic, it will notice this later and issue a
9401: warning. In the case above the compiler would complain about @code{x}
9402: being undefined at its use. You can see from the obscure examples in
9403: this section that it takes quite unusual control structures to get the
9404: compiler into trouble, and even then it will often do fine.
1.23 crook 9405:
1.78 anton 9406: If the @code{BEGIN} is reachable from above, the most optimistic guess
9407: is that all locals visible before the @code{BEGIN} will also be
9408: visible after the @code{BEGIN}. This guess is valid for all loops that
9409: are entered only through the @code{BEGIN}, in particular, for normal
9410: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9411: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9412: compiler. When the branch to the @code{BEGIN} is finally generated by
9413: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9414: warns the user if it was too optimistic:
1.26 crook 9415: @example
1.78 anton 9416: IF
9417: @{ x @}
9418: BEGIN
9419: \ x ?
9420: [ 1 cs-roll ] THEN
9421: ...
9422: UNTIL
1.26 crook 9423: @end example
1.23 crook 9424:
1.78 anton 9425: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9426: optimistically assumes that it lives until the @code{THEN}. It notices
9427: this difference when it compiles the @code{UNTIL} and issues a
9428: warning. The user can avoid the warning, and make sure that @code{x}
9429: is not used in the wrong area by using explicit scoping:
9430: @example
9431: IF
9432: SCOPE
9433: @{ x @}
9434: ENDSCOPE
9435: BEGIN
9436: [ 1 cs-roll ] THEN
9437: ...
9438: UNTIL
9439: @end example
1.23 crook 9440:
1.78 anton 9441: Since the guess is optimistic, there will be no spurious error messages
9442: about undefined locals.
1.44 crook 9443:
1.78 anton 9444: If the @code{BEGIN} is not reachable from above (e.g., after
9445: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9446: optimistic guess, as the locals visible after the @code{BEGIN} may be
9447: defined later. Therefore, the compiler assumes that no locals are
9448: visible after the @code{BEGIN}. However, the user can use
9449: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9450: visible at the BEGIN as at the point where the top control-flow stack
9451: item was created.
1.23 crook 9452:
1.44 crook 9453:
1.78 anton 9454: doc-assume-live
1.26 crook 9455:
1.23 crook 9456:
1.78 anton 9457: @noindent
9458: E.g.,
9459: @example
9460: @{ x @}
9461: AHEAD
9462: ASSUME-LIVE
9463: BEGIN
9464: x
9465: [ 1 CS-ROLL ] THEN
9466: ...
9467: UNTIL
9468: @end example
1.44 crook 9469:
1.78 anton 9470: Other cases where the locals are defined before the @code{BEGIN} can be
9471: handled by inserting an appropriate @code{CS-ROLL} before the
9472: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9473: behind the @code{ASSUME-LIVE}).
1.23 crook 9474:
1.78 anton 9475: Cases where locals are defined after the @code{BEGIN} (but should be
9476: visible immediately after the @code{BEGIN}) can only be handled by
9477: rearranging the loop. E.g., the ``most insidious'' example above can be
9478: arranged into:
9479: @example
9480: BEGIN
9481: @{ x @}
9482: ... 0=
9483: WHILE
9484: x
9485: REPEAT
9486: @end example
1.44 crook 9487:
1.78 anton 9488: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9489: @subsubsection How long do locals live?
9490: @cindex locals lifetime
9491: @cindex lifetime of locals
1.23 crook 9492:
1.78 anton 9493: The right answer for the lifetime question would be: A local lives at
9494: least as long as it can be accessed. For a value-flavoured local this
9495: means: until the end of its visibility. However, a variable-flavoured
9496: local could be accessed through its address far beyond its visibility
9497: scope. Ultimately, this would mean that such locals would have to be
9498: garbage collected. Since this entails un-Forth-like implementation
9499: complexities, I adopted the same cowardly solution as some other
9500: languages (e.g., C): The local lives only as long as it is visible;
9501: afterwards its address is invalid (and programs that access it
9502: afterwards are erroneous).
1.23 crook 9503:
1.78 anton 9504: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9505: @subsubsection Locals programming style
9506: @cindex locals programming style
9507: @cindex programming style, locals
1.23 crook 9508:
1.78 anton 9509: The freedom to define locals anywhere has the potential to change
9510: programming styles dramatically. In particular, the need to use the
9511: return stack for intermediate storage vanishes. Moreover, all stack
9512: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9513: determined arguments) can be eliminated: If the stack items are in the
9514: wrong order, just write a locals definition for all of them; then
9515: write the items in the order you want.
1.23 crook 9516:
1.78 anton 9517: This seems a little far-fetched and eliminating stack manipulations is
9518: unlikely to become a conscious programming objective. Still, the number
9519: of stack manipulations will be reduced dramatically if local variables
9520: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9521: a traditional implementation of @code{max}).
1.23 crook 9522:
1.78 anton 9523: This shows one potential benefit of locals: making Forth programs more
9524: readable. Of course, this benefit will only be realized if the
9525: programmers continue to honour the principle of factoring instead of
9526: using the added latitude to make the words longer.
1.23 crook 9527:
1.78 anton 9528: @cindex single-assignment style for locals
9529: Using @code{TO} can and should be avoided. Without @code{TO},
9530: every value-flavoured local has only a single assignment and many
9531: advantages of functional languages apply to Forth. I.e., programs are
9532: easier to analyse, to optimize and to read: It is clear from the
9533: definition what the local stands for, it does not turn into something
9534: different later.
1.23 crook 9535:
1.78 anton 9536: E.g., a definition using @code{TO} might look like this:
9537: @example
9538: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9539: u1 u2 min 0
9540: ?do
9541: addr1 c@@ addr2 c@@ -
9542: ?dup-if
9543: unloop exit
9544: then
9545: addr1 char+ TO addr1
9546: addr2 char+ TO addr2
9547: loop
9548: u1 u2 - ;
1.26 crook 9549: @end example
1.78 anton 9550: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9551: every loop iteration. @code{strcmp} is a typical example of the
9552: readability problems of using @code{TO}. When you start reading
9553: @code{strcmp}, you think that @code{addr1} refers to the start of the
9554: string. Only near the end of the loop you realize that it is something
9555: else.
1.23 crook 9556:
1.78 anton 9557: This can be avoided by defining two locals at the start of the loop that
9558: are initialized with the right value for the current iteration.
9559: @example
9560: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9561: addr1 addr2
9562: u1 u2 min 0
9563: ?do @{ s1 s2 @}
9564: s1 c@@ s2 c@@ -
9565: ?dup-if
9566: unloop exit
9567: then
9568: s1 char+ s2 char+
9569: loop
9570: 2drop
9571: u1 u2 - ;
9572: @end example
9573: Here it is clear from the start that @code{s1} has a different value
9574: in every loop iteration.
1.23 crook 9575:
1.78 anton 9576: @node Locals implementation, , Locals programming style, Gforth locals
9577: @subsubsection Locals implementation
9578: @cindex locals implementation
9579: @cindex implementation of locals
1.23 crook 9580:
1.78 anton 9581: @cindex locals stack
9582: Gforth uses an extra locals stack. The most compelling reason for
9583: this is that the return stack is not float-aligned; using an extra stack
9584: also eliminates the problems and restrictions of using the return stack
9585: as locals stack. Like the other stacks, the locals stack grows toward
9586: lower addresses. A few primitives allow an efficient implementation:
9587:
9588:
9589: doc-@local#
9590: doc-f@local#
9591: doc-laddr#
9592: doc-lp+!#
9593: doc-lp!
9594: doc->l
9595: doc-f>l
9596:
9597:
9598: In addition to these primitives, some specializations of these
9599: primitives for commonly occurring inline arguments are provided for
9600: efficiency reasons, e.g., @code{@@local0} as specialization of
9601: @code{@@local#} for the inline argument 0. The following compiling words
9602: compile the right specialized version, or the general version, as
9603: appropriate:
1.23 crook 9604:
1.5 anton 9605:
1.107 dvdkhlng 9606: @c doc-compile-@local
9607: @c doc-compile-f@local
1.78 anton 9608: doc-compile-lp+!
1.5 anton 9609:
9610:
1.78 anton 9611: Combinations of conditional branches and @code{lp+!#} like
9612: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9613: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9614:
1.78 anton 9615: A special area in the dictionary space is reserved for keeping the
9616: local variable names. @code{@{} switches the dictionary pointer to this
9617: area and @code{@}} switches it back and generates the locals
9618: initializing code. @code{W:} etc.@ are normal defining words. This
9619: special area is cleared at the start of every colon definition.
1.5 anton 9620:
1.78 anton 9621: @cindex word list for defining locals
9622: A special feature of Gforth's dictionary is used to implement the
9623: definition of locals without type specifiers: every word list (aka
9624: vocabulary) has its own methods for searching
9625: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9626: with a special search method: When it is searched for a word, it
9627: actually creates that word using @code{W:}. @code{@{} changes the search
9628: order to first search the word list containing @code{@}}, @code{W:} etc.,
9629: and then the word list for defining locals without type specifiers.
1.5 anton 9630:
1.78 anton 9631: The lifetime rules support a stack discipline within a colon
9632: definition: The lifetime of a local is either nested with other locals
9633: lifetimes or it does not overlap them.
1.23 crook 9634:
1.78 anton 9635: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9636: pointer manipulation is generated. Between control structure words
9637: locals definitions can push locals onto the locals stack. @code{AGAIN}
9638: is the simplest of the other three control flow words. It has to
9639: restore the locals stack depth of the corresponding @code{BEGIN}
9640: before branching. The code looks like this:
9641: @format
9642: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9643: @code{branch} <begin>
9644: @end format
1.26 crook 9645:
1.78 anton 9646: @code{UNTIL} is a little more complicated: If it branches back, it
9647: must adjust the stack just like @code{AGAIN}. But if it falls through,
9648: the locals stack must not be changed. The compiler generates the
9649: following code:
9650: @format
9651: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9652: @end format
9653: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9654:
1.78 anton 9655: @code{THEN} can produce somewhat inefficient code:
9656: @format
9657: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9658: <orig target>:
9659: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9660: @end format
9661: The second @code{lp+!#} adjusts the locals stack pointer from the
9662: level at the @i{orig} point to the level after the @code{THEN}. The
9663: first @code{lp+!#} adjusts the locals stack pointer from the current
9664: level to the level at the orig point, so the complete effect is an
9665: adjustment from the current level to the right level after the
9666: @code{THEN}.
1.26 crook 9667:
1.78 anton 9668: @cindex locals information on the control-flow stack
9669: @cindex control-flow stack items, locals information
9670: In a conventional Forth implementation a dest control-flow stack entry
9671: is just the target address and an orig entry is just the address to be
9672: patched. Our locals implementation adds a word list to every orig or dest
9673: item. It is the list of locals visible (or assumed visible) at the point
9674: described by the entry. Our implementation also adds a tag to identify
9675: the kind of entry, in particular to differentiate between live and dead
9676: (reachable and unreachable) orig entries.
1.26 crook 9677:
1.78 anton 9678: A few unusual operations have to be performed on locals word lists:
1.44 crook 9679:
1.5 anton 9680:
1.78 anton 9681: doc-common-list
9682: doc-sub-list?
9683: doc-list-size
1.52 anton 9684:
9685:
1.78 anton 9686: Several features of our locals word list implementation make these
9687: operations easy to implement: The locals word lists are organised as
9688: linked lists; the tails of these lists are shared, if the lists
9689: contain some of the same locals; and the address of a name is greater
9690: than the address of the names behind it in the list.
1.5 anton 9691:
1.78 anton 9692: Another important implementation detail is the variable
9693: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9694: determine if they can be reached directly or only through the branch
9695: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9696: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9697: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9698:
1.78 anton 9699: Counted loops are similar to other loops in most respects, but
9700: @code{LEAVE} requires special attention: It performs basically the same
9701: service as @code{AHEAD}, but it does not create a control-flow stack
9702: entry. Therefore the information has to be stored elsewhere;
9703: traditionally, the information was stored in the target fields of the
9704: branches created by the @code{LEAVE}s, by organizing these fields into a
9705: linked list. Unfortunately, this clever trick does not provide enough
9706: space for storing our extended control flow information. Therefore, we
9707: introduce another stack, the leave stack. It contains the control-flow
9708: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9709:
1.78 anton 9710: Local names are kept until the end of the colon definition, even if
9711: they are no longer visible in any control-flow path. In a few cases
9712: this may lead to increased space needs for the locals name area, but
9713: usually less than reclaiming this space would cost in code size.
1.5 anton 9714:
1.44 crook 9715:
1.78 anton 9716: @node ANS Forth locals, , Gforth locals, Locals
9717: @subsection ANS Forth locals
9718: @cindex locals, ANS Forth style
1.5 anton 9719:
1.78 anton 9720: The ANS Forth locals wordset does not define a syntax for locals, but
9721: words that make it possible to define various syntaxes. One of the
9722: possible syntaxes is a subset of the syntax we used in the Gforth locals
9723: wordset, i.e.:
1.29 crook 9724:
9725: @example
1.78 anton 9726: @{ local1 local2 ... -- comment @}
9727: @end example
9728: @noindent
9729: or
9730: @example
9731: @{ local1 local2 ... @}
1.29 crook 9732: @end example
9733:
1.78 anton 9734: The order of the locals corresponds to the order in a stack comment. The
9735: restrictions are:
1.5 anton 9736:
1.78 anton 9737: @itemize @bullet
9738: @item
9739: Locals can only be cell-sized values (no type specifiers are allowed).
9740: @item
9741: Locals can be defined only outside control structures.
9742: @item
9743: Locals can interfere with explicit usage of the return stack. For the
9744: exact (and long) rules, see the standard. If you don't use return stack
9745: accessing words in a definition using locals, you will be all right. The
9746: purpose of this rule is to make locals implementation on the return
9747: stack easier.
9748: @item
9749: The whole definition must be in one line.
9750: @end itemize
1.5 anton 9751:
1.78 anton 9752: Locals defined in ANS Forth behave like @code{VALUE}s
9753: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9754: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9755:
1.78 anton 9756: Since the syntax above is supported by Gforth directly, you need not do
9757: anything to use it. If you want to port a program using this syntax to
9758: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9759: syntax on the other system.
1.5 anton 9760:
1.78 anton 9761: Note that a syntax shown in the standard, section A.13 looks
9762: similar, but is quite different in having the order of locals
9763: reversed. Beware!
1.5 anton 9764:
1.78 anton 9765: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9766:
1.78 anton 9767: doc-(local)
1.5 anton 9768:
1.78 anton 9769: The ANS Forth locals extension wordset defines a syntax using
9770: @code{locals|}, but it is so awful that we strongly recommend not to use
9771: it. We have implemented this syntax to make porting to Gforth easy, but
9772: do not document it here. The problem with this syntax is that the locals
9773: are defined in an order reversed with respect to the standard stack
9774: comment notation, making programs harder to read, and easier to misread
9775: and miswrite. The only merit of this syntax is that it is easy to
9776: implement using the ANS Forth locals wordset.
1.53 anton 9777:
9778:
1.78 anton 9779: @c ----------------------------------------------------------
9780: @node Structures, Object-oriented Forth, Locals, Words
9781: @section Structures
9782: @cindex structures
9783: @cindex records
1.53 anton 9784:
1.78 anton 9785: This section presents the structure package that comes with Gforth. A
9786: version of the package implemented in ANS Forth is available in
9787: @file{compat/struct.fs}. This package was inspired by a posting on
9788: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9789: possibly John Hayes). A version of this section has been published in
9790: M. Anton Ertl,
9791: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9792: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9793: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9794:
1.78 anton 9795: @menu
9796: * Why explicit structure support?::
9797: * Structure Usage::
9798: * Structure Naming Convention::
9799: * Structure Implementation::
9800: * Structure Glossary::
9801: @end menu
1.55 anton 9802:
1.78 anton 9803: @node Why explicit structure support?, Structure Usage, Structures, Structures
9804: @subsection Why explicit structure support?
1.53 anton 9805:
1.78 anton 9806: @cindex address arithmetic for structures
9807: @cindex structures using address arithmetic
9808: If we want to use a structure containing several fields, we could simply
9809: reserve memory for it, and access the fields using address arithmetic
9810: (@pxref{Address arithmetic}). As an example, consider a structure with
9811: the following fields
1.57 anton 9812:
1.78 anton 9813: @table @code
9814: @item a
9815: is a float
9816: @item b
9817: is a cell
9818: @item c
9819: is a float
9820: @end table
1.57 anton 9821:
1.78 anton 9822: Given the (float-aligned) base address of the structure we get the
9823: address of the field
1.52 anton 9824:
1.78 anton 9825: @table @code
9826: @item a
9827: without doing anything further.
9828: @item b
9829: with @code{float+}
9830: @item c
9831: with @code{float+ cell+ faligned}
9832: @end table
1.52 anton 9833:
1.78 anton 9834: It is easy to see that this can become quite tiring.
1.52 anton 9835:
1.78 anton 9836: Moreover, it is not very readable, because seeing a
9837: @code{cell+} tells us neither which kind of structure is
9838: accessed nor what field is accessed; we have to somehow infer the kind
9839: of structure, and then look up in the documentation, which field of
9840: that structure corresponds to that offset.
1.53 anton 9841:
1.78 anton 9842: Finally, this kind of address arithmetic also causes maintenance
9843: troubles: If you add or delete a field somewhere in the middle of the
9844: structure, you have to find and change all computations for the fields
9845: afterwards.
1.52 anton 9846:
1.78 anton 9847: So, instead of using @code{cell+} and friends directly, how
9848: about storing the offsets in constants:
1.52 anton 9849:
1.78 anton 9850: @example
9851: 0 constant a-offset
9852: 0 float+ constant b-offset
9853: 0 float+ cell+ faligned c-offset
9854: @end example
1.64 pazsan 9855:
1.78 anton 9856: Now we can get the address of field @code{x} with @code{x-offset
9857: +}. This is much better in all respects. Of course, you still
9858: have to change all later offset definitions if you add a field. You can
9859: fix this by declaring the offsets in the following way:
1.57 anton 9860:
1.78 anton 9861: @example
9862: 0 constant a-offset
9863: a-offset float+ constant b-offset
9864: b-offset cell+ faligned constant c-offset
9865: @end example
1.57 anton 9866:
1.78 anton 9867: Since we always use the offsets with @code{+}, we could use a defining
9868: word @code{cfield} that includes the @code{+} in the action of the
9869: defined word:
1.64 pazsan 9870:
1.78 anton 9871: @example
9872: : cfield ( n "name" -- )
9873: create ,
9874: does> ( name execution: addr1 -- addr2 )
9875: @@ + ;
1.64 pazsan 9876:
1.78 anton 9877: 0 cfield a
9878: 0 a float+ cfield b
9879: 0 b cell+ faligned cfield c
9880: @end example
1.64 pazsan 9881:
1.78 anton 9882: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9883:
1.78 anton 9884: The structure field words now can be used quite nicely. However,
9885: their definition is still a bit cumbersome: We have to repeat the
9886: name, the information about size and alignment is distributed before
9887: and after the field definitions etc. The structure package presented
9888: here addresses these problems.
1.64 pazsan 9889:
1.78 anton 9890: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9891: @subsection Structure Usage
9892: @cindex structure usage
1.57 anton 9893:
1.78 anton 9894: @cindex @code{field} usage
9895: @cindex @code{struct} usage
9896: @cindex @code{end-struct} usage
9897: You can define a structure for a (data-less) linked list with:
1.57 anton 9898: @example
1.78 anton 9899: struct
9900: cell% field list-next
9901: end-struct list%
1.57 anton 9902: @end example
9903:
1.78 anton 9904: With the address of the list node on the stack, you can compute the
9905: address of the field that contains the address of the next node with
9906: @code{list-next}. E.g., you can determine the length of a list
9907: with:
1.57 anton 9908:
9909: @example
1.78 anton 9910: : list-length ( list -- n )
9911: \ "list" is a pointer to the first element of a linked list
9912: \ "n" is the length of the list
9913: 0 BEGIN ( list1 n1 )
9914: over
9915: WHILE ( list1 n1 )
9916: 1+ swap list-next @@ swap
9917: REPEAT
9918: nip ;
1.57 anton 9919: @end example
9920:
1.78 anton 9921: You can reserve memory for a list node in the dictionary with
9922: @code{list% %allot}, which leaves the address of the list node on the
9923: stack. For the equivalent allocation on the heap you can use @code{list%
9924: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9925: use @code{list% %allocate}). You can get the the size of a list
9926: node with @code{list% %size} and its alignment with @code{list%
9927: %alignment}.
9928:
9929: Note that in ANS Forth the body of a @code{create}d word is
9930: @code{aligned} but not necessarily @code{faligned};
9931: therefore, if you do a:
1.57 anton 9932:
9933: @example
1.78 anton 9934: create @emph{name} foo% %allot drop
1.57 anton 9935: @end example
9936:
1.78 anton 9937: @noindent
9938: then the memory alloted for @code{foo%} is guaranteed to start at the
9939: body of @code{@emph{name}} only if @code{foo%} contains only character,
9940: cell and double fields. Therefore, if your structure contains floats,
9941: better use
1.57 anton 9942:
9943: @example
1.78 anton 9944: foo% %allot constant @emph{name}
1.57 anton 9945: @end example
9946:
1.78 anton 9947: @cindex structures containing structures
9948: You can include a structure @code{foo%} as a field of
9949: another structure, like this:
1.65 anton 9950: @example
1.78 anton 9951: struct
9952: ...
9953: foo% field ...
9954: ...
9955: end-struct ...
1.65 anton 9956: @end example
1.52 anton 9957:
1.78 anton 9958: @cindex structure extension
9959: @cindex extended records
9960: Instead of starting with an empty structure, you can extend an
9961: existing structure. E.g., a plain linked list without data, as defined
9962: above, is hardly useful; You can extend it to a linked list of integers,
9963: like this:@footnote{This feature is also known as @emph{extended
9964: records}. It is the main innovation in the Oberon language; in other
9965: words, adding this feature to Modula-2 led Wirth to create a new
9966: language, write a new compiler etc. Adding this feature to Forth just
9967: required a few lines of code.}
1.52 anton 9968:
1.78 anton 9969: @example
9970: list%
9971: cell% field intlist-int
9972: end-struct intlist%
9973: @end example
1.55 anton 9974:
1.78 anton 9975: @code{intlist%} is a structure with two fields:
9976: @code{list-next} and @code{intlist-int}.
1.55 anton 9977:
1.78 anton 9978: @cindex structures containing arrays
9979: You can specify an array type containing @emph{n} elements of
9980: type @code{foo%} like this:
1.55 anton 9981:
9982: @example
1.78 anton 9983: foo% @emph{n} *
1.56 anton 9984: @end example
1.55 anton 9985:
1.78 anton 9986: You can use this array type in any place where you can use a normal
9987: type, e.g., when defining a @code{field}, or with
9988: @code{%allot}.
9989:
9990: @cindex first field optimization
9991: The first field is at the base address of a structure and the word for
9992: this field (e.g., @code{list-next}) actually does not change the address
9993: on the stack. You may be tempted to leave it away in the interest of
9994: run-time and space efficiency. This is not necessary, because the
9995: structure package optimizes this case: If you compile a first-field
9996: words, no code is generated. So, in the interest of readability and
9997: maintainability you should include the word for the field when accessing
9998: the field.
1.52 anton 9999:
10000:
1.78 anton 10001: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10002: @subsection Structure Naming Convention
10003: @cindex structure naming convention
1.52 anton 10004:
1.78 anton 10005: The field names that come to (my) mind are often quite generic, and,
10006: if used, would cause frequent name clashes. E.g., many structures
10007: probably contain a @code{counter} field. The structure names
10008: that come to (my) mind are often also the logical choice for the names
10009: of words that create such a structure.
1.52 anton 10010:
1.78 anton 10011: Therefore, I have adopted the following naming conventions:
1.52 anton 10012:
1.78 anton 10013: @itemize @bullet
10014: @cindex field naming convention
10015: @item
10016: The names of fields are of the form
10017: @code{@emph{struct}-@emph{field}}, where
10018: @code{@emph{struct}} is the basic name of the structure, and
10019: @code{@emph{field}} is the basic name of the field. You can
10020: think of field words as converting the (address of the)
10021: structure into the (address of the) field.
1.52 anton 10022:
1.78 anton 10023: @cindex structure naming convention
10024: @item
10025: The names of structures are of the form
10026: @code{@emph{struct}%}, where
10027: @code{@emph{struct}} is the basic name of the structure.
10028: @end itemize
1.52 anton 10029:
1.78 anton 10030: This naming convention does not work that well for fields of extended
10031: structures; e.g., the integer list structure has a field
10032: @code{intlist-int}, but has @code{list-next}, not
10033: @code{intlist-next}.
1.53 anton 10034:
1.78 anton 10035: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10036: @subsection Structure Implementation
10037: @cindex structure implementation
10038: @cindex implementation of structures
1.52 anton 10039:
1.78 anton 10040: The central idea in the implementation is to pass the data about the
10041: structure being built on the stack, not in some global
10042: variable. Everything else falls into place naturally once this design
10043: decision is made.
1.53 anton 10044:
1.78 anton 10045: The type description on the stack is of the form @emph{align
10046: size}. Keeping the size on the top-of-stack makes dealing with arrays
10047: very simple.
1.53 anton 10048:
1.78 anton 10049: @code{field} is a defining word that uses @code{Create}
10050: and @code{DOES>}. The body of the field contains the offset
10051: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10052:
10053: @example
1.78 anton 10054: @@ +
1.53 anton 10055: @end example
10056:
1.78 anton 10057: @noindent
10058: i.e., add the offset to the address, giving the stack effect
10059: @i{addr1 -- addr2} for a field.
10060:
10061: @cindex first field optimization, implementation
10062: This simple structure is slightly complicated by the optimization
10063: for fields with offset 0, which requires a different
10064: @code{DOES>}-part (because we cannot rely on there being
10065: something on the stack if such a field is invoked during
10066: compilation). Therefore, we put the different @code{DOES>}-parts
10067: in separate words, and decide which one to invoke based on the
10068: offset. For a zero offset, the field is basically a noop; it is
10069: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10070:
1.78 anton 10071: @node Structure Glossary, , Structure Implementation, Structures
10072: @subsection Structure Glossary
10073: @cindex structure glossary
1.53 anton 10074:
1.5 anton 10075:
1.78 anton 10076: doc-%align
10077: doc-%alignment
10078: doc-%alloc
10079: doc-%allocate
10080: doc-%allot
10081: doc-cell%
10082: doc-char%
10083: doc-dfloat%
10084: doc-double%
10085: doc-end-struct
10086: doc-field
10087: doc-float%
10088: doc-naligned
10089: doc-sfloat%
10090: doc-%size
10091: doc-struct
1.54 anton 10092:
10093:
1.26 crook 10094: @c -------------------------------------------------------------
1.78 anton 10095: @node Object-oriented Forth, Programming Tools, Structures, Words
10096: @section Object-oriented Forth
10097:
10098: Gforth comes with three packages for object-oriented programming:
10099: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10100: is preloaded, so you have to @code{include} them before use. The most
10101: important differences between these packages (and others) are discussed
10102: in @ref{Comparison with other object models}. All packages are written
10103: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10104:
1.78 anton 10105: @menu
10106: * Why object-oriented programming?::
10107: * Object-Oriented Terminology::
10108: * Objects::
10109: * OOF::
10110: * Mini-OOF::
10111: * Comparison with other object models::
10112: @end menu
1.5 anton 10113:
1.78 anton 10114: @c ----------------------------------------------------------------
10115: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10116: @subsection Why object-oriented programming?
10117: @cindex object-oriented programming motivation
10118: @cindex motivation for object-oriented programming
1.44 crook 10119:
1.78 anton 10120: Often we have to deal with several data structures (@emph{objects}),
10121: that have to be treated similarly in some respects, but differently in
10122: others. Graphical objects are the textbook example: circles, triangles,
10123: dinosaurs, icons, and others, and we may want to add more during program
10124: development. We want to apply some operations to any graphical object,
10125: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10126: has to do something different for every kind of object.
10127: @comment TODO add some other operations eg perimeter, area
10128: @comment and tie in to concrete examples later..
1.5 anton 10129:
1.78 anton 10130: We could implement @code{draw} as a big @code{CASE}
10131: control structure that executes the appropriate code depending on the
10132: kind of object to be drawn. This would be not be very elegant, and,
10133: moreover, we would have to change @code{draw} every time we add
10134: a new kind of graphical object (say, a spaceship).
1.44 crook 10135:
1.78 anton 10136: What we would rather do is: When defining spaceships, we would tell
10137: the system: ``Here's how you @code{draw} a spaceship; you figure
10138: out the rest''.
1.5 anton 10139:
1.78 anton 10140: This is the problem that all systems solve that (rightfully) call
10141: themselves object-oriented; the object-oriented packages presented here
10142: solve this problem (and not much else).
10143: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10144:
1.78 anton 10145: @c ------------------------------------------------------------------------
10146: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10147: @subsection Object-Oriented Terminology
10148: @cindex object-oriented terminology
10149: @cindex terminology for object-oriented programming
1.5 anton 10150:
1.78 anton 10151: This section is mainly for reference, so you don't have to understand
10152: all of it right away. The terminology is mainly Smalltalk-inspired. In
10153: short:
1.44 crook 10154:
1.78 anton 10155: @table @emph
10156: @cindex class
10157: @item class
10158: a data structure definition with some extras.
1.5 anton 10159:
1.78 anton 10160: @cindex object
10161: @item object
10162: an instance of the data structure described by the class definition.
1.5 anton 10163:
1.78 anton 10164: @cindex instance variables
10165: @item instance variables
10166: fields of the data structure.
1.5 anton 10167:
1.78 anton 10168: @cindex selector
10169: @cindex method selector
10170: @cindex virtual function
10171: @item selector
10172: (or @emph{method selector}) a word (e.g.,
10173: @code{draw}) that performs an operation on a variety of data
10174: structures (classes). A selector describes @emph{what} operation to
10175: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10176:
1.78 anton 10177: @cindex method
10178: @item method
10179: the concrete definition that performs the operation
10180: described by the selector for a specific class. A method specifies
10181: @emph{how} the operation is performed for a specific class.
1.5 anton 10182:
1.78 anton 10183: @cindex selector invocation
10184: @cindex message send
10185: @cindex invoking a selector
10186: @item selector invocation
10187: a call of a selector. One argument of the call (the TOS (top-of-stack))
10188: is used for determining which method is used. In Smalltalk terminology:
10189: a message (consisting of the selector and the other arguments) is sent
10190: to the object.
1.5 anton 10191:
1.78 anton 10192: @cindex receiving object
10193: @item receiving object
10194: the object used for determining the method executed by a selector
10195: invocation. In the @file{objects.fs} model, it is the object that is on
10196: the TOS when the selector is invoked. (@emph{Receiving} comes from
10197: the Smalltalk @emph{message} terminology.)
1.5 anton 10198:
1.78 anton 10199: @cindex child class
10200: @cindex parent class
10201: @cindex inheritance
10202: @item child class
10203: a class that has (@emph{inherits}) all properties (instance variables,
10204: selectors, methods) from a @emph{parent class}. In Smalltalk
10205: terminology: The subclass inherits from the superclass. In C++
10206: terminology: The derived class inherits from the base class.
1.5 anton 10207:
1.78 anton 10208: @end table
1.5 anton 10209:
1.78 anton 10210: @c If you wonder about the message sending terminology, it comes from
10211: @c a time when each object had it's own task and objects communicated via
10212: @c message passing; eventually the Smalltalk developers realized that
10213: @c they can do most things through simple (indirect) calls. They kept the
10214: @c terminology.
1.5 anton 10215:
1.78 anton 10216: @c --------------------------------------------------------------
10217: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10218: @subsection The @file{objects.fs} model
10219: @cindex objects
10220: @cindex object-oriented programming
1.26 crook 10221:
1.78 anton 10222: @cindex @file{objects.fs}
10223: @cindex @file{oof.fs}
1.26 crook 10224:
1.78 anton 10225: This section describes the @file{objects.fs} package. This material also
10226: has been published in M. Anton Ertl,
10227: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10228: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10229: 37--43.
10230: @c McKewan's and Zsoter's packages
1.26 crook 10231:
1.78 anton 10232: This section assumes that you have read @ref{Structures}.
1.5 anton 10233:
1.78 anton 10234: The techniques on which this model is based have been used to implement
10235: the parser generator, Gray, and have also been used in Gforth for
10236: implementing the various flavours of word lists (hashed or not,
10237: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10238:
10239:
1.26 crook 10240: @menu
1.78 anton 10241: * Properties of the Objects model::
10242: * Basic Objects Usage::
10243: * The Objects base class::
10244: * Creating objects::
10245: * Object-Oriented Programming Style::
10246: * Class Binding::
10247: * Method conveniences::
10248: * Classes and Scoping::
10249: * Dividing classes::
10250: * Object Interfaces::
10251: * Objects Implementation::
10252: * Objects Glossary::
1.26 crook 10253: @end menu
1.5 anton 10254:
1.78 anton 10255: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10256:
1.78 anton 10257: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10258: @subsubsection Properties of the @file{objects.fs} model
10259: @cindex @file{objects.fs} properties
1.5 anton 10260:
1.78 anton 10261: @itemize @bullet
10262: @item
10263: It is straightforward to pass objects on the stack. Passing
10264: selectors on the stack is a little less convenient, but possible.
1.44 crook 10265:
1.78 anton 10266: @item
10267: Objects are just data structures in memory, and are referenced by their
10268: address. You can create words for objects with normal defining words
10269: like @code{constant}. Likewise, there is no difference between instance
10270: variables that contain objects and those that contain other data.
1.5 anton 10271:
1.78 anton 10272: @item
10273: Late binding is efficient and easy to use.
1.44 crook 10274:
1.78 anton 10275: @item
10276: It avoids parsing, and thus avoids problems with state-smartness
10277: and reduced extensibility; for convenience there are a few parsing
10278: words, but they have non-parsing counterparts. There are also a few
10279: defining words that parse. This is hard to avoid, because all standard
10280: defining words parse (except @code{:noname}); however, such
10281: words are not as bad as many other parsing words, because they are not
10282: state-smart.
1.5 anton 10283:
1.78 anton 10284: @item
10285: It does not try to incorporate everything. It does a few things and does
10286: them well (IMO). In particular, this model was not designed to support
10287: information hiding (although it has features that may help); you can use
10288: a separate package for achieving this.
1.5 anton 10289:
1.78 anton 10290: @item
10291: It is layered; you don't have to learn and use all features to use this
10292: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10293: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10294: are optional and independent of each other.
1.5 anton 10295:
1.78 anton 10296: @item
10297: An implementation in ANS Forth is available.
1.5 anton 10298:
1.78 anton 10299: @end itemize
1.5 anton 10300:
1.44 crook 10301:
1.78 anton 10302: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10303: @subsubsection Basic @file{objects.fs} Usage
10304: @cindex basic objects usage
10305: @cindex objects, basic usage
1.5 anton 10306:
1.78 anton 10307: You can define a class for graphical objects like this:
1.44 crook 10308:
1.78 anton 10309: @cindex @code{class} usage
10310: @cindex @code{end-class} usage
10311: @cindex @code{selector} usage
1.5 anton 10312: @example
1.78 anton 10313: object class \ "object" is the parent class
10314: selector draw ( x y graphical -- )
10315: end-class graphical
10316: @end example
10317:
10318: This code defines a class @code{graphical} with an
10319: operation @code{draw}. We can perform the operation
10320: @code{draw} on any @code{graphical} object, e.g.:
10321:
10322: @example
10323: 100 100 t-rex draw
1.26 crook 10324: @end example
1.5 anton 10325:
1.78 anton 10326: @noindent
10327: where @code{t-rex} is a word (say, a constant) that produces a
10328: graphical object.
10329:
10330: @comment TODO add a 2nd operation eg perimeter.. and use for
10331: @comment a concrete example
1.5 anton 10332:
1.78 anton 10333: @cindex abstract class
10334: How do we create a graphical object? With the present definitions,
10335: we cannot create a useful graphical object. The class
10336: @code{graphical} describes graphical objects in general, but not
10337: any concrete graphical object type (C++ users would call it an
10338: @emph{abstract class}); e.g., there is no method for the selector
10339: @code{draw} in the class @code{graphical}.
1.5 anton 10340:
1.78 anton 10341: For concrete graphical objects, we define child classes of the
10342: class @code{graphical}, e.g.:
1.5 anton 10343:
1.78 anton 10344: @cindex @code{overrides} usage
10345: @cindex @code{field} usage in class definition
1.26 crook 10346: @example
1.78 anton 10347: graphical class \ "graphical" is the parent class
10348: cell% field circle-radius
1.5 anton 10349:
1.78 anton 10350: :noname ( x y circle -- )
10351: circle-radius @@ draw-circle ;
10352: overrides draw
1.5 anton 10353:
1.78 anton 10354: :noname ( n-radius circle -- )
10355: circle-radius ! ;
10356: overrides construct
1.5 anton 10357:
1.78 anton 10358: end-class circle
10359: @end example
1.44 crook 10360:
1.78 anton 10361: Here we define a class @code{circle} as a child of @code{graphical},
10362: with field @code{circle-radius} (which behaves just like a field
10363: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10364: for the selectors @code{draw} and @code{construct} (@code{construct} is
10365: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10366:
1.78 anton 10367: Now we can create a circle on the heap (i.e.,
10368: @code{allocate}d memory) with:
1.44 crook 10369:
1.78 anton 10370: @cindex @code{heap-new} usage
1.5 anton 10371: @example
1.78 anton 10372: 50 circle heap-new constant my-circle
1.5 anton 10373: @end example
10374:
1.78 anton 10375: @noindent
10376: @code{heap-new} invokes @code{construct}, thus
10377: initializing the field @code{circle-radius} with 50. We can draw
10378: this new circle at (100,100) with:
1.5 anton 10379:
10380: @example
1.78 anton 10381: 100 100 my-circle draw
1.5 anton 10382: @end example
10383:
1.78 anton 10384: @cindex selector invocation, restrictions
10385: @cindex class definition, restrictions
10386: Note: You can only invoke a selector if the object on the TOS
10387: (the receiving object) belongs to the class where the selector was
10388: defined or one of its descendents; e.g., you can invoke
10389: @code{draw} only for objects belonging to @code{graphical}
10390: or its descendents (e.g., @code{circle}). Immediately before
10391: @code{end-class}, the search order has to be the same as
10392: immediately after @code{class}.
10393:
10394: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10395: @subsubsection The @file{object.fs} base class
10396: @cindex @code{object} class
10397:
10398: When you define a class, you have to specify a parent class. So how do
10399: you start defining classes? There is one class available from the start:
10400: @code{object}. It is ancestor for all classes and so is the
10401: only class that has no parent. It has two selectors: @code{construct}
10402: and @code{print}.
10403:
10404: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10405: @subsubsection Creating objects
10406: @cindex creating objects
10407: @cindex object creation
10408: @cindex object allocation options
10409:
10410: @cindex @code{heap-new} discussion
10411: @cindex @code{dict-new} discussion
10412: @cindex @code{construct} discussion
10413: You can create and initialize an object of a class on the heap with
10414: @code{heap-new} ( ... class -- object ) and in the dictionary
10415: (allocation with @code{allot}) with @code{dict-new} (
10416: ... class -- object ). Both words invoke @code{construct}, which
10417: consumes the stack items indicated by "..." above.
10418:
10419: @cindex @code{init-object} discussion
10420: @cindex @code{class-inst-size} discussion
10421: If you want to allocate memory for an object yourself, you can get its
10422: alignment and size with @code{class-inst-size 2@@} ( class --
10423: align size ). Once you have memory for an object, you can initialize
10424: it with @code{init-object} ( ... class object -- );
10425: @code{construct} does only a part of the necessary work.
10426:
10427: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10428: @subsubsection Object-Oriented Programming Style
10429: @cindex object-oriented programming style
10430: @cindex programming style, object-oriented
1.5 anton 10431:
1.78 anton 10432: This section is not exhaustive.
1.5 anton 10433:
1.78 anton 10434: @cindex stack effects of selectors
10435: @cindex selectors and stack effects
10436: In general, it is a good idea to ensure that all methods for the
10437: same selector have the same stack effect: when you invoke a selector,
10438: you often have no idea which method will be invoked, so, unless all
10439: methods have the same stack effect, you will not know the stack effect
10440: of the selector invocation.
1.5 anton 10441:
1.78 anton 10442: One exception to this rule is methods for the selector
10443: @code{construct}. We know which method is invoked, because we
10444: specify the class to be constructed at the same place. Actually, I
10445: defined @code{construct} as a selector only to give the users a
10446: convenient way to specify initialization. The way it is used, a
10447: mechanism different from selector invocation would be more natural
10448: (but probably would take more code and more space to explain).
1.5 anton 10449:
1.78 anton 10450: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10451: @subsubsection Class Binding
10452: @cindex class binding
10453: @cindex early binding
1.5 anton 10454:
1.78 anton 10455: @cindex late binding
10456: Normal selector invocations determine the method at run-time depending
10457: on the class of the receiving object. This run-time selection is called
10458: @i{late binding}.
1.5 anton 10459:
1.78 anton 10460: Sometimes it's preferable to invoke a different method. For example,
10461: you might want to use the simple method for @code{print}ing
10462: @code{object}s instead of the possibly long-winded @code{print} method
10463: of the receiver class. You can achieve this by replacing the invocation
10464: of @code{print} with:
1.5 anton 10465:
1.78 anton 10466: @cindex @code{[bind]} usage
1.5 anton 10467: @example
1.78 anton 10468: [bind] object print
1.5 anton 10469: @end example
10470:
1.78 anton 10471: @noindent
10472: in compiled code or:
10473:
10474: @cindex @code{bind} usage
1.5 anton 10475: @example
1.78 anton 10476: bind object print
1.5 anton 10477: @end example
10478:
1.78 anton 10479: @cindex class binding, alternative to
10480: @noindent
10481: in interpreted code. Alternatively, you can define the method with a
10482: name (e.g., @code{print-object}), and then invoke it through the
10483: name. Class binding is just a (often more convenient) way to achieve
10484: the same effect; it avoids name clutter and allows you to invoke
10485: methods directly without naming them first.
1.5 anton 10486:
1.78 anton 10487: @cindex superclass binding
10488: @cindex parent class binding
10489: A frequent use of class binding is this: When we define a method
10490: for a selector, we often want the method to do what the selector does
10491: in the parent class, and a little more. There is a special word for
10492: this purpose: @code{[parent]}; @code{[parent]
10493: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10494: selector}}, where @code{@emph{parent}} is the parent
10495: class of the current class. E.g., a method definition might look like:
1.44 crook 10496:
1.78 anton 10497: @cindex @code{[parent]} usage
10498: @example
10499: :noname
10500: dup [parent] foo \ do parent's foo on the receiving object
10501: ... \ do some more
10502: ; overrides foo
10503: @end example
1.6 pazsan 10504:
1.78 anton 10505: @cindex class binding as optimization
10506: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10507: March 1997), Andrew McKewan presents class binding as an optimization
10508: technique. I recommend not using it for this purpose unless you are in
10509: an emergency. Late binding is pretty fast with this model anyway, so the
10510: benefit of using class binding is small; the cost of using class binding
10511: where it is not appropriate is reduced maintainability.
1.44 crook 10512:
1.78 anton 10513: While we are at programming style questions: You should bind
10514: selectors only to ancestor classes of the receiving object. E.g., say,
10515: you know that the receiving object is of class @code{foo} or its
10516: descendents; then you should bind only to @code{foo} and its
10517: ancestors.
1.12 anton 10518:
1.78 anton 10519: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10520: @subsubsection Method conveniences
10521: @cindex method conveniences
1.44 crook 10522:
1.78 anton 10523: In a method you usually access the receiving object pretty often. If
10524: you define the method as a plain colon definition (e.g., with
10525: @code{:noname}), you may have to do a lot of stack
10526: gymnastics. To avoid this, you can define the method with @code{m:
10527: ... ;m}. E.g., you could define the method for
10528: @code{draw}ing a @code{circle} with
1.6 pazsan 10529:
1.78 anton 10530: @cindex @code{this} usage
10531: @cindex @code{m:} usage
10532: @cindex @code{;m} usage
10533: @example
10534: m: ( x y circle -- )
10535: ( x y ) this circle-radius @@ draw-circle ;m
10536: @end example
1.6 pazsan 10537:
1.78 anton 10538: @cindex @code{exit} in @code{m: ... ;m}
10539: @cindex @code{exitm} discussion
10540: @cindex @code{catch} in @code{m: ... ;m}
10541: When this method is executed, the receiver object is removed from the
10542: stack; you can access it with @code{this} (admittedly, in this
10543: example the use of @code{m: ... ;m} offers no advantage). Note
10544: that I specify the stack effect for the whole method (i.e. including
10545: the receiver object), not just for the code between @code{m:}
10546: and @code{;m}. You cannot use @code{exit} in
10547: @code{m:...;m}; instead, use
10548: @code{exitm}.@footnote{Moreover, for any word that calls
10549: @code{catch} and was defined before loading
10550: @code{objects.fs}, you have to redefine it like I redefined
10551: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10552:
1.78 anton 10553: @cindex @code{inst-var} usage
10554: You will frequently use sequences of the form @code{this
10555: @emph{field}} (in the example above: @code{this
10556: circle-radius}). If you use the field only in this way, you can
10557: define it with @code{inst-var} and eliminate the
10558: @code{this} before the field name. E.g., the @code{circle}
10559: class above could also be defined with:
1.6 pazsan 10560:
1.78 anton 10561: @example
10562: graphical class
10563: cell% inst-var radius
1.6 pazsan 10564:
1.78 anton 10565: m: ( x y circle -- )
10566: radius @@ draw-circle ;m
10567: overrides draw
1.6 pazsan 10568:
1.78 anton 10569: m: ( n-radius circle -- )
10570: radius ! ;m
10571: overrides construct
1.6 pazsan 10572:
1.78 anton 10573: end-class circle
10574: @end example
1.6 pazsan 10575:
1.78 anton 10576: @code{radius} can only be used in @code{circle} and its
10577: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10578:
1.78 anton 10579: @cindex @code{inst-value} usage
10580: You can also define fields with @code{inst-value}, which is
10581: to @code{inst-var} what @code{value} is to
10582: @code{variable}. You can change the value of such a field with
10583: @code{[to-inst]}. E.g., we could also define the class
10584: @code{circle} like this:
1.44 crook 10585:
1.78 anton 10586: @example
10587: graphical class
10588: inst-value radius
1.6 pazsan 10589:
1.78 anton 10590: m: ( x y circle -- )
10591: radius draw-circle ;m
10592: overrides draw
1.44 crook 10593:
1.78 anton 10594: m: ( n-radius circle -- )
10595: [to-inst] radius ;m
10596: overrides construct
1.6 pazsan 10597:
1.78 anton 10598: end-class circle
10599: @end example
1.6 pazsan 10600:
1.78 anton 10601: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10602:
1.78 anton 10603: @c Finally, you can define named methods with @code{:m}. One use of this
10604: @c feature is the definition of words that occur only in one class and are
10605: @c not intended to be overridden, but which still need method context
10606: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10607: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10608:
10609:
1.78 anton 10610: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10611: @subsubsection Classes and Scoping
10612: @cindex classes and scoping
10613: @cindex scoping and classes
1.6 pazsan 10614:
1.78 anton 10615: Inheritance is frequent, unlike structure extension. This exacerbates
10616: the problem with the field name convention (@pxref{Structure Naming
10617: Convention}): One always has to remember in which class the field was
10618: originally defined; changing a part of the class structure would require
10619: changes for renaming in otherwise unaffected code.
1.6 pazsan 10620:
1.78 anton 10621: @cindex @code{inst-var} visibility
10622: @cindex @code{inst-value} visibility
10623: To solve this problem, I added a scoping mechanism (which was not in my
10624: original charter): A field defined with @code{inst-var} (or
10625: @code{inst-value}) is visible only in the class where it is defined and in
10626: the descendent classes of this class. Using such fields only makes
10627: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10628:
1.78 anton 10629: This scoping mechanism allows us to use the unadorned field name,
10630: because name clashes with unrelated words become much less likely.
1.6 pazsan 10631:
1.78 anton 10632: @cindex @code{protected} discussion
10633: @cindex @code{private} discussion
10634: Once we have this mechanism, we can also use it for controlling the
10635: visibility of other words: All words defined after
10636: @code{protected} are visible only in the current class and its
10637: descendents. @code{public} restores the compilation
10638: (i.e. @code{current}) word list that was in effect before. If you
10639: have several @code{protected}s without an intervening
10640: @code{public} or @code{set-current}, @code{public}
10641: will restore the compilation word list in effect before the first of
10642: these @code{protected}s.
1.6 pazsan 10643:
1.78 anton 10644: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10645: @subsubsection Dividing classes
10646: @cindex Dividing classes
10647: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10648:
1.78 anton 10649: You may want to do the definition of methods separate from the
10650: definition of the class, its selectors, fields, and instance variables,
10651: i.e., separate the implementation from the definition. You can do this
10652: in the following way:
1.6 pazsan 10653:
1.78 anton 10654: @example
10655: graphical class
10656: inst-value radius
10657: end-class circle
1.6 pazsan 10658:
1.78 anton 10659: ... \ do some other stuff
1.6 pazsan 10660:
1.78 anton 10661: circle methods \ now we are ready
1.44 crook 10662:
1.78 anton 10663: m: ( x y circle -- )
10664: radius draw-circle ;m
10665: overrides draw
1.6 pazsan 10666:
1.78 anton 10667: m: ( n-radius circle -- )
10668: [to-inst] radius ;m
10669: overrides construct
1.44 crook 10670:
1.78 anton 10671: end-methods
10672: @end example
1.7 pazsan 10673:
1.78 anton 10674: You can use several @code{methods}...@code{end-methods} sections. The
10675: only things you can do to the class in these sections are: defining
10676: methods, and overriding the class's selectors. You must not define new
10677: selectors or fields.
1.7 pazsan 10678:
1.78 anton 10679: Note that you often have to override a selector before using it. In
10680: particular, you usually have to override @code{construct} with a new
10681: method before you can invoke @code{heap-new} and friends. E.g., you
10682: must not create a circle before the @code{overrides construct} sequence
10683: in the example above.
1.7 pazsan 10684:
1.78 anton 10685: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10686: @subsubsection Object Interfaces
10687: @cindex object interfaces
10688: @cindex interfaces for objects
1.7 pazsan 10689:
1.78 anton 10690: In this model you can only call selectors defined in the class of the
10691: receiving objects or in one of its ancestors. If you call a selector
10692: with a receiving object that is not in one of these classes, the
10693: result is undefined; if you are lucky, the program crashes
10694: immediately.
1.7 pazsan 10695:
1.78 anton 10696: @cindex selectors common to hardly-related classes
10697: Now consider the case when you want to have a selector (or several)
10698: available in two classes: You would have to add the selector to a
10699: common ancestor class, in the worst case to @code{object}. You
10700: may not want to do this, e.g., because someone else is responsible for
10701: this ancestor class.
1.7 pazsan 10702:
1.78 anton 10703: The solution for this problem is interfaces. An interface is a
10704: collection of selectors. If a class implements an interface, the
10705: selectors become available to the class and its descendents. A class
10706: can implement an unlimited number of interfaces. For the problem
10707: discussed above, we would define an interface for the selector(s), and
10708: both classes would implement the interface.
1.7 pazsan 10709:
1.78 anton 10710: As an example, consider an interface @code{storage} for
10711: writing objects to disk and getting them back, and a class
10712: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10713:
1.78 anton 10714: @cindex @code{interface} usage
10715: @cindex @code{end-interface} usage
10716: @cindex @code{implementation} usage
10717: @example
10718: interface
10719: selector write ( file object -- )
10720: selector read1 ( file object -- )
10721: end-interface storage
1.13 pazsan 10722:
1.78 anton 10723: bar class
10724: storage implementation
1.13 pazsan 10725:
1.78 anton 10726: ... overrides write
10727: ... overrides read1
10728: ...
10729: end-class foo
10730: @end example
1.13 pazsan 10731:
1.78 anton 10732: @noindent
10733: (I would add a word @code{read} @i{( file -- object )} that uses
10734: @code{read1} internally, but that's beyond the point illustrated
10735: here.)
1.13 pazsan 10736:
1.78 anton 10737: Note that you cannot use @code{protected} in an interface; and
10738: of course you cannot define fields.
1.13 pazsan 10739:
1.78 anton 10740: In the Neon model, all selectors are available for all classes;
10741: therefore it does not need interfaces. The price you pay in this model
10742: is slower late binding, and therefore, added complexity to avoid late
10743: binding.
1.13 pazsan 10744:
1.78 anton 10745: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10746: @subsubsection @file{objects.fs} Implementation
10747: @cindex @file{objects.fs} implementation
1.13 pazsan 10748:
1.78 anton 10749: @cindex @code{object-map} discussion
10750: An object is a piece of memory, like one of the data structures
10751: described with @code{struct...end-struct}. It has a field
10752: @code{object-map} that points to the method map for the object's
10753: class.
1.13 pazsan 10754:
1.78 anton 10755: @cindex method map
10756: @cindex virtual function table
10757: The @emph{method map}@footnote{This is Self terminology; in C++
10758: terminology: virtual function table.} is an array that contains the
10759: execution tokens (@i{xt}s) of the methods for the object's class. Each
10760: selector contains an offset into a method map.
1.13 pazsan 10761:
1.78 anton 10762: @cindex @code{selector} implementation, class
10763: @code{selector} is a defining word that uses
10764: @code{CREATE} and @code{DOES>}. The body of the
10765: selector contains the offset; the @code{DOES>} action for a
10766: class selector is, basically:
1.8 pazsan 10767:
10768: @example
1.78 anton 10769: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10770: @end example
10771:
1.78 anton 10772: Since @code{object-map} is the first field of the object, it
10773: does not generate any code. As you can see, calling a selector has a
10774: small, constant cost.
1.26 crook 10775:
1.78 anton 10776: @cindex @code{current-interface} discussion
10777: @cindex class implementation and representation
10778: A class is basically a @code{struct} combined with a method
10779: map. During the class definition the alignment and size of the class
10780: are passed on the stack, just as with @code{struct}s, so
10781: @code{field} can also be used for defining class
10782: fields. However, passing more items on the stack would be
10783: inconvenient, so @code{class} builds a data structure in memory,
10784: which is accessed through the variable
10785: @code{current-interface}. After its definition is complete, the
10786: class is represented on the stack by a pointer (e.g., as parameter for
10787: a child class definition).
1.26 crook 10788:
1.78 anton 10789: A new class starts off with the alignment and size of its parent,
10790: and a copy of the parent's method map. Defining new fields extends the
10791: size and alignment; likewise, defining new selectors extends the
10792: method map. @code{overrides} just stores a new @i{xt} in the method
10793: map at the offset given by the selector.
1.13 pazsan 10794:
1.78 anton 10795: @cindex class binding, implementation
10796: Class binding just gets the @i{xt} at the offset given by the selector
10797: from the class's method map and @code{compile,}s (in the case of
10798: @code{[bind]}) it.
1.13 pazsan 10799:
1.78 anton 10800: @cindex @code{this} implementation
10801: @cindex @code{catch} and @code{this}
10802: @cindex @code{this} and @code{catch}
10803: I implemented @code{this} as a @code{value}. At the
10804: start of an @code{m:...;m} method the old @code{this} is
10805: stored to the return stack and restored at the end; and the object on
10806: the TOS is stored @code{TO this}. This technique has one
10807: disadvantage: If the user does not leave the method via
10808: @code{;m}, but via @code{throw} or @code{exit},
10809: @code{this} is not restored (and @code{exit} may
10810: crash). To deal with the @code{throw} problem, I have redefined
10811: @code{catch} to save and restore @code{this}; the same
10812: should be done with any word that can catch an exception. As for
10813: @code{exit}, I simply forbid it (as a replacement, there is
10814: @code{exitm}).
1.13 pazsan 10815:
1.78 anton 10816: @cindex @code{inst-var} implementation
10817: @code{inst-var} is just the same as @code{field}, with
10818: a different @code{DOES>} action:
1.13 pazsan 10819: @example
1.78 anton 10820: @@ this +
1.8 pazsan 10821: @end example
1.78 anton 10822: Similar for @code{inst-value}.
1.8 pazsan 10823:
1.78 anton 10824: @cindex class scoping implementation
10825: Each class also has a word list that contains the words defined with
10826: @code{inst-var} and @code{inst-value}, and its protected
10827: words. It also has a pointer to its parent. @code{class} pushes
10828: the word lists of the class and all its ancestors onto the search order stack,
10829: and @code{end-class} drops them.
1.20 pazsan 10830:
1.78 anton 10831: @cindex interface implementation
10832: An interface is like a class without fields, parent and protected
10833: words; i.e., it just has a method map. If a class implements an
10834: interface, its method map contains a pointer to the method map of the
10835: interface. The positive offsets in the map are reserved for class
10836: methods, therefore interface map pointers have negative
10837: offsets. Interfaces have offsets that are unique throughout the
10838: system, unlike class selectors, whose offsets are only unique for the
10839: classes where the selector is available (invokable).
1.20 pazsan 10840:
1.78 anton 10841: This structure means that interface selectors have to perform one
10842: indirection more than class selectors to find their method. Their body
10843: contains the interface map pointer offset in the class method map, and
10844: the method offset in the interface method map. The
10845: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10846:
10847: @example
1.78 anton 10848: ( object selector-body )
10849: 2dup selector-interface @@ ( object selector-body object interface-offset )
10850: swap object-map @@ + @@ ( object selector-body map )
10851: swap selector-offset @@ + @@ execute
1.20 pazsan 10852: @end example
10853:
1.78 anton 10854: where @code{object-map} and @code{selector-offset} are
10855: first fields and generate no code.
1.20 pazsan 10856:
1.78 anton 10857: As a concrete example, consider the following code:
1.20 pazsan 10858:
10859: @example
1.78 anton 10860: interface
10861: selector if1sel1
10862: selector if1sel2
10863: end-interface if1
1.20 pazsan 10864:
1.78 anton 10865: object class
10866: if1 implementation
10867: selector cl1sel1
10868: cell% inst-var cl1iv1
1.20 pazsan 10869:
1.78 anton 10870: ' m1 overrides construct
10871: ' m2 overrides if1sel1
10872: ' m3 overrides if1sel2
10873: ' m4 overrides cl1sel2
10874: end-class cl1
1.20 pazsan 10875:
1.78 anton 10876: create obj1 object dict-new drop
10877: create obj2 cl1 dict-new drop
10878: @end example
1.20 pazsan 10879:
1.78 anton 10880: The data structure created by this code (including the data structure
10881: for @code{object}) is shown in the
10882: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10883: @comment TODO add this diagram..
1.20 pazsan 10884:
1.78 anton 10885: @node Objects Glossary, , Objects Implementation, Objects
10886: @subsubsection @file{objects.fs} Glossary
10887: @cindex @file{objects.fs} Glossary
1.20 pazsan 10888:
10889:
1.78 anton 10890: doc---objects-bind
10891: doc---objects-<bind>
10892: doc---objects-bind'
10893: doc---objects-[bind]
10894: doc---objects-class
10895: doc---objects-class->map
10896: doc---objects-class-inst-size
10897: doc---objects-class-override!
1.79 anton 10898: doc---objects-class-previous
10899: doc---objects-class>order
1.78 anton 10900: doc---objects-construct
10901: doc---objects-current'
10902: doc---objects-[current]
10903: doc---objects-current-interface
10904: doc---objects-dict-new
10905: doc---objects-end-class
10906: doc---objects-end-class-noname
10907: doc---objects-end-interface
10908: doc---objects-end-interface-noname
10909: doc---objects-end-methods
10910: doc---objects-exitm
10911: doc---objects-heap-new
10912: doc---objects-implementation
10913: doc---objects-init-object
10914: doc---objects-inst-value
10915: doc---objects-inst-var
10916: doc---objects-interface
10917: doc---objects-m:
10918: doc---objects-:m
10919: doc---objects-;m
10920: doc---objects-method
10921: doc---objects-methods
10922: doc---objects-object
10923: doc---objects-overrides
10924: doc---objects-[parent]
10925: doc---objects-print
10926: doc---objects-protected
10927: doc---objects-public
10928: doc---objects-selector
10929: doc---objects-this
10930: doc---objects-<to-inst>
10931: doc---objects-[to-inst]
10932: doc---objects-to-this
10933: doc---objects-xt-new
1.20 pazsan 10934:
10935:
1.78 anton 10936: @c -------------------------------------------------------------
10937: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10938: @subsection The @file{oof.fs} model
10939: @cindex oof
10940: @cindex object-oriented programming
1.20 pazsan 10941:
1.78 anton 10942: @cindex @file{objects.fs}
10943: @cindex @file{oof.fs}
1.20 pazsan 10944:
1.78 anton 10945: This section describes the @file{oof.fs} package.
1.20 pazsan 10946:
1.78 anton 10947: The package described in this section has been used in bigFORTH since 1991, and
10948: used for two large applications: a chromatographic system used to
10949: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10950:
1.78 anton 10951: You can find a description (in German) of @file{oof.fs} in @cite{Object
10952: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10953: 10(2), 1994.
1.20 pazsan 10954:
1.78 anton 10955: @menu
10956: * Properties of the OOF model::
10957: * Basic OOF Usage::
10958: * The OOF base class::
10959: * Class Declaration::
10960: * Class Implementation::
10961: @end menu
1.20 pazsan 10962:
1.78 anton 10963: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10964: @subsubsection Properties of the @file{oof.fs} model
10965: @cindex @file{oof.fs} properties
1.20 pazsan 10966:
1.78 anton 10967: @itemize @bullet
10968: @item
10969: This model combines object oriented programming with information
10970: hiding. It helps you writing large application, where scoping is
10971: necessary, because it provides class-oriented scoping.
1.20 pazsan 10972:
1.78 anton 10973: @item
10974: Named objects, object pointers, and object arrays can be created,
10975: selector invocation uses the ``object selector'' syntax. Selector invocation
10976: to objects and/or selectors on the stack is a bit less convenient, but
10977: possible.
1.44 crook 10978:
1.78 anton 10979: @item
10980: Selector invocation and instance variable usage of the active object is
10981: straightforward, since both make use of the active object.
1.44 crook 10982:
1.78 anton 10983: @item
10984: Late binding is efficient and easy to use.
1.20 pazsan 10985:
1.78 anton 10986: @item
10987: State-smart objects parse selectors. However, extensibility is provided
10988: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10989:
1.78 anton 10990: @item
10991: An implementation in ANS Forth is available.
1.20 pazsan 10992:
1.78 anton 10993: @end itemize
1.23 crook 10994:
10995:
1.78 anton 10996: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10997: @subsubsection Basic @file{oof.fs} Usage
10998: @cindex @file{oof.fs} usage
1.23 crook 10999:
1.78 anton 11000: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11001:
1.78 anton 11002: You can define a class for graphical objects like this:
1.23 crook 11003:
1.78 anton 11004: @cindex @code{class} usage
11005: @cindex @code{class;} usage
11006: @cindex @code{method} usage
11007: @example
11008: object class graphical \ "object" is the parent class
1.139 pazsan 11009: method draw ( x y -- )
1.78 anton 11010: class;
11011: @end example
1.23 crook 11012:
1.78 anton 11013: This code defines a class @code{graphical} with an
11014: operation @code{draw}. We can perform the operation
11015: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11016:
1.78 anton 11017: @example
11018: 100 100 t-rex draw
11019: @end example
1.23 crook 11020:
1.78 anton 11021: @noindent
11022: where @code{t-rex} is an object or object pointer, created with e.g.
11023: @code{graphical : t-rex}.
1.23 crook 11024:
1.78 anton 11025: @cindex abstract class
11026: How do we create a graphical object? With the present definitions,
11027: we cannot create a useful graphical object. The class
11028: @code{graphical} describes graphical objects in general, but not
11029: any concrete graphical object type (C++ users would call it an
11030: @emph{abstract class}); e.g., there is no method for the selector
11031: @code{draw} in the class @code{graphical}.
1.23 crook 11032:
1.78 anton 11033: For concrete graphical objects, we define child classes of the
11034: class @code{graphical}, e.g.:
1.23 crook 11035:
1.78 anton 11036: @example
11037: graphical class circle \ "graphical" is the parent class
11038: cell var circle-radius
11039: how:
11040: : draw ( x y -- )
11041: circle-radius @@ draw-circle ;
1.23 crook 11042:
1.139 pazsan 11043: : init ( n-radius -- )
1.78 anton 11044: circle-radius ! ;
11045: class;
11046: @end example
1.1 anton 11047:
1.78 anton 11048: Here we define a class @code{circle} as a child of @code{graphical},
11049: with a field @code{circle-radius}; it defines new methods for the
11050: selectors @code{draw} and @code{init} (@code{init} is defined in
11051: @code{object}, the parent class of @code{graphical}).
1.1 anton 11052:
1.78 anton 11053: Now we can create a circle in the dictionary with:
1.1 anton 11054:
1.78 anton 11055: @example
11056: 50 circle : my-circle
11057: @end example
1.21 crook 11058:
1.78 anton 11059: @noindent
11060: @code{:} invokes @code{init}, thus initializing the field
11061: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11062: with:
1.1 anton 11063:
1.78 anton 11064: @example
11065: 100 100 my-circle draw
11066: @end example
1.1 anton 11067:
1.78 anton 11068: @cindex selector invocation, restrictions
11069: @cindex class definition, restrictions
11070: Note: You can only invoke a selector if the receiving object belongs to
11071: the class where the selector was defined or one of its descendents;
11072: e.g., you can invoke @code{draw} only for objects belonging to
11073: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11074: mechanism will check if you try to invoke a selector that is not
11075: defined in this class hierarchy, so you'll get an error at compilation
11076: time.
1.1 anton 11077:
11078:
1.78 anton 11079: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11080: @subsubsection The @file{oof.fs} base class
11081: @cindex @file{oof.fs} base class
1.1 anton 11082:
1.78 anton 11083: When you define a class, you have to specify a parent class. So how do
11084: you start defining classes? There is one class available from the start:
11085: @code{object}. You have to use it as ancestor for all classes. It is the
11086: only class that has no parent. Classes are also objects, except that
11087: they don't have instance variables; class manipulation such as
11088: inheritance or changing definitions of a class is handled through
11089: selectors of the class @code{object}.
1.1 anton 11090:
1.78 anton 11091: @code{object} provides a number of selectors:
1.1 anton 11092:
1.78 anton 11093: @itemize @bullet
11094: @item
11095: @code{class} for subclassing, @code{definitions} to add definitions
11096: later on, and @code{class?} to get type informations (is the class a
11097: subclass of the class passed on the stack?).
1.1 anton 11098:
1.78 anton 11099: doc---object-class
11100: doc---object-definitions
11101: doc---object-class?
1.1 anton 11102:
11103:
1.26 crook 11104: @item
1.78 anton 11105: @code{init} and @code{dispose} as constructor and destructor of the
11106: object. @code{init} is invocated after the object's memory is allocated,
11107: while @code{dispose} also handles deallocation. Thus if you redefine
11108: @code{dispose}, you have to call the parent's dispose with @code{super
11109: dispose}, too.
11110:
11111: doc---object-init
11112: doc---object-dispose
11113:
1.1 anton 11114:
1.26 crook 11115: @item
1.78 anton 11116: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11117: @code{[]} to create named and unnamed objects and object arrays or
11118: object pointers.
11119:
11120: doc---object-new
11121: doc---object-new[]
11122: doc---object-:
11123: doc---object-ptr
11124: doc---object-asptr
11125: doc---object-[]
11126:
1.1 anton 11127:
1.26 crook 11128: @item
1.78 anton 11129: @code{::} and @code{super} for explicit scoping. You should use explicit
11130: scoping only for super classes or classes with the same set of instance
11131: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11132:
1.78 anton 11133: doc---object-::
11134: doc---object-super
1.21 crook 11135:
11136:
1.26 crook 11137: @item
1.78 anton 11138: @code{self} to get the address of the object
1.21 crook 11139:
1.78 anton 11140: doc---object-self
1.21 crook 11141:
11142:
1.78 anton 11143: @item
11144: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11145: pointers and instance defers.
1.21 crook 11146:
1.78 anton 11147: doc---object-bind
11148: doc---object-bound
11149: doc---object-link
11150: doc---object-is
1.21 crook 11151:
11152:
1.78 anton 11153: @item
11154: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11155: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11156:
1.78 anton 11157: doc---object-'
11158: doc---object-postpone
1.21 crook 11159:
11160:
1.78 anton 11161: @item
11162: @code{with} and @code{endwith} to select the active object from the
11163: stack, and enable its scope. Using @code{with} and @code{endwith}
11164: also allows you to create code using selector @code{postpone} without being
11165: trapped by the state-smart objects.
1.21 crook 11166:
1.78 anton 11167: doc---object-with
11168: doc---object-endwith
1.21 crook 11169:
11170:
1.78 anton 11171: @end itemize
1.21 crook 11172:
1.78 anton 11173: @node Class Declaration, Class Implementation, The OOF base class, OOF
11174: @subsubsection Class Declaration
11175: @cindex class declaration
1.21 crook 11176:
1.78 anton 11177: @itemize @bullet
11178: @item
11179: Instance variables
1.21 crook 11180:
1.78 anton 11181: doc---oof-var
1.21 crook 11182:
11183:
1.78 anton 11184: @item
11185: Object pointers
1.21 crook 11186:
1.78 anton 11187: doc---oof-ptr
11188: doc---oof-asptr
1.21 crook 11189:
11190:
1.78 anton 11191: @item
11192: Instance defers
1.21 crook 11193:
1.78 anton 11194: doc---oof-defer
1.21 crook 11195:
11196:
1.78 anton 11197: @item
11198: Method selectors
1.21 crook 11199:
1.78 anton 11200: doc---oof-early
11201: doc---oof-method
1.21 crook 11202:
11203:
1.78 anton 11204: @item
11205: Class-wide variables
1.21 crook 11206:
1.78 anton 11207: doc---oof-static
1.21 crook 11208:
11209:
1.78 anton 11210: @item
11211: End declaration
1.1 anton 11212:
1.78 anton 11213: doc---oof-how:
11214: doc---oof-class;
1.21 crook 11215:
11216:
1.78 anton 11217: @end itemize
1.21 crook 11218:
1.78 anton 11219: @c -------------------------------------------------------------
11220: @node Class Implementation, , Class Declaration, OOF
11221: @subsubsection Class Implementation
11222: @cindex class implementation
1.21 crook 11223:
1.78 anton 11224: @c -------------------------------------------------------------
11225: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11226: @subsection The @file{mini-oof.fs} model
11227: @cindex mini-oof
1.21 crook 11228:
1.78 anton 11229: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11230: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11231: and reduces to the bare minimum of features. This is based on a posting
11232: of Bernd Paysan in comp.lang.forth.
1.21 crook 11233:
1.78 anton 11234: @menu
11235: * Basic Mini-OOF Usage::
11236: * Mini-OOF Example::
11237: * Mini-OOF Implementation::
11238: @end menu
1.21 crook 11239:
1.78 anton 11240: @c -------------------------------------------------------------
11241: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11242: @subsubsection Basic @file{mini-oof.fs} Usage
11243: @cindex mini-oof usage
1.21 crook 11244:
1.78 anton 11245: There is a base class (@code{class}, which allocates one cell for the
11246: object pointer) plus seven other words: to define a method, a variable,
11247: a class; to end a class, to resolve binding, to allocate an object and
11248: to compile a class method.
11249: @comment TODO better description of the last one
1.26 crook 11250:
1.21 crook 11251:
1.78 anton 11252: doc-object
11253: doc-method
11254: doc-var
11255: doc-class
11256: doc-end-class
11257: doc-defines
11258: doc-new
11259: doc-::
1.21 crook 11260:
11261:
11262:
1.78 anton 11263: @c -------------------------------------------------------------
11264: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11265: @subsubsection Mini-OOF Example
11266: @cindex mini-oof example
1.1 anton 11267:
1.78 anton 11268: A short example shows how to use this package. This example, in slightly
11269: extended form, is supplied as @file{moof-exm.fs}
11270: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11271:
1.26 crook 11272: @example
1.78 anton 11273: object class
11274: method init
11275: method draw
11276: end-class graphical
1.26 crook 11277: @end example
1.20 pazsan 11278:
1.78 anton 11279: This code defines a class @code{graphical} with an
11280: operation @code{draw}. We can perform the operation
11281: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11282:
1.26 crook 11283: @example
1.78 anton 11284: 100 100 t-rex draw
1.26 crook 11285: @end example
1.12 anton 11286:
1.78 anton 11287: where @code{t-rex} is an object or object pointer, created with e.g.
11288: @code{graphical new Constant t-rex}.
1.12 anton 11289:
1.78 anton 11290: For concrete graphical objects, we define child classes of the
11291: class @code{graphical}, e.g.:
1.12 anton 11292:
1.26 crook 11293: @example
11294: graphical class
1.78 anton 11295: cell var circle-radius
11296: end-class circle \ "graphical" is the parent class
1.12 anton 11297:
1.78 anton 11298: :noname ( x y -- )
11299: circle-radius @@ draw-circle ; circle defines draw
11300: :noname ( r -- )
11301: circle-radius ! ; circle defines init
11302: @end example
1.12 anton 11303:
1.78 anton 11304: There is no implicit init method, so we have to define one. The creation
11305: code of the object now has to call init explicitely.
1.21 crook 11306:
1.78 anton 11307: @example
11308: circle new Constant my-circle
11309: 50 my-circle init
1.12 anton 11310: @end example
11311:
1.78 anton 11312: It is also possible to add a function to create named objects with
11313: automatic call of @code{init}, given that all objects have @code{init}
11314: on the same place:
1.38 anton 11315:
1.78 anton 11316: @example
11317: : new: ( .. o "name" -- )
11318: new dup Constant init ;
11319: 80 circle new: large-circle
11320: @end example
1.12 anton 11321:
1.78 anton 11322: We can draw this new circle at (100,100) with:
1.12 anton 11323:
1.78 anton 11324: @example
11325: 100 100 my-circle draw
11326: @end example
1.12 anton 11327:
1.78 anton 11328: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11329: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11330:
1.78 anton 11331: Object-oriented systems with late binding typically use a
11332: ``vtable''-approach: the first variable in each object is a pointer to a
11333: table, which contains the methods as function pointers. The vtable
11334: may also contain other information.
1.12 anton 11335:
1.79 anton 11336: So first, let's declare selectors:
1.37 anton 11337:
11338: @example
1.79 anton 11339: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11340: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11341: @end example
1.37 anton 11342:
1.79 anton 11343: During selector declaration, the number of selectors and instance
11344: variables is on the stack (in address units). @code{method} creates one
11345: selector and increments the selector number. To execute a selector, it
1.78 anton 11346: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11347: executes the method @i{xt} stored there. Each selector takes the object
11348: it is invoked with as top of stack parameter; it passes the parameters
11349: (including the object) unchanged to the appropriate method which should
1.78 anton 11350: consume that object.
1.37 anton 11351:
1.78 anton 11352: Now, we also have to declare instance variables
1.37 anton 11353:
1.78 anton 11354: @example
1.79 anton 11355: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11356: DOES> ( o -- addr ) @@ + ;
1.37 anton 11357: @end example
11358:
1.78 anton 11359: As before, a word is created with the current offset. Instance
11360: variables can have different sizes (cells, floats, doubles, chars), so
11361: all we do is take the size and add it to the offset. If your machine
11362: has alignment restrictions, put the proper @code{aligned} or
11363: @code{faligned} before the variable, to adjust the variable
11364: offset. That's why it is on the top of stack.
1.37 anton 11365:
1.78 anton 11366: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11367:
1.78 anton 11368: @example
11369: Create object 1 cells , 2 cells ,
1.79 anton 11370: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11371: @end example
1.12 anton 11372:
1.78 anton 11373: For inheritance, the vtable of the parent object has to be
11374: copied when a new, derived class is declared. This gives all the
11375: methods of the parent class, which can be overridden, though.
1.12 anton 11376:
1.78 anton 11377: @example
1.79 anton 11378: : end-class ( class selectors vars "name" -- )
1.78 anton 11379: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11380: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11381: @end example
1.12 anton 11382:
1.78 anton 11383: The first line creates the vtable, initialized with
11384: @code{noop}s. The second line is the inheritance mechanism, it
11385: copies the xts from the parent vtable.
1.12 anton 11386:
1.78 anton 11387: We still have no way to define new methods, let's do that now:
1.12 anton 11388:
1.26 crook 11389: @example
1.79 anton 11390: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11391: @end example
1.12 anton 11392:
1.78 anton 11393: To allocate a new object, we need a word, too:
1.12 anton 11394:
1.78 anton 11395: @example
11396: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11397: @end example
11398:
1.78 anton 11399: Sometimes derived classes want to access the method of the
11400: parent object. There are two ways to achieve this with Mini-OOF:
11401: first, you could use named words, and second, you could look up the
11402: vtable of the parent object.
1.12 anton 11403:
1.78 anton 11404: @example
11405: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11406: @end example
1.12 anton 11407:
11408:
1.78 anton 11409: Nothing can be more confusing than a good example, so here is
11410: one. First let's declare a text object (called
11411: @code{button}), that stores text and position:
1.12 anton 11412:
1.78 anton 11413: @example
11414: object class
11415: cell var text
11416: cell var len
11417: cell var x
11418: cell var y
11419: method init
11420: method draw
11421: end-class button
11422: @end example
1.12 anton 11423:
1.78 anton 11424: @noindent
11425: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11426:
1.26 crook 11427: @example
1.78 anton 11428: :noname ( o -- )
11429: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11430: button defines draw
11431: :noname ( addr u o -- )
11432: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11433: button defines init
1.26 crook 11434: @end example
1.12 anton 11435:
1.78 anton 11436: @noindent
11437: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11438: new data and no new selectors:
1.78 anton 11439:
11440: @example
11441: button class
11442: end-class bold-button
1.12 anton 11443:
1.78 anton 11444: : bold 27 emit ." [1m" ;
11445: : normal 27 emit ." [0m" ;
11446: @end example
1.1 anton 11447:
1.78 anton 11448: @noindent
11449: The class @code{bold-button} has a different draw method to
11450: @code{button}, but the new method is defined in terms of the draw method
11451: for @code{button}:
1.20 pazsan 11452:
1.78 anton 11453: @example
11454: :noname bold [ button :: draw ] normal ; bold-button defines draw
11455: @end example
1.21 crook 11456:
1.78 anton 11457: @noindent
1.79 anton 11458: Finally, create two objects and apply selectors:
1.21 crook 11459:
1.26 crook 11460: @example
1.78 anton 11461: button new Constant foo
11462: s" thin foo" foo init
11463: page
11464: foo draw
11465: bold-button new Constant bar
11466: s" fat bar" bar init
11467: 1 bar y !
11468: bar draw
1.26 crook 11469: @end example
1.21 crook 11470:
11471:
1.78 anton 11472: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11473: @subsection Comparison with other object models
11474: @cindex comparison of object models
11475: @cindex object models, comparison
11476:
11477: Many object-oriented Forth extensions have been proposed (@cite{A survey
11478: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11479: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11480: relation of the object models described here to two well-known and two
11481: closely-related (by the use of method maps) models. Andras Zsoter
11482: helped us with this section.
11483:
11484: @cindex Neon model
11485: The most popular model currently seems to be the Neon model (see
11486: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11487: 1997) by Andrew McKewan) but this model has a number of limitations
11488: @footnote{A longer version of this critique can be
11489: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11490: Dimensions, May 1997) by Anton Ertl.}:
11491:
11492: @itemize @bullet
11493: @item
11494: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11495: to pass objects on the stack.
1.21 crook 11496:
1.78 anton 11497: @item
11498: It requires that the selector parses the input stream (at
1.79 anton 11499: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11500: hard to find.
1.21 crook 11501:
1.78 anton 11502: @item
1.79 anton 11503: It allows using every selector on every object; this eliminates the
11504: need for interfaces, but makes it harder to create efficient
11505: implementations.
1.78 anton 11506: @end itemize
1.21 crook 11507:
1.78 anton 11508: @cindex Pountain's object-oriented model
11509: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11510: Press, London, 1987) by Dick Pountain. However, it is not really about
11511: object-oriented programming, because it hardly deals with late
11512: binding. Instead, it focuses on features like information hiding and
11513: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11514:
1.78 anton 11515: @cindex Zsoter's object-oriented model
1.79 anton 11516: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11517: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11518: describes a model that makes heavy use of an active object (like
11519: @code{this} in @file{objects.fs}): The active object is not only used
11520: for accessing all fields, but also specifies the receiving object of
11521: every selector invocation; you have to change the active object
11522: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11523: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11524: the method entry point is unnecessary with Zsoter's model, because the
11525: receiving object is the active object already. On the other hand, the
11526: explicit change is absolutely necessary in that model, because otherwise
11527: no one could ever change the active object. An ANS Forth implementation
11528: of this model is available through
11529: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11530:
1.78 anton 11531: @cindex @file{oof.fs}, differences to other models
11532: The @file{oof.fs} model combines information hiding and overloading
11533: resolution (by keeping names in various word lists) with object-oriented
11534: programming. It sets the active object implicitly on method entry, but
11535: also allows explicit changing (with @code{>o...o>} or with
11536: @code{with...endwith}). It uses parsing and state-smart objects and
11537: classes for resolving overloading and for early binding: the object or
11538: class parses the selector and determines the method from this. If the
11539: selector is not parsed by an object or class, it performs a call to the
11540: selector for the active object (late binding), like Zsoter's model.
11541: Fields are always accessed through the active object. The big
11542: disadvantage of this model is the parsing and the state-smartness, which
11543: reduces extensibility and increases the opportunities for subtle bugs;
11544: essentially, you are only safe if you never tick or @code{postpone} an
11545: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11546:
1.78 anton 11547: @cindex @file{mini-oof.fs}, differences to other models
11548: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11549: version of the @file{objects.fs} model, but syntactically it is a
11550: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11551:
11552:
1.78 anton 11553: @c -------------------------------------------------------------
1.150 anton 11554: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11555: @section Programming Tools
11556: @cindex programming tools
1.21 crook 11557:
1.78 anton 11558: @c !! move this and assembler down below OO stuff.
1.21 crook 11559:
1.78 anton 11560: @menu
1.150 anton 11561: * Examining:: Data and Code.
11562: * Forgetting words:: Usually before reloading.
1.78 anton 11563: * Debugging:: Simple and quick.
11564: * Assertions:: Making your programs self-checking.
11565: * Singlestep Debugger:: Executing your program word by word.
11566: @end menu
1.21 crook 11567:
1.78 anton 11568: @node Examining, Forgetting words, Programming Tools, Programming Tools
11569: @subsection Examining data and code
11570: @cindex examining data and code
11571: @cindex data examination
11572: @cindex code examination
1.44 crook 11573:
1.78 anton 11574: The following words inspect the stack non-destructively:
1.21 crook 11575:
1.78 anton 11576: doc-.s
11577: doc-f.s
1.158 anton 11578: doc-maxdepth-.s
1.44 crook 11579:
1.78 anton 11580: There is a word @code{.r} but it does @i{not} display the return stack!
11581: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11582:
1.78 anton 11583: doc-depth
11584: doc-fdepth
11585: doc-clearstack
1.124 anton 11586: doc-clearstacks
1.21 crook 11587:
1.78 anton 11588: The following words inspect memory.
1.21 crook 11589:
1.78 anton 11590: doc-?
11591: doc-dump
1.21 crook 11592:
1.78 anton 11593: And finally, @code{see} allows to inspect code:
1.21 crook 11594:
1.78 anton 11595: doc-see
11596: doc-xt-see
1.111 anton 11597: doc-simple-see
11598: doc-simple-see-range
1.21 crook 11599:
1.78 anton 11600: @node Forgetting words, Debugging, Examining, Programming Tools
11601: @subsection Forgetting words
11602: @cindex words, forgetting
11603: @cindex forgeting words
1.21 crook 11604:
1.78 anton 11605: @c anton: other, maybe better places for this subsection: Defining Words;
11606: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11607:
1.78 anton 11608: Forth allows you to forget words (and everything that was alloted in the
11609: dictonary after them) in a LIFO manner.
1.21 crook 11610:
1.78 anton 11611: doc-marker
1.21 crook 11612:
1.78 anton 11613: The most common use of this feature is during progam development: when
11614: you change a source file, forget all the words it defined and load it
11615: again (since you also forget everything defined after the source file
11616: was loaded, you have to reload that, too). Note that effects like
11617: storing to variables and destroyed system words are not undone when you
11618: forget words. With a system like Gforth, that is fast enough at
11619: starting up and compiling, I find it more convenient to exit and restart
11620: Gforth, as this gives me a clean slate.
1.21 crook 11621:
1.78 anton 11622: Here's an example of using @code{marker} at the start of a source file
11623: that you are debugging; it ensures that you only ever have one copy of
11624: the file's definitions compiled at any time:
1.21 crook 11625:
1.78 anton 11626: @example
11627: [IFDEF] my-code
11628: my-code
11629: [ENDIF]
1.26 crook 11630:
1.78 anton 11631: marker my-code
11632: init-included-files
1.21 crook 11633:
1.78 anton 11634: \ .. definitions start here
11635: \ .
11636: \ .
11637: \ end
11638: @end example
1.21 crook 11639:
1.26 crook 11640:
1.78 anton 11641: @node Debugging, Assertions, Forgetting words, Programming Tools
11642: @subsection Debugging
11643: @cindex debugging
1.21 crook 11644:
1.78 anton 11645: Languages with a slow edit/compile/link/test development loop tend to
11646: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11647:
1.78 anton 11648: A much better (faster) way in fast-compiling languages is to add
11649: printing code at well-selected places, let the program run, look at
11650: the output, see where things went wrong, add more printing code, etc.,
11651: until the bug is found.
1.21 crook 11652:
1.78 anton 11653: The simple debugging aids provided in @file{debugs.fs}
11654: are meant to support this style of debugging.
1.21 crook 11655:
1.78 anton 11656: The word @code{~~} prints debugging information (by default the source
11657: location and the stack contents). It is easy to insert. If you use Emacs
11658: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11659: query-replace them with nothing). The deferred words
1.101 anton 11660: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11661: @code{~~}. The default source location output format works well with
11662: Emacs' compilation mode, so you can step through the program at the
11663: source level using @kbd{C-x `} (the advantage over a stepping debugger
11664: is that you can step in any direction and you know where the crash has
11665: happened or where the strange data has occurred).
1.21 crook 11666:
1.78 anton 11667: doc-~~
11668: doc-printdebugdata
1.101 anton 11669: doc-.debugline
1.21 crook 11670:
1.106 anton 11671: @cindex filenames in @code{~~} output
11672: @code{~~} (and assertions) will usually print the wrong file name if a
11673: marker is executed in the same file after their occurance. They will
11674: print @samp{*somewhere*} as file name if a marker is executed in the
11675: same file before their occurance.
11676:
11677:
1.78 anton 11678: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11679: @subsection Assertions
11680: @cindex assertions
1.21 crook 11681:
1.78 anton 11682: It is a good idea to make your programs self-checking, especially if you
11683: make an assumption that may become invalid during maintenance (for
11684: example, that a certain field of a data structure is never zero). Gforth
11685: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11686:
11687: @example
1.78 anton 11688: assert( @i{flag} )
1.26 crook 11689: @end example
11690:
1.78 anton 11691: The code between @code{assert(} and @code{)} should compute a flag, that
11692: should be true if everything is alright and false otherwise. It should
11693: not change anything else on the stack. The overall stack effect of the
11694: assertion is @code{( -- )}. E.g.
1.21 crook 11695:
1.26 crook 11696: @example
1.78 anton 11697: assert( 1 1 + 2 = ) \ what we learn in school
11698: assert( dup 0<> ) \ assert that the top of stack is not zero
11699: assert( false ) \ this code should not be reached
1.21 crook 11700: @end example
11701:
1.78 anton 11702: The need for assertions is different at different times. During
11703: debugging, we want more checking, in production we sometimes care more
11704: for speed. Therefore, assertions can be turned off, i.e., the assertion
11705: becomes a comment. Depending on the importance of an assertion and the
11706: time it takes to check it, you may want to turn off some assertions and
11707: keep others turned on. Gforth provides several levels of assertions for
11708: this purpose:
11709:
11710:
11711: doc-assert0(
11712: doc-assert1(
11713: doc-assert2(
11714: doc-assert3(
11715: doc-assert(
11716: doc-)
1.21 crook 11717:
11718:
1.78 anton 11719: The variable @code{assert-level} specifies the highest assertions that
11720: are turned on. I.e., at the default @code{assert-level} of one,
11721: @code{assert0(} and @code{assert1(} assertions perform checking, while
11722: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11723:
1.78 anton 11724: The value of @code{assert-level} is evaluated at compile-time, not at
11725: run-time. Therefore you cannot turn assertions on or off at run-time;
11726: you have to set the @code{assert-level} appropriately before compiling a
11727: piece of code. You can compile different pieces of code at different
11728: @code{assert-level}s (e.g., a trusted library at level 1 and
11729: newly-written code at level 3).
1.26 crook 11730:
11731:
1.78 anton 11732: doc-assert-level
1.26 crook 11733:
11734:
1.78 anton 11735: If an assertion fails, a message compatible with Emacs' compilation mode
11736: is produced and the execution is aborted (currently with @code{ABORT"}.
11737: If there is interest, we will introduce a special throw code. But if you
11738: intend to @code{catch} a specific condition, using @code{throw} is
11739: probably more appropriate than an assertion).
1.106 anton 11740:
11741: @cindex filenames in assertion output
11742: Assertions (and @code{~~}) will usually print the wrong file name if a
11743: marker is executed in the same file after their occurance. They will
11744: print @samp{*somewhere*} as file name if a marker is executed in the
11745: same file before their occurance.
1.44 crook 11746:
1.78 anton 11747: Definitions in ANS Forth for these assertion words are provided
11748: in @file{compat/assert.fs}.
1.26 crook 11749:
1.44 crook 11750:
1.78 anton 11751: @node Singlestep Debugger, , Assertions, Programming Tools
11752: @subsection Singlestep Debugger
11753: @cindex singlestep Debugger
11754: @cindex debugging Singlestep
1.44 crook 11755:
1.159 anton 11756: The singlestep debugger works only with the engine @code{gforth-ditc}.
1.112 anton 11757:
1.78 anton 11758: When you create a new word there's often the need to check whether it
11759: behaves correctly or not. You can do this by typing @code{dbg
11760: badword}. A debug session might look like this:
1.26 crook 11761:
1.78 anton 11762: @example
11763: : badword 0 DO i . LOOP ; ok
11764: 2 dbg badword
11765: : badword
11766: Scanning code...
1.44 crook 11767:
1.78 anton 11768: Nesting debugger ready!
1.44 crook 11769:
1.78 anton 11770: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11771: 400D4740 8049F68 DO -> [ 0 ]
11772: 400D4744 804A0C8 i -> [ 1 ] 00000
11773: 400D4748 400C5E60 . -> 0 [ 0 ]
11774: 400D474C 8049D0C LOOP -> [ 0 ]
11775: 400D4744 804A0C8 i -> [ 1 ] 00001
11776: 400D4748 400C5E60 . -> 1 [ 0 ]
11777: 400D474C 8049D0C LOOP -> [ 0 ]
11778: 400D4758 804B384 ; -> ok
11779: @end example
1.21 crook 11780:
1.78 anton 11781: Each line displayed is one step. You always have to hit return to
11782: execute the next word that is displayed. If you don't want to execute
11783: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11784: an overview what keys are available:
1.44 crook 11785:
1.78 anton 11786: @table @i
1.44 crook 11787:
1.78 anton 11788: @item @key{RET}
11789: Next; Execute the next word.
1.21 crook 11790:
1.78 anton 11791: @item n
11792: Nest; Single step through next word.
1.44 crook 11793:
1.78 anton 11794: @item u
11795: Unnest; Stop debugging and execute rest of word. If we got to this word
11796: with nest, continue debugging with the calling word.
1.44 crook 11797:
1.78 anton 11798: @item d
11799: Done; Stop debugging and execute rest.
1.21 crook 11800:
1.78 anton 11801: @item s
11802: Stop; Abort immediately.
1.44 crook 11803:
1.78 anton 11804: @end table
1.44 crook 11805:
1.78 anton 11806: Debugging large application with this mechanism is very difficult, because
11807: you have to nest very deeply into the program before the interesting part
11808: begins. This takes a lot of time.
1.26 crook 11809:
1.78 anton 11810: To do it more directly put a @code{BREAK:} command into your source code.
11811: When program execution reaches @code{BREAK:} the single step debugger is
11812: invoked and you have all the features described above.
1.44 crook 11813:
1.78 anton 11814: If you have more than one part to debug it is useful to know where the
11815: program has stopped at the moment. You can do this by the
11816: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11817: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11818:
1.26 crook 11819:
1.78 anton 11820: doc-dbg
11821: doc-break:
11822: doc-break"
1.44 crook 11823:
1.150 anton 11824: @c ------------------------------------------------------------
11825: @node C Interface, Assembler and Code Words, Programming Tools, Words
11826: @section C Interface
11827: @cindex C interface
11828: @cindex foreign language interface
11829: @cindex interface to C functions
11830:
11831: Note that the C interface is not yet complete; a better way of
11832: declaring C functions is planned, as well as a way of declaring
11833: structs, unions, and their fields.
11834:
11835: @menu
11836: * Calling C Functions::
11837: * Declaring C Functions::
11838: * Callbacks::
1.155 anton 11839: * Low-Level C Interface Words::
1.150 anton 11840: @end menu
11841:
1.151 pazsan 11842: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 11843: @subsection Calling C functions
1.155 anton 11844: @cindex C functions, calls to
11845: @cindex calling C functions
1.150 anton 11846:
1.151 pazsan 11847: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 11848: can call it as follows: You push the arguments on the stack(s), and
11849: then call the word for the C function. The arguments have to be
11850: pushed in the same order as the arguments appear in the C
11851: documentation (i.e., the first argument is deepest on the stack).
11852: Integer and pointer arguments have to be pushed on the data stack,
11853: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 11854: by the called C function.
1.150 anton 11855:
1.155 anton 11856: On returning from the C function, the return value, if any, resides on
11857: the appropriate stack: an integer return value is pushed on the data
11858: stack, an FP return value on the FP stack, and a void return value
11859: results in not pushing anything. Note that most C functions have a
11860: return value, even if that is often not used in C; in Forth, you have
11861: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 11862:
1.177 ! anton 11863: The C interface automatically converts between the C type and the
! 11864: Forth type as necessary, on a best-effort basis (in some cases, there
! 11865: may be some loss).
1.150 anton 11866:
11867: As an example, consider the POSIX function @code{lseek()}:
11868:
11869: @example
11870: off_t lseek(int fd, off_t offset, int whence);
11871: @end example
11872:
11873: This function takes three integer arguments, and returns an integer
11874: argument, so a Forth call for setting the current file offset to the
11875: start of the file could look like this:
11876:
11877: @example
11878: fd @@ 0 SEEK_SET lseek -1 = if
11879: ... \ error handling
11880: then
11881: @end example
11882:
11883: You might be worried that an @code{off_t} does not fit into a cell, so
11884: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 11885: of the return values. In that case, in your declaration of the
11886: function (@pxref{Declaring C Functions}) you should declare it to use
11887: double-cells for the off_t argument and return value, and maybe give
11888: the resulting Forth word a different name, like @code{dlseek}; the
11889: result could be called like this:
1.150 anton 11890:
11891: @example
11892: fd @@ 0. SEEK_SET dlseek -1. d= if
11893: ... \ error handling
11894: then
11895: @end example
11896:
11897: Passing and returning structs or unions is currently not supported by
11898: our interface@footnote{If you know the calling convention of your C
11899: compiler, you usually can call such functions in some way, but that
11900: way is usually not portable between platforms, and sometimes not even
11901: between C compilers.}.
11902:
1.177 ! anton 11903: Calling functions with a variable number of arguments (@emph{variadic}
! 11904: functions, e.g., @code{printf()}) is only supported by having you
! 11905: declare one function-calling word for each argument pattern, and
! 11906: calling the appropriate word for the desired pattern.
! 11907:
1.150 anton 11908:
1.155 anton 11909:
1.151 pazsan 11910: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
1.150 anton 11911: @subsection Declaring C Functions
1.155 anton 11912: @cindex C functions, declarations
11913: @cindex declaring C functions
1.150 anton 11914:
11915: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 ! anton 11916: it. The declaration consists of two parts:
! 11917:
! 11918: @table @b
! 11919:
! 11920: @item The C part
! 11921: is the C declaration of the function, or more typically, a C-style
! 11922: @code{#include} of a file that contains the declaration of the C
! 11923: function.
! 11924:
! 11925: @item The Forth part
! 11926: declares the Forth types of the parameters and the Forth word name
! 11927: corresponding to the C function.
! 11928:
! 11929: @end table
! 11930:
! 11931: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
! 11932: declarations are:
! 11933:
! 11934: @example
! 11935: \c #define _FILE_OFFSET_BITS 64
! 11936: \c #include <sys/types.h>
! 11937: \c #include <unistd.h>
! 11938: c-function lseek lseek n n n -- n
! 11939: c-function dlseek lseek n d n -- d
! 11940: @end example
! 11941:
! 11942: The C part of the declarations is prefixed by @ocde{\c}, and the rest
! 11943: of the line is ordinary C code. You can use as many lines of C
! 11944: declarations as you like, and they are visible for all further
! 11945: function declarations.
! 11946:
! 11947: The Forth part declares each interface word with @code{c-function},
! 11948: followed by the Forth name of the word, the C name of the called
! 11949: function, and the stack effect of the word. The stack effect contains
! 11950: an arbitrary number of types of parameters, then \code{--}, and then
! 11951: exactly one type for the return value. The possible types are:
! 11952:
! 11953: @table @code
! 11954:
! 11955: @item n
! 11956: single-cell integer
! 11957:
! 11958: @item a
! 11959: address (single-cell)
! 11960:
! 11961: @item d
! 11962: double-cell integer
! 11963:
! 11964: @item r
! 11965: floating-point value
! 11966:
! 11967: @item func
! 11968: C function pointer
! 11969:
! 11970: @item void
! 11971: no value (used as return type for void functions)
! 11972:
! 11973: @end table
! 11974:
! 11975: @cindex variadic C functions
! 11976:
! 11977: To deal with variadic C functions, you can declare one Forth word for
! 11978: every pattern you want to use, e.g.:
! 11979:
! 11980: @example
! 11981: \c #include <stdio.h>
! 11982: c-function printf-nr printf a n r -- n
! 11983: c-function printf-rn printf a r n -- n
! 11984: @end example
! 11985:
! 11986: Note that with C functions declared as variadic (or if you don't
! 11987: provide a prototype), the C interface has no C type to convert to, so
! 11988: no automatic conversion happens, which may lead to portability
! 11989: problems in some cases. In such cases you can perform the conversion
! 11990: explicitly on the C level, e.g., as follows:
! 11991:
! 11992: @example
! 11993: \c #define printf_ull(s,ull) printf(s,(unsigned long long)ull)
! 11994: c-function printf-ull printf_ull a n -- n
! 11995: @end example
! 11996:
! 11997: Here, instead of calling @code{printf()} directly, we define a macro
! 11998: that casts (converts) the Forth single-cell (unsigned) integer into a
! 11999: C @code{unsigned long long} before calling @code{printf()}.
! 12000:
! 12001: doc-\c
! 12002: doc-c-function
! 12003:
! 12004: In order to work, this C interface invokes GCC at run-time and uses
! 12005: dynamic linking. If these features are not availabkle, there are
! 12006: other, less convenient C interfaces in @file{lib.fs} and
! 12007: @file{oldlib.fs}. These interfaces are mostly undocumented and mostly
! 12008: incompatible with each other and with the documented C interface; you
! 12009: can find some examples for the @file{lib.fs} interface in @file{lib.fs}.
! 12010:
! 12011:
! 12012:
1.150 anton 12013:
1.155 anton 12014:
12015: @node Callbacks, Low-Level C Interface Words, Declaring C Functions, C Interface
1.150 anton 12016: @subsection Callbacks
1.155 anton 12017: @cindex Callback functions written in Forth
12018: @cindex C function pointers to Forth words
12019:
1.177 ! anton 12020: Callbacks are not yet supported by the documented C interface. You
! 12021: can use the undocumented @file{lib.fs} interface for callbacks.
! 12022:
1.155 anton 12023: In some cases you have to pass a function pointer to a C function,
12024: i.e., the library wants to call back to your application (and the
12025: pointed-to function is called a callback function). You can pass the
12026: address of an existing C function (that you get with @code{lib-sym},
12027: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12028: function, you probably want to define the function as a Forth word.
12029:
12030: @c I don't understand the existing callback interface from the example - anton
12031:
1.165 anton 12032:
12033: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12034: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12035: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12036: @c > > C-Funktionsadresse auf dem TOS).
12037: @c >
12038: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12039: @c > gesehen habe, wozu das gut ist.
12040: @c
12041: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12042: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12043: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12044: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12045: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12046: @c demselben Prototyp.
12047:
12048:
1.177 ! anton 12049: @node C interface internals
! 12050: @subsection How the C interface works
! 12051:
! 12052: The documented C interface works by generating a C code out of the
! 12053: declarations.
! 12054:
! 12055: In particular, for every Forth word declared with @code{c-function},
! 12056: it generates a wrapper function in C that takes the Forth data from
! 12057: the Forth stacks, and calls the target C function with these data as
! 12058: arguments. The C compiler then performs an implicit conversion
! 12059: between the Forth type from the stack, and the C type for the
! 12060: parameter, which is given by the C function prototype. After the C
! 12061: function returns, the return value is likewise implicitly converted to
! 12062: a Forth type and written back on the stack.
! 12063:
! 12064: The @code{\c} lines are literally included in the C code (but without
! 12065: the @code{\c}), and provide the necessary declarations so that the C
! 12066: compiler knows the C types and has enough information to perform the
! 12067: conversion.
! 12068:
! 12069: These wrapper functions are eventually compiled and dynamically linked
! 12070: into Gforth, and then they can be called.
! 12071:
! 12072:
1.155 anton 12073: @node Low-Level C Interface Words, , Callbacks, C Interface
12074: @subsection Low-Level C Interface Words
1.44 crook 12075:
1.155 anton 12076: doc-open-lib
12077: doc-lib-sym
1.177 ! anton 12078: doc-call-c
1.26 crook 12079:
1.78 anton 12080: @c -------------------------------------------------------------
1.150 anton 12081: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12082: @section Assembler and Code Words
12083: @cindex assembler
12084: @cindex code words
1.44 crook 12085:
1.78 anton 12086: @menu
12087: * Code and ;code::
12088: * Common Assembler:: Assembler Syntax
12089: * Common Disassembler::
12090: * 386 Assembler:: Deviations and special cases
12091: * Alpha Assembler:: Deviations and special cases
12092: * MIPS assembler:: Deviations and special cases
1.161 anton 12093: * PowerPC assembler:: Deviations and special cases
1.78 anton 12094: * Other assemblers:: How to write them
12095: @end menu
1.21 crook 12096:
1.78 anton 12097: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12098: @subsection @code{Code} and @code{;code}
1.26 crook 12099:
1.78 anton 12100: Gforth provides some words for defining primitives (words written in
12101: machine code), and for defining the machine-code equivalent of
12102: @code{DOES>}-based defining words. However, the machine-independent
12103: nature of Gforth poses a few problems: First of all, Gforth runs on
12104: several architectures, so it can provide no standard assembler. What's
12105: worse is that the register allocation not only depends on the processor,
12106: but also on the @code{gcc} version and options used.
1.44 crook 12107:
1.78 anton 12108: The words that Gforth offers encapsulate some system dependences (e.g.,
12109: the header structure), so a system-independent assembler may be used in
12110: Gforth. If you do not have an assembler, you can compile machine code
12111: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12112: because these words emit stuff in @i{data} space; it works because
12113: Gforth has unified code/data spaces. Assembler isn't likely to be
12114: portable anyway.}.
1.21 crook 12115:
1.44 crook 12116:
1.78 anton 12117: doc-assembler
12118: doc-init-asm
12119: doc-code
12120: doc-end-code
12121: doc-;code
12122: doc-flush-icache
1.44 crook 12123:
1.21 crook 12124:
1.78 anton 12125: If @code{flush-icache} does not work correctly, @code{code} words
12126: etc. will not work (reliably), either.
1.44 crook 12127:
1.78 anton 12128: The typical usage of these @code{code} words can be shown most easily by
12129: analogy to the equivalent high-level defining words:
1.44 crook 12130:
1.78 anton 12131: @example
12132: : foo code foo
12133: <high-level Forth words> <assembler>
12134: ; end-code
12135:
12136: : bar : bar
12137: <high-level Forth words> <high-level Forth words>
12138: CREATE CREATE
12139: <high-level Forth words> <high-level Forth words>
12140: DOES> ;code
12141: <high-level Forth words> <assembler>
12142: ; end-code
12143: @end example
1.21 crook 12144:
1.78 anton 12145: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12146:
1.78 anton 12147: @cindex registers of the inner interpreter
12148: In the assembly code you will want to refer to the inner interpreter's
12149: registers (e.g., the data stack pointer) and you may want to use other
12150: registers for temporary storage. Unfortunately, the register allocation
12151: is installation-dependent.
1.44 crook 12152:
1.78 anton 12153: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12154: (return stack pointer) may be in different places in @code{gforth} and
12155: @code{gforth-fast}, or different installations. This means that you
12156: cannot write a @code{NEXT} routine that works reliably on both versions
12157: or different installations; so for doing @code{NEXT}, I recommend
12158: jumping to @code{' noop >code-address}, which contains nothing but a
12159: @code{NEXT}.
1.21 crook 12160:
1.78 anton 12161: For general accesses to the inner interpreter's registers, the easiest
12162: solution is to use explicit register declarations (@pxref{Explicit Reg
12163: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12164: all of the inner interpreter's registers: You have to compile Gforth
12165: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12166: the appropriate declarations must be present in the @code{machine.h}
12167: file (see @code{mips.h} for an example; you can find a full list of all
12168: declarable register symbols with @code{grep register engine.c}). If you
12169: give explicit registers to all variables that are declared at the
12170: beginning of @code{engine()}, you should be able to use the other
12171: caller-saved registers for temporary storage. Alternatively, you can use
12172: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12173: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12174: reserve a register (however, this restriction on register allocation may
12175: slow Gforth significantly).
1.44 crook 12176:
1.78 anton 12177: If this solution is not viable (e.g., because @code{gcc} does not allow
12178: you to explicitly declare all the registers you need), you have to find
12179: out by looking at the code where the inner interpreter's registers
12180: reside and which registers can be used for temporary storage. You can
12181: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12182:
1.78 anton 12183: In any case, it is good practice to abstract your assembly code from the
12184: actual register allocation. E.g., if the data stack pointer resides in
12185: register @code{$17}, create an alias for this register called @code{sp},
12186: and use that in your assembly code.
1.21 crook 12187:
1.78 anton 12188: @cindex code words, portable
12189: Another option for implementing normal and defining words efficiently
12190: is to add the desired functionality to the source of Gforth. For normal
12191: words you just have to edit @file{primitives} (@pxref{Automatic
12192: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12193: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12194: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12195:
1.78 anton 12196: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12197: @subsection Common Assembler
1.44 crook 12198:
1.78 anton 12199: The assemblers in Gforth generally use a postfix syntax, i.e., the
12200: instruction name follows the operands.
1.21 crook 12201:
1.78 anton 12202: The operands are passed in the usual order (the same that is used in the
12203: manual of the architecture). Since they all are Forth words, they have
12204: to be separated by spaces; you can also use Forth words to compute the
12205: operands.
1.44 crook 12206:
1.78 anton 12207: The instruction names usually end with a @code{,}. This makes it easier
12208: to visually separate instructions if you put several of them on one
12209: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12210:
1.78 anton 12211: Registers are usually specified by number; e.g., (decimal) @code{11}
12212: specifies registers R11 and F11 on the Alpha architecture (which one,
12213: depends on the instruction). The usual names are also available, e.g.,
12214: @code{s2} for R11 on Alpha.
1.21 crook 12215:
1.78 anton 12216: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12217: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12218: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12219: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12220: conditions are specified in a way specific to each assembler.
1.1 anton 12221:
1.78 anton 12222: Note that the register assignments of the Gforth engine can change
12223: between Gforth versions, or even between different compilations of the
12224: same Gforth version (e.g., if you use a different GCC version). So if
12225: you want to refer to Gforth's registers (e.g., the stack pointer or
12226: TOS), I recommend defining your own words for refering to these
12227: registers, and using them later on; then you can easily adapt to a
12228: changed register assignment. The stability of the register assignment
12229: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12230:
1.100 anton 12231: The most common use of these registers is to dispatch to the next word
12232: (the @code{next} routine). A portable way to do this is to jump to
12233: @code{' noop >code-address} (of course, this is less efficient than
12234: integrating the @code{next} code and scheduling it well).
1.1 anton 12235:
1.96 anton 12236: Another difference between Gforth version is that the top of stack is
12237: kept in memory in @code{gforth} and, on most platforms, in a register in
12238: @code{gforth-fast}.
12239:
1.78 anton 12240: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12241: @subsection Common Disassembler
1.127 anton 12242: @cindex disassembler, general
12243: @cindex gdb disassembler
1.1 anton 12244:
1.78 anton 12245: You can disassemble a @code{code} word with @code{see}
12246: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12247:
1.127 anton 12248: doc-discode
1.44 crook 12249:
1.127 anton 12250: There are two kinds of disassembler for Gforth: The Forth disassembler
12251: (available on some CPUs) and the gdb disassembler (available on
12252: platforms with @command{gdb} and @command{mktemp}). If both are
12253: available, the Forth disassembler is used by default. If you prefer
12254: the gdb disassembler, say
12255:
12256: @example
12257: ' disasm-gdb is discode
12258: @end example
12259:
12260: If neither is available, @code{discode} performs @code{dump}.
12261:
12262: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12263: assembler (i.e., same syntax, etc.). It also includes additional
12264: information in comments. In particular, the address of the instruction
12265: is given in a comment before the instruction.
1.1 anton 12266:
1.127 anton 12267: The gdb disassembler produces output in the same format as the gdb
12268: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12269: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12270: the 386 and AMD64 architectures).
12271:
1.78 anton 12272: @code{See} may display more or less than the actual code of the word,
12273: because the recognition of the end of the code is unreliable. You can
1.127 anton 12274: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12275: the code word is not immediately followed by a named word. If you have
1.116 anton 12276: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12277: to ensure that the end is recognized.
1.21 crook 12278:
1.78 anton 12279: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12280: @subsection 386 Assembler
1.44 crook 12281:
1.78 anton 12282: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12283: available under GPL, and originally part of bigFORTH.
1.21 crook 12284:
1.78 anton 12285: The 386 disassembler included in Gforth was written by Andrew McKewan
12286: and is in the public domain.
1.21 crook 12287:
1.91 anton 12288: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12289:
1.78 anton 12290: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12291:
1.78 anton 12292: The assembler includes all instruction of the Athlon, i.e. 486 core
12293: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12294: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12295: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12296:
1.78 anton 12297: There are several prefixes to switch between different operation sizes,
12298: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12299: double-word accesses. Addressing modes can be switched with @code{.wa}
12300: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12301: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12302:
1.78 anton 12303: For floating point operations, the prefixes are @code{.fs} (IEEE
12304: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12305: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12306:
1.78 anton 12307: The MMX opcodes don't have size prefixes, they are spelled out like in
12308: the Intel assembler. Instead of move from and to memory, there are
12309: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12310:
1.78 anton 12311: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12312: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12313: e.g., @code{3 #}. Here are some examples of addressing modes in various
12314: syntaxes:
1.21 crook 12315:
1.26 crook 12316: @example
1.91 anton 12317: Gforth Intel (NASM) AT&T (gas) Name
12318: .w ax ax %ax register (16 bit)
12319: ax eax %eax register (32 bit)
12320: 3 # offset 3 $3 immediate
12321: 1000 #) byte ptr 1000 1000 displacement
12322: bx ) [ebx] (%ebx) base
12323: 100 di d) 100[edi] 100(%edi) base+displacement
12324: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12325: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12326: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12327: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12328: @end example
12329:
12330: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12331: @code{DI)} to enforce 32-bit displacement fields (useful for
12332: later patching).
1.21 crook 12333:
1.78 anton 12334: Some example of instructions are:
1.1 anton 12335:
12336: @example
1.78 anton 12337: ax bx mov \ move ebx,eax
12338: 3 # ax mov \ mov eax,3
1.137 pazsan 12339: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12340: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12341: .w ax bx mov \ mov bx,ax
1.1 anton 12342: @end example
12343:
1.78 anton 12344: The following forms are supported for binary instructions:
1.1 anton 12345:
12346: @example
1.78 anton 12347: <reg> <reg> <inst>
12348: <n> # <reg> <inst>
12349: <mem> <reg> <inst>
12350: <reg> <mem> <inst>
1.136 pazsan 12351: <n> # <mem> <inst>
1.1 anton 12352: @end example
12353:
1.136 pazsan 12354: The shift/rotate syntax is:
1.1 anton 12355:
1.26 crook 12356: @example
1.78 anton 12357: <reg/mem> 1 # shl \ shortens to shift without immediate
12358: <reg/mem> 4 # shl
12359: <reg/mem> cl shl
1.26 crook 12360: @end example
1.1 anton 12361:
1.78 anton 12362: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12363: the byte version.
1.1 anton 12364:
1.78 anton 12365: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12366: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12367: pc < >= <= >}. (Note that most of these words shadow some Forth words
12368: when @code{assembler} is in front of @code{forth} in the search path,
12369: e.g., in @code{code} words). Currently the control structure words use
12370: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12371: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12372:
1.78 anton 12373: Here is an example of a @code{code} word (assumes that the stack pointer
12374: is in esi and the TOS is in ebx):
1.21 crook 12375:
1.26 crook 12376: @example
1.78 anton 12377: code my+ ( n1 n2 -- n )
12378: 4 si D) bx add
12379: 4 # si add
12380: Next
12381: end-code
1.26 crook 12382: @end example
1.21 crook 12383:
1.161 anton 12384:
1.78 anton 12385: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12386: @subsection Alpha Assembler
1.21 crook 12387:
1.78 anton 12388: The Alpha assembler and disassembler were originally written by Bernd
12389: Thallner.
1.26 crook 12390:
1.78 anton 12391: The register names @code{a0}--@code{a5} are not available to avoid
12392: shadowing hex numbers.
1.2 jwilke 12393:
1.78 anton 12394: Immediate forms of arithmetic instructions are distinguished by a
12395: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12396: does not count as arithmetic instruction).
1.2 jwilke 12397:
1.78 anton 12398: You have to specify all operands to an instruction, even those that
12399: other assemblers consider optional, e.g., the destination register for
12400: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12401:
1.78 anton 12402: You can specify conditions for @code{if,} by removing the first @code{b}
12403: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12404:
1.26 crook 12405: @example
1.78 anton 12406: 11 fgt if, \ if F11>0e
12407: ...
12408: endif,
1.26 crook 12409: @end example
1.2 jwilke 12410:
1.78 anton 12411: @code{fbgt,} gives @code{fgt}.
12412:
1.161 anton 12413: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12414: @subsection MIPS assembler
1.2 jwilke 12415:
1.78 anton 12416: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12417:
1.78 anton 12418: Currently the assembler and disassembler only cover the MIPS-I
12419: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12420:
1.78 anton 12421: The register names @code{$a0}--@code{$a3} are not available to avoid
12422: shadowing hex numbers.
1.2 jwilke 12423:
1.78 anton 12424: Because there is no way to distinguish registers from immediate values,
12425: you have to explicitly use the immediate forms of instructions, i.e.,
12426: @code{addiu,}, not just @code{addu,} (@command{as} does this
12427: implicitly).
1.2 jwilke 12428:
1.78 anton 12429: If the architecture manual specifies several formats for the instruction
12430: (e.g., for @code{jalr,}), you usually have to use the one with more
12431: arguments (i.e., two for @code{jalr,}). When in doubt, see
12432: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12433:
1.78 anton 12434: Branches and jumps in the MIPS architecture have a delay slot. You have
12435: to fill it yourself (the simplest way is to use @code{nop,}), the
12436: assembler does not do it for you (unlike @command{as}). Even
12437: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12438: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12439: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12440:
1.78 anton 12441: Note that you must not put branches, jumps, or @code{li,} into the delay
12442: slot: @code{li,} may expand to several instructions, and control flow
12443: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12444:
1.78 anton 12445: For branches the argument specifying the target is a relative address;
12446: You have to add the address of the delay slot to get the absolute
12447: address.
1.1 anton 12448:
1.78 anton 12449: The MIPS architecture also has load delay slots and restrictions on
12450: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12451: yourself to satisfy these restrictions, the assembler does not do it for
12452: you.
1.1 anton 12453:
1.78 anton 12454: You can specify the conditions for @code{if,} etc. by taking a
12455: conditional branch and leaving away the @code{b} at the start and the
12456: @code{,} at the end. E.g.,
1.1 anton 12457:
1.26 crook 12458: @example
1.78 anton 12459: 4 5 eq if,
12460: ... \ do something if $4 equals $5
12461: then,
1.26 crook 12462: @end example
1.1 anton 12463:
1.161 anton 12464:
12465: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
12466: @subsection PowerPC assembler
12467:
1.162 anton 12468: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12469: Revucky.
12470:
1.162 anton 12471: This assembler does not follow the convention of ending mnemonic names
12472: with a ``,'', so some mnemonic names shadow regular Forth words (in
12473: particular: @code{and or xor fabs}); so if you want to use the Forth
12474: words, you have to make them visible first, e.g., with @code{also
12475: forth}.
12476:
1.161 anton 12477: Registers are referred to by their number, e.g., @code{9} means the
12478: integer register 9 or the FP register 9 (depending on the
12479: instruction).
12480:
12481: Because there is no way to distinguish registers from immediate values,
12482: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12483: @code{addi,}, not just @code{add,}.
1.161 anton 12484:
1.162 anton 12485: The assembler and disassembler usually support the most general form
1.161 anton 12486: of an instruction, but usually not the shorter forms (especially for
12487: branches).
12488:
12489:
12490:
12491: @node Other assemblers, , PowerPC assembler, Assembler and Code Words
1.78 anton 12492: @subsection Other assemblers
12493:
12494: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12495: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12496: an assembler already. If you are writing them from scratch, please use
12497: a similar syntax style as the one we use (i.e., postfix, commas at the
12498: end of the instruction names, @pxref{Common Assembler}); make the output
12499: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12500: similar to the style we used.
12501:
12502: Hints on implementation: The most important part is to have a good test
12503: suite that contains all instructions. Once you have that, the rest is
12504: easy. For actual coding you can take a look at
12505: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12506: the assembler and disassembler, avoiding redundancy and some potential
12507: bugs. You can also look at that file (and @pxref{Advanced does> usage
12508: example}) to get ideas how to factor a disassembler.
12509:
12510: Start with the disassembler, because it's easier to reuse data from the
12511: disassembler for the assembler than the other way round.
1.1 anton 12512:
1.78 anton 12513: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12514: how simple it can be.
1.1 anton 12515:
1.161 anton 12516:
12517:
12518:
1.78 anton 12519: @c -------------------------------------------------------------
12520: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12521: @section Threading Words
12522: @cindex threading words
1.1 anton 12523:
1.78 anton 12524: @cindex code address
12525: These words provide access to code addresses and other threading stuff
12526: in Gforth (and, possibly, other interpretive Forths). It more or less
12527: abstracts away the differences between direct and indirect threading
12528: (and, for direct threading, the machine dependences). However, at
12529: present this wordset is still incomplete. It is also pretty low-level;
12530: some day it will hopefully be made unnecessary by an internals wordset
12531: that abstracts implementation details away completely.
1.1 anton 12532:
1.78 anton 12533: The terminology used here stems from indirect threaded Forth systems; in
12534: such a system, the XT of a word is represented by the CFA (code field
12535: address) of a word; the CFA points to a cell that contains the code
12536: address. The code address is the address of some machine code that
12537: performs the run-time action of invoking the word (e.g., the
12538: @code{dovar:} routine pushes the address of the body of the word (a
12539: variable) on the stack
12540: ).
1.1 anton 12541:
1.78 anton 12542: @cindex code address
12543: @cindex code field address
12544: In an indirect threaded Forth, you can get the code address of @i{name}
12545: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12546: >code-address}, independent of the threading method.
1.1 anton 12547:
1.78 anton 12548: doc-threading-method
12549: doc->code-address
12550: doc-code-address!
1.1 anton 12551:
1.78 anton 12552: @cindex @code{does>}-handler
12553: @cindex @code{does>}-code
12554: For a word defined with @code{DOES>}, the code address usually points to
12555: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12556: routine (in Gforth on some platforms, it can also point to the dodoes
12557: routine itself). What you are typically interested in, though, is
12558: whether a word is a @code{DOES>}-defined word, and what Forth code it
12559: executes; @code{>does-code} tells you that.
1.1 anton 12560:
1.78 anton 12561: doc->does-code
1.1 anton 12562:
1.78 anton 12563: To create a @code{DOES>}-defined word with the following basic words,
12564: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12565: @code{/does-handler} aus behind you have to place your executable Forth
12566: code. Finally you have to create a word and modify its behaviour with
12567: @code{does-handler!}.
1.1 anton 12568:
1.78 anton 12569: doc-does-code!
12570: doc-does-handler!
12571: doc-/does-handler
1.1 anton 12572:
1.78 anton 12573: The code addresses produced by various defining words are produced by
12574: the following words:
1.1 anton 12575:
1.78 anton 12576: doc-docol:
12577: doc-docon:
12578: doc-dovar:
12579: doc-douser:
12580: doc-dodefer:
12581: doc-dofield:
1.1 anton 12582:
1.99 anton 12583: @cindex definer
12584: The following two words generalize @code{>code-address},
12585: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12586:
12587: doc->definer
12588: doc-definer!
12589:
1.26 crook 12590: @c -------------------------------------------------------------
1.78 anton 12591: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12592: @section Passing Commands to the Operating System
12593: @cindex operating system - passing commands
12594: @cindex shell commands
12595:
12596: Gforth allows you to pass an arbitrary string to the host operating
12597: system shell (if such a thing exists) for execution.
12598:
12599: doc-sh
12600: doc-system
12601: doc-$?
1.23 crook 12602: doc-getenv
1.44 crook 12603:
1.26 crook 12604: @c -------------------------------------------------------------
1.47 crook 12605: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12606: @section Keeping track of Time
12607: @cindex time-related words
12608:
12609: doc-ms
12610: doc-time&date
1.79 anton 12611: doc-utime
12612: doc-cputime
1.47 crook 12613:
12614:
12615: @c -------------------------------------------------------------
12616: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12617: @section Miscellaneous Words
12618: @cindex miscellaneous words
12619:
1.29 crook 12620: @comment TODO find homes for these
12621:
1.26 crook 12622: These section lists the ANS Forth words that are not documented
1.21 crook 12623: elsewhere in this manual. Ultimately, they all need proper homes.
12624:
1.68 anton 12625: doc-quit
1.44 crook 12626:
1.26 crook 12627: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12628: (@pxref{ANS conformance}):
1.21 crook 12629:
12630: @code{EDITOR}
12631: @code{EMIT?}
12632: @code{FORGET}
12633:
1.24 anton 12634: @c ******************************************************************
12635: @node Error messages, Tools, Words, Top
12636: @chapter Error messages
12637: @cindex error messages
12638: @cindex backtrace
12639:
12640: A typical Gforth error message looks like this:
12641:
12642: @example
1.86 anton 12643: in file included from \evaluated string/:-1
1.24 anton 12644: in file included from ./yyy.fs:1
12645: ./xxx.fs:4: Invalid memory address
1.134 anton 12646: >>>bar<<<
1.79 anton 12647: Backtrace:
1.25 anton 12648: $400E664C @@
12649: $400E6664 foo
1.24 anton 12650: @end example
12651:
12652: The message identifying the error is @code{Invalid memory address}. The
12653: error happened when text-interpreting line 4 of the file
12654: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12655: word on the line where the error happened, is pointed out (with
1.134 anton 12656: @code{>>>} and @code{<<<}).
1.24 anton 12657:
12658: The file containing the error was included in line 1 of @file{./yyy.fs},
12659: and @file{yyy.fs} was included from a non-file (in this case, by giving
12660: @file{yyy.fs} as command-line parameter to Gforth).
12661:
12662: At the end of the error message you find a return stack dump that can be
12663: interpreted as a backtrace (possibly empty). On top you find the top of
12664: the return stack when the @code{throw} happened, and at the bottom you
12665: find the return stack entry just above the return stack of the topmost
12666: text interpreter.
12667:
12668: To the right of most return stack entries you see a guess for the word
12669: that pushed that return stack entry as its return address. This gives a
12670: backtrace. In our case we see that @code{bar} called @code{foo}, and
12671: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12672: address} exception).
12673:
12674: Note that the backtrace is not perfect: We don't know which return stack
12675: entries are return addresses (so we may get false positives); and in
12676: some cases (e.g., for @code{abort"}) we cannot determine from the return
12677: address the word that pushed the return address, so for some return
12678: addresses you see no names in the return stack dump.
1.25 anton 12679:
12680: @cindex @code{catch} and backtraces
12681: The return stack dump represents the return stack at the time when a
12682: specific @code{throw} was executed. In programs that make use of
12683: @code{catch}, it is not necessarily clear which @code{throw} should be
12684: used for the return stack dump (e.g., consider one @code{throw} that
12685: indicates an error, which is caught, and during recovery another error
1.160 anton 12686: happens; which @code{throw} should be used for the stack dump?).
12687: Gforth presents the return stack dump for the first @code{throw} after
12688: the last executed (not returned-to) @code{catch} or @code{nothrow};
12689: this works well in the usual case. To get the right backtrace, you
12690: usually want to insert @code{nothrow} or @code{['] false catch drop}
12691: after a @code{catch} if the error is not rethrown.
1.25 anton 12692:
12693: @cindex @code{gforth-fast} and backtraces
12694: @cindex @code{gforth-fast}, difference from @code{gforth}
12695: @cindex backtraces with @code{gforth-fast}
12696: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12697: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12698: from primitives (e.g., invalid memory address, stack empty etc.);
12699: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12700: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12701: exception caused by a primitive in @code{gforth-fast}, you will
12702: typically see no return stack dump at all; however, if the exception is
12703: caught by @code{catch} (e.g., for restoring some state), and then
12704: @code{throw}n again, the return stack dump will be for the first such
12705: @code{throw}.
1.2 jwilke 12706:
1.5 anton 12707: @c ******************************************************************
1.24 anton 12708: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12709: @chapter Tools
12710:
12711: @menu
12712: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12713: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12714: @end menu
12715:
12716: See also @ref{Emacs and Gforth}.
12717:
1.126 pazsan 12718: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12719: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12720: @cindex @file{ans-report.fs}
12721: @cindex report the words used in your program
12722: @cindex words used in your program
12723:
12724: If you want to label a Forth program as ANS Forth Program, you must
12725: document which wordsets the program uses; for extension wordsets, it is
12726: helpful to list the words the program requires from these wordsets
12727: (because Forth systems are allowed to provide only some words of them).
12728:
12729: The @file{ans-report.fs} tool makes it easy for you to determine which
12730: words from which wordset and which non-ANS words your application
12731: uses. You simply have to include @file{ans-report.fs} before loading the
12732: program you want to check. After loading your program, you can get the
12733: report with @code{print-ans-report}. A typical use is to run this as
12734: batch job like this:
12735: @example
12736: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12737: @end example
12738:
12739: The output looks like this (for @file{compat/control.fs}):
12740: @example
12741: The program uses the following words
12742: from CORE :
12743: : POSTPONE THEN ; immediate ?dup IF 0=
12744: from BLOCK-EXT :
12745: \
12746: from FILE :
12747: (
12748: @end example
12749:
12750: @subsection Caveats
12751:
12752: Note that @file{ans-report.fs} just checks which words are used, not whether
12753: they are used in an ANS Forth conforming way!
12754:
12755: Some words are defined in several wordsets in the
12756: standard. @file{ans-report.fs} reports them for only one of the
12757: wordsets, and not necessarily the one you expect. It depends on usage
12758: which wordset is the right one to specify. E.g., if you only use the
12759: compilation semantics of @code{S"}, it is a Core word; if you also use
12760: its interpretation semantics, it is a File word.
1.124 anton 12761:
12762:
1.127 anton 12763: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12764: @section Stack depth changes during interpretation
12765: @cindex @file{depth-changes.fs}
12766: @cindex depth changes during interpretation
12767: @cindex stack depth changes during interpretation
12768: @cindex items on the stack after interpretation
12769:
12770: Sometimes you notice that, after loading a file, there are items left
12771: on the stack. The tool @file{depth-changes.fs} helps you find out
12772: quickly where in the file these stack items are coming from.
12773:
12774: The simplest way of using @file{depth-changes.fs} is to include it
12775: before the file(s) you want to check, e.g.:
12776:
12777: @example
12778: gforth depth-changes.fs my-file.fs
12779: @end example
12780:
12781: This will compare the stack depths of the data and FP stack at every
12782: empty line (in interpretation state) against these depths at the last
12783: empty line (in interpretation state). If the depths are not equal,
12784: the position in the file and the stack contents are printed with
12785: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12786: change has occured in the paragraph of non-empty lines before the
12787: indicated line. It is a good idea to leave an empty line at the end
12788: of the file, so the last paragraph is checked, too.
12789:
12790: Checking only at empty lines usually works well, but sometimes you
12791: have big blocks of non-empty lines (e.g., when building a big table),
12792: and you want to know where in this block the stack depth changed. You
12793: can check all interpreted lines with
12794:
12795: @example
12796: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12797: @end example
12798:
12799: This checks the stack depth at every end-of-line. So the depth change
12800: occured in the line reported by the @code{~~} (not in the line
12801: before).
12802:
12803: Note that, while this offers better accuracy in indicating where the
12804: stack depth changes, it will often report many intentional stack depth
12805: changes (e.g., when an interpreted computation stretches across
12806: several lines). You can suppress the checking of some lines by
12807: putting backslashes at the end of these lines (not followed by white
12808: space), and using
12809:
12810: @example
12811: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12812: @end example
1.1 anton 12813:
12814: @c ******************************************************************
1.65 anton 12815: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12816: @chapter ANS conformance
12817: @cindex ANS conformance of Gforth
12818:
12819: To the best of our knowledge, Gforth is an
12820:
12821: ANS Forth System
12822: @itemize @bullet
12823: @item providing the Core Extensions word set
12824: @item providing the Block word set
12825: @item providing the Block Extensions word set
12826: @item providing the Double-Number word set
12827: @item providing the Double-Number Extensions word set
12828: @item providing the Exception word set
12829: @item providing the Exception Extensions word set
12830: @item providing the Facility word set
1.40 anton 12831: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12832: @item providing the File Access word set
12833: @item providing the File Access Extensions word set
12834: @item providing the Floating-Point word set
12835: @item providing the Floating-Point Extensions word set
12836: @item providing the Locals word set
12837: @item providing the Locals Extensions word set
12838: @item providing the Memory-Allocation word set
12839: @item providing the Memory-Allocation Extensions word set (that one's easy)
12840: @item providing the Programming-Tools word set
12841: @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
12842: @item providing the Search-Order word set
12843: @item providing the Search-Order Extensions word set
12844: @item providing the String word set
12845: @item providing the String Extensions word set (another easy one)
12846: @end itemize
12847:
1.118 anton 12848: Gforth has the following environmental restrictions:
12849:
12850: @cindex environmental restrictions
12851: @itemize @bullet
12852: @item
12853: While processing the OS command line, if an exception is not caught,
12854: Gforth exits with a non-zero exit code instyead of performing QUIT.
12855:
12856: @item
12857: When an @code{throw} is performed after a @code{query}, Gforth does not
12858: allways restore the input source specification in effect at the
12859: corresponding catch.
12860:
12861: @end itemize
12862:
12863:
1.1 anton 12864: @cindex system documentation
12865: In addition, ANS Forth systems are required to document certain
12866: implementation choices. This chapter tries to meet these
12867: requirements. In many cases it gives a way to ask the system for the
12868: information instead of providing the information directly, in
12869: particular, if the information depends on the processor, the operating
12870: system or the installation options chosen, or if they are likely to
12871: change during the maintenance of Gforth.
12872:
12873: @comment The framework for the rest has been taken from pfe.
12874:
12875: @menu
12876: * The Core Words::
12877: * The optional Block word set::
12878: * The optional Double Number word set::
12879: * The optional Exception word set::
12880: * The optional Facility word set::
12881: * The optional File-Access word set::
12882: * The optional Floating-Point word set::
12883: * The optional Locals word set::
12884: * The optional Memory-Allocation word set::
12885: * The optional Programming-Tools word set::
12886: * The optional Search-Order word set::
12887: @end menu
12888:
12889:
12890: @c =====================================================================
12891: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12892: @comment node-name, next, previous, up
12893: @section The Core Words
12894: @c =====================================================================
12895: @cindex core words, system documentation
12896: @cindex system documentation, core words
12897:
12898: @menu
12899: * core-idef:: Implementation Defined Options
12900: * core-ambcond:: Ambiguous Conditions
12901: * core-other:: Other System Documentation
12902: @end menu
12903:
12904: @c ---------------------------------------------------------------------
12905: @node core-idef, core-ambcond, The Core Words, The Core Words
12906: @subsection Implementation Defined Options
12907: @c ---------------------------------------------------------------------
12908: @cindex core words, implementation-defined options
12909: @cindex implementation-defined options, core words
12910:
12911:
12912: @table @i
12913: @item (Cell) aligned addresses:
12914: @cindex cell-aligned addresses
12915: @cindex aligned addresses
12916: processor-dependent. Gforth's alignment words perform natural alignment
12917: (e.g., an address aligned for a datum of size 8 is divisible by
12918: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12919:
12920: @item @code{EMIT} and non-graphic characters:
12921: @cindex @code{EMIT} and non-graphic characters
12922: @cindex non-graphic characters and @code{EMIT}
12923: The character is output using the C library function (actually, macro)
12924: @code{putc}.
12925:
12926: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12927: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12928: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12929: @cindex @code{ACCEPT}, editing
12930: @cindex @code{EXPECT}, editing
12931: This is modeled on the GNU readline library (@pxref{Readline
12932: Interaction, , Command Line Editing, readline, The GNU Readline
12933: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12934: producing a full word completion every time you type it (instead of
1.28 crook 12935: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12936:
12937: @item character set:
12938: @cindex character set
12939: The character set of your computer and display device. Gforth is
12940: 8-bit-clean (but some other component in your system may make trouble).
12941:
12942: @item Character-aligned address requirements:
12943: @cindex character-aligned address requirements
12944: installation-dependent. Currently a character is represented by a C
12945: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12946: (Comments on that requested).
12947:
12948: @item character-set extensions and matching of names:
12949: @cindex character-set extensions and matching of names
1.26 crook 12950: @cindex case-sensitivity for name lookup
12951: @cindex name lookup, case-sensitivity
12952: @cindex locale and case-sensitivity
1.21 crook 12953: Any character except the ASCII NUL character can be used in a
1.1 anton 12954: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12955: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12956: function is probably influenced by the locale. E.g., the @code{C} locale
12957: does not know about accents and umlauts, so they are matched
12958: case-sensitively in that locale. For portability reasons it is best to
12959: write programs such that they work in the @code{C} locale. Then one can
12960: use libraries written by a Polish programmer (who might use words
12961: containing ISO Latin-2 encoded characters) and by a French programmer
12962: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12963: funny results for some of the words (which ones, depends on the font you
12964: are using)). Also, the locale you prefer may not be available in other
12965: operating systems. Hopefully, Unicode will solve these problems one day.
12966:
12967: @item conditions under which control characters match a space delimiter:
12968: @cindex space delimiters
12969: @cindex control characters as delimiters
1.117 anton 12970: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12971: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12972: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12973: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12974: interpreter (aka text interpreter) by default, treats all white-space
12975: characters as delimiters.
12976:
1.26 crook 12977: @item format of the control-flow stack:
12978: @cindex control-flow stack, format
12979: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12980: stack item in cells is given by the constant @code{cs-item-size}. At the
12981: time of this writing, an item consists of a (pointer to a) locals list
12982: (third), an address in the code (second), and a tag for identifying the
12983: item (TOS). The following tags are used: @code{defstart},
12984: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12985: @code{scopestart}.
12986:
12987: @item conversion of digits > 35
12988: @cindex digits > 35
12989: The characters @code{[\]^_'} are the digits with the decimal value
12990: 36@minus{}41. There is no way to input many of the larger digits.
12991:
12992: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12993: @cindex @code{EXPECT}, display after end of input
12994: @cindex @code{ACCEPT}, display after end of input
12995: The cursor is moved to the end of the entered string. If the input is
12996: terminated using the @kbd{Return} key, a space is typed.
12997:
12998: @item exception abort sequence of @code{ABORT"}:
12999: @cindex exception abort sequence of @code{ABORT"}
13000: @cindex @code{ABORT"}, exception abort sequence
13001: The error string is stored into the variable @code{"error} and a
13002: @code{-2 throw} is performed.
13003:
13004: @item input line terminator:
13005: @cindex input line terminator
13006: @cindex line terminator on input
1.26 crook 13007: @cindex newline character on input
1.1 anton 13008: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13009: lines. One of these characters is typically produced when you type the
13010: @kbd{Enter} or @kbd{Return} key.
13011:
13012: @item maximum size of a counted string:
13013: @cindex maximum size of a counted string
13014: @cindex counted string, maximum size
13015: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13016: on all platforms, but this may change.
1.1 anton 13017:
13018: @item maximum size of a parsed string:
13019: @cindex maximum size of a parsed string
13020: @cindex parsed string, maximum size
13021: Given by the constant @code{/line}. Currently 255 characters.
13022:
13023: @item maximum size of a definition name, in characters:
13024: @cindex maximum size of a definition name, in characters
13025: @cindex name, maximum length
1.113 anton 13026: MAXU/8
1.1 anton 13027:
13028: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13029: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13030: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13031: MAXU/8
1.1 anton 13032:
13033: @item method of selecting the user input device:
13034: @cindex user input device, method of selecting
13035: The user input device is the standard input. There is currently no way to
13036: change it from within Gforth. However, the input can typically be
13037: redirected in the command line that starts Gforth.
13038:
13039: @item method of selecting the user output device:
13040: @cindex user output device, method of selecting
13041: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13042: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13043: output when the user output device is a terminal, otherwise the output
13044: is buffered.
1.1 anton 13045:
13046: @item methods of dictionary compilation:
13047: What are we expected to document here?
13048:
13049: @item number of bits in one address unit:
13050: @cindex number of bits in one address unit
13051: @cindex address unit, size in bits
13052: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13053: platforms.
1.1 anton 13054:
13055: @item number representation and arithmetic:
13056: @cindex number representation and arithmetic
1.79 anton 13057: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13058:
13059: @item ranges for integer types:
13060: @cindex ranges for integer types
13061: @cindex integer types, ranges
13062: Installation-dependent. Make environmental queries for @code{MAX-N},
13063: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13064: unsigned (and positive) types is 0. The lower bound for signed types on
13065: two's complement and one's complement machines machines can be computed
13066: by adding 1 to the upper bound.
13067:
13068: @item read-only data space regions:
13069: @cindex read-only data space regions
13070: @cindex data-space, read-only regions
13071: The whole Forth data space is writable.
13072:
13073: @item size of buffer at @code{WORD}:
13074: @cindex size of buffer at @code{WORD}
13075: @cindex @code{WORD} buffer size
13076: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13077: shared with the pictured numeric output string. If overwriting
13078: @code{PAD} is acceptable, it is as large as the remaining dictionary
13079: space, although only as much can be sensibly used as fits in a counted
13080: string.
13081:
13082: @item size of one cell in address units:
13083: @cindex cell size
13084: @code{1 cells .}.
13085:
13086: @item size of one character in address units:
13087: @cindex char size
1.79 anton 13088: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13089:
13090: @item size of the keyboard terminal buffer:
13091: @cindex size of the keyboard terminal buffer
13092: @cindex terminal buffer, size
13093: Varies. You can determine the size at a specific time using @code{lp@@
13094: tib - .}. It is shared with the locals stack and TIBs of files that
13095: include the current file. You can change the amount of space for TIBs
13096: and locals stack at Gforth startup with the command line option
13097: @code{-l}.
13098:
13099: @item size of the pictured numeric output buffer:
13100: @cindex size of the pictured numeric output buffer
13101: @cindex pictured numeric output buffer, size
13102: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13103: shared with @code{WORD}.
13104:
13105: @item size of the scratch area returned by @code{PAD}:
13106: @cindex size of the scratch area returned by @code{PAD}
13107: @cindex @code{PAD} size
13108: The remainder of dictionary space. @code{unused pad here - - .}.
13109:
13110: @item system case-sensitivity characteristics:
13111: @cindex case-sensitivity characteristics
1.26 crook 13112: Dictionary searches are case-insensitive (except in
1.1 anton 13113: @code{TABLE}s). However, as explained above under @i{character-set
13114: extensions}, the matching for non-ASCII characters is determined by the
13115: locale you are using. In the default @code{C} locale all non-ASCII
13116: characters are matched case-sensitively.
13117:
13118: @item system prompt:
13119: @cindex system prompt
13120: @cindex prompt
13121: @code{ ok} in interpret state, @code{ compiled} in compile state.
13122:
13123: @item division rounding:
13124: @cindex division rounding
1.166 anton 13125: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13126: division (with the default installation of Gforth). You can check
13127: this with @code{s" floored" environment? drop .}. If you write
13128: programs that need a specific division rounding, best use
13129: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13130:
13131: @item values of @code{STATE} when true:
13132: @cindex @code{STATE} values
13133: -1.
13134:
13135: @item values returned after arithmetic overflow:
13136: On two's complement machines, arithmetic is performed modulo
13137: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13138: arithmetic (with appropriate mapping for signed types). Division by
13139: zero typically results in a @code{-55 throw} (Floating-point
13140: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13141: division overflow can result in these throws, or in @code{-11 throw};
13142: in @code{gforth-fast} division overflow and divide by zero may also
13143: result in returning bogus results without producing an exception.
1.1 anton 13144:
13145: @item whether the current definition can be found after @t{DOES>}:
13146: @cindex @t{DOES>}, visibility of current definition
13147: No.
13148:
13149: @end table
13150:
13151: @c ---------------------------------------------------------------------
13152: @node core-ambcond, core-other, core-idef, The Core Words
13153: @subsection Ambiguous conditions
13154: @c ---------------------------------------------------------------------
13155: @cindex core words, ambiguous conditions
13156: @cindex ambiguous conditions, core words
13157:
13158: @table @i
13159:
13160: @item a name is neither a word nor a number:
13161: @cindex name not found
1.26 crook 13162: @cindex undefined word
1.80 anton 13163: @code{-13 throw} (Undefined word).
1.1 anton 13164:
13165: @item a definition name exceeds the maximum length allowed:
1.26 crook 13166: @cindex word name too long
1.1 anton 13167: @code{-19 throw} (Word name too long)
13168:
13169: @item addressing a region not inside the various data spaces of the forth system:
13170: @cindex Invalid memory address
1.32 anton 13171: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13172: typically readable. Accessing other addresses gives results dependent on
13173: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13174: address).
13175:
13176: @item argument type incompatible with parameter:
1.26 crook 13177: @cindex argument type mismatch
1.1 anton 13178: This is usually not caught. Some words perform checks, e.g., the control
13179: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13180: mismatch).
13181:
13182: @item attempting to obtain the execution token of a word with undefined execution semantics:
13183: @cindex Interpreting a compile-only word, for @code{'} etc.
13184: @cindex execution token of words with undefined execution semantics
13185: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13186: get an execution token for @code{compile-only-error} (which performs a
13187: @code{-14 throw} when executed).
13188:
13189: @item dividing by zero:
13190: @cindex dividing by zero
13191: @cindex floating point unidentified fault, integer division
1.80 anton 13192: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13193: zero); on other systems, this typically results in a @code{-55 throw}
13194: (Floating-point unidentified fault).
1.1 anton 13195:
13196: @item insufficient data stack or return stack space:
13197: @cindex insufficient data stack or return stack space
13198: @cindex stack overflow
1.26 crook 13199: @cindex address alignment exception, stack overflow
1.1 anton 13200: @cindex Invalid memory address, stack overflow
13201: Depending on the operating system, the installation, and the invocation
13202: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13203: it is not checked. If it is checked, you typically get a @code{-3 throw}
13204: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13205: throw} (Invalid memory address) (depending on the platform and how you
13206: achieved the overflow) as soon as the overflow happens. If it is not
13207: checked, overflows typically result in mysterious illegal memory
13208: accesses, producing @code{-9 throw} (Invalid memory address) or
13209: @code{-23 throw} (Address alignment exception); they might also destroy
13210: the internal data structure of @code{ALLOCATE} and friends, resulting in
13211: various errors in these words.
1.1 anton 13212:
13213: @item insufficient space for loop control parameters:
13214: @cindex insufficient space for loop control parameters
1.80 anton 13215: Like other return stack overflows.
1.1 anton 13216:
13217: @item insufficient space in the dictionary:
13218: @cindex insufficient space in the dictionary
13219: @cindex dictionary overflow
1.12 anton 13220: If you try to allot (either directly with @code{allot}, or indirectly
13221: with @code{,}, @code{create} etc.) more memory than available in the
13222: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13223: to access memory beyond the end of the dictionary, the results are
13224: similar to stack overflows.
1.1 anton 13225:
13226: @item interpreting a word with undefined interpretation semantics:
13227: @cindex interpreting a word with undefined interpretation semantics
13228: @cindex Interpreting a compile-only word
13229: For some words, we have defined interpretation semantics. For the
13230: others: @code{-14 throw} (Interpreting a compile-only word).
13231:
13232: @item modifying the contents of the input buffer or a string literal:
13233: @cindex modifying the contents of the input buffer or a string literal
13234: These are located in writable memory and can be modified.
13235:
13236: @item overflow of the pictured numeric output string:
13237: @cindex overflow of the pictured numeric output string
13238: @cindex pictured numeric output string, overflow
1.24 anton 13239: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13240:
13241: @item parsed string overflow:
13242: @cindex parsed string overflow
13243: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13244:
13245: @item producing a result out of range:
13246: @cindex result out of range
13247: On two's complement machines, arithmetic is performed modulo
13248: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13249: arithmetic (with appropriate mapping for signed types). Division by
13250: zero typically results in a @code{-10 throw} (divide by zero) or
13251: @code{-55 throw} (floating point unidentified fault). Overflow on
13252: division may result in these errors or in @code{-11 throw} (result out
13253: of range). @code{Gforth-fast} may silently produce bogus results on
13254: division overflow or division by zero. @code{Convert} and
1.24 anton 13255: @code{>number} currently overflow silently.
1.1 anton 13256:
13257: @item reading from an empty data or return stack:
13258: @cindex stack empty
13259: @cindex stack underflow
1.24 anton 13260: @cindex return stack underflow
1.1 anton 13261: The data stack is checked by the outer (aka text) interpreter after
13262: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13263: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13264: depending on operating system, installation, and invocation. If they are
13265: caught by a check, they typically result in @code{-4 throw} (Stack
13266: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13267: (Invalid memory address), depending on the platform and which stack
13268: underflows and by how much. Note that even if the system uses checking
13269: (through the MMU), your program may have to underflow by a significant
13270: number of stack items to trigger the reaction (the reason for this is
13271: that the MMU, and therefore the checking, works with a page-size
13272: granularity). If there is no checking, the symptoms resulting from an
13273: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13274: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13275: (Invalid memory address) and Illegal Instruction (typically @code{-260
13276: throw}).
1.1 anton 13277:
13278: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13279: @cindex unexpected end of the input buffer
13280: @cindex zero-length string as a name
13281: @cindex Attempt to use zero-length string as a name
13282: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13283: use zero-length string as a name). Words like @code{'} probably will not
13284: find what they search. Note that it is possible to create zero-length
13285: names with @code{nextname} (should it not?).
13286:
13287: @item @code{>IN} greater than input buffer:
13288: @cindex @code{>IN} greater than input buffer
13289: The next invocation of a parsing word returns a string with length 0.
13290:
13291: @item @code{RECURSE} appears after @code{DOES>}:
13292: @cindex @code{RECURSE} appears after @code{DOES>}
13293: Compiles a recursive call to the defining word, not to the defined word.
13294:
13295: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13296: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13297: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13298: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13299: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13300: the end of the file was reached), its source-id may be
13301: reused. Therefore, restoring an input source specification referencing a
13302: closed file may lead to unpredictable results instead of a @code{-12
13303: THROW}.
13304:
13305: In the future, Gforth may be able to restore input source specifications
13306: from other than the current input source.
13307:
13308: @item data space containing definitions gets de-allocated:
13309: @cindex data space containing definitions gets de-allocated
13310: Deallocation with @code{allot} is not checked. This typically results in
13311: memory access faults or execution of illegal instructions.
13312:
13313: @item data space read/write with incorrect alignment:
13314: @cindex data space read/write with incorrect alignment
13315: @cindex alignment faults
1.26 crook 13316: @cindex address alignment exception
1.1 anton 13317: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13318: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13319: alignment turned on, incorrect alignment results in a @code{-9 throw}
13320: (Invalid memory address). There are reportedly some processors with
1.12 anton 13321: alignment restrictions that do not report violations.
1.1 anton 13322:
13323: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13324: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13325: Like other alignment errors.
13326:
13327: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13328: Like other stack underflows.
13329:
13330: @item loop control parameters not available:
13331: @cindex loop control parameters not available
13332: Not checked. The counted loop words simply assume that the top of return
13333: stack items are loop control parameters and behave accordingly.
13334:
13335: @item most recent definition does not have a name (@code{IMMEDIATE}):
13336: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13337: @cindex last word was headerless
13338: @code{abort" last word was headerless"}.
13339:
13340: @item name not defined by @code{VALUE} used by @code{TO}:
13341: @cindex name not defined by @code{VALUE} used by @code{TO}
13342: @cindex @code{TO} on non-@code{VALUE}s
13343: @cindex Invalid name argument, @code{TO}
13344: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13345: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13346:
13347: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13348: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13349: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13350: @code{-13 throw} (Undefined word)
13351:
13352: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13353: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13354: Gforth behaves as if they were of the same type. I.e., you can predict
13355: the behaviour by interpreting all parameters as, e.g., signed.
13356:
13357: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13358: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13359: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13360: compilation semantics of @code{TO}.
13361:
13362: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13363: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13364: @cindex @code{WORD}, string overflow
13365: Not checked. The string will be ok, but the count will, of course,
13366: contain only the least significant bits of the length.
13367:
13368: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13369: @cindex @code{LSHIFT}, large shift counts
13370: @cindex @code{RSHIFT}, large shift counts
13371: Processor-dependent. Typical behaviours are returning 0 and using only
13372: the low bits of the shift count.
13373:
13374: @item word not defined via @code{CREATE}:
13375: @cindex @code{>BODY} of non-@code{CREATE}d words
13376: @code{>BODY} produces the PFA of the word no matter how it was defined.
13377:
13378: @cindex @code{DOES>} of non-@code{CREATE}d words
13379: @code{DOES>} changes the execution semantics of the last defined word no
13380: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13381: @code{CREATE , DOES>}.
13382:
13383: @item words improperly used outside @code{<#} and @code{#>}:
13384: Not checked. As usual, you can expect memory faults.
13385:
13386: @end table
13387:
13388:
13389: @c ---------------------------------------------------------------------
13390: @node core-other, , core-ambcond, The Core Words
13391: @subsection Other system documentation
13392: @c ---------------------------------------------------------------------
13393: @cindex other system documentation, core words
13394: @cindex core words, other system documentation
13395:
13396: @table @i
13397: @item nonstandard words using @code{PAD}:
13398: @cindex @code{PAD} use by nonstandard words
13399: None.
13400:
13401: @item operator's terminal facilities available:
13402: @cindex operator's terminal facilities available
1.80 anton 13403: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13404: and you can give commands to Gforth interactively. The actual facilities
13405: available depend on how you invoke Gforth.
13406:
13407: @item program data space available:
13408: @cindex program data space available
13409: @cindex data space available
13410: @code{UNUSED .} gives the remaining dictionary space. The total
13411: dictionary space can be specified with the @code{-m} switch
13412: (@pxref{Invoking Gforth}) when Gforth starts up.
13413:
13414: @item return stack space available:
13415: @cindex return stack space available
13416: You can compute the total return stack space in cells with
13417: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13418: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13419:
13420: @item stack space available:
13421: @cindex stack space available
13422: You can compute the total data stack space in cells with
13423: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13424: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13425:
13426: @item system dictionary space required, in address units:
13427: @cindex system dictionary space required, in address units
13428: Type @code{here forthstart - .} after startup. At the time of this
13429: writing, this gives 80080 (bytes) on a 32-bit system.
13430: @end table
13431:
13432:
13433: @c =====================================================================
13434: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13435: @section The optional Block word set
13436: @c =====================================================================
13437: @cindex system documentation, block words
13438: @cindex block words, system documentation
13439:
13440: @menu
13441: * block-idef:: Implementation Defined Options
13442: * block-ambcond:: Ambiguous Conditions
13443: * block-other:: Other System Documentation
13444: @end menu
13445:
13446:
13447: @c ---------------------------------------------------------------------
13448: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13449: @subsection Implementation Defined Options
13450: @c ---------------------------------------------------------------------
13451: @cindex implementation-defined options, block words
13452: @cindex block words, implementation-defined options
13453:
13454: @table @i
13455: @item the format for display by @code{LIST}:
13456: @cindex @code{LIST} display format
13457: First the screen number is displayed, then 16 lines of 64 characters,
13458: each line preceded by the line number.
13459:
13460: @item the length of a line affected by @code{\}:
13461: @cindex length of a line affected by @code{\}
13462: @cindex @code{\}, line length in blocks
13463: 64 characters.
13464: @end table
13465:
13466:
13467: @c ---------------------------------------------------------------------
13468: @node block-ambcond, block-other, block-idef, The optional Block word set
13469: @subsection Ambiguous conditions
13470: @c ---------------------------------------------------------------------
13471: @cindex block words, ambiguous conditions
13472: @cindex ambiguous conditions, block words
13473:
13474: @table @i
13475: @item correct block read was not possible:
13476: @cindex block read not possible
13477: Typically results in a @code{throw} of some OS-derived value (between
13478: -512 and -2048). If the blocks file was just not long enough, blanks are
13479: supplied for the missing portion.
13480:
13481: @item I/O exception in block transfer:
13482: @cindex I/O exception in block transfer
13483: @cindex block transfer, I/O exception
13484: Typically results in a @code{throw} of some OS-derived value (between
13485: -512 and -2048).
13486:
13487: @item invalid block number:
13488: @cindex invalid block number
13489: @cindex block number invalid
13490: @code{-35 throw} (Invalid block number)
13491:
13492: @item a program directly alters the contents of @code{BLK}:
13493: @cindex @code{BLK}, altering @code{BLK}
13494: The input stream is switched to that other block, at the same
13495: position. If the storing to @code{BLK} happens when interpreting
13496: non-block input, the system will get quite confused when the block ends.
13497:
13498: @item no current block buffer for @code{UPDATE}:
13499: @cindex @code{UPDATE}, no current block buffer
13500: @code{UPDATE} has no effect.
13501:
13502: @end table
13503:
13504: @c ---------------------------------------------------------------------
13505: @node block-other, , block-ambcond, The optional Block word set
13506: @subsection Other system documentation
13507: @c ---------------------------------------------------------------------
13508: @cindex other system documentation, block words
13509: @cindex block words, other system documentation
13510:
13511: @table @i
13512: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13513: No restrictions (yet).
13514:
13515: @item the number of blocks available for source and data:
13516: depends on your disk space.
13517:
13518: @end table
13519:
13520:
13521: @c =====================================================================
13522: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13523: @section The optional Double Number word set
13524: @c =====================================================================
13525: @cindex system documentation, double words
13526: @cindex double words, system documentation
13527:
13528: @menu
13529: * double-ambcond:: Ambiguous Conditions
13530: @end menu
13531:
13532:
13533: @c ---------------------------------------------------------------------
13534: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13535: @subsection Ambiguous conditions
13536: @c ---------------------------------------------------------------------
13537: @cindex double words, ambiguous conditions
13538: @cindex ambiguous conditions, double words
13539:
13540: @table @i
1.29 crook 13541: @item @i{d} outside of range of @i{n} in @code{D>S}:
13542: @cindex @code{D>S}, @i{d} out of range of @i{n}
13543: The least significant cell of @i{d} is produced.
1.1 anton 13544:
13545: @end table
13546:
13547:
13548: @c =====================================================================
13549: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13550: @section The optional Exception word set
13551: @c =====================================================================
13552: @cindex system documentation, exception words
13553: @cindex exception words, system documentation
13554:
13555: @menu
13556: * exception-idef:: Implementation Defined Options
13557: @end menu
13558:
13559:
13560: @c ---------------------------------------------------------------------
13561: @node exception-idef, , The optional Exception word set, The optional Exception word set
13562: @subsection Implementation Defined Options
13563: @c ---------------------------------------------------------------------
13564: @cindex implementation-defined options, exception words
13565: @cindex exception words, implementation-defined options
13566:
13567: @table @i
13568: @item @code{THROW}-codes used in the system:
13569: @cindex @code{THROW}-codes used in the system
13570: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13571: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13572: codes -512@minus{}-2047 are used for OS errors (for file and memory
13573: allocation operations). The mapping from OS error numbers to throw codes
13574: is -512@minus{}@code{errno}. One side effect of this mapping is that
13575: undefined OS errors produce a message with a strange number; e.g.,
13576: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13577: @end table
13578:
13579: @c =====================================================================
13580: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13581: @section The optional Facility word set
13582: @c =====================================================================
13583: @cindex system documentation, facility words
13584: @cindex facility words, system documentation
13585:
13586: @menu
13587: * facility-idef:: Implementation Defined Options
13588: * facility-ambcond:: Ambiguous Conditions
13589: @end menu
13590:
13591:
13592: @c ---------------------------------------------------------------------
13593: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13594: @subsection Implementation Defined Options
13595: @c ---------------------------------------------------------------------
13596: @cindex implementation-defined options, facility words
13597: @cindex facility words, implementation-defined options
13598:
13599: @table @i
13600: @item encoding of keyboard events (@code{EKEY}):
13601: @cindex keyboard events, encoding in @code{EKEY}
13602: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13603: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13604: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13605: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13606: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13607: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13608:
1.1 anton 13609:
13610: @item duration of a system clock tick:
13611: @cindex duration of a system clock tick
13612: @cindex clock tick duration
13613: System dependent. With respect to @code{MS}, the time is specified in
13614: microseconds. How well the OS and the hardware implement this, is
13615: another question.
13616:
13617: @item repeatability to be expected from the execution of @code{MS}:
13618: @cindex repeatability to be expected from the execution of @code{MS}
13619: @cindex @code{MS}, repeatability to be expected
13620: System dependent. On Unix, a lot depends on load. If the system is
13621: lightly loaded, and the delay is short enough that Gforth does not get
13622: swapped out, the performance should be acceptable. Under MS-DOS and
13623: other single-tasking systems, it should be good.
13624:
13625: @end table
13626:
13627:
13628: @c ---------------------------------------------------------------------
13629: @node facility-ambcond, , facility-idef, The optional Facility word set
13630: @subsection Ambiguous conditions
13631: @c ---------------------------------------------------------------------
13632: @cindex facility words, ambiguous conditions
13633: @cindex ambiguous conditions, facility words
13634:
13635: @table @i
13636: @item @code{AT-XY} can't be performed on user output device:
13637: @cindex @code{AT-XY} can't be performed on user output device
13638: Largely terminal dependent. No range checks are done on the arguments.
13639: No errors are reported. You may see some garbage appearing, you may see
13640: simply nothing happen.
13641:
13642: @end table
13643:
13644:
13645: @c =====================================================================
13646: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13647: @section The optional File-Access word set
13648: @c =====================================================================
13649: @cindex system documentation, file words
13650: @cindex file words, system documentation
13651:
13652: @menu
13653: * file-idef:: Implementation Defined Options
13654: * file-ambcond:: Ambiguous Conditions
13655: @end menu
13656:
13657: @c ---------------------------------------------------------------------
13658: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13659: @subsection Implementation Defined Options
13660: @c ---------------------------------------------------------------------
13661: @cindex implementation-defined options, file words
13662: @cindex file words, implementation-defined options
13663:
13664: @table @i
13665: @item file access methods used:
13666: @cindex file access methods used
13667: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13668: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13669: @code{wb}): The file is cleared, if it exists, and created, if it does
13670: not (with both @code{open-file} and @code{create-file}). Under Unix
13671: @code{create-file} creates a file with 666 permissions modified by your
13672: umask.
13673:
13674: @item file exceptions:
13675: @cindex file exceptions
13676: The file words do not raise exceptions (except, perhaps, memory access
13677: faults when you pass illegal addresses or file-ids).
13678:
13679: @item file line terminator:
13680: @cindex file line terminator
13681: System-dependent. Gforth uses C's newline character as line
13682: terminator. What the actual character code(s) of this are is
13683: system-dependent.
13684:
13685: @item file name format:
13686: @cindex file name format
13687: System dependent. Gforth just uses the file name format of your OS.
13688:
13689: @item information returned by @code{FILE-STATUS}:
13690: @cindex @code{FILE-STATUS}, returned information
13691: @code{FILE-STATUS} returns the most powerful file access mode allowed
13692: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13693: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13694: along with the returned mode.
13695:
13696: @item input file state after an exception when including source:
13697: @cindex exception when including source
13698: All files that are left via the exception are closed.
13699:
1.29 crook 13700: @item @i{ior} values and meaning:
13701: @cindex @i{ior} values and meaning
1.68 anton 13702: @cindex @i{wior} values and meaning
1.29 crook 13703: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13704: intended as throw codes. They typically are in the range
13705: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13706: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13707:
13708: @item maximum depth of file input nesting:
13709: @cindex maximum depth of file input nesting
13710: @cindex file input nesting, maximum depth
13711: limited by the amount of return stack, locals/TIB stack, and the number
13712: of open files available. This should not give you troubles.
13713:
13714: @item maximum size of input line:
13715: @cindex maximum size of input line
13716: @cindex input line size, maximum
13717: @code{/line}. Currently 255.
13718:
13719: @item methods of mapping block ranges to files:
13720: @cindex mapping block ranges to files
13721: @cindex files containing blocks
13722: @cindex blocks in files
13723: By default, blocks are accessed in the file @file{blocks.fb} in the
13724: current working directory. The file can be switched with @code{USE}.
13725:
13726: @item number of string buffers provided by @code{S"}:
13727: @cindex @code{S"}, number of string buffers
13728: 1
13729:
13730: @item size of string buffer used by @code{S"}:
13731: @cindex @code{S"}, size of string buffer
13732: @code{/line}. currently 255.
13733:
13734: @end table
13735:
13736: @c ---------------------------------------------------------------------
13737: @node file-ambcond, , file-idef, The optional File-Access word set
13738: @subsection Ambiguous conditions
13739: @c ---------------------------------------------------------------------
13740: @cindex file words, ambiguous conditions
13741: @cindex ambiguous conditions, file words
13742:
13743: @table @i
13744: @item attempting to position a file outside its boundaries:
13745: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13746: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13747: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13748:
13749: @item attempting to read from file positions not yet written:
13750: @cindex reading from file positions not yet written
13751: End-of-file, i.e., zero characters are read and no error is reported.
13752:
1.29 crook 13753: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13754: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13755: An appropriate exception may be thrown, but a memory fault or other
13756: problem is more probable.
13757:
1.29 crook 13758: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13759: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13760: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13761: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13762: thrown.
13763:
13764: @item named file cannot be opened (@code{INCLUDED}):
13765: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13766: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13767:
13768: @item requesting an unmapped block number:
13769: @cindex unmapped block numbers
13770: There are no unmapped legal block numbers. On some operating systems,
13771: writing a block with a large number may overflow the file system and
13772: have an error message as consequence.
13773:
13774: @item using @code{source-id} when @code{blk} is non-zero:
13775: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13776: @code{source-id} performs its function. Typically it will give the id of
13777: the source which loaded the block. (Better ideas?)
13778:
13779: @end table
13780:
13781:
13782: @c =====================================================================
13783: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13784: @section The optional Floating-Point word set
13785: @c =====================================================================
13786: @cindex system documentation, floating-point words
13787: @cindex floating-point words, system documentation
13788:
13789: @menu
13790: * floating-idef:: Implementation Defined Options
13791: * floating-ambcond:: Ambiguous Conditions
13792: @end menu
13793:
13794:
13795: @c ---------------------------------------------------------------------
13796: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13797: @subsection Implementation Defined Options
13798: @c ---------------------------------------------------------------------
13799: @cindex implementation-defined options, floating-point words
13800: @cindex floating-point words, implementation-defined options
13801:
13802: @table @i
13803: @item format and range of floating point numbers:
13804: @cindex format and range of floating point numbers
13805: @cindex floating point numbers, format and range
13806: System-dependent; the @code{double} type of C.
13807:
1.29 crook 13808: @item results of @code{REPRESENT} when @i{float} is out of range:
13809: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13810: System dependent; @code{REPRESENT} is implemented using the C library
13811: function @code{ecvt()} and inherits its behaviour in this respect.
13812:
13813: @item rounding or truncation of floating-point numbers:
13814: @cindex rounding of floating-point numbers
13815: @cindex truncation of floating-point numbers
13816: @cindex floating-point numbers, rounding or truncation
13817: System dependent; the rounding behaviour is inherited from the hosting C
13818: compiler. IEEE-FP-based (i.e., most) systems by default round to
13819: nearest, and break ties by rounding to even (i.e., such that the last
13820: bit of the mantissa is 0).
13821:
13822: @item size of floating-point stack:
13823: @cindex floating-point stack size
13824: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13825: the floating-point stack (in floats). You can specify this on startup
13826: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13827:
13828: @item width of floating-point stack:
13829: @cindex floating-point stack width
13830: @code{1 floats}.
13831:
13832: @end table
13833:
13834:
13835: @c ---------------------------------------------------------------------
13836: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13837: @subsection Ambiguous conditions
13838: @c ---------------------------------------------------------------------
13839: @cindex floating-point words, ambiguous conditions
13840: @cindex ambiguous conditions, floating-point words
13841:
13842: @table @i
13843: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13844: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13845: System-dependent. Typically results in a @code{-23 THROW} like other
13846: alignment violations.
13847:
13848: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13849: @cindex @code{f@@} used with an address that is not float aligned
13850: @cindex @code{f!} used with an address that is not float aligned
13851: System-dependent. Typically results in a @code{-23 THROW} like other
13852: alignment violations.
13853:
13854: @item floating-point result out of range:
13855: @cindex floating-point result out of range
1.80 anton 13856: System-dependent. Can result in a @code{-43 throw} (floating point
13857: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13858: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13859: unidentified fault), or can produce a special value representing, e.g.,
13860: Infinity.
13861:
13862: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13863: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13864: System-dependent. Typically results in an alignment fault like other
13865: alignment violations.
13866:
1.35 anton 13867: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13868: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13869: The floating-point number is converted into decimal nonetheless.
13870:
13871: @item Both arguments are equal to zero (@code{FATAN2}):
13872: @cindex @code{FATAN2}, both arguments are equal to zero
13873: System-dependent. @code{FATAN2} is implemented using the C library
13874: function @code{atan2()}.
13875:
1.29 crook 13876: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13877: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13878: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13879: because of small errors and the tan will be a very large (or very small)
13880: but finite number.
13881:
1.29 crook 13882: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13883: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13884: The result is rounded to the nearest float.
13885:
13886: @item dividing by zero:
13887: @cindex dividing by zero, floating-point
13888: @cindex floating-point dividing by zero
13889: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13890: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13891: (floating point divide by zero) or @code{-55 throw} (Floating-point
13892: unidentified fault).
1.1 anton 13893:
13894: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13895: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13896: System dependent. On IEEE-FP based systems the number is converted into
13897: an infinity.
13898:
1.29 crook 13899: @item @i{float}<1 (@code{FACOSH}):
13900: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13901: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13902: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13903:
1.29 crook 13904: @item @i{float}=<-1 (@code{FLNP1}):
13905: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13906: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13907: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13908: negative infinity for @i{float}=-1).
1.1 anton 13909:
1.29 crook 13910: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13911: @cindex @code{FLN}, @i{float}=<0
13912: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13913: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13914: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13915: negative infinity for @i{float}=0).
1.1 anton 13916:
1.29 crook 13917: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13918: @cindex @code{FASINH}, @i{float}<0
13919: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13920: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13921: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13922: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13923: C library?).
1.1 anton 13924:
1.29 crook 13925: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13926: @cindex @code{FACOS}, |@i{float}|>1
13927: @cindex @code{FASIN}, |@i{float}|>1
13928: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13929: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13930: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13931:
1.29 crook 13932: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13933: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13934: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13935: Platform-dependent; typically, some double number is produced and no
13936: error is reported.
1.1 anton 13937:
13938: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13939: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13940: @code{Precision} characters of the numeric output area are used. If
13941: @code{precision} is too high, these words will smash the data or code
13942: close to @code{here}.
1.1 anton 13943: @end table
13944:
13945: @c =====================================================================
13946: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13947: @section The optional Locals word set
13948: @c =====================================================================
13949: @cindex system documentation, locals words
13950: @cindex locals words, system documentation
13951:
13952: @menu
13953: * locals-idef:: Implementation Defined Options
13954: * locals-ambcond:: Ambiguous Conditions
13955: @end menu
13956:
13957:
13958: @c ---------------------------------------------------------------------
13959: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13960: @subsection Implementation Defined Options
13961: @c ---------------------------------------------------------------------
13962: @cindex implementation-defined options, locals words
13963: @cindex locals words, implementation-defined options
13964:
13965: @table @i
13966: @item maximum number of locals in a definition:
13967: @cindex maximum number of locals in a definition
13968: @cindex locals, maximum number in a definition
13969: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13970: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13971: characters. The number of locals in a definition is bounded by the size
13972: of locals-buffer, which contains the names of the locals.
13973:
13974: @end table
13975:
13976:
13977: @c ---------------------------------------------------------------------
13978: @node locals-ambcond, , locals-idef, The optional Locals word set
13979: @subsection Ambiguous conditions
13980: @c ---------------------------------------------------------------------
13981: @cindex locals words, ambiguous conditions
13982: @cindex ambiguous conditions, locals words
13983:
13984: @table @i
13985: @item executing a named local in interpretation state:
13986: @cindex local in interpretation state
13987: @cindex Interpreting a compile-only word, for a local
13988: Locals have no interpretation semantics. If you try to perform the
13989: interpretation semantics, you will get a @code{-14 throw} somewhere
13990: (Interpreting a compile-only word). If you perform the compilation
13991: semantics, the locals access will be compiled (irrespective of state).
13992:
1.29 crook 13993: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13994: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13995: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13996: @cindex Invalid name argument, @code{TO}
13997: @code{-32 throw} (Invalid name argument)
13998:
13999: @end table
14000:
14001:
14002: @c =====================================================================
14003: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14004: @section The optional Memory-Allocation word set
14005: @c =====================================================================
14006: @cindex system documentation, memory-allocation words
14007: @cindex memory-allocation words, system documentation
14008:
14009: @menu
14010: * memory-idef:: Implementation Defined Options
14011: @end menu
14012:
14013:
14014: @c ---------------------------------------------------------------------
14015: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14016: @subsection Implementation Defined Options
14017: @c ---------------------------------------------------------------------
14018: @cindex implementation-defined options, memory-allocation words
14019: @cindex memory-allocation words, implementation-defined options
14020:
14021: @table @i
1.29 crook 14022: @item values and meaning of @i{ior}:
14023: @cindex @i{ior} values and meaning
14024: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14025: intended as throw codes. They typically are in the range
14026: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14027: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14028:
14029: @end table
14030:
14031: @c =====================================================================
14032: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14033: @section The optional Programming-Tools word set
14034: @c =====================================================================
14035: @cindex system documentation, programming-tools words
14036: @cindex programming-tools words, system documentation
14037:
14038: @menu
14039: * programming-idef:: Implementation Defined Options
14040: * programming-ambcond:: Ambiguous Conditions
14041: @end menu
14042:
14043:
14044: @c ---------------------------------------------------------------------
14045: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14046: @subsection Implementation Defined Options
14047: @c ---------------------------------------------------------------------
14048: @cindex implementation-defined options, programming-tools words
14049: @cindex programming-tools words, implementation-defined options
14050:
14051: @table @i
14052: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14053: @cindex @code{;CODE} ending sequence
14054: @cindex @code{CODE} ending sequence
14055: @code{END-CODE}
14056:
14057: @item manner of processing input following @code{;CODE} and @code{CODE}:
14058: @cindex @code{;CODE}, processing input
14059: @cindex @code{CODE}, processing input
14060: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14061: the input is processed by the text interpreter, (starting) in interpret
14062: state.
14063:
14064: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14065: @cindex @code{ASSEMBLER}, search order capability
14066: The ANS Forth search order word set.
14067:
14068: @item source and format of display by @code{SEE}:
14069: @cindex @code{SEE}, source and format of output
1.80 anton 14070: The source for @code{see} is the executable code used by the inner
1.1 anton 14071: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14072: (and on some platforms, assembly code for primitives) as well as
14073: possible.
1.1 anton 14074:
14075: @end table
14076:
14077: @c ---------------------------------------------------------------------
14078: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14079: @subsection Ambiguous conditions
14080: @c ---------------------------------------------------------------------
14081: @cindex programming-tools words, ambiguous conditions
14082: @cindex ambiguous conditions, programming-tools words
14083:
14084: @table @i
14085:
1.21 crook 14086: @item deleting the compilation word list (@code{FORGET}):
14087: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14088: Not implemented (yet).
14089:
1.29 crook 14090: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14091: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14092: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14093: @cindex control-flow stack underflow
14094: This typically results in an @code{abort"} with a descriptive error
14095: message (may change into a @code{-22 throw} (Control structure mismatch)
14096: in the future). You may also get a memory access error. If you are
14097: unlucky, this ambiguous condition is not caught.
14098:
1.29 crook 14099: @item @i{name} can't be found (@code{FORGET}):
14100: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14101: Not implemented (yet).
14102:
1.29 crook 14103: @item @i{name} not defined via @code{CREATE}:
14104: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14105: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14106: the execution semantics of the last defined word no matter how it was
14107: defined.
14108:
14109: @item @code{POSTPONE} applied to @code{[IF]}:
14110: @cindex @code{POSTPONE} applied to @code{[IF]}
14111: @cindex @code{[IF]} and @code{POSTPONE}
14112: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14113: equivalent to @code{[IF]}.
14114:
14115: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14116: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14117: Continue in the same state of conditional compilation in the next outer
14118: input source. Currently there is no warning to the user about this.
14119:
14120: @item removing a needed definition (@code{FORGET}):
14121: @cindex @code{FORGET}, removing a needed definition
14122: Not implemented (yet).
14123:
14124: @end table
14125:
14126:
14127: @c =====================================================================
14128: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14129: @section The optional Search-Order word set
14130: @c =====================================================================
14131: @cindex system documentation, search-order words
14132: @cindex search-order words, system documentation
14133:
14134: @menu
14135: * search-idef:: Implementation Defined Options
14136: * search-ambcond:: Ambiguous Conditions
14137: @end menu
14138:
14139:
14140: @c ---------------------------------------------------------------------
14141: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14142: @subsection Implementation Defined Options
14143: @c ---------------------------------------------------------------------
14144: @cindex implementation-defined options, search-order words
14145: @cindex search-order words, implementation-defined options
14146:
14147: @table @i
14148: @item maximum number of word lists in search order:
14149: @cindex maximum number of word lists in search order
14150: @cindex search order, maximum depth
14151: @code{s" wordlists" environment? drop .}. Currently 16.
14152:
14153: @item minimum search order:
14154: @cindex minimum search order
14155: @cindex search order, minimum
14156: @code{root root}.
14157:
14158: @end table
14159:
14160: @c ---------------------------------------------------------------------
14161: @node search-ambcond, , search-idef, The optional Search-Order word set
14162: @subsection Ambiguous conditions
14163: @c ---------------------------------------------------------------------
14164: @cindex search-order words, ambiguous conditions
14165: @cindex ambiguous conditions, search-order words
14166:
14167: @table @i
1.21 crook 14168: @item changing the compilation word list (during compilation):
14169: @cindex changing the compilation word list (during compilation)
14170: @cindex compilation word list, change before definition ends
14171: The word is entered into the word list that was the compilation word list
1.1 anton 14172: at the start of the definition. Any changes to the name field (e.g.,
14173: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14174: are applied to the latest defined word (as reported by @code{latest} or
14175: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14176:
14177: @item search order empty (@code{previous}):
14178: @cindex @code{previous}, search order empty
1.26 crook 14179: @cindex vocstack empty, @code{previous}
1.1 anton 14180: @code{abort" Vocstack empty"}.
14181:
14182: @item too many word lists in search order (@code{also}):
14183: @cindex @code{also}, too many word lists in search order
1.26 crook 14184: @cindex vocstack full, @code{also}
1.1 anton 14185: @code{abort" Vocstack full"}.
14186:
14187: @end table
14188:
14189: @c ***************************************************************
1.65 anton 14190: @node Standard vs Extensions, Model, ANS conformance, Top
14191: @chapter Should I use Gforth extensions?
14192: @cindex Gforth extensions
14193:
14194: As you read through the rest of this manual, you will see documentation
14195: for @i{Standard} words, and documentation for some appealing Gforth
14196: @i{extensions}. You might ask yourself the question: @i{``Should I
14197: restrict myself to the standard, or should I use the extensions?''}
14198:
14199: The answer depends on the goals you have for the program you are working
14200: on:
14201:
14202: @itemize @bullet
14203:
14204: @item Is it just for yourself or do you want to share it with others?
14205:
14206: @item
14207: If you want to share it, do the others all use Gforth?
14208:
14209: @item
14210: If it is just for yourself, do you want to restrict yourself to Gforth?
14211:
14212: @end itemize
14213:
14214: If restricting the program to Gforth is ok, then there is no reason not
14215: to use extensions. It is still a good idea to keep to the standard
14216: where it is easy, in case you want to reuse these parts in another
14217: program that you want to be portable.
14218:
14219: If you want to be able to port the program to other Forth systems, there
14220: are the following points to consider:
14221:
14222: @itemize @bullet
14223:
14224: @item
14225: Most Forth systems that are being maintained support the ANS Forth
14226: standard. So if your program complies with the standard, it will be
14227: portable among many systems.
14228:
14229: @item
14230: A number of the Gforth extensions can be implemented in ANS Forth using
14231: public-domain files provided in the @file{compat/} directory. These are
14232: mentioned in the text in passing. There is no reason not to use these
14233: extensions, your program will still be ANS Forth compliant; just include
14234: the appropriate compat files with your program.
14235:
14236: @item
14237: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14238: analyse your program and determine what non-Standard words it relies
14239: upon. However, it does not check whether you use standard words in a
14240: non-standard way.
14241:
14242: @item
14243: Some techniques are not standardized by ANS Forth, and are hard or
14244: impossible to implement in a standard way, but can be implemented in
14245: most Forth systems easily, and usually in similar ways (e.g., accessing
14246: word headers). Forth has a rich historical precedent for programmers
14247: taking advantage of implementation-dependent features of their tools
14248: (for example, relying on a knowledge of the dictionary
14249: structure). Sometimes these techniques are necessary to extract every
14250: last bit of performance from the hardware, sometimes they are just a
14251: programming shorthand.
14252:
14253: @item
14254: Does using a Gforth extension save more work than the porting this part
14255: to other Forth systems (if any) will cost?
14256:
14257: @item
14258: Is the additional functionality worth the reduction in portability and
14259: the additional porting problems?
14260:
14261: @end itemize
14262:
14263: In order to perform these consideratios, you need to know what's
14264: standard and what's not. This manual generally states if something is
1.81 anton 14265: non-standard, but the authoritative source is the
14266: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14267: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14268: into the thought processes of the technical committee.
14269:
14270: Note also that portability between Forth systems is not the only
14271: portability issue; there is also the issue of portability between
14272: different platforms (processor/OS combinations).
14273:
14274: @c ***************************************************************
14275: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14276: @chapter Model
14277:
14278: This chapter has yet to be written. It will contain information, on
14279: which internal structures you can rely.
14280:
14281: @c ***************************************************************
14282: @node Integrating Gforth, Emacs and Gforth, Model, Top
14283: @chapter Integrating Gforth into C programs
14284:
14285: This is not yet implemented.
14286:
14287: Several people like to use Forth as scripting language for applications
14288: that are otherwise written in C, C++, or some other language.
14289:
14290: The Forth system ATLAST provides facilities for embedding it into
14291: applications; unfortunately it has several disadvantages: most
14292: importantly, it is not based on ANS Forth, and it is apparently dead
14293: (i.e., not developed further and not supported). The facilities
1.21 crook 14294: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14295: making the switch should not be hard.
14296:
14297: We also tried to design the interface such that it can easily be
14298: implemented by other Forth systems, so that we may one day arrive at a
14299: standardized interface. Such a standard interface would allow you to
14300: replace the Forth system without having to rewrite C code.
14301:
14302: You embed the Gforth interpreter by linking with the library
14303: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14304: global symbols in this library that belong to the interface, have the
14305: prefix @code{forth_}. (Global symbols that are used internally have the
14306: prefix @code{gforth_}).
14307:
14308: You can include the declarations of Forth types and the functions and
14309: variables of the interface with @code{#include <forth.h>}.
14310:
14311: Types.
14312:
14313: Variables.
14314:
14315: Data and FP Stack pointer. Area sizes.
14316:
14317: functions.
14318:
14319: forth_init(imagefile)
14320: forth_evaluate(string) exceptions?
14321: forth_goto(address) (or forth_execute(xt)?)
14322: forth_continue() (a corountining mechanism)
14323:
14324: Adding primitives.
14325:
14326: No checking.
14327:
14328: Signals?
14329:
14330: Accessing the Stacks
14331:
1.26 crook 14332: @c ******************************************************************
1.1 anton 14333: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14334: @chapter Emacs and Gforth
14335: @cindex Emacs and Gforth
14336:
14337: @cindex @file{gforth.el}
14338: @cindex @file{forth.el}
14339: @cindex Rydqvist, Goran
1.107 dvdkhlng 14340: @cindex Kuehling, David
1.1 anton 14341: @cindex comment editing commands
14342: @cindex @code{\}, editing with Emacs
14343: @cindex debug tracer editing commands
14344: @cindex @code{~~}, removal with Emacs
14345: @cindex Forth mode in Emacs
1.107 dvdkhlng 14346:
1.1 anton 14347: Gforth comes with @file{gforth.el}, an improved version of
14348: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14349: improvements are:
14350:
14351: @itemize @bullet
14352: @item
1.107 dvdkhlng 14353: A better handling of indentation.
14354: @item
14355: A custom hilighting engine for Forth-code.
1.26 crook 14356: @item
14357: Comment paragraph filling (@kbd{M-q})
14358: @item
14359: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14360: @item
14361: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14362: @item
14363: Support of the @code{info-lookup} feature for looking up the
14364: documentation of a word.
1.107 dvdkhlng 14365: @item
14366: Support for reading and writing blocks files.
1.26 crook 14367: @end itemize
14368:
1.107 dvdkhlng 14369: To get a basic description of these features, enter Forth mode and
14370: type @kbd{C-h m}.
1.1 anton 14371:
14372: @cindex source location of error or debugging output in Emacs
14373: @cindex error output, finding the source location in Emacs
14374: @cindex debugging output, finding the source location in Emacs
14375: In addition, Gforth supports Emacs quite well: The source code locations
14376: given in error messages, debugging output (from @code{~~}) and failed
14377: assertion messages are in the right format for Emacs' compilation mode
14378: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14379: Manual}) so the source location corresponding to an error or other
14380: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14381: @kbd{C-c C-c} for the error under the cursor).
14382:
1.107 dvdkhlng 14383: @cindex viewing the documentation of a word in Emacs
14384: @cindex context-sensitive help
14385: Moreover, for words documented in this manual, you can look up the
14386: glossary entry quickly by using @kbd{C-h TAB}
14387: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14388: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14389: later and does not work for words containing @code{:}.
14390:
14391: @menu
14392: * Installing gforth.el:: Making Emacs aware of Forth.
14393: * Emacs Tags:: Viewing the source of a word in Emacs.
14394: * Hilighting:: Making Forth code look prettier.
14395: * Auto-Indentation:: Customizing auto-indentation.
14396: * Blocks Files:: Reading and writing blocks files.
14397: @end menu
14398:
14399: @c ----------------------------------
1.109 anton 14400: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14401: @section Installing gforth.el
14402: @cindex @file{.emacs}
14403: @cindex @file{gforth.el}, installation
14404: To make the features from @file{gforth.el} available in Emacs, add
14405: the following lines to your @file{.emacs} file:
14406:
14407: @example
14408: (autoload 'forth-mode "gforth.el")
14409: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14410: auto-mode-alist))
14411: (autoload 'forth-block-mode "gforth.el")
14412: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14413: auto-mode-alist))
14414: (add-hook 'forth-mode-hook (function (lambda ()
14415: ;; customize variables here:
14416: (setq forth-indent-level 4)
14417: (setq forth-minor-indent-level 2)
14418: (setq forth-hilight-level 3)
14419: ;;; ...
14420: )))
14421: @end example
14422:
14423: @c ----------------------------------
14424: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14425: @section Emacs Tags
1.1 anton 14426: @cindex @file{TAGS} file
14427: @cindex @file{etags.fs}
14428: @cindex viewing the source of a word in Emacs
1.43 anton 14429: @cindex @code{require}, placement in files
14430: @cindex @code{include}, placement in files
1.107 dvdkhlng 14431: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14432: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14433: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14434: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14435: several tags files at the same time (e.g., one for the Gforth sources
14436: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14437: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14438: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14439: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14440: with @file{etags.fs}, you should avoid putting definitions both before
14441: and after @code{require} etc., otherwise you will see the same file
14442: visited several times by commands like @code{tags-search}.
1.1 anton 14443:
1.107 dvdkhlng 14444: @c ----------------------------------
14445: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14446: @section Hilighting
14447: @cindex hilighting Forth code in Emacs
14448: @cindex highlighting Forth code in Emacs
14449: @file{gforth.el} comes with a custom source hilighting engine. When
14450: you open a file in @code{forth-mode}, it will be completely parsed,
14451: assigning faces to keywords, comments, strings etc. While you edit
14452: the file, modified regions get parsed and updated on-the-fly.
14453:
14454: Use the variable `forth-hilight-level' to change the level of
14455: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14456: you set the hilighting level to 0, the parser will still work in the
14457: background, collecting information about whether regions of text are
14458: ``compiled'' or ``interpreted''. Those information are required for
14459: auto-indentation to work properly. Set `forth-disable-parser' to
14460: non-nil if your computer is too slow to handle parsing. This will
14461: have an impact on the smartness of the auto-indentation engine,
14462: though.
14463:
14464: Sometimes Forth sources define new features that should be hilighted,
14465: new control structures, defining-words etc. You can use the variable
14466: `forth-custom-words' to make @code{forth-mode} hilight additional
14467: words and constructs. See the docstring of `forth-words' for details
14468: (in Emacs, type @kbd{C-h v forth-words}).
14469:
14470: `forth-custom-words' is meant to be customized in your
14471: @file{.emacs} file. To customize hilighing in a file-specific manner,
14472: set `forth-local-words' in a local-variables section at the end of
14473: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14474:
14475: Example:
14476: @example
14477: 0 [IF]
14478: Local Variables:
14479: forth-local-words:
14480: ((("t:") definition-starter (font-lock-keyword-face . 1)
14481: "[ \t\n]" t name (font-lock-function-name-face . 3))
14482: ((";t") definition-ender (font-lock-keyword-face . 1)))
14483: End:
14484: [THEN]
14485: @end example
14486:
14487: @c ----------------------------------
14488: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14489: @section Auto-Indentation
14490: @cindex auto-indentation of Forth code in Emacs
14491: @cindex indentation of Forth code in Emacs
14492: @code{forth-mode} automatically tries to indent lines in a smart way,
14493: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14494:
14495: Simple customization can be achieved by setting
14496: `forth-indent-level' and `forth-minor-indent-level' in your
14497: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14498: per default by multiples of 4 columns. To use the more traditional
14499: 3-column indentation, add the following lines to your @file{.emacs}:
14500:
14501: @example
14502: (add-hook 'forth-mode-hook (function (lambda ()
14503: ;; customize variables here:
14504: (setq forth-indent-level 3)
14505: (setq forth-minor-indent-level 1)
14506: )))
14507: @end example
14508:
14509: If you want indentation to recognize non-default words, customize it
14510: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14511: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14512: v forth-indent-words}).
14513:
14514: To customize indentation in a file-specific manner, set
14515: `forth-local-indent-words' in a local-variables section at the end of
14516: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14517: Emacs Manual}).
14518:
14519: Example:
14520: @example
14521: 0 [IF]
14522: Local Variables:
14523: forth-local-indent-words:
14524: ((("t:") (0 . 2) (0 . 2))
14525: ((";t") (-2 . 0) (0 . -2)))
14526: End:
14527: [THEN]
14528: @end example
14529:
14530: @c ----------------------------------
1.109 anton 14531: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14532: @section Blocks Files
14533: @cindex blocks files, use with Emacs
14534: @code{forth-mode} Autodetects blocks files by checking whether the
14535: length of the first line exceeds 1023 characters. It then tries to
14536: convert the file into normal text format. When you save the file, it
14537: will be written to disk as normal stream-source file.
14538:
14539: If you want to write blocks files, use @code{forth-blocks-mode}. It
14540: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14541:
1.107 dvdkhlng 14542: @itemize @bullet
14543: @item
14544: Files are written to disk in blocks file format.
14545: @item
14546: Screen numbers are displayed in the mode line (enumerated beginning
14547: with the value of `forth-block-base')
14548: @item
14549: Warnings are displayed when lines exceed 64 characters.
14550: @item
14551: The beginning of the currently edited block is marked with an
14552: overlay-arrow.
14553: @end itemize
1.41 anton 14554:
1.107 dvdkhlng 14555: There are some restrictions you should be aware of. When you open a
14556: blocks file that contains tabulator or newline characters, these
14557: characters will be translated into spaces when the file is written
14558: back to disk. If tabs or newlines are encountered during blocks file
14559: reading, an error is output to the echo area. So have a look at the
14560: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14561:
1.107 dvdkhlng 14562: Please consult the docstring of @code{forth-blocks-mode} for more
14563: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14564:
1.26 crook 14565: @c ******************************************************************
1.1 anton 14566: @node Image Files, Engine, Emacs and Gforth, Top
14567: @chapter Image Files
1.26 crook 14568: @cindex image file
14569: @cindex @file{.fi} files
1.1 anton 14570: @cindex precompiled Forth code
14571: @cindex dictionary in persistent form
14572: @cindex persistent form of dictionary
14573:
14574: An image file is a file containing an image of the Forth dictionary,
14575: i.e., compiled Forth code and data residing in the dictionary. By
14576: convention, we use the extension @code{.fi} for image files.
14577:
14578: @menu
1.18 anton 14579: * Image Licensing Issues:: Distribution terms for images.
14580: * Image File Background:: Why have image files?
1.67 anton 14581: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14582: * Data-Relocatable Image Files:: are better.
1.67 anton 14583: * Fully Relocatable Image Files:: better yet.
1.18 anton 14584: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14585: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14586: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14587: @end menu
14588:
1.18 anton 14589: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14590: @section Image Licensing Issues
14591: @cindex license for images
14592: @cindex image license
14593:
14594: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14595: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14596: original image; i.e., according to copyright law it is a derived work of
14597: the original image.
14598:
14599: Since Gforth is distributed under the GNU GPL, the newly created image
14600: falls under the GNU GPL, too. In particular, this means that if you
14601: distribute the image, you have to make all of the sources for the image
1.113 anton 14602: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14603: GNU General Public License (Section 3)}.
14604:
14605: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14606: contains only code compiled from the sources you gave it; if none of
14607: these sources is under the GPL, the terms discussed above do not apply
14608: to the image. However, if your image needs an engine (a gforth binary)
14609: that is under the GPL, you should make sure that you distribute both in
14610: a way that is at most a @emph{mere aggregation}, if you don't want the
14611: terms of the GPL to apply to the image.
14612:
14613: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14614: @section Image File Background
14615: @cindex image file background
14616:
1.80 anton 14617: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14618: definitions written in Forth. Since the Forth compiler itself belongs to
14619: those definitions, it is not possible to start the system with the
1.80 anton 14620: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14621: code as an image file in nearly executable form. When Gforth starts up,
14622: a C routine loads the image file into memory, optionally relocates the
14623: addresses, then sets up the memory (stacks etc.) according to
14624: information in the image file, and (finally) starts executing Forth
14625: code.
1.1 anton 14626:
14627: The image file variants represent different compromises between the
14628: goals of making it easy to generate image files and making them
14629: portable.
14630:
14631: @cindex relocation at run-time
1.26 crook 14632: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14633: run-time. This avoids many of the complications discussed below (image
14634: files are data relocatable without further ado), but costs performance
14635: (one addition per memory access).
14636:
14637: @cindex relocation at load-time
1.26 crook 14638: By contrast, the Gforth loader performs relocation at image load time. The
14639: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14640: appropriate code-field addresses (or code addresses in the case of
14641: direct threading).
14642:
14643: There are three kinds of image files, with different degrees of
14644: relocatability: non-relocatable, data-relocatable, and fully relocatable
14645: image files.
14646:
14647: @cindex image file loader
14648: @cindex relocating loader
14649: @cindex loader for image files
14650: These image file variants have several restrictions in common; they are
14651: caused by the design of the image file loader:
14652:
14653: @itemize @bullet
14654: @item
14655: There is only one segment; in particular, this means, that an image file
14656: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14657: them). The contents of the stacks are not represented, either.
1.1 anton 14658:
14659: @item
14660: The only kinds of relocation supported are: adding the same offset to
14661: all cells that represent data addresses; and replacing special tokens
14662: with code addresses or with pieces of machine code.
14663:
14664: If any complex computations involving addresses are performed, the
14665: results cannot be represented in the image file. Several applications that
14666: use such computations come to mind:
14667: @itemize @minus
14668: @item
14669: Hashing addresses (or data structures which contain addresses) for table
14670: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14671: purpose, you will have no problem, because the hash tables are
14672: recomputed automatically when the system is started. If you use your own
14673: hash tables, you will have to do something similar.
14674:
14675: @item
14676: There's a cute implementation of doubly-linked lists that uses
14677: @code{XOR}ed addresses. You could represent such lists as singly-linked
14678: in the image file, and restore the doubly-linked representation on
14679: startup.@footnote{In my opinion, though, you should think thrice before
14680: using a doubly-linked list (whatever implementation).}
14681:
14682: @item
14683: The code addresses of run-time routines like @code{docol:} cannot be
14684: represented in the image file (because their tokens would be replaced by
14685: machine code in direct threaded implementations). As a workaround,
14686: compute these addresses at run-time with @code{>code-address} from the
14687: executions tokens of appropriate words (see the definitions of
1.80 anton 14688: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14689:
14690: @item
14691: On many architectures addresses are represented in machine code in some
14692: shifted or mangled form. You cannot put @code{CODE} words that contain
14693: absolute addresses in this form in a relocatable image file. Workarounds
14694: are representing the address in some relative form (e.g., relative to
14695: the CFA, which is present in some register), or loading the address from
14696: a place where it is stored in a non-mangled form.
14697: @end itemize
14698: @end itemize
14699:
14700: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14701: @section Non-Relocatable Image Files
14702: @cindex non-relocatable image files
1.26 crook 14703: @cindex image file, non-relocatable
1.1 anton 14704:
14705: These files are simple memory dumps of the dictionary. They are specific
14706: to the executable (i.e., @file{gforth} file) they were created
14707: with. What's worse, they are specific to the place on which the
14708: dictionary resided when the image was created. Now, there is no
14709: guarantee that the dictionary will reside at the same place the next
14710: time you start Gforth, so there's no guarantee that a non-relocatable
14711: image will work the next time (Gforth will complain instead of crashing,
14712: though).
14713:
14714: You can create a non-relocatable image file with
14715:
1.44 crook 14716:
1.1 anton 14717: doc-savesystem
14718:
1.44 crook 14719:
1.1 anton 14720: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14721: @section Data-Relocatable Image Files
14722: @cindex data-relocatable image files
1.26 crook 14723: @cindex image file, data-relocatable
1.1 anton 14724:
14725: These files contain relocatable data addresses, but fixed code addresses
14726: (instead of tokens). They are specific to the executable (i.e.,
14727: @file{gforth} file) they were created with. For direct threading on some
14728: architectures (e.g., the i386), data-relocatable images do not work. You
14729: get a data-relocatable image, if you use @file{gforthmi} with a
14730: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14731: Relocatable Image Files}).
14732:
14733: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14734: @section Fully Relocatable Image Files
14735: @cindex fully relocatable image files
1.26 crook 14736: @cindex image file, fully relocatable
1.1 anton 14737:
14738: @cindex @file{kern*.fi}, relocatability
14739: @cindex @file{gforth.fi}, relocatability
14740: These image files have relocatable data addresses, and tokens for code
14741: addresses. They can be used with different binaries (e.g., with and
14742: without debugging) on the same machine, and even across machines with
14743: the same data formats (byte order, cell size, floating point
14744: format). However, they are usually specific to the version of Gforth
14745: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14746: are fully relocatable.
14747:
14748: There are two ways to create a fully relocatable image file:
14749:
14750: @menu
1.29 crook 14751: * gforthmi:: The normal way
1.1 anton 14752: * cross.fs:: The hard way
14753: @end menu
14754:
14755: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14756: @subsection @file{gforthmi}
14757: @cindex @file{comp-i.fs}
14758: @cindex @file{gforthmi}
14759:
14760: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14761: image @i{file} that contains everything you would load by invoking
14762: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14763: @example
1.29 crook 14764: gforthmi @i{file} @i{options}
1.1 anton 14765: @end example
14766:
14767: E.g., if you want to create an image @file{asm.fi} that has the file
14768: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14769: like this:
14770:
14771: @example
14772: gforthmi asm.fi asm.fs
14773: @end example
14774:
1.27 crook 14775: @file{gforthmi} is implemented as a sh script and works like this: It
14776: produces two non-relocatable images for different addresses and then
14777: compares them. Its output reflects this: first you see the output (if
1.62 crook 14778: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14779: files, then you see the output of the comparing program: It displays the
14780: offset used for data addresses and the offset used for code addresses;
1.1 anton 14781: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14782: image files, it displays a line like this:
1.1 anton 14783:
14784: @example
14785: 78DC BFFFFA50 BFFFFA40
14786: @end example
14787:
14788: This means that at offset $78dc from @code{forthstart}, one input image
14789: contains $bffffa50, and the other contains $bffffa40. Since these cells
14790: cannot be represented correctly in the output image, you should examine
14791: these places in the dictionary and verify that these cells are dead
14792: (i.e., not read before they are written).
1.39 anton 14793:
14794: @cindex --application, @code{gforthmi} option
14795: If you insert the option @code{--application} in front of the image file
14796: name, you will get an image that uses the @code{--appl-image} option
14797: instead of the @code{--image-file} option (@pxref{Invoking
14798: Gforth}). When you execute such an image on Unix (by typing the image
14799: name as command), the Gforth engine will pass all options to the image
14800: instead of trying to interpret them as engine options.
1.1 anton 14801:
1.27 crook 14802: If you type @file{gforthmi} with no arguments, it prints some usage
14803: instructions.
14804:
1.1 anton 14805: @cindex @code{savesystem} during @file{gforthmi}
14806: @cindex @code{bye} during @file{gforthmi}
14807: @cindex doubly indirect threaded code
1.44 crook 14808: @cindex environment variables
14809: @cindex @code{GFORTHD} -- environment variable
14810: @cindex @code{GFORTH} -- environment variable
1.1 anton 14811: @cindex @code{gforth-ditc}
1.29 crook 14812: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14813: words @code{savesystem} and @code{bye} must be visible. A special doubly
14814: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14815: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14816: this executable through the environment variable @code{GFORTHD}
14817: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14818: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14819: data-relocatable image (because there is no code address offset). The
14820: normal @file{gforth} executable is used for creating the relocatable
14821: image; you can pass the exact filename of this executable through the
14822: environment variable @code{GFORTH}.
1.1 anton 14823:
14824: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14825: @subsection @file{cross.fs}
14826: @cindex @file{cross.fs}
14827: @cindex cross-compiler
14828: @cindex metacompiler
1.47 crook 14829: @cindex target compiler
1.1 anton 14830:
14831: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14832: programming language (@pxref{Cross Compiler}).
1.1 anton 14833:
1.47 crook 14834: @code{cross} allows you to create image files for machines with
1.1 anton 14835: different data sizes and data formats than the one used for generating
14836: the image file. You can also use it to create an application image that
14837: does not contain a Forth compiler. These features are bought with
14838: restrictions and inconveniences in programming. E.g., addresses have to
14839: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14840: order to make the code relocatable.
14841:
14842:
14843: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14844: @section Stack and Dictionary Sizes
14845: @cindex image file, stack and dictionary sizes
14846: @cindex dictionary size default
14847: @cindex stack size default
14848:
14849: If you invoke Gforth with a command line flag for the size
14850: (@pxref{Invoking Gforth}), the size you specify is stored in the
14851: dictionary. If you save the dictionary with @code{savesystem} or create
14852: an image with @file{gforthmi}, this size will become the default
14853: for the resulting image file. E.g., the following will create a
1.21 crook 14854: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14855:
14856: @example
14857: gforthmi gforth.fi -m 1M
14858: @end example
14859:
14860: In other words, if you want to set the default size for the dictionary
14861: and the stacks of an image, just invoke @file{gforthmi} with the
14862: appropriate options when creating the image.
14863:
14864: @cindex stack size, cache-friendly
14865: Note: For cache-friendly behaviour (i.e., good performance), you should
14866: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14867: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14868: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14869:
14870: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14871: @section Running Image Files
14872: @cindex running image files
14873: @cindex invoking image files
14874: @cindex image file invocation
14875:
14876: @cindex -i, invoke image file
14877: @cindex --image file, invoke image file
1.29 crook 14878: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14879: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14880: @example
1.29 crook 14881: gforth -i @i{image}
1.1 anton 14882: @end example
14883:
14884: @cindex executable image file
1.26 crook 14885: @cindex image file, executable
1.1 anton 14886: If your operating system supports starting scripts with a line of the
14887: form @code{#! ...}, you just have to type the image file name to start
14888: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14889: just a convention). I.e., to run Gforth with the image file @i{image},
14890: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14891: This works because every @code{.fi} file starts with a line of this
14892: format:
14893:
14894: @example
14895: #! /usr/local/bin/gforth-0.4.0 -i
14896: @end example
14897:
14898: The file and pathname for the Gforth engine specified on this line is
14899: the specific Gforth executable that it was built against; i.e. the value
14900: of the environment variable @code{GFORTH} at the time that
14901: @file{gforthmi} was executed.
1.1 anton 14902:
1.27 crook 14903: You can make use of the same shell capability to make a Forth source
14904: file into an executable. For example, if you place this text in a file:
1.26 crook 14905:
14906: @example
14907: #! /usr/local/bin/gforth
14908:
14909: ." Hello, world" CR
14910: bye
14911: @end example
14912:
14913: @noindent
1.27 crook 14914: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14915: directly from the command line. The sequence @code{#!} is used in two
14916: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14917: system@footnote{The Unix kernel actually recognises two types of files:
14918: executable files and files of data, where the data is processed by an
14919: interpreter that is specified on the ``interpreter line'' -- the first
14920: line of the file, starting with the sequence #!. There may be a small
14921: limit (e.g., 32) on the number of characters that may be specified on
14922: the interpreter line.} secondly it is treated as a comment character by
14923: Gforth. Because of the second usage, a space is required between
1.80 anton 14924: @code{#!} and the path to the executable (moreover, some Unixes
14925: require the sequence @code{#! /}).
1.27 crook 14926:
14927: The disadvantage of this latter technique, compared with using
1.80 anton 14928: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14929: compiled on-the-fly, each time the program is invoked.
1.26 crook 14930:
1.1 anton 14931: doc-#!
14932:
1.44 crook 14933:
1.1 anton 14934: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14935: @section Modifying the Startup Sequence
14936: @cindex startup sequence for image file
14937: @cindex image file initialization sequence
14938: @cindex initialization sequence of image file
14939:
1.120 anton 14940: You can add your own initialization to the startup sequence of an image
14941: through the deferred word @code{'cold}. @code{'cold} is invoked just
14942: before the image-specific command line processing (i.e., loading files
14943: and evaluating (@code{-e}) strings) starts.
1.1 anton 14944:
14945: A sequence for adding your initialization usually looks like this:
14946:
14947: @example
14948: :noname
14949: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14950: ... \ your stuff
14951: ; IS 'cold
14952: @end example
14953:
1.157 anton 14954: After @code{'cold}, Gforth processes the image options
14955: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
14956: another deferred word. This normally prints Gforth's startup message
14957: and does nothing else.
14958:
1.1 anton 14959: @cindex turnkey image files
1.26 crook 14960: @cindex image file, turnkey applications
1.157 anton 14961: So, if you want to make a turnkey image (i.e., an image for an
14962: application instead of an extended Forth system), you can do this in
14963: two ways:
14964:
14965: @itemize @bullet
14966:
14967: @item
14968: If you want to do your interpretation of the OS command-line
14969: arguments, hook into @code{'cold}. In that case you probably also
14970: want to build the image with @code{gforthmi --application}
14971: (@pxref{gforthmi}) to keep the engine from processing OS command line
14972: options. You can then do your own command-line processing with
14973: @code{next-arg}
14974:
14975: @item
14976: If you want to have the normal Gforth processing of OS command-line
14977: arguments, hook into @code{bootmessage}.
14978:
14979: @end itemize
14980:
14981: In either case, you probably do not want the word that you execute in
14982: these hooks to exit normally, but use @code{bye} or @code{throw}.
14983: Otherwise the Gforth startup process would continue and eventually
14984: present the Forth command line to the user.
1.26 crook 14985:
14986: doc-'cold
1.157 anton 14987: doc-bootmessage
1.44 crook 14988:
1.1 anton 14989: @c ******************************************************************
1.113 anton 14990: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14991: @chapter Engine
14992: @cindex engine
14993: @cindex virtual machine
14994:
1.26 crook 14995: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14996: may be helpful for finding your way in the Gforth sources.
14997:
1.109 anton 14998: The ideas in this section have also been published in the following
14999: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15000: Forth-Tagung '93; M. Anton Ertl,
15001: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15002: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15003: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15004: Threaded code variations and optimizations (extended version)}},
15005: Forth-Tagung '02.
1.1 anton 15006:
15007: @menu
15008: * Portability::
15009: * Threading::
15010: * Primitives::
15011: * Performance::
15012: @end menu
15013:
15014: @node Portability, Threading, Engine, Engine
15015: @section Portability
15016: @cindex engine portability
15017:
1.26 crook 15018: An important goal of the Gforth Project is availability across a wide
15019: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15020: achieved this goal by manually coding the engine in assembly language
15021: for several then-popular processors. This approach is very
15022: labor-intensive and the results are short-lived due to progress in
15023: computer architecture.
1.1 anton 15024:
15025: @cindex C, using C for the engine
15026: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15027: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15028: particularly popular for UNIX-based Forths due to the large variety of
15029: architectures of UNIX machines. Unfortunately an implementation in C
15030: does not mix well with the goals of efficiency and with using
15031: traditional techniques: Indirect or direct threading cannot be expressed
15032: in C, and switch threading, the fastest technique available in C, is
15033: significantly slower. Another problem with C is that it is very
15034: cumbersome to express double integer arithmetic.
15035:
15036: @cindex GNU C for the engine
15037: @cindex long long
15038: Fortunately, there is a portable language that does not have these
15039: limitations: GNU C, the version of C processed by the GNU C compiler
15040: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15041: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15042: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15043: threading possible, its @code{long long} type (@pxref{Long Long, ,
15044: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15045: double numbers on many systems. GNU C is freely available on all
1.1 anton 15046: important (and many unimportant) UNIX machines, VMS, 80386s running
15047: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15048: on all these machines.
15049:
15050: Writing in a portable language has the reputation of producing code that
15051: is slower than assembly. For our Forth engine we repeatedly looked at
15052: the code produced by the compiler and eliminated most compiler-induced
15053: inefficiencies by appropriate changes in the source code.
15054:
15055: @cindex explicit register declarations
15056: @cindex --enable-force-reg, configuration flag
15057: @cindex -DFORCE_REG
15058: However, register allocation cannot be portably influenced by the
15059: programmer, leading to some inefficiencies on register-starved
15060: machines. We use explicit register declarations (@pxref{Explicit Reg
15061: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15062: improve the speed on some machines. They are turned on by using the
15063: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15064: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15065: machine, but also on the compiler version: On some machines some
15066: compiler versions produce incorrect code when certain explicit register
15067: declarations are used. So by default @code{-DFORCE_REG} is not used.
15068:
15069: @node Threading, Primitives, Portability, Engine
15070: @section Threading
15071: @cindex inner interpreter implementation
15072: @cindex threaded code implementation
15073:
15074: @cindex labels as values
15075: GNU C's labels as values extension (available since @code{gcc-2.0},
15076: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15077: makes it possible to take the address of @i{label} by writing
15078: @code{&&@i{label}}. This address can then be used in a statement like
15079: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15080: @code{goto x}.
15081:
1.26 crook 15082: @cindex @code{NEXT}, indirect threaded
1.1 anton 15083: @cindex indirect threaded inner interpreter
15084: @cindex inner interpreter, indirect threaded
1.26 crook 15085: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15086: @example
15087: cfa = *ip++;
15088: ca = *cfa;
15089: goto *ca;
15090: @end example
15091: @cindex instruction pointer
15092: For those unfamiliar with the names: @code{ip} is the Forth instruction
15093: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15094: execution token and points to the code field of the next word to be
15095: executed; The @code{ca} (code address) fetched from there points to some
15096: executable code, e.g., a primitive or the colon definition handler
15097: @code{docol}.
15098:
1.26 crook 15099: @cindex @code{NEXT}, direct threaded
1.1 anton 15100: @cindex direct threaded inner interpreter
15101: @cindex inner interpreter, direct threaded
15102: Direct threading is even simpler:
15103: @example
15104: ca = *ip++;
15105: goto *ca;
15106: @end example
15107:
15108: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15109: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15110:
15111: @menu
15112: * Scheduling::
15113: * Direct or Indirect Threaded?::
1.109 anton 15114: * Dynamic Superinstructions::
1.1 anton 15115: * DOES>::
15116: @end menu
15117:
15118: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15119: @subsection Scheduling
15120: @cindex inner interpreter optimization
15121:
15122: There is a little complication: Pipelined and superscalar processors,
15123: i.e., RISC and some modern CISC machines can process independent
15124: instructions while waiting for the results of an instruction. The
15125: compiler usually reorders (schedules) the instructions in a way that
15126: achieves good usage of these delay slots. However, on our first tries
15127: the compiler did not do well on scheduling primitives. E.g., for
15128: @code{+} implemented as
15129: @example
15130: n=sp[0]+sp[1];
15131: sp++;
15132: sp[0]=n;
15133: NEXT;
15134: @end example
1.81 anton 15135: the @code{NEXT} comes strictly after the other code, i.e., there is
15136: nearly no scheduling. After a little thought the problem becomes clear:
15137: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15138: addresses (and the version of @code{gcc} we used would not know it even
15139: if it was possible), so it could not move the load of the cfa above the
15140: store to the TOS. Indeed the pointers could be the same, if code on or
15141: very near the top of stack were executed. In the interest of speed we
15142: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15143: in scheduling: @code{NEXT} is divided into several parts:
15144: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15145: like:
1.1 anton 15146: @example
1.81 anton 15147: NEXT_P0;
1.1 anton 15148: n=sp[0]+sp[1];
15149: sp++;
15150: NEXT_P1;
15151: sp[0]=n;
15152: NEXT_P2;
15153: @end example
15154:
1.81 anton 15155: There are various schemes that distribute the different operations of
15156: NEXT between these parts in several ways; in general, different schemes
15157: perform best on different processors. We use a scheme for most
15158: architectures that performs well for most processors of this
1.109 anton 15159: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15160: the scheme on installation time.
15161:
1.1 anton 15162:
1.109 anton 15163: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15164: @subsection Direct or Indirect Threaded?
15165: @cindex threading, direct or indirect?
15166:
1.109 anton 15167: Threaded forth code consists of references to primitives (simple machine
15168: code routines like @code{+}) and to non-primitives (e.g., colon
15169: definitions, variables, constants); for a specific class of
15170: non-primitives (e.g., variables) there is one code routine (e.g.,
15171: @code{dovar}), but each variable needs a separate reference to its data.
15172:
15173: Traditionally Forth has been implemented as indirect threaded code,
15174: because this allows to use only one cell to reference a non-primitive
15175: (basically you point to the data, and find the code address there).
15176:
15177: @cindex primitive-centric threaded code
15178: However, threaded code in Gforth (since 0.6.0) uses two cells for
15179: non-primitives, one for the code address, and one for the data address;
15180: the data pointer is an immediate argument for the virtual machine
15181: instruction represented by the code address. We call this
15182: @emph{primitive-centric} threaded code, because all code addresses point
15183: to simple primitives. E.g., for a variable, the code address is for
15184: @code{lit} (also used for integer literals like @code{99}).
15185:
15186: Primitive-centric threaded code allows us to use (faster) direct
15187: threading as dispatch method, completely portably (direct threaded code
15188: in Gforth before 0.6.0 required architecture-specific code). It also
15189: eliminates the performance problems related to I-cache consistency that
15190: 386 implementations have with direct threaded code, and allows
15191: additional optimizations.
15192:
15193: @cindex hybrid direct/indirect threaded code
15194: There is a catch, however: the @var{xt} parameter of @code{execute} can
15195: occupy only one cell, so how do we pass non-primitives with their code
15196: @emph{and} data addresses to them? Our answer is to use indirect
15197: threaded dispatch for @code{execute} and other words that use a
15198: single-cell xt. So, normal threaded code in colon definitions uses
15199: direct threading, and @code{execute} and similar words, which dispatch
15200: to xts on the data stack, use indirect threaded code. We call this
15201: @emph{hybrid direct/indirect} threaded code.
15202:
15203: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15204: @cindex gforth engine
15205: @cindex gforth-fast engine
15206: The engines @command{gforth} and @command{gforth-fast} use hybrid
15207: direct/indirect threaded code. This means that with these engines you
15208: cannot use @code{,} to compile an xt. Instead, you have to use
15209: @code{compile,}.
15210:
15211: @cindex gforth-itc engine
1.115 anton 15212: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15213: This engine uses plain old indirect threaded code. It still compiles in
15214: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15215: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15216: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15217: and execute @code{' , is compile,}. Your program can check if it is
15218: running on a hybrid direct/indirect threaded engine or a pure indirect
15219: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15220:
15221:
15222: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15223: @subsection Dynamic Superinstructions
15224: @cindex Dynamic superinstructions with replication
15225: @cindex Superinstructions
15226: @cindex Replication
15227:
15228: The engines @command{gforth} and @command{gforth-fast} use another
15229: optimization: Dynamic superinstructions with replication. As an
15230: example, consider the following colon definition:
15231:
15232: @example
15233: : squared ( n1 -- n2 )
15234: dup * ;
15235: @end example
15236:
15237: Gforth compiles this into the threaded code sequence
15238:
15239: @example
15240: dup
15241: *
15242: ;s
15243: @end example
15244:
15245: In normal direct threaded code there is a code address occupying one
15246: cell for each of these primitives. Each code address points to a
15247: machine code routine, and the interpreter jumps to this machine code in
15248: order to execute the primitive. The routines for these three
15249: primitives are (in @command{gforth-fast} on the 386):
15250:
15251: @example
15252: Code dup
15253: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15254: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15255: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15256: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15257: end-code
15258: Code *
15259: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15260: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15261: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15262: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15263: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15264: end-code
15265: Code ;s
15266: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15267: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15268: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15269: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15270: end-code
15271: @end example
15272:
15273: With dynamic superinstructions and replication the compiler does not
15274: just lay down the threaded code, but also copies the machine code
15275: fragments, usually without the jump at the end.
15276:
15277: @example
15278: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15279: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15280: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15281: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15282: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15283: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15284: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15285: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15286: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15287: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15288: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15289: @end example
15290:
15291: Only when a threaded-code control-flow change happens (e.g., in
15292: @code{;s}), the jump is appended. This optimization eliminates many of
15293: these jumps and makes the rest much more predictable. The speedup
15294: depends on the processor and the application; on the Athlon and Pentium
15295: III this optimization typically produces a speedup by a factor of 2.
15296:
15297: The code addresses in the direct-threaded code are set to point to the
15298: appropriate points in the copied machine code, in this example like
15299: this:
1.1 anton 15300:
1.109 anton 15301: @example
15302: primitive code address
15303: dup $4057D27D
15304: * $4057D286
15305: ;s $4057D292
15306: @end example
15307:
15308: Thus there can be threaded-code jumps to any place in this piece of
15309: code. This also simplifies decompilation quite a bit.
15310:
15311: @cindex --no-dynamic command-line option
15312: @cindex --no-super command-line option
15313: You can disable this optimization with @option{--no-dynamic}. You can
15314: use the copying without eliminating the jumps (i.e., dynamic
15315: replication, but without superinstructions) with @option{--no-super};
15316: this gives the branch prediction benefit alone; the effect on
1.110 anton 15317: performance depends on the CPU; on the Athlon and Pentium III the
15318: speedup is a little less than for dynamic superinstructions with
15319: replication.
15320:
15321: @cindex patching threaded code
15322: One use of these options is if you want to patch the threaded code.
15323: With superinstructions, many of the dispatch jumps are eliminated, so
15324: patching often has no effect. These options preserve all the dispatch
15325: jumps.
1.109 anton 15326:
15327: @cindex --dynamic command-line option
1.110 anton 15328: On some machines dynamic superinstructions are disabled by default,
15329: because it is unsafe on these machines. However, if you feel
15330: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15331:
15332: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15333: @subsection DOES>
15334: @cindex @code{DOES>} implementation
15335:
1.26 crook 15336: @cindex @code{dodoes} routine
15337: @cindex @code{DOES>}-code
1.1 anton 15338: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15339: the chunk of code executed by every word defined by a
1.109 anton 15340: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15341: this is only needed if the xt of the word is @code{execute}d. The main
15342: problem here is: How to find the Forth code to be executed, i.e. the
15343: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15344: solutions:
1.1 anton 15345:
1.21 crook 15346: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15347: @code{DOES>}-code address is stored in the cell after the code address
15348: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15349: illegal in the Forth-79 and all later standards, because in fig-Forth
15350: this address lies in the body (which is illegal in these
15351: standards). However, by making the code field larger for all words this
15352: solution becomes legal again. We use this approach. Leaving a cell
15353: unused in most words is a bit wasteful, but on the machines we are
15354: targeting this is hardly a problem.
15355:
1.1 anton 15356:
15357: @node Primitives, Performance, Threading, Engine
15358: @section Primitives
15359: @cindex primitives, implementation
15360: @cindex virtual machine instructions, implementation
15361:
15362: @menu
15363: * Automatic Generation::
15364: * TOS Optimization::
15365: * Produced code::
15366: @end menu
15367:
15368: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15369: @subsection Automatic Generation
15370: @cindex primitives, automatic generation
15371:
15372: @cindex @file{prims2x.fs}
1.109 anton 15373:
1.1 anton 15374: Since the primitives are implemented in a portable language, there is no
15375: longer any need to minimize the number of primitives. On the contrary,
15376: having many primitives has an advantage: speed. In order to reduce the
15377: number of errors in primitives and to make programming them easier, we
1.109 anton 15378: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15379: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15380: generates most (and sometimes all) of the C code for a primitive from
15381: the stack effect notation. The source for a primitive has the following
15382: form:
1.1 anton 15383:
15384: @cindex primitive source format
15385: @format
1.58 anton 15386: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15387: [@code{""}@i{glossary entry}@code{""}]
15388: @i{C code}
1.1 anton 15389: [@code{:}
1.29 crook 15390: @i{Forth code}]
1.1 anton 15391: @end format
15392:
15393: The items in brackets are optional. The category and glossary fields
15394: are there for generating the documentation, the Forth code is there
15395: for manual implementations on machines without GNU C. E.g., the source
15396: for the primitive @code{+} is:
15397: @example
1.58 anton 15398: + ( n1 n2 -- n ) core plus
1.1 anton 15399: n = n1+n2;
15400: @end example
15401:
15402: This looks like a specification, but in fact @code{n = n1+n2} is C
15403: code. Our primitive generation tool extracts a lot of information from
15404: the stack effect notations@footnote{We use a one-stack notation, even
15405: though we have separate data and floating-point stacks; The separate
15406: notation can be generated easily from the unified notation.}: The number
15407: of items popped from and pushed on the stack, their type, and by what
15408: name they are referred to in the C code. It then generates a C code
15409: prelude and postlude for each primitive. The final C code for @code{+}
15410: looks like this:
15411:
15412: @example
1.46 pazsan 15413: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15414: /* */ /* documentation */
1.81 anton 15415: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15416: @{
15417: DEF_CA /* definition of variable ca (indirect threading) */
15418: Cell n1; /* definitions of variables */
15419: Cell n2;
15420: Cell n;
1.81 anton 15421: NEXT_P0; /* NEXT part 0 */
1.1 anton 15422: n1 = (Cell) sp[1]; /* input */
15423: n2 = (Cell) TOS;
15424: sp += 1; /* stack adjustment */
15425: @{
15426: n = n1+n2; /* C code taken from the source */
15427: @}
15428: NEXT_P1; /* NEXT part 1 */
15429: TOS = (Cell)n; /* output */
15430: NEXT_P2; /* NEXT part 2 */
15431: @}
15432: @end example
15433:
15434: This looks long and inefficient, but the GNU C compiler optimizes quite
15435: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15436: HP RISC machines: Defining the @code{n}s does not produce any code, and
15437: using them as intermediate storage also adds no cost.
15438:
1.26 crook 15439: There are also other optimizations that are not illustrated by this
15440: example: assignments between simple variables are usually for free (copy
1.1 anton 15441: propagation). If one of the stack items is not used by the primitive
15442: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15443: (dead code elimination). On the other hand, there are some things that
15444: the compiler does not do, therefore they are performed by
15445: @file{prims2x.fs}: The compiler does not optimize code away that stores
15446: a stack item to the place where it just came from (e.g., @code{over}).
15447:
15448: While programming a primitive is usually easy, there are a few cases
15449: where the programmer has to take the actions of the generator into
15450: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15451: fall through to @code{NEXT}.
1.109 anton 15452:
15453: For more information
1.1 anton 15454:
15455: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15456: @subsection TOS Optimization
15457: @cindex TOS optimization for primitives
15458: @cindex primitives, keeping the TOS in a register
15459:
15460: An important optimization for stack machine emulators, e.g., Forth
15461: engines, is keeping one or more of the top stack items in
1.29 crook 15462: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15463: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15464: @itemize @bullet
15465: @item
1.29 crook 15466: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15467: due to fewer loads from and stores to the stack.
1.29 crook 15468: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15469: @i{y<n}, due to additional moves between registers.
1.1 anton 15470: @end itemize
15471:
15472: @cindex -DUSE_TOS
15473: @cindex -DUSE_NO_TOS
15474: In particular, keeping one item in a register is never a disadvantage,
15475: if there are enough registers. Keeping two items in registers is a
15476: disadvantage for frequent words like @code{?branch}, constants,
15477: variables, literals and @code{i}. Therefore our generator only produces
15478: code that keeps zero or one items in registers. The generated C code
15479: covers both cases; the selection between these alternatives is made at
15480: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15481: code for @code{+} is just a simple variable name in the one-item case,
15482: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15483: GNU C compiler tries to keep simple variables like @code{TOS} in
15484: registers, and it usually succeeds, if there are enough registers.
15485:
15486: @cindex -DUSE_FTOS
15487: @cindex -DUSE_NO_FTOS
15488: The primitive generator performs the TOS optimization for the
15489: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15490: operations the benefit of this optimization is even larger:
15491: floating-point operations take quite long on most processors, but can be
15492: performed in parallel with other operations as long as their results are
15493: not used. If the FP-TOS is kept in a register, this works. If
15494: it is kept on the stack, i.e., in memory, the store into memory has to
15495: wait for the result of the floating-point operation, lengthening the
15496: execution time of the primitive considerably.
15497:
15498: The TOS optimization makes the automatic generation of primitives a
15499: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15500: @code{TOS} is not sufficient. There are some special cases to
15501: consider:
15502: @itemize @bullet
15503: @item In the case of @code{dup ( w -- w w )} the generator must not
15504: eliminate the store to the original location of the item on the stack,
15505: if the TOS optimization is turned on.
15506: @item Primitives with stack effects of the form @code{--}
1.29 crook 15507: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15508: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15509: must load the TOS from the stack at the end. But for the null stack
15510: effect @code{--} no stores or loads should be generated.
15511: @end itemize
15512:
15513: @node Produced code, , TOS Optimization, Primitives
15514: @subsection Produced code
15515: @cindex primitives, assembly code listing
15516:
15517: @cindex @file{engine.s}
15518: To see what assembly code is produced for the primitives on your machine
15519: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15520: look at the resulting file @file{engine.s}. Alternatively, you can also
15521: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15522:
15523: @node Performance, , Primitives, Engine
15524: @section Performance
15525: @cindex performance of some Forth interpreters
15526: @cindex engine performance
15527: @cindex benchmarking Forth systems
15528: @cindex Gforth performance
15529:
15530: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15531: impossible to write a significantly faster threaded-code engine.
1.1 anton 15532:
15533: On register-starved machines like the 386 architecture processors
15534: improvements are possible, because @code{gcc} does not utilize the
15535: registers as well as a human, even with explicit register declarations;
15536: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15537: and hand-tuned it for the 486; this system is 1.19 times faster on the
15538: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15539: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15540: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15541: registers fit in real registers (and we can even afford to use the TOS
15542: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15543: earlier results. And dynamic superinstructions provide another speedup
15544: (but only around a factor 1.2 on the 486).
1.1 anton 15545:
15546: @cindex Win32Forth performance
15547: @cindex NT Forth performance
15548: @cindex eforth performance
15549: @cindex ThisForth performance
15550: @cindex PFE performance
15551: @cindex TILE performance
1.81 anton 15552: The potential advantage of assembly language implementations is not
1.112 anton 15553: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15554: (direct threaded, compiled with @code{gcc-2.95.1} and
15555: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15556: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15557: (with and without peephole (aka pinhole) optimization of the threaded
15558: code); all these systems were written in assembly language. We also
15559: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15560: with @code{gcc-2.6.3} with the default configuration for Linux:
15561: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15562: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15563: employs peephole optimization of the threaded code) and TILE (compiled
15564: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15565: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15566: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15567: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15568: then extended it to run the benchmarks, added the peephole optimizer,
15569: ran the benchmarks and reported the results.
1.40 anton 15570:
1.1 anton 15571: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15572: matrix multiplication come from the Stanford integer benchmarks and have
15573: been translated into Forth by Martin Fraeman; we used the versions
15574: included in the TILE Forth package, but with bigger data set sizes; and
15575: a recursive Fibonacci number computation for benchmarking calling
15576: performance. The following table shows the time taken for the benchmarks
15577: scaled by the time taken by Gforth (in other words, it shows the speedup
15578: factor that Gforth achieved over the other systems).
15579:
15580: @example
1.112 anton 15581: relative Win32- NT eforth This-
15582: time Gforth Forth Forth eforth +opt PFE Forth TILE
15583: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15584: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15585: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15586: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15587: @end example
15588:
1.26 crook 15589: You may be quite surprised by the good performance of Gforth when
15590: compared with systems written in assembly language. One important reason
15591: for the disappointing performance of these other systems is probably
15592: that they are not written optimally for the 486 (e.g., they use the
15593: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15594: but costly method for relocating the Forth image: like @code{cforth}, it
15595: computes the actual addresses at run time, resulting in two address
15596: computations per @code{NEXT} (@pxref{Image File Background}).
15597:
1.1 anton 15598: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15599: explained with the self-imposed restriction of the latter systems to
15600: standard C, which makes efficient threading impossible (however, the
1.4 anton 15601: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15602: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15603: Moreover, current C compilers have a hard time optimizing other aspects
15604: of the ThisForth and the TILE source.
15605:
1.26 crook 15606: The performance of Gforth on 386 architecture processors varies widely
15607: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15608: allocate any of the virtual machine registers into real machine
15609: registers by itself and would not work correctly with explicit register
1.112 anton 15610: declarations, giving a significantly slower engine (on a 486DX2/66
15611: running the Sieve) than the one measured above.
1.1 anton 15612:
1.26 crook 15613: Note that there have been several releases of Win32Forth since the
15614: release presented here, so the results presented above may have little
1.40 anton 15615: predictive value for the performance of Win32Forth today (results for
15616: the current release on an i486DX2/66 are welcome).
1.1 anton 15617:
15618: @cindex @file{Benchres}
1.66 anton 15619: In
15620: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15621: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15622: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15623: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15624: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15625: than the version used here. You can find a newer version of these
15626: measurements at
1.47 crook 15627: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15628: find numbers for Gforth on various machines in @file{Benchres}.
15629:
1.26 crook 15630: @c ******************************************************************
1.113 anton 15631: @c @node Binding to System Library, Cross Compiler, Engine, Top
15632: @c @chapter Binding to System Library
1.13 pazsan 15633:
1.113 anton 15634: @c ****************************************************************
15635: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15636: @chapter Cross Compiler
1.47 crook 15637: @cindex @file{cross.fs}
15638: @cindex cross-compiler
15639: @cindex metacompiler
15640: @cindex target compiler
1.13 pazsan 15641:
1.46 pazsan 15642: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15643: mostly written in Forth, including crucial parts like the outer
15644: interpreter and compiler, it needs compiled Forth code to get
15645: started. The cross compiler allows to create new images for other
15646: architectures, even running under another Forth system.
1.13 pazsan 15647:
15648: @menu
1.67 anton 15649: * Using the Cross Compiler::
15650: * How the Cross Compiler Works::
1.13 pazsan 15651: @end menu
15652:
1.21 crook 15653: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15654: @section Using the Cross Compiler
1.46 pazsan 15655:
15656: The cross compiler uses a language that resembles Forth, but isn't. The
15657: main difference is that you can execute Forth code after definition,
15658: while you usually can't execute the code compiled by cross, because the
15659: code you are compiling is typically for a different computer than the
15660: one you are compiling on.
15661:
1.81 anton 15662: @c anton: This chapter is somewhat different from waht I would expect: I
15663: @c would expect an explanation of the cross language and how to create an
15664: @c application image with it. The section explains some aspects of
15665: @c creating a Gforth kernel.
15666:
1.46 pazsan 15667: The Makefile is already set up to allow you to create kernels for new
15668: architectures with a simple make command. The generic kernels using the
15669: GCC compiled virtual machine are created in the normal build process
15670: with @code{make}. To create a embedded Gforth executable for e.g. the
15671: 8086 processor (running on a DOS machine), type
15672:
15673: @example
15674: make kernl-8086.fi
15675: @end example
15676:
15677: This will use the machine description from the @file{arch/8086}
15678: directory to create a new kernel. A machine file may look like that:
15679:
15680: @example
15681: \ Parameter for target systems 06oct92py
15682:
15683: 4 Constant cell \ cell size in bytes
15684: 2 Constant cell<< \ cell shift to bytes
15685: 5 Constant cell>bit \ cell shift to bits
15686: 8 Constant bits/char \ bits per character
15687: 8 Constant bits/byte \ bits per byte [default: 8]
15688: 8 Constant float \ bytes per float
15689: 8 Constant /maxalign \ maximum alignment in bytes
15690: false Constant bigendian \ byte order
15691: ( true=big, false=little )
15692:
15693: include machpc.fs \ feature list
15694: @end example
15695:
15696: This part is obligatory for the cross compiler itself, the feature list
15697: is used by the kernel to conditionally compile some features in and out,
15698: depending on whether the target supports these features.
15699:
15700: There are some optional features, if you define your own primitives,
15701: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15702: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15703: @code{prims-include} includes primitives, and @code{>boot} prepares for
15704: booting.
15705:
15706: @example
15707: : asm-include ." Include assembler" cr
15708: s" arch/8086/asm.fs" included ;
15709:
15710: : prims-include ." Include primitives" cr
15711: s" arch/8086/prim.fs" included ;
15712:
15713: : >boot ." Prepare booting" cr
15714: s" ' boot >body into-forth 1+ !" evaluate ;
15715: @end example
15716:
15717: These words are used as sort of macro during the cross compilation in
1.81 anton 15718: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15719: be possible --- but more complicated --- to write a new kernel project
15720: file, too.
15721:
15722: @file{kernel/main.fs} expects the machine description file name on the
15723: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15724: @code{mach-file} leaves a counted string on the stack, or
15725: @code{machine-file} leaves an address, count pair of the filename on the
15726: stack.
15727:
15728: The feature list is typically controlled using @code{SetValue}, generic
15729: files that are used by several projects can use @code{DefaultValue}
15730: instead. Both functions work like @code{Value}, when the value isn't
15731: defined, but @code{SetValue} works like @code{to} if the value is
15732: defined, and @code{DefaultValue} doesn't set anything, if the value is
15733: defined.
15734:
15735: @example
15736: \ generic mach file for pc gforth 03sep97jaw
15737:
15738: true DefaultValue NIL \ relocating
15739:
15740: >ENVIRON
15741:
15742: true DefaultValue file \ controls the presence of the
15743: \ file access wordset
15744: true DefaultValue OS \ flag to indicate a operating system
15745:
15746: true DefaultValue prims \ true: primitives are c-code
15747:
15748: true DefaultValue floating \ floating point wordset is present
15749:
15750: true DefaultValue glocals \ gforth locals are present
15751: \ will be loaded
15752: true DefaultValue dcomps \ double number comparisons
15753:
15754: true DefaultValue hash \ hashing primitives are loaded/present
15755:
15756: true DefaultValue xconds \ used together with glocals,
15757: \ special conditionals supporting gforths'
15758: \ local variables
15759: true DefaultValue header \ save a header information
15760:
15761: true DefaultValue backtrace \ enables backtrace code
15762:
15763: false DefaultValue ec
15764: false DefaultValue crlf
15765:
15766: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15767:
15768: &16 KB DefaultValue stack-size
15769: &15 KB &512 + DefaultValue fstack-size
15770: &15 KB DefaultValue rstack-size
15771: &14 KB &512 + DefaultValue lstack-size
15772: @end example
1.13 pazsan 15773:
1.48 anton 15774: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15775: @section How the Cross Compiler Works
1.13 pazsan 15776:
15777: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15778: @appendix Bugs
1.1 anton 15779: @cindex bug reporting
15780:
1.21 crook 15781: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15782:
1.103 anton 15783: If you find a bug, please submit a bug report through
15784: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15785:
15786: @itemize @bullet
15787: @item
1.81 anton 15788: A program (or a sequence of keyboard commands) that reproduces the bug.
15789: @item
15790: A description of what you think constitutes the buggy behaviour.
15791: @item
1.21 crook 15792: The Gforth version used (it is announced at the start of an
15793: interactive Gforth session).
15794: @item
15795: The machine and operating system (on Unix
15796: systems @code{uname -a} will report this information).
15797: @item
1.81 anton 15798: The installation options (you can find the configure options at the
15799: start of @file{config.status}) and configuration (@code{configure}
15800: output or @file{config.cache}).
1.21 crook 15801: @item
15802: A complete list of changes (if any) you (or your installer) have made to the
15803: Gforth sources.
15804: @end itemize
1.1 anton 15805:
15806: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15807: to Report Bugs, gcc.info, GNU C Manual}.
15808:
15809:
1.21 crook 15810: @node Origin, Forth-related information, Bugs, Top
15811: @appendix Authors and Ancestors of Gforth
1.1 anton 15812:
15813: @section Authors and Contributors
15814: @cindex authors of Gforth
15815: @cindex contributors to Gforth
15816:
15817: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15818: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15819: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 15820: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
15821: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
15822: and Stuart Ramsden inspired us with their continuous feedback. Lennart
15823: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
15824: working on automatic support for calling C libraries. Helpful comments
15825: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
15826: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
15827: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
15828: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
15829: comments from many others; thank you all, sorry for not listing you
15830: here (but digging through my mailbox to extract your names is on my
15831: to-do list).
1.1 anton 15832:
15833: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15834: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15835: was developed across the Internet, and its authors did not meet
1.20 pazsan 15836: physically for the first 4 years of development.
1.1 anton 15837:
15838: @section Pedigree
1.26 crook 15839: @cindex pedigree of Gforth
1.1 anton 15840:
1.81 anton 15841: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15842: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15843:
1.20 pazsan 15844: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15845: 32 bit native code version of VolksForth for the Atari ST, written
15846: mostly by Dietrich Weineck.
15847:
1.81 anton 15848: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15849: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 15850: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 15851:
1.147 anton 15852: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15853: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 15854:
15855: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15856: 1979. Robert Selzer and Bill Ragsdale developed the original
15857: implementation of fig-Forth for the 6502 based on microForth.
15858:
15859: The principal architect of microForth was Dean Sanderson. microForth was
15860: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15861: the 1802, and subsequently implemented on the 8080, the 6800 and the
15862: Z80.
15863:
15864: All earlier Forth systems were custom-made, usually by Charles Moore,
15865: who discovered (as he puts it) Forth during the late 60s. The first full
15866: Forth existed in 1971.
15867:
1.81 anton 15868: A part of the information in this section comes from
15869: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15870: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 15871: Charles H. Moore, presented at the HOPL-II conference and preprinted
15872: in SIGPLAN Notices 28(3), 1993. You can find more historical and
15873: genealogical information about Forth there. For a more general (and
15874: graphical) Forth family tree look see
15875: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15876: Forth Family Tree and Timeline}.
1.1 anton 15877:
1.81 anton 15878: @c ------------------------------------------------------------------
1.113 anton 15879: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15880: @appendix Other Forth-related information
15881: @cindex Forth-related information
15882:
1.81 anton 15883: @c anton: I threw most of this stuff out, because it can be found through
15884: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15885:
15886: @cindex comp.lang.forth
15887: @cindex frequently asked questions
1.81 anton 15888: There is an active news group (comp.lang.forth) discussing Forth
15889: (including Gforth) and Forth-related issues. Its
15890: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15891: (frequently asked questions and their answers) contains a lot of
15892: information on Forth. You should read it before posting to
15893: comp.lang.forth.
1.21 crook 15894:
1.81 anton 15895: The ANS Forth standard is most usable in its
15896: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15897:
1.113 anton 15898: @c ---------------------------------------------------
15899: @node Licenses, Word Index, Forth-related information, Top
15900: @appendix Licenses
15901:
15902: @menu
15903: * GNU Free Documentation License:: License for copying this manual.
15904: * Copying:: GPL (for copying this software).
15905: @end menu
15906:
15907: @include fdl.texi
15908:
15909: @include gpl.texi
15910:
15911:
15912:
1.81 anton 15913: @c ------------------------------------------------------------------
1.113 anton 15914: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15915: @unnumbered Word Index
15916:
1.26 crook 15917: This index is a list of Forth words that have ``glossary'' entries
15918: within this manual. Each word is listed with its stack effect and
15919: wordset.
1.1 anton 15920:
15921: @printindex fn
15922:
1.81 anton 15923: @c anton: the name index seems superfluous given the word and concept indices.
15924:
15925: @c @node Name Index, Concept Index, Word Index, Top
15926: @c @unnumbered Name Index
1.41 anton 15927:
1.81 anton 15928: @c This index is a list of Forth words that have ``glossary'' entries
15929: @c within this manual.
1.41 anton 15930:
1.81 anton 15931: @c @printindex ky
1.41 anton 15932:
1.113 anton 15933: @c -------------------------------------------------------
1.81 anton 15934: @node Concept Index, , Word Index, Top
1.1 anton 15935: @unnumbered Concept and Word Index
15936:
1.26 crook 15937: Not all entries listed in this index are present verbatim in the
15938: text. This index also duplicates, in abbreviated form, all of the words
15939: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15940:
15941: @printindex cp
15942:
15943: @bye
1.81 anton 15944:
15945:
1.1 anton 15946:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>