Annotation of gforth/doc/gforth.ds, revision 1.178
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.178 ! anton 334: * Terminal output:: Cursor positioning etc.
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::
1.178 ! anton 410: * C interface internals::
1.155 anton 411: * Low-Level C Interface Words::
412:
1.78 anton 413: Assembler and Code Words
414:
415: * Code and ;code::
416: * Common Assembler:: Assembler Syntax
417: * Common Disassembler::
418: * 386 Assembler:: Deviations and special cases
419: * Alpha Assembler:: Deviations and special cases
420: * MIPS assembler:: Deviations and special cases
1.167 anton 421: * PowerPC assembler:: Deviations and special cases
1.78 anton 422: * Other assemblers:: How to write them
423:
1.12 anton 424: Tools
425:
426: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 427: * Stack depth changes:: Where does this stack item come from?
1.12 anton 428:
429: ANS conformance
430:
431: * The Core Words::
432: * The optional Block word set::
433: * The optional Double Number word set::
434: * The optional Exception word set::
435: * The optional Facility word set::
436: * The optional File-Access word set::
437: * The optional Floating-Point word set::
438: * The optional Locals word set::
439: * The optional Memory-Allocation word set::
440: * The optional Programming-Tools word set::
441: * The optional Search-Order word set::
442:
443: The Core Words
444:
445: * core-idef:: Implementation Defined Options
446: * core-ambcond:: Ambiguous Conditions
447: * core-other:: Other System Documentation
448:
449: The optional Block word set
450:
451: * block-idef:: Implementation Defined Options
452: * block-ambcond:: Ambiguous Conditions
453: * block-other:: Other System Documentation
454:
455: The optional Double Number word set
456:
457: * double-ambcond:: Ambiguous Conditions
458:
459: The optional Exception word set
460:
461: * exception-idef:: Implementation Defined Options
462:
463: The optional Facility word set
464:
465: * facility-idef:: Implementation Defined Options
466: * facility-ambcond:: Ambiguous Conditions
467:
468: The optional File-Access word set
469:
470: * file-idef:: Implementation Defined Options
471: * file-ambcond:: Ambiguous Conditions
472:
473: The optional Floating-Point word set
474:
475: * floating-idef:: Implementation Defined Options
476: * floating-ambcond:: Ambiguous Conditions
477:
478: The optional Locals word set
479:
480: * locals-idef:: Implementation Defined Options
481: * locals-ambcond:: Ambiguous Conditions
482:
483: The optional Memory-Allocation word set
484:
485: * memory-idef:: Implementation Defined Options
486:
487: The optional Programming-Tools word set
488:
489: * programming-idef:: Implementation Defined Options
490: * programming-ambcond:: Ambiguous Conditions
491:
492: The optional Search-Order word set
493:
494: * search-idef:: Implementation Defined Options
495: * search-ambcond:: Ambiguous Conditions
496:
1.109 anton 497: Emacs and Gforth
498:
499: * Installing gforth.el:: Making Emacs aware of Forth.
500: * Emacs Tags:: Viewing the source of a word in Emacs.
501: * Hilighting:: Making Forth code look prettier.
502: * Auto-Indentation:: Customizing auto-indentation.
503: * Blocks Files:: Reading and writing blocks files.
504:
1.12 anton 505: Image Files
506:
1.24 anton 507: * Image Licensing Issues:: Distribution terms for images.
508: * Image File Background:: Why have image files?
1.67 anton 509: * Non-Relocatable Image Files:: don't always work.
1.24 anton 510: * Data-Relocatable Image Files:: are better.
1.67 anton 511: * Fully Relocatable Image Files:: better yet.
1.24 anton 512: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 513: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 514: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 515:
516: Fully Relocatable Image Files
517:
1.27 crook 518: * gforthmi:: The normal way
1.12 anton 519: * cross.fs:: The hard way
520:
521: Engine
522:
523: * Portability::
524: * Threading::
525: * Primitives::
526: * Performance::
527:
528: Threading
529:
530: * Scheduling::
531: * Direct or Indirect Threaded?::
1.109 anton 532: * Dynamic Superinstructions::
1.12 anton 533: * DOES>::
534:
535: Primitives
536:
537: * Automatic Generation::
538: * TOS Optimization::
539: * Produced code::
1.13 pazsan 540:
541: Cross Compiler
542:
1.67 anton 543: * Using the Cross Compiler::
544: * How the Cross Compiler Works::
1.13 pazsan 545:
1.113 anton 546: Licenses
547:
548: * GNU Free Documentation License:: License for copying this manual.
549: * Copying:: GPL (for copying this software).
550:
1.24 anton 551: @end detailmenu
1.1 anton 552: @end menu
553:
1.113 anton 554: @c ----------------------------------------------------------
1.1 anton 555: @iftex
556: @unnumbered Preface
557: @cindex Preface
1.21 crook 558: This manual documents Gforth. Some introductory material is provided for
559: readers who are unfamiliar with Forth or who are migrating to Gforth
560: from other Forth compilers. However, this manual is primarily a
561: reference manual.
1.1 anton 562: @end iftex
563:
1.28 crook 564: @comment TODO much more blurb here.
1.26 crook 565:
566: @c ******************************************************************
1.113 anton 567: @node Goals, Gforth Environment, Top, Top
1.26 crook 568: @comment node-name, next, previous, up
569: @chapter Goals of Gforth
570: @cindex goals of the Gforth project
571: The goal of the Gforth Project is to develop a standard model for
572: ANS Forth. This can be split into several subgoals:
573:
574: @itemize @bullet
575: @item
576: Gforth should conform to the ANS Forth Standard.
577: @item
578: It should be a model, i.e. it should define all the
579: implementation-dependent things.
580: @item
581: It should become standard, i.e. widely accepted and used. This goal
582: is the most difficult one.
583: @end itemize
584:
585: To achieve these goals Gforth should be
586: @itemize @bullet
587: @item
588: Similar to previous models (fig-Forth, F83)
589: @item
590: Powerful. It should provide for all the things that are considered
591: necessary today and even some that are not yet considered necessary.
592: @item
593: Efficient. It should not get the reputation of being exceptionally
594: slow.
595: @item
596: Free.
597: @item
598: Available on many machines/easy to port.
599: @end itemize
600:
601: Have we achieved these goals? Gforth conforms to the ANS Forth
602: standard. It may be considered a model, but we have not yet documented
603: which parts of the model are stable and which parts we are likely to
604: change. It certainly has not yet become a de facto standard, but it
605: appears to be quite popular. It has some similarities to and some
606: differences from previous models. It has some powerful features, but not
607: yet everything that we envisioned. We certainly have achieved our
1.65 anton 608: execution speed goals (@pxref{Performance})@footnote{However, in 1998
609: the bar was raised when the major commercial Forth vendors switched to
610: native code compilers.}. It is free and available on many machines.
1.29 crook 611:
1.26 crook 612: @c ******************************************************************
1.48 anton 613: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 614: @chapter Gforth Environment
615: @cindex Gforth environment
1.21 crook 616:
1.45 crook 617: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 618: material in this chapter.
1.21 crook 619:
620: @menu
1.29 crook 621: * Invoking Gforth:: Getting in
622: * Leaving Gforth:: Getting out
623: * Command-line editing::
1.48 anton 624: * Environment variables:: that affect how Gforth starts up
1.29 crook 625: * Gforth Files:: What gets installed and where
1.112 anton 626: * Gforth in pipes::
1.48 anton 627: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 628: @end menu
629:
1.49 anton 630: For related information about the creation of images see @ref{Image Files}.
1.29 crook 631:
1.21 crook 632: @comment ----------------------------------------------
1.48 anton 633: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 634: @section Invoking Gforth
635: @cindex invoking Gforth
636: @cindex running Gforth
637: @cindex command-line options
638: @cindex options on the command line
639: @cindex flags on the command line
1.21 crook 640:
1.30 anton 641: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 642: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 643: will usually just say @code{gforth} -- this automatically loads the
644: default image file @file{gforth.fi}. In many other cases the default
645: Gforth image will be invoked like this:
1.21 crook 646: @example
1.30 anton 647: gforth [file | -e forth-code] ...
1.21 crook 648: @end example
1.29 crook 649: @noindent
650: This interprets the contents of the files and the Forth code in the order they
651: are given.
1.21 crook 652:
1.109 anton 653: In addition to the @command{gforth} engine, there is also an engine
654: called @command{gforth-fast}, which is faster, but gives less
655: informative error messages (@pxref{Error messages}) and may catch some
1.166 anton 656: errors (in particular, stack underflows and integer division errors)
657: later or not at all. You should use it for debugged,
1.109 anton 658: performance-critical programs.
659:
660: Moreover, there is an engine called @command{gforth-itc}, which is
661: useful in some backwards-compatibility situations (@pxref{Direct or
662: Indirect Threaded?}).
1.30 anton 663:
1.29 crook 664: In general, the command line looks like this:
1.21 crook 665:
666: @example
1.30 anton 667: gforth[-fast] [engine options] [image options]
1.21 crook 668: @end example
669:
1.30 anton 670: The engine options must come before the rest of the command
1.29 crook 671: line. They are:
1.26 crook 672:
1.29 crook 673: @table @code
674: @cindex -i, command-line option
675: @cindex --image-file, command-line option
676: @item --image-file @i{file}
677: @itemx -i @i{file}
678: Loads the Forth image @i{file} instead of the default
679: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 680:
1.39 anton 681: @cindex --appl-image, command-line option
682: @item --appl-image @i{file}
683: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 684: to the image (instead of processing them as engine options). This is
685: useful for building executable application images on Unix, built with
1.39 anton 686: @code{gforthmi --application ...}.
687:
1.29 crook 688: @cindex --path, command-line option
689: @cindex -p, command-line option
690: @item --path @i{path}
691: @itemx -p @i{path}
692: Uses @i{path} for searching the image file and Forth source code files
693: instead of the default in the environment variable @code{GFORTHPATH} or
694: the path specified at installation time (e.g.,
695: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
696: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 697:
1.29 crook 698: @cindex --dictionary-size, command-line option
699: @cindex -m, command-line option
700: @cindex @i{size} parameters for command-line options
701: @cindex size of the dictionary and the stacks
702: @item --dictionary-size @i{size}
703: @itemx -m @i{size}
704: Allocate @i{size} space for the Forth dictionary space instead of
705: using the default specified in the image (typically 256K). The
706: @i{size} specification for this and subsequent options consists of
707: an integer and a unit (e.g.,
708: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
709: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
710: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
711: @code{e} is used.
1.21 crook 712:
1.29 crook 713: @cindex --data-stack-size, command-line option
714: @cindex -d, command-line option
715: @item --data-stack-size @i{size}
716: @itemx -d @i{size}
717: Allocate @i{size} space for the data stack instead of using the
718: default specified in the image (typically 16K).
1.21 crook 719:
1.29 crook 720: @cindex --return-stack-size, command-line option
721: @cindex -r, command-line option
722: @item --return-stack-size @i{size}
723: @itemx -r @i{size}
724: Allocate @i{size} space for the return stack instead of using the
725: default specified in the image (typically 15K).
1.21 crook 726:
1.29 crook 727: @cindex --fp-stack-size, command-line option
728: @cindex -f, command-line option
729: @item --fp-stack-size @i{size}
730: @itemx -f @i{size}
731: Allocate @i{size} space for the floating point stack instead of
732: using the default specified in the image (typically 15.5K). In this case
733: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 734:
1.48 anton 735: @cindex --locals-stack-size, command-line option
736: @cindex -l, command-line option
737: @item --locals-stack-size @i{size}
738: @itemx -l @i{size}
739: Allocate @i{size} space for the locals stack instead of using the
740: default specified in the image (typically 14.5K).
741:
1.176 anton 742: @cindex --vm-commit, command-line option
743: @cindex overcommit memory for dictionary and stacks
744: @cindex memory overcommit for dictionary and stacks
745: @item --vm-commit
746: Normally, Gforth tries to start up even if there is not enough virtual
747: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
748: on OSs that support it); so you can ask for a really big dictionary
749: and/or stacks, and as long as you don't use more virtual memory than
750: is available, everything will be fine (but if you use more, processes
751: get killed). With this option you just use the default allocation
752: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
753: means that you cannot and should not ask for as big dictionary and
754: stacks, but once Gforth successfully starts up, out-of-memory won't
755: kill it.
756:
1.48 anton 757: @cindex -h, command-line option
758: @cindex --help, command-line option
759: @item --help
760: @itemx -h
761: Print a message about the command-line options
762:
763: @cindex -v, command-line option
764: @cindex --version, command-line option
765: @item --version
766: @itemx -v
767: Print version and exit
768:
769: @cindex --debug, command-line option
770: @item --debug
771: Print some information useful for debugging on startup.
772:
773: @cindex --offset-image, command-line option
774: @item --offset-image
775: Start the dictionary at a slightly different position than would be used
776: otherwise (useful for creating data-relocatable images,
777: @pxref{Data-Relocatable Image Files}).
778:
779: @cindex --no-offset-im, command-line option
780: @item --no-offset-im
781: Start the dictionary at the normal position.
782:
783: @cindex --clear-dictionary, command-line option
784: @item --clear-dictionary
785: Initialize all bytes in the dictionary to 0 before loading the image
786: (@pxref{Data-Relocatable Image Files}).
787:
788: @cindex --die-on-signal, command-line-option
789: @item --die-on-signal
790: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
791: or the segmentation violation SIGSEGV) by translating it into a Forth
792: @code{THROW}. With this option, Gforth exits if it receives such a
793: signal. This option is useful when the engine and/or the image might be
794: severely broken (such that it causes another signal before recovering
795: from the first); this option avoids endless loops in such cases.
1.109 anton 796:
1.119 anton 797: @cindex --no-dynamic, command-line option
798: @cindex --dynamic, command-line option
1.109 anton 799: @item --no-dynamic
800: @item --dynamic
801: Disable or enable dynamic superinstructions with replication
802: (@pxref{Dynamic Superinstructions}).
803:
1.119 anton 804: @cindex --no-super, command-line option
1.109 anton 805: @item --no-super
1.110 anton 806: Disable dynamic superinstructions, use just dynamic replication; this is
807: useful if you want to patch threaded code (@pxref{Dynamic
808: Superinstructions}).
1.119 anton 809:
810: @cindex --ss-number, command-line option
811: @item --ss-number=@var{N}
812: Use only the first @var{N} static superinstructions compiled into the
813: engine (default: use them all; note that only @code{gforth-fast} has
814: any). This option is useful for measuring the performance impact of
815: static superinstructions.
816:
817: @cindex --ss-min-..., command-line options
818: @item --ss-min-codesize
819: @item --ss-min-ls
820: @item --ss-min-lsu
821: @item --ss-min-nexts
822: Use specified metric for determining the cost of a primitive or static
823: superinstruction for static superinstruction selection. @code{Codesize}
824: is the native code size of the primive or static superinstruction,
825: @code{ls} is the number of loads and stores, @code{lsu} is the number of
826: loads, stores, and updates, and @code{nexts} is the number of dispatches
827: (not taking dynamic superinstructions into account), i.e. every
828: primitive or static superinstruction has cost 1. Default:
829: @code{codesize} if you use dynamic code generation, otherwise
830: @code{nexts}.
831:
832: @cindex --ss-greedy, command-line option
833: @item --ss-greedy
834: This option is useful for measuring the performance impact of static
835: superinstructions. By default, an optimal shortest-path algorithm is
836: used for selecting static superinstructions. With @option{--ss-greedy}
837: this algorithm is modified to assume that anything after the static
838: superinstruction currently under consideration is not combined into
839: static superinstructions. With @option{--ss-min-nexts} this produces
840: the same result as a greedy algorithm that always selects the longest
841: superinstruction available at the moment. E.g., if there are
842: superinstructions AB and BCD, then for the sequence A B C D the optimal
843: algorithm will select A BCD and the greedy algorithm will select AB C D.
844:
845: @cindex --print-metrics, command-line option
846: @item --print-metrics
847: Prints some metrics used during static superinstruction selection:
848: @code{code size} is the actual size of the dynamically generated code.
849: @code{Metric codesize} is the sum of the codesize metrics as seen by
850: static superinstruction selection; there is a difference from @code{code
851: size}, because not all primitives and static superinstructions are
852: compiled into dynamically generated code, and because of markers. The
853: other metrics correspond to the @option{ss-min-...} options. This
854: option is useful for evaluating the effects of the @option{--ss-...}
855: options.
1.109 anton 856:
1.48 anton 857: @end table
858:
859: @cindex loading files at startup
860: @cindex executing code on startup
861: @cindex batch processing with Gforth
862: As explained above, the image-specific command-line arguments for the
863: default image @file{gforth.fi} consist of a sequence of filenames and
864: @code{-e @var{forth-code}} options that are interpreted in the sequence
865: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 866: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
867: option takes only one argument; if you want to evaluate more Forth
868: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 869: after processing the command line (instead of entering interactive mode)
1.121 anton 870: append @code{-e bye} to the command line. You can also process the
871: command-line arguments with a Forth program (@pxref{OS command line
872: arguments}).
1.48 anton 873:
874: @cindex versions, invoking other versions of Gforth
875: If you have several versions of Gforth installed, @code{gforth} will
876: invoke the version that was installed last. @code{gforth-@i{version}}
877: invokes a specific version. If your environment contains the variable
878: @code{GFORTHPATH}, you may want to override it by using the
879: @code{--path} option.
880:
881: Not yet implemented:
882: On startup the system first executes the system initialization file
883: (unless the option @code{--no-init-file} is given; note that the system
884: resulting from using this option may not be ANS Forth conformant). Then
885: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 886: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 887: then in @file{~}, then in the normal path (see above).
888:
889:
890:
891: @comment ----------------------------------------------
892: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
893: @section Leaving Gforth
894: @cindex Gforth - leaving
895: @cindex leaving Gforth
896:
897: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
898: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
899: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 900: data are discarded. For ways of saving the state of the system before
901: leaving Gforth see @ref{Image Files}.
1.48 anton 902:
903: doc-bye
904:
905:
906: @comment ----------------------------------------------
1.65 anton 907: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 908: @section Command-line editing
909: @cindex command-line editing
910:
911: Gforth maintains a history file that records every line that you type to
912: the text interpreter. This file is preserved between sessions, and is
913: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
914: repeatedly you can recall successively older commands from this (or
915: previous) session(s). The full list of command-line editing facilities is:
916:
917: @itemize @bullet
918: @item
919: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
920: commands from the history buffer.
921: @item
922: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
923: from the history buffer.
924: @item
925: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
926: @item
927: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
928: @item
929: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
930: closing up the line.
931: @item
932: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
933: @item
934: @kbd{Ctrl-a} to move the cursor to the start of the line.
935: @item
936: @kbd{Ctrl-e} to move the cursor to the end of the line.
937: @item
938: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
939: line.
940: @item
941: @key{TAB} to step through all possible full-word completions of the word
942: currently being typed.
943: @item
1.65 anton 944: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
945: using @code{bye}).
946: @item
947: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
948: character under the cursor.
1.48 anton 949: @end itemize
950:
951: When editing, displayable characters are inserted to the left of the
952: cursor position; the line is always in ``insert'' (as opposed to
953: ``overstrike'') mode.
954:
955: @cindex history file
956: @cindex @file{.gforth-history}
957: On Unix systems, the history file is @file{~/.gforth-history} by
958: default@footnote{i.e. it is stored in the user's home directory.}. You
959: can find out the name and location of your history file using:
960:
961: @example
962: history-file type \ Unix-class systems
963:
964: history-file type \ Other systems
965: history-dir type
966: @end example
967:
968: If you enter long definitions by hand, you can use a text editor to
969: paste them out of the history file into a Forth source file for reuse at
970: a later time.
971:
972: Gforth never trims the size of the history file, so you should do this
973: periodically, if necessary.
974:
975: @comment this is all defined in history.fs
976: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
977: @comment chosen?
978:
979:
980: @comment ----------------------------------------------
1.65 anton 981: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 982: @section Environment variables
983: @cindex environment variables
984:
985: Gforth uses these environment variables:
986:
987: @itemize @bullet
988: @item
989: @cindex @code{GFORTHHIST} -- environment variable
990: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
991: open/create the history file, @file{.gforth-history}. Default:
992: @code{$HOME}.
993:
994: @item
995: @cindex @code{GFORTHPATH} -- environment variable
996: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
997: for Forth source-code files.
998:
999: @item
1.147 anton 1000: @cindex @code{LANG} -- environment variable
1001: @code{LANG} -- see @code{LC_CTYPE}
1002:
1003: @item
1004: @cindex @code{LC_ALL} -- environment variable
1005: @code{LC_ALL} -- see @code{LC_CTYPE}
1006:
1007: @item
1008: @cindex @code{LC_CTYPE} -- environment variable
1009: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1010: startup, Gforth uses the UTF-8 encoding for strings internally and
1011: expects its input and produces its output in UTF-8 encoding, otherwise
1012: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1013: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1014: that is unset, in @code{LANG}.
1015:
1016: @item
1.129 anton 1017: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1018:
1019: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1020: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1021: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1022: and the command are directly concatenated, so if a space between them is
1023: necessary, append it to the prefix.
1024:
1025: @item
1.48 anton 1026: @cindex @code{GFORTH} -- environment variable
1.49 anton 1027: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1028:
1029: @item
1030: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1031: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1032:
1033: @item
1034: @cindex @code{TMP}, @code{TEMP} - environment variable
1035: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1036: location for the history file.
1037: @end itemize
1038:
1039: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1040: @comment mentioning these.
1041:
1042: All the Gforth environment variables default to sensible values if they
1043: are not set.
1044:
1045:
1046: @comment ----------------------------------------------
1.112 anton 1047: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1048: @section Gforth files
1049: @cindex Gforth files
1050:
1051: When you install Gforth on a Unix system, it installs files in these
1052: locations by default:
1053:
1054: @itemize @bullet
1055: @item
1056: @file{/usr/local/bin/gforth}
1057: @item
1058: @file{/usr/local/bin/gforthmi}
1059: @item
1060: @file{/usr/local/man/man1/gforth.1} - man page.
1061: @item
1062: @file{/usr/local/info} - the Info version of this manual.
1063: @item
1064: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1065: @item
1066: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1067: @item
1068: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1069: @item
1070: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1071: @end itemize
1072:
1073: You can select different places for installation by using
1074: @code{configure} options (listed with @code{configure --help}).
1075:
1076: @comment ----------------------------------------------
1.112 anton 1077: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1078: @section Gforth in pipes
1079: @cindex pipes, Gforth as part of
1080:
1081: Gforth can be used in pipes created elsewhere (described here). It can
1082: also create pipes on its own (@pxref{Pipes}).
1083:
1084: @cindex input from pipes
1085: If you pipe into Gforth, your program should read with @code{read-file}
1086: or @code{read-line} from @code{stdin} (@pxref{General files}).
1087: @code{Key} does not recognize the end of input. Words like
1088: @code{accept} echo the input and are therefore usually not useful for
1089: reading from a pipe. You have to invoke the Forth program with an OS
1090: command-line option, as you have no chance to use the Forth command line
1091: (the text interpreter would try to interpret the pipe input).
1092:
1093: @cindex output in pipes
1094: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1095:
1096: @cindex silent exiting from Gforth
1097: When you write to a pipe that has been closed at the other end, Gforth
1098: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1099: into the exception @code{broken-pipe-error}. If your application does
1100: not catch that exception, the system catches it and exits, usually
1101: silently (unless you were working on the Forth command line; then it
1102: prints an error message and exits). This is usually the desired
1103: behaviour.
1104:
1105: If you do not like this behaviour, you have to catch the exception
1106: yourself, and react to it.
1107:
1108: Here's an example of an invocation of Gforth that is usable in a pipe:
1109:
1110: @example
1111: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1112: type repeat ; foo bye"
1113: @end example
1114:
1115: This example just copies the input verbatim to the output. A very
1116: simple pipe containing this example looks like this:
1117:
1118: @example
1119: cat startup.fs |
1120: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1121: type repeat ; foo bye"|
1122: head
1123: @end example
1124:
1125: @cindex stderr and pipes
1126: Pipes involving Gforth's @code{stderr} output do not work.
1127:
1128: @comment ----------------------------------------------
1129: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1130: @section Startup speed
1131: @cindex Startup speed
1132: @cindex speed, startup
1133:
1134: If Gforth is used for CGI scripts or in shell scripts, its startup
1135: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1136: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1137: system time.
1138:
1139: If startup speed is a problem, you may consider the following ways to
1140: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1141: (for example, by using Fast-CGI).
1.48 anton 1142:
1.112 anton 1143: An easy step that influences Gforth startup speed is the use of the
1144: @option{--no-dynamic} option; this decreases image loading speed, but
1145: increases compile-time and run-time.
1146:
1147: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1148: building it with @code{XLDFLAGS=-static}. This requires more memory for
1149: the code and will therefore slow down the first invocation, but
1150: subsequent invocations avoid the dynamic linking overhead. Another
1151: disadvantage is that Gforth won't profit from library upgrades. As a
1152: result, @code{gforth-static -e bye} takes about 17.1ms user and
1153: 8.2ms system time.
1154:
1155: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1156: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1157: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1158: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1159: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1160: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1161: address for the dictionary, for whatever reason; so you better provide a
1162: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1163: bye} takes about 15.3ms user and 7.5ms system time.
1164:
1165: The final step is to disable dictionary hashing in Gforth. Gforth
1166: builds the hash table on startup, which takes much of the startup
1167: overhead. You can do this by commenting out the @code{include hash.fs}
1168: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1169: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1170: The disadvantages are that functionality like @code{table} and
1171: @code{ekey} is missing and that text interpretation (e.g., compiling)
1172: now takes much longer. So, you should only use this method if there is
1173: no significant text interpretation to perform (the script should be
1.62 crook 1174: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1175: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1176:
1177: @c ******************************************************************
1178: @node Tutorial, Introduction, Gforth Environment, Top
1179: @chapter Forth Tutorial
1180: @cindex Tutorial
1181: @cindex Forth Tutorial
1182:
1.67 anton 1183: @c Topics from nac's Introduction that could be mentioned:
1184: @c press <ret> after each line
1185: @c Prompt
1186: @c numbers vs. words in dictionary on text interpretation
1187: @c what happens on redefinition
1188: @c parsing words (in particular, defining words)
1189:
1.83 anton 1190: The difference of this chapter from the Introduction
1191: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1192: be used while sitting in front of a computer, and covers much more
1193: material, but does not explain how the Forth system works.
1194:
1.62 crook 1195: This tutorial can be used with any ANS-compliant Forth; any
1196: Gforth-specific features are marked as such and you can skip them if you
1197: work with another Forth. This tutorial does not explain all features of
1198: Forth, just enough to get you started and give you some ideas about the
1199: facilities available in Forth. Read the rest of the manual and the
1200: standard when you are through this.
1.48 anton 1201:
1202: The intended way to use this tutorial is that you work through it while
1203: sitting in front of the console, take a look at the examples and predict
1204: what they will do, then try them out; if the outcome is not as expected,
1205: find out why (e.g., by trying out variations of the example), so you
1206: understand what's going on. There are also some assignments that you
1207: should solve.
1208:
1209: This tutorial assumes that you have programmed before and know what,
1210: e.g., a loop is.
1211:
1212: @c !! explain compat library
1213:
1214: @menu
1215: * Starting Gforth Tutorial::
1216: * Syntax Tutorial::
1217: * Crash Course Tutorial::
1218: * Stack Tutorial::
1219: * Arithmetics Tutorial::
1220: * Stack Manipulation Tutorial::
1221: * Using files for Forth code Tutorial::
1222: * Comments Tutorial::
1223: * Colon Definitions Tutorial::
1224: * Decompilation Tutorial::
1225: * Stack-Effect Comments Tutorial::
1226: * Types Tutorial::
1227: * Factoring Tutorial::
1228: * Designing the stack effect Tutorial::
1229: * Local Variables Tutorial::
1230: * Conditional execution Tutorial::
1231: * Flags and Comparisons Tutorial::
1232: * General Loops Tutorial::
1233: * Counted loops Tutorial::
1234: * Recursion Tutorial::
1235: * Leaving definitions or loops Tutorial::
1236: * Return Stack Tutorial::
1237: * Memory Tutorial::
1238: * Characters and Strings Tutorial::
1239: * Alignment Tutorial::
1.87 anton 1240: * Files Tutorial::
1.48 anton 1241: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1242: * Execution Tokens Tutorial::
1243: * Exceptions Tutorial::
1244: * Defining Words Tutorial::
1245: * Arrays and Records Tutorial::
1246: * POSTPONE Tutorial::
1247: * Literal Tutorial::
1248: * Advanced macros Tutorial::
1249: * Compilation Tokens Tutorial::
1250: * Wordlists and Search Order Tutorial::
1251: @end menu
1252:
1253: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1254: @section Starting Gforth
1.66 anton 1255: @cindex starting Gforth tutorial
1.48 anton 1256: You can start Gforth by typing its name:
1257:
1258: @example
1259: gforth
1260: @end example
1261:
1262: That puts you into interactive mode; you can leave Gforth by typing
1263: @code{bye}. While in Gforth, you can edit the command line and access
1264: the command line history with cursor keys, similar to bash.
1265:
1266:
1267: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1268: @section Syntax
1.66 anton 1269: @cindex syntax tutorial
1.48 anton 1270:
1.171 anton 1271: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1272: space). Words are separated by white space. E.g., each of the
1273: following lines contains exactly one word:
1274:
1275: @example
1276: word
1277: !@@#$%^&*()
1278: 1234567890
1279: 5!a
1280: @end example
1281:
1282: A frequent beginner's error is to leave away necessary white space,
1283: resulting in an error like @samp{Undefined word}; so if you see such an
1284: error, check if you have put spaces wherever necessary.
1285:
1286: @example
1287: ." hello, world" \ correct
1288: ."hello, world" \ gives an "Undefined word" error
1289: @end example
1290:
1.65 anton 1291: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1292: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1293: your system is case-sensitive, you may have to type all the examples
1294: given here in upper case.
1295:
1296:
1297: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1298: @section Crash Course
1299:
1300: Type
1301:
1302: @example
1303: 0 0 !
1304: here execute
1305: ' catch >body 20 erase abort
1306: ' (quit) >body 20 erase
1307: @end example
1308:
1309: The last two examples are guaranteed to destroy parts of Gforth (and
1310: most other systems), so you better leave Gforth afterwards (if it has
1311: not finished by itself). On some systems you may have to kill gforth
1312: from outside (e.g., in Unix with @code{kill}).
1313:
1314: Now that you know how to produce crashes (and that there's not much to
1315: them), let's learn how to produce meaningful programs.
1316:
1317:
1318: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1319: @section Stack
1.66 anton 1320: @cindex stack tutorial
1.48 anton 1321:
1322: The most obvious feature of Forth is the stack. When you type in a
1323: number, it is pushed on the stack. You can display the content of the
1324: stack with @code{.s}.
1325:
1326: @example
1327: 1 2 .s
1328: 3 .s
1329: @end example
1330:
1331: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1332: appear in @code{.s} output as they appeared in the input.
1333:
1334: You can print the top of stack element with @code{.}.
1335:
1336: @example
1337: 1 2 3 . . .
1338: @end example
1339:
1340: In general, words consume their stack arguments (@code{.s} is an
1341: exception).
1342:
1.141 anton 1343: @quotation Assignment
1.48 anton 1344: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1345: @end quotation
1.48 anton 1346:
1347:
1348: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1349: @section Arithmetics
1.66 anton 1350: @cindex arithmetics tutorial
1.48 anton 1351:
1352: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1353: operate on the top two stack items:
1354:
1355: @example
1.67 anton 1356: 2 2 .s
1357: + .s
1358: .
1.48 anton 1359: 2 1 - .
1360: 7 3 mod .
1361: @end example
1362:
1363: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1364: as in the corresponding infix expression (this is generally the case in
1365: Forth).
1366:
1367: Parentheses are superfluous (and not available), because the order of
1368: the words unambiguously determines the order of evaluation and the
1369: operands:
1370:
1371: @example
1372: 3 4 + 5 * .
1373: 3 4 5 * + .
1374: @end example
1375:
1.141 anton 1376: @quotation Assignment
1.48 anton 1377: What are the infix expressions corresponding to the Forth code above?
1378: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1379: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1380: @end quotation
1.48 anton 1381:
1382: To change the sign, use @code{negate}:
1383:
1384: @example
1385: 2 negate .
1386: @end example
1387:
1.141 anton 1388: @quotation Assignment
1.48 anton 1389: Convert -(-3)*4-5 to Forth.
1.141 anton 1390: @end quotation
1.48 anton 1391:
1392: @code{/mod} performs both @code{/} and @code{mod}.
1393:
1394: @example
1395: 7 3 /mod . .
1396: @end example
1397:
1.66 anton 1398: Reference: @ref{Arithmetic}.
1399:
1400:
1.48 anton 1401: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1402: @section Stack Manipulation
1.66 anton 1403: @cindex stack manipulation tutorial
1.48 anton 1404:
1405: Stack manipulation words rearrange the data on the stack.
1406:
1407: @example
1408: 1 .s drop .s
1409: 1 .s dup .s drop drop .s
1410: 1 2 .s over .s drop drop drop
1411: 1 2 .s swap .s drop drop
1412: 1 2 3 .s rot .s drop drop drop
1413: @end example
1414:
1415: These are the most important stack manipulation words. There are also
1416: variants that manipulate twice as many stack items:
1417:
1418: @example
1419: 1 2 3 4 .s 2swap .s 2drop 2drop
1420: @end example
1421:
1422: Two more stack manipulation words are:
1423:
1424: @example
1425: 1 2 .s nip .s drop
1426: 1 2 .s tuck .s 2drop drop
1427: @end example
1428:
1.141 anton 1429: @quotation Assignment
1.48 anton 1430: Replace @code{nip} and @code{tuck} with combinations of other stack
1431: manipulation words.
1432:
1433: @example
1434: Given: How do you get:
1435: 1 2 3 3 2 1
1436: 1 2 3 1 2 3 2
1437: 1 2 3 1 2 3 3
1438: 1 2 3 1 3 3
1439: 1 2 3 2 1 3
1440: 1 2 3 4 4 3 2 1
1441: 1 2 3 1 2 3 1 2 3
1442: 1 2 3 4 1 2 3 4 1 2
1443: 1 2 3
1444: 1 2 3 1 2 3 4
1445: 1 2 3 1 3
1446: @end example
1.141 anton 1447: @end quotation
1.48 anton 1448:
1449: @example
1450: 5 dup * .
1451: @end example
1452:
1.141 anton 1453: @quotation Assignment
1.48 anton 1454: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1455: Write a piece of Forth code that expects two numbers on the stack
1456: (@var{a} and @var{b}, with @var{b} on top) and computes
1457: @code{(a-b)(a+1)}.
1.141 anton 1458: @end quotation
1.48 anton 1459:
1.66 anton 1460: Reference: @ref{Stack Manipulation}.
1461:
1462:
1.48 anton 1463: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1464: @section Using files for Forth code
1.66 anton 1465: @cindex loading Forth code, tutorial
1466: @cindex files containing Forth code, tutorial
1.48 anton 1467:
1468: While working at the Forth command line is convenient for one-line
1469: examples and short one-off code, you probably want to store your source
1470: code in files for convenient editing and persistence. You can use your
1471: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1472: Gforth}) to create @var{file.fs} and use
1.48 anton 1473:
1474: @example
1.102 anton 1475: s" @var{file.fs}" included
1.48 anton 1476: @end example
1477:
1478: to load it into your Forth system. The file name extension I use for
1479: Forth files is @samp{.fs}.
1480:
1481: You can easily start Gforth with some files loaded like this:
1482:
1483: @example
1.102 anton 1484: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1485: @end example
1486:
1487: If an error occurs during loading these files, Gforth terminates,
1488: whereas an error during @code{INCLUDED} within Gforth usually gives you
1489: a Gforth command line. Starting the Forth system every time gives you a
1490: clean start every time, without interference from the results of earlier
1491: tries.
1492:
1493: I often put all the tests in a file, then load the code and run the
1494: tests with
1495:
1496: @example
1.102 anton 1497: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1498: @end example
1499:
1500: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1501: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1502: restart this command without ado.
1503:
1504: The advantage of this approach is that the tests can be repeated easily
1505: every time the program ist changed, making it easy to catch bugs
1506: introduced by the change.
1507:
1.66 anton 1508: Reference: @ref{Forth source files}.
1509:
1.48 anton 1510:
1511: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1512: @section Comments
1.66 anton 1513: @cindex comments tutorial
1.48 anton 1514:
1515: @example
1516: \ That's a comment; it ends at the end of the line
1517: ( Another comment; it ends here: ) .s
1518: @end example
1519:
1520: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1521: separated with white space from the following text.
1522:
1523: @example
1524: \This gives an "Undefined word" error
1525: @end example
1526:
1527: The first @code{)} ends a comment started with @code{(}, so you cannot
1528: nest @code{(}-comments; and you cannot comment out text containing a
1529: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1530: avoid @code{)} in word names.}.
1531:
1532: I use @code{\}-comments for descriptive text and for commenting out code
1533: of one or more line; I use @code{(}-comments for describing the stack
1534: effect, the stack contents, or for commenting out sub-line pieces of
1535: code.
1536:
1537: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1538: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1539: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1540: with @kbd{M-q}.
1541:
1.66 anton 1542: Reference: @ref{Comments}.
1543:
1.48 anton 1544:
1545: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1546: @section Colon Definitions
1.66 anton 1547: @cindex colon definitions, tutorial
1548: @cindex definitions, tutorial
1549: @cindex procedures, tutorial
1550: @cindex functions, tutorial
1.48 anton 1551:
1552: are similar to procedures and functions in other programming languages.
1553:
1554: @example
1555: : squared ( n -- n^2 )
1556: dup * ;
1557: 5 squared .
1558: 7 squared .
1559: @end example
1560:
1561: @code{:} starts the colon definition; its name is @code{squared}. The
1562: following comment describes its stack effect. The words @code{dup *}
1563: are not executed, but compiled into the definition. @code{;} ends the
1564: colon definition.
1565:
1566: The newly-defined word can be used like any other word, including using
1567: it in other definitions:
1568:
1569: @example
1570: : cubed ( n -- n^3 )
1571: dup squared * ;
1572: -5 cubed .
1573: : fourth-power ( n -- n^4 )
1574: squared squared ;
1575: 3 fourth-power .
1576: @end example
1577:
1.141 anton 1578: @quotation Assignment
1.48 anton 1579: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1580: @code{/mod} in terms of other Forth words, and check if they work (hint:
1581: test your tests on the originals first). Don't let the
1582: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1583: @end quotation
1.48 anton 1584:
1.66 anton 1585: Reference: @ref{Colon Definitions}.
1586:
1.48 anton 1587:
1588: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1589: @section Decompilation
1.66 anton 1590: @cindex decompilation tutorial
1591: @cindex see tutorial
1.48 anton 1592:
1593: You can decompile colon definitions with @code{see}:
1594:
1595: @example
1596: see squared
1597: see cubed
1598: @end example
1599:
1600: In Gforth @code{see} shows you a reconstruction of the source code from
1601: the executable code. Informations that were present in the source, but
1602: not in the executable code, are lost (e.g., comments).
1603:
1.65 anton 1604: You can also decompile the predefined words:
1605:
1606: @example
1607: see .
1608: see +
1609: @end example
1610:
1611:
1.48 anton 1612: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1613: @section Stack-Effect Comments
1.66 anton 1614: @cindex stack-effect comments, tutorial
1615: @cindex --, tutorial
1.48 anton 1616: By convention the comment after the name of a definition describes the
1.171 anton 1617: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1618: the stack before the execution of the definition, i.e., the parameters
1619: that are passed into the colon definition; the part behind the @samp{--}
1620: is the state of the stack after the execution of the definition, i.e.,
1621: the results of the definition. The stack comment only shows the top
1622: stack items that the definition accesses and/or changes.
1623:
1624: You should put a correct stack effect on every definition, even if it is
1625: just @code{( -- )}. You should also add some descriptive comment to
1626: more complicated words (I usually do this in the lines following
1627: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1628: you have to work through every definition before you can understand
1.48 anton 1629: any).
1630:
1.141 anton 1631: @quotation Assignment
1.48 anton 1632: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1633: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1634: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1635: are done, you can compare your stack effects to those in this manual
1.48 anton 1636: (@pxref{Word Index}).
1.141 anton 1637: @end quotation
1.48 anton 1638:
1639: Sometimes programmers put comments at various places in colon
1640: definitions that describe the contents of the stack at that place (stack
1641: comments); i.e., they are like the first part of a stack-effect
1642: comment. E.g.,
1643:
1644: @example
1645: : cubed ( n -- n^3 )
1646: dup squared ( n n^2 ) * ;
1647: @end example
1648:
1649: In this case the stack comment is pretty superfluous, because the word
1650: is simple enough. If you think it would be a good idea to add such a
1651: comment to increase readability, you should also consider factoring the
1652: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1653: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1654: however, if you decide not to refactor it, then having such a comment is
1655: better than not having it.
1656:
1657: The names of the stack items in stack-effect and stack comments in the
1658: standard, in this manual, and in many programs specify the type through
1659: a type prefix, similar to Fortran and Hungarian notation. The most
1660: frequent prefixes are:
1661:
1662: @table @code
1663: @item n
1664: signed integer
1665: @item u
1666: unsigned integer
1667: @item c
1668: character
1669: @item f
1670: Boolean flags, i.e. @code{false} or @code{true}.
1671: @item a-addr,a-
1672: Cell-aligned address
1673: @item c-addr,c-
1674: Char-aligned address (note that a Char may have two bytes in Windows NT)
1675: @item xt
1676: Execution token, same size as Cell
1677: @item w,x
1678: Cell, can contain an integer or an address. It usually takes 32, 64 or
1679: 16 bits (depending on your platform and Forth system). A cell is more
1680: commonly known as machine word, but the term @emph{word} already means
1681: something different in Forth.
1682: @item d
1683: signed double-cell integer
1684: @item ud
1685: unsigned double-cell integer
1686: @item r
1687: Float (on the FP stack)
1688: @end table
1689:
1690: You can find a more complete list in @ref{Notation}.
1691:
1.141 anton 1692: @quotation Assignment
1.48 anton 1693: Write stack-effect comments for all definitions you have written up to
1694: now.
1.141 anton 1695: @end quotation
1.48 anton 1696:
1697:
1698: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1699: @section Types
1.66 anton 1700: @cindex types tutorial
1.48 anton 1701:
1702: In Forth the names of the operations are not overloaded; so similar
1703: operations on different types need different names; e.g., @code{+} adds
1704: integers, and you have to use @code{f+} to add floating-point numbers.
1705: The following prefixes are often used for related operations on
1706: different types:
1707:
1708: @table @code
1709: @item (none)
1710: signed integer
1711: @item u
1712: unsigned integer
1713: @item c
1714: character
1715: @item d
1716: signed double-cell integer
1717: @item ud, du
1718: unsigned double-cell integer
1719: @item 2
1720: two cells (not-necessarily double-cell numbers)
1721: @item m, um
1722: mixed single-cell and double-cell operations
1723: @item f
1724: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1725: and @samp{r} represents FP numbers).
1.48 anton 1726: @end table
1727:
1728: If there are no differences between the signed and the unsigned variant
1729: (e.g., for @code{+}), there is only the prefix-less variant.
1730:
1731: Forth does not perform type checking, neither at compile time, nor at
1732: run time. If you use the wrong oeration, the data are interpreted
1733: incorrectly:
1734:
1735: @example
1736: -1 u.
1737: @end example
1738:
1739: If you have only experience with type-checked languages until now, and
1740: have heard how important type-checking is, don't panic! In my
1741: experience (and that of other Forthers), type errors in Forth code are
1742: usually easy to find (once you get used to it), the increased vigilance
1743: of the programmer tends to catch some harder errors in addition to most
1744: type errors, and you never have to work around the type system, so in
1745: most situations the lack of type-checking seems to be a win (projects to
1746: add type checking to Forth have not caught on).
1747:
1748:
1749: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1750: @section Factoring
1.66 anton 1751: @cindex factoring tutorial
1.48 anton 1752:
1753: If you try to write longer definitions, you will soon find it hard to
1754: keep track of the stack contents. Therefore, good Forth programmers
1755: tend to write only short definitions (e.g., three lines). The art of
1756: finding meaningful short definitions is known as factoring (as in
1757: factoring polynomials).
1758:
1759: Well-factored programs offer additional advantages: smaller, more
1760: general words, are easier to test and debug and can be reused more and
1761: better than larger, specialized words.
1762:
1763: So, if you run into difficulties with stack management, when writing
1764: code, try to define meaningful factors for the word, and define the word
1765: in terms of those. Even if a factor contains only two words, it is
1766: often helpful.
1767:
1.65 anton 1768: Good factoring is not easy, and it takes some practice to get the knack
1769: for it; but even experienced Forth programmers often don't find the
1770: right solution right away, but only when rewriting the program. So, if
1771: you don't come up with a good solution immediately, keep trying, don't
1772: despair.
1.48 anton 1773:
1774: @c example !!
1775:
1776:
1777: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1778: @section Designing the stack effect
1.66 anton 1779: @cindex Stack effect design, tutorial
1780: @cindex design of stack effects, tutorial
1.48 anton 1781:
1782: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1783: function; and since there is only one result, you don't have to deal with
1.48 anton 1784: the order of results, either.
1785:
1.117 anton 1786: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1787: parameter and result order of a definition is important and should be
1788: designed well. The general guideline is to design the stack effect such
1789: that the word is simple to use in most cases, even if that complicates
1790: the implementation of the word. Some concrete rules are:
1791:
1792: @itemize @bullet
1793:
1794: @item
1795: Words consume all of their parameters (e.g., @code{.}).
1796:
1797: @item
1798: If there is a convention on the order of parameters (e.g., from
1799: mathematics or another programming language), stick with it (e.g.,
1800: @code{-}).
1801:
1802: @item
1803: If one parameter usually requires only a short computation (e.g., it is
1804: a constant), pass it on the top of the stack. Conversely, parameters
1805: that usually require a long sequence of code to compute should be passed
1806: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1807: read, because the reader does not need to keep track of the bottom item
1.48 anton 1808: through a long sequence of code (or, alternatively, through stack
1.49 anton 1809: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1810: address on top of the stack because it is usually simpler to compute
1811: than the stored value (often the address is just a variable).
1812:
1813: @item
1814: Similarly, results that are usually consumed quickly should be returned
1815: on the top of stack, whereas a result that is often used in long
1816: computations should be passed as bottom result. E.g., the file words
1817: like @code{open-file} return the error code on the top of stack, because
1818: it is usually consumed quickly by @code{throw}; moreover, the error code
1819: has to be checked before doing anything with the other results.
1820:
1821: @end itemize
1822:
1823: These rules are just general guidelines, don't lose sight of the overall
1824: goal to make the words easy to use. E.g., if the convention rule
1825: conflicts with the computation-length rule, you might decide in favour
1826: of the convention if the word will be used rarely, and in favour of the
1827: computation-length rule if the word will be used frequently (because
1828: with frequent use the cost of breaking the computation-length rule would
1829: be quite high, and frequent use makes it easier to remember an
1830: unconventional order).
1831:
1832: @c example !! structure package
1833:
1.65 anton 1834:
1.48 anton 1835: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1836: @section Local Variables
1.66 anton 1837: @cindex local variables, tutorial
1.48 anton 1838:
1839: You can define local variables (@emph{locals}) in a colon definition:
1840:
1841: @example
1842: : swap @{ a b -- b a @}
1843: b a ;
1844: 1 2 swap .s 2drop
1845: @end example
1846:
1847: (If your Forth system does not support this syntax, include
1848: @file{compat/anslocals.fs} first).
1849:
1850: In this example @code{@{ a b -- b a @}} is the locals definition; it
1851: takes two cells from the stack, puts the top of stack in @code{b} and
1852: the next stack element in @code{a}. @code{--} starts a comment ending
1853: with @code{@}}. After the locals definition, using the name of the
1854: local will push its value on the stack. You can leave the comment
1855: part (@code{-- b a}) away:
1856:
1857: @example
1858: : swap ( x1 x2 -- x2 x1 )
1859: @{ a b @} b a ;
1860: @end example
1861:
1862: In Gforth you can have several locals definitions, anywhere in a colon
1863: definition; in contrast, in a standard program you can have only one
1864: locals definition per colon definition, and that locals definition must
1.163 anton 1865: be outside any control structure.
1.48 anton 1866:
1867: With locals you can write slightly longer definitions without running
1868: into stack trouble. However, I recommend trying to write colon
1869: definitions without locals for exercise purposes to help you gain the
1870: essential factoring skills.
1871:
1.141 anton 1872: @quotation Assignment
1.48 anton 1873: Rewrite your definitions until now with locals
1.141 anton 1874: @end quotation
1.48 anton 1875:
1.66 anton 1876: Reference: @ref{Locals}.
1877:
1.48 anton 1878:
1879: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1880: @section Conditional execution
1.66 anton 1881: @cindex conditionals, tutorial
1882: @cindex if, tutorial
1.48 anton 1883:
1884: In Forth you can use control structures only inside colon definitions.
1885: An @code{if}-structure looks like this:
1886:
1887: @example
1888: : abs ( n1 -- +n2 )
1889: dup 0 < if
1890: negate
1891: endif ;
1892: 5 abs .
1893: -5 abs .
1894: @end example
1895:
1896: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1897: the following code is performed, otherwise execution continues after the
1.51 pazsan 1898: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1899: elements and produces a flag:
1.48 anton 1900:
1901: @example
1902: 1 2 < .
1903: 2 1 < .
1904: 1 1 < .
1905: @end example
1906:
1907: Actually the standard name for @code{endif} is @code{then}. This
1908: tutorial presents the examples using @code{endif}, because this is often
1909: less confusing for people familiar with other programming languages
1910: where @code{then} has a different meaning. If your system does not have
1911: @code{endif}, define it with
1912:
1913: @example
1914: : endif postpone then ; immediate
1915: @end example
1916:
1917: You can optionally use an @code{else}-part:
1918:
1919: @example
1920: : min ( n1 n2 -- n )
1921: 2dup < if
1922: drop
1923: else
1924: nip
1925: endif ;
1926: 2 3 min .
1927: 3 2 min .
1928: @end example
1929:
1.141 anton 1930: @quotation Assignment
1.48 anton 1931: Write @code{min} without @code{else}-part (hint: what's the definition
1932: of @code{nip}?).
1.141 anton 1933: @end quotation
1.48 anton 1934:
1.66 anton 1935: Reference: @ref{Selection}.
1936:
1.48 anton 1937:
1938: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1939: @section Flags and Comparisons
1.66 anton 1940: @cindex flags tutorial
1941: @cindex comparison tutorial
1.48 anton 1942:
1943: In a false-flag all bits are clear (0 when interpreted as integer). In
1944: a canonical true-flag all bits are set (-1 as a twos-complement signed
1945: integer); in many contexts (e.g., @code{if}) any non-zero value is
1946: treated as true flag.
1947:
1948: @example
1949: false .
1950: true .
1951: true hex u. decimal
1952: @end example
1953:
1954: Comparison words produce canonical flags:
1955:
1956: @example
1957: 1 1 = .
1958: 1 0= .
1959: 0 1 < .
1960: 0 0 < .
1961: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1962: -1 1 < .
1963: @end example
1964:
1.66 anton 1965: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1966: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1967: these combinations are standard (for details see the standard,
1968: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1969:
1.171 anton 1970: You can use @code{and or xor invert} as operations on canonical flags.
1971: Actually they are bitwise operations:
1.48 anton 1972:
1973: @example
1974: 1 2 and .
1975: 1 2 or .
1976: 1 3 xor .
1977: 1 invert .
1978: @end example
1979:
1980: You can convert a zero/non-zero flag into a canonical flag with
1981: @code{0<>} (and complement it on the way with @code{0=}).
1982:
1983: @example
1984: 1 0= .
1985: 1 0<> .
1986: @end example
1987:
1.65 anton 1988: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1989: operation of the Boolean operations to avoid @code{if}s:
1990:
1991: @example
1992: : foo ( n1 -- n2 )
1993: 0= if
1994: 14
1995: else
1996: 0
1997: endif ;
1998: 0 foo .
1999: 1 foo .
2000:
2001: : foo ( n1 -- n2 )
2002: 0= 14 and ;
2003: 0 foo .
2004: 1 foo .
2005: @end example
2006:
1.141 anton 2007: @quotation Assignment
1.48 anton 2008: Write @code{min} without @code{if}.
1.141 anton 2009: @end quotation
1.48 anton 2010:
1.66 anton 2011: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2012: @ref{Bitwise operations}.
2013:
1.48 anton 2014:
2015: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2016: @section General Loops
1.66 anton 2017: @cindex loops, indefinite, tutorial
1.48 anton 2018:
2019: The endless loop is the most simple one:
2020:
2021: @example
2022: : endless ( -- )
2023: 0 begin
2024: dup . 1+
2025: again ;
2026: endless
2027: @end example
2028:
2029: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2030: does nothing at run-time, @code{again} jumps back to @code{begin}.
2031:
2032: A loop with one exit at any place looks like this:
2033:
2034: @example
2035: : log2 ( +n1 -- n2 )
2036: \ logarithmus dualis of n1>0, rounded down to the next integer
2037: assert( dup 0> )
2038: 2/ 0 begin
2039: over 0> while
2040: 1+ swap 2/ swap
2041: repeat
2042: nip ;
2043: 7 log2 .
2044: 8 log2 .
2045: @end example
2046:
2047: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2048: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2049: continues behind the @code{while}. @code{Repeat} jumps back to
2050: @code{begin}, just like @code{again}.
2051:
2052: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2053: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2054: one bit (arithmetic shift right):
2055:
2056: @example
2057: -5 2 / .
2058: -5 2/ .
2059: @end example
2060:
2061: @code{assert(} is no standard word, but you can get it on systems other
2062: then Gforth by including @file{compat/assert.fs}. You can see what it
2063: does by trying
2064:
2065: @example
2066: 0 log2 .
2067: @end example
2068:
2069: Here's a loop with an exit at the end:
2070:
2071: @example
2072: : log2 ( +n1 -- n2 )
2073: \ logarithmus dualis of n1>0, rounded down to the next integer
2074: assert( dup 0 > )
2075: -1 begin
2076: 1+ swap 2/ swap
2077: over 0 <=
2078: until
2079: nip ;
2080: @end example
2081:
2082: @code{Until} consumes a flag; if it is non-zero, execution continues at
2083: the @code{begin}, otherwise after the @code{until}.
2084:
1.141 anton 2085: @quotation Assignment
1.48 anton 2086: Write a definition for computing the greatest common divisor.
1.141 anton 2087: @end quotation
1.48 anton 2088:
1.66 anton 2089: Reference: @ref{Simple Loops}.
2090:
1.48 anton 2091:
2092: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2093: @section Counted loops
1.66 anton 2094: @cindex loops, counted, tutorial
1.48 anton 2095:
2096: @example
2097: : ^ ( n1 u -- n )
1.171 anton 2098: \ n = the uth power of n1
1.48 anton 2099: 1 swap 0 u+do
2100: over *
2101: loop
2102: nip ;
2103: 3 2 ^ .
2104: 4 3 ^ .
2105: @end example
2106:
2107: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2108: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2109: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2110: times (or not at all, if @code{u3-u4<0}).
2111:
2112: You can see the stack effect design rules at work in the stack effect of
2113: the loop start words: Since the start value of the loop is more
2114: frequently constant than the end value, the start value is passed on
2115: the top-of-stack.
2116:
2117: You can access the counter of a counted loop with @code{i}:
2118:
2119: @example
2120: : fac ( u -- u! )
2121: 1 swap 1+ 1 u+do
2122: i *
2123: loop ;
2124: 5 fac .
2125: 7 fac .
2126: @end example
2127:
2128: There is also @code{+do}, which expects signed numbers (important for
2129: deciding whether to enter the loop).
2130:
1.141 anton 2131: @quotation Assignment
1.48 anton 2132: Write a definition for computing the nth Fibonacci number.
1.141 anton 2133: @end quotation
1.48 anton 2134:
1.65 anton 2135: You can also use increments other than 1:
2136:
2137: @example
2138: : up2 ( n1 n2 -- )
2139: +do
2140: i .
2141: 2 +loop ;
2142: 10 0 up2
2143:
2144: : down2 ( n1 n2 -- )
2145: -do
2146: i .
2147: 2 -loop ;
2148: 0 10 down2
2149: @end example
1.48 anton 2150:
1.66 anton 2151: Reference: @ref{Counted Loops}.
2152:
1.48 anton 2153:
2154: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2155: @section Recursion
1.66 anton 2156: @cindex recursion tutorial
1.48 anton 2157:
2158: Usually the name of a definition is not visible in the definition; but
2159: earlier definitions are usually visible:
2160:
2161: @example
1.166 anton 2162: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2163: : / ( n1 n2 -- n )
2164: dup 0= if
2165: -10 throw \ report division by zero
2166: endif
2167: / \ old version
2168: ;
2169: 1 0 /
2170: @end example
2171:
2172: For recursive definitions you can use @code{recursive} (non-standard) or
2173: @code{recurse}:
2174:
2175: @example
2176: : fac1 ( n -- n! ) recursive
2177: dup 0> if
2178: dup 1- fac1 *
2179: else
2180: drop 1
2181: endif ;
2182: 7 fac1 .
2183:
2184: : fac2 ( n -- n! )
2185: dup 0> if
2186: dup 1- recurse *
2187: else
2188: drop 1
2189: endif ;
2190: 8 fac2 .
2191: @end example
2192:
1.141 anton 2193: @quotation Assignment
1.48 anton 2194: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2195: @end quotation
1.48 anton 2196:
1.66 anton 2197: Reference (including indirect recursion): @xref{Calls and returns}.
2198:
1.48 anton 2199:
2200: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2201: @section Leaving definitions or loops
1.66 anton 2202: @cindex leaving definitions, tutorial
2203: @cindex leaving loops, tutorial
1.48 anton 2204:
2205: @code{EXIT} exits the current definition right away. For every counted
2206: loop that is left in this way, an @code{UNLOOP} has to be performed
2207: before the @code{EXIT}:
2208:
2209: @c !! real examples
2210: @example
2211: : ...
2212: ... u+do
2213: ... if
2214: ... unloop exit
2215: endif
2216: ...
2217: loop
2218: ... ;
2219: @end example
2220:
2221: @code{LEAVE} leaves the innermost counted loop right away:
2222:
2223: @example
2224: : ...
2225: ... u+do
2226: ... if
2227: ... leave
2228: endif
2229: ...
2230: loop
2231: ... ;
2232: @end example
2233:
1.65 anton 2234: @c !! example
1.48 anton 2235:
1.66 anton 2236: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2237:
2238:
1.48 anton 2239: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2240: @section Return Stack
1.66 anton 2241: @cindex return stack tutorial
1.48 anton 2242:
2243: In addition to the data stack Forth also has a second stack, the return
2244: stack; most Forth systems store the return addresses of procedure calls
2245: there (thus its name). Programmers can also use this stack:
2246:
2247: @example
2248: : foo ( n1 n2 -- )
2249: .s
2250: >r .s
1.50 anton 2251: r@@ .
1.48 anton 2252: >r .s
1.50 anton 2253: r@@ .
1.48 anton 2254: r> .
1.50 anton 2255: r@@ .
1.48 anton 2256: r> . ;
2257: 1 2 foo
2258: @end example
2259:
2260: @code{>r} takes an element from the data stack and pushes it onto the
2261: return stack; conversely, @code{r>} moves an elementm from the return to
2262: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2263: on the data stack.
1.48 anton 2264:
2265: Forth programmers usually use the return stack for storing data
2266: temporarily, if using the data stack alone would be too complex, and
2267: factoring and locals are not an option:
2268:
2269: @example
2270: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2271: rot >r rot r> ;
2272: @end example
2273:
2274: The return address of the definition and the loop control parameters of
2275: counted loops usually reside on the return stack, so you have to take
2276: all items, that you have pushed on the return stack in a colon
2277: definition or counted loop, from the return stack before the definition
2278: or loop ends. You cannot access items that you pushed on the return
2279: stack outside some definition or loop within the definition of loop.
2280:
2281: If you miscount the return stack items, this usually ends in a crash:
2282:
2283: @example
2284: : crash ( n -- )
2285: >r ;
2286: 5 crash
2287: @end example
2288:
2289: You cannot mix using locals and using the return stack (according to the
2290: standard; Gforth has no problem). However, they solve the same
2291: problems, so this shouldn't be an issue.
2292:
1.141 anton 2293: @quotation Assignment
1.48 anton 2294: Can you rewrite any of the definitions you wrote until now in a better
2295: way using the return stack?
1.141 anton 2296: @end quotation
1.48 anton 2297:
1.66 anton 2298: Reference: @ref{Return stack}.
2299:
1.48 anton 2300:
2301: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2302: @section Memory
1.66 anton 2303: @cindex memory access/allocation tutorial
1.48 anton 2304:
2305: You can create a global variable @code{v} with
2306:
2307: @example
2308: variable v ( -- addr )
2309: @end example
2310:
2311: @code{v} pushes the address of a cell in memory on the stack. This cell
2312: was reserved by @code{variable}. You can use @code{!} (store) to store
2313: values into this cell and @code{@@} (fetch) to load the value from the
2314: stack into memory:
2315:
2316: @example
2317: v .
2318: 5 v ! .s
1.50 anton 2319: v @@ .
1.48 anton 2320: @end example
2321:
1.65 anton 2322: You can see a raw dump of memory with @code{dump}:
2323:
2324: @example
2325: v 1 cells .s dump
2326: @end example
2327:
2328: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2329: generally, address units (aus)) that @code{n1 cells} occupy. You can
2330: also reserve more memory:
1.48 anton 2331:
2332: @example
2333: create v2 20 cells allot
1.65 anton 2334: v2 20 cells dump
1.48 anton 2335: @end example
2336:
1.65 anton 2337: creates a word @code{v2} and reserves 20 uninitialized cells; the
2338: address pushed by @code{v2} points to the start of these 20 cells. You
2339: can use address arithmetic to access these cells:
1.48 anton 2340:
2341: @example
2342: 3 v2 5 cells + !
1.65 anton 2343: v2 20 cells dump
1.48 anton 2344: @end example
2345:
2346: You can reserve and initialize memory with @code{,}:
2347:
2348: @example
2349: create v3
2350: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2351: v3 @@ .
2352: v3 cell+ @@ .
2353: v3 2 cells + @@ .
1.65 anton 2354: v3 5 cells dump
1.48 anton 2355: @end example
2356:
1.141 anton 2357: @quotation Assignment
1.48 anton 2358: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2359: @code{u} cells, with the first of these cells at @code{addr}, the next
2360: one at @code{addr cell+} etc.
1.141 anton 2361: @end quotation
1.48 anton 2362:
2363: You can also reserve memory without creating a new word:
2364:
2365: @example
1.60 anton 2366: here 10 cells allot .
2367: here .
1.48 anton 2368: @end example
2369:
2370: @code{Here} pushes the start address of the memory area. You should
2371: store it somewhere, or you will have a hard time finding the memory area
2372: again.
2373:
2374: @code{Allot} manages dictionary memory. The dictionary memory contains
2375: the system's data structures for words etc. on Gforth and most other
2376: Forth systems. It is managed like a stack: You can free the memory that
2377: you have just @code{allot}ed with
2378:
2379: @example
2380: -10 cells allot
1.60 anton 2381: here .
1.48 anton 2382: @end example
2383:
2384: Note that you cannot do this if you have created a new word in the
2385: meantime (because then your @code{allot}ed memory is no longer on the
2386: top of the dictionary ``stack'').
2387:
2388: Alternatively, you can use @code{allocate} and @code{free} which allow
2389: freeing memory in any order:
2390:
2391: @example
2392: 10 cells allocate throw .s
2393: 20 cells allocate throw .s
2394: swap
2395: free throw
2396: free throw
2397: @end example
2398:
2399: The @code{throw}s deal with errors (e.g., out of memory).
2400:
1.65 anton 2401: And there is also a
2402: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2403: garbage collector}, which eliminates the need to @code{free} memory
2404: explicitly.
1.48 anton 2405:
1.66 anton 2406: Reference: @ref{Memory}.
2407:
1.48 anton 2408:
2409: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2410: @section Characters and Strings
1.66 anton 2411: @cindex strings tutorial
2412: @cindex characters tutorial
1.48 anton 2413:
2414: On the stack characters take up a cell, like numbers. In memory they
2415: have their own size (one 8-bit byte on most systems), and therefore
2416: require their own words for memory access:
2417:
2418: @example
2419: create v4
2420: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2421: v4 4 chars + c@@ .
1.65 anton 2422: v4 5 chars dump
1.48 anton 2423: @end example
2424:
2425: The preferred representation of strings on the stack is @code{addr
2426: u-count}, where @code{addr} is the address of the first character and
2427: @code{u-count} is the number of characters in the string.
2428:
2429: @example
2430: v4 5 type
2431: @end example
2432:
2433: You get a string constant with
2434:
2435: @example
2436: s" hello, world" .s
2437: type
2438: @end example
2439:
2440: Make sure you have a space between @code{s"} and the string; @code{s"}
2441: is a normal Forth word and must be delimited with white space (try what
2442: happens when you remove the space).
2443:
2444: However, this interpretive use of @code{s"} is quite restricted: the
2445: string exists only until the next call of @code{s"} (some Forth systems
2446: keep more than one of these strings, but usually they still have a
1.62 crook 2447: limited lifetime).
1.48 anton 2448:
2449: @example
2450: s" hello," s" world" .s
2451: type
2452: type
2453: @end example
2454:
1.62 crook 2455: You can also use @code{s"} in a definition, and the resulting
2456: strings then live forever (well, for as long as the definition):
1.48 anton 2457:
2458: @example
2459: : foo s" hello," s" world" ;
2460: foo .s
2461: type
2462: type
2463: @end example
2464:
1.141 anton 2465: @quotation Assignment
1.48 anton 2466: @code{Emit ( c -- )} types @code{c} as character (not a number).
2467: Implement @code{type ( addr u -- )}.
1.141 anton 2468: @end quotation
1.48 anton 2469:
1.66 anton 2470: Reference: @ref{Memory Blocks}.
2471:
2472:
1.84 pazsan 2473: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2474: @section Alignment
1.66 anton 2475: @cindex alignment tutorial
2476: @cindex memory alignment tutorial
1.48 anton 2477:
2478: On many processors cells have to be aligned in memory, if you want to
2479: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2480: not require alignment, access to aligned cells is faster).
1.48 anton 2481:
2482: @code{Create} aligns @code{here} (i.e., the place where the next
2483: allocation will occur, and that the @code{create}d word points to).
2484: Likewise, the memory produced by @code{allocate} starts at an aligned
2485: address. Adding a number of @code{cells} to an aligned address produces
2486: another aligned address.
2487:
2488: However, address arithmetic involving @code{char+} and @code{chars} can
2489: create an address that is not cell-aligned. @code{Aligned ( addr --
2490: a-addr )} produces the next aligned address:
2491:
2492: @example
1.50 anton 2493: v3 char+ aligned .s @@ .
2494: v3 char+ .s @@ .
1.48 anton 2495: @end example
2496:
2497: Similarly, @code{align} advances @code{here} to the next aligned
2498: address:
2499:
2500: @example
2501: create v5 97 c,
2502: here .
2503: align here .
2504: 1000 ,
2505: @end example
2506:
2507: Note that you should use aligned addresses even if your processor does
2508: not require them, if you want your program to be portable.
2509:
1.66 anton 2510: Reference: @ref{Address arithmetic}.
2511:
1.48 anton 2512:
1.84 pazsan 2513: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2514: @section Files
2515: @cindex files tutorial
2516:
2517: This section gives a short introduction into how to use files inside
2518: Forth. It's broken up into five easy steps:
2519:
2520: @enumerate 1
2521: @item Opened an ASCII text file for input
2522: @item Opened a file for output
2523: @item Read input file until string matched (or some other condition matched)
2524: @item Wrote some lines from input ( modified or not) to output
2525: @item Closed the files.
2526: @end enumerate
2527:
1.153 anton 2528: Reference: @ref{General files}.
2529:
1.84 pazsan 2530: @subsection Open file for input
2531:
2532: @example
2533: s" foo.in" r/o open-file throw Value fd-in
2534: @end example
2535:
2536: @subsection Create file for output
2537:
2538: @example
2539: s" foo.out" w/o create-file throw Value fd-out
2540: @end example
2541:
2542: The available file modes are r/o for read-only access, r/w for
2543: read-write access, and w/o for write-only access. You could open both
2544: files with r/w, too, if you like. All file words return error codes; for
2545: most applications, it's best to pass there error codes with @code{throw}
2546: to the outer error handler.
2547:
2548: If you want words for opening and assigning, define them as follows:
2549:
2550: @example
2551: 0 Value fd-in
2552: 0 Value fd-out
2553: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2554: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2555: @end example
2556:
2557: Usage example:
2558:
2559: @example
2560: s" foo.in" open-input
2561: s" foo.out" open-output
2562: @end example
2563:
2564: @subsection Scan file for a particular line
2565:
2566: @example
2567: 256 Constant max-line
2568: Create line-buffer max-line 2 + allot
2569:
2570: : scan-file ( addr u -- )
2571: begin
2572: line-buffer max-line fd-in read-line throw
2573: while
2574: >r 2dup line-buffer r> compare 0=
2575: until
2576: else
2577: drop
2578: then
2579: 2drop ;
2580: @end example
2581:
2582: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2583: the buffer at addr, and returns the number of bytes read, a flag that is
2584: false when the end of file is reached, and an error code.
1.84 pazsan 2585:
2586: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2587: returns zero if both strings are equal. It returns a positive number if
2588: the first string is lexically greater, a negative if the second string
2589: is lexically greater.
2590:
2591: We haven't seen this loop here; it has two exits. Since the @code{while}
2592: exits with the number of bytes read on the stack, we have to clean up
2593: that separately; that's after the @code{else}.
2594:
2595: Usage example:
2596:
2597: @example
2598: s" The text I search is here" scan-file
2599: @end example
2600:
2601: @subsection Copy input to output
2602:
2603: @example
2604: : copy-file ( -- )
2605: begin
2606: line-buffer max-line fd-in read-line throw
2607: while
2608: line-buffer swap fd-out write-file throw
2609: repeat ;
2610: @end example
2611:
2612: @subsection Close files
2613:
2614: @example
2615: fd-in close-file throw
2616: fd-out close-file throw
2617: @end example
2618:
2619: Likewise, you can put that into definitions, too:
2620:
2621: @example
2622: : close-input ( -- ) fd-in close-file throw ;
2623: : close-output ( -- ) fd-out close-file throw ;
2624: @end example
2625:
1.141 anton 2626: @quotation Assignment
1.84 pazsan 2627: How could you modify @code{copy-file} so that it copies until a second line is
2628: matched? Can you write a program that extracts a section of a text file,
2629: given the line that starts and the line that terminates that section?
1.141 anton 2630: @end quotation
1.84 pazsan 2631:
2632: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2633: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2634: @cindex semantics tutorial
2635: @cindex interpretation semantics tutorial
2636: @cindex compilation semantics tutorial
2637: @cindex immediate, tutorial
1.48 anton 2638:
2639: When a word is compiled, it behaves differently from being interpreted.
2640: E.g., consider @code{+}:
2641:
2642: @example
2643: 1 2 + .
2644: : foo + ;
2645: @end example
2646:
2647: These two behaviours are known as compilation and interpretation
2648: semantics. For normal words (e.g., @code{+}), the compilation semantics
2649: is to append the interpretation semantics to the currently defined word
2650: (@code{foo} in the example above). I.e., when @code{foo} is executed
2651: later, the interpretation semantics of @code{+} (i.e., adding two
2652: numbers) will be performed.
2653:
2654: However, there are words with non-default compilation semantics, e.g.,
2655: the control-flow words like @code{if}. You can use @code{immediate} to
2656: change the compilation semantics of the last defined word to be equal to
2657: the interpretation semantics:
2658:
2659: @example
2660: : [FOO] ( -- )
2661: 5 . ; immediate
2662:
2663: [FOO]
2664: : bar ( -- )
2665: [FOO] ;
2666: bar
2667: see bar
2668: @end example
2669:
2670: Two conventions to mark words with non-default compilation semnatics are
2671: names with brackets (more frequently used) and to write them all in
2672: upper case (less frequently used).
2673:
2674: In Gforth (and many other systems) you can also remove the
2675: interpretation semantics with @code{compile-only} (the compilation
2676: semantics is derived from the original interpretation semantics):
2677:
2678: @example
2679: : flip ( -- )
2680: 6 . ; compile-only \ but not immediate
2681: flip
2682:
2683: : flop ( -- )
2684: flip ;
2685: flop
2686: @end example
2687:
2688: In this example the interpretation semantics of @code{flop} is equal to
2689: the original interpretation semantics of @code{flip}.
2690:
2691: The text interpreter has two states: in interpret state, it performs the
2692: interpretation semantics of words it encounters; in compile state, it
2693: performs the compilation semantics of these words.
2694:
2695: Among other things, @code{:} switches into compile state, and @code{;}
2696: switches back to interpret state. They contain the factors @code{]}
2697: (switch to compile state) and @code{[} (switch to interpret state), that
2698: do nothing but switch the state.
2699:
2700: @example
2701: : xxx ( -- )
2702: [ 5 . ]
2703: ;
2704:
2705: xxx
2706: see xxx
2707: @end example
2708:
2709: These brackets are also the source of the naming convention mentioned
2710: above.
2711:
1.66 anton 2712: Reference: @ref{Interpretation and Compilation Semantics}.
2713:
1.48 anton 2714:
2715: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2716: @section Execution Tokens
1.66 anton 2717: @cindex execution tokens tutorial
2718: @cindex XT tutorial
1.48 anton 2719:
2720: @code{' word} gives you the execution token (XT) of a word. The XT is a
2721: cell representing the interpretation semantics of a word. You can
2722: execute this semantics with @code{execute}:
2723:
2724: @example
2725: ' + .s
2726: 1 2 rot execute .
2727: @end example
2728:
2729: The XT is similar to a function pointer in C. However, parameter
2730: passing through the stack makes it a little more flexible:
2731:
2732: @example
2733: : map-array ( ... addr u xt -- ... )
1.50 anton 2734: \ executes xt ( ... x -- ... ) for every element of the array starting
2735: \ at addr and containing u elements
1.48 anton 2736: @{ xt @}
2737: cells over + swap ?do
1.50 anton 2738: i @@ xt execute
1.48 anton 2739: 1 cells +loop ;
2740:
2741: create a 3 , 4 , 2 , -1 , 4 ,
2742: a 5 ' . map-array .s
2743: 0 a 5 ' + map-array .
2744: s" max-n" environment? drop .s
2745: a 5 ' min map-array .
2746: @end example
2747:
2748: You can use map-array with the XTs of words that consume one element
2749: more than they produce. In theory you can also use it with other XTs,
2750: but the stack effect then depends on the size of the array, which is
2751: hard to understand.
2752:
1.51 pazsan 2753: Since XTs are cell-sized, you can store them in memory and manipulate
2754: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2755: word with @code{compile,}:
2756:
2757: @example
2758: : foo1 ( n1 n2 -- n )
2759: [ ' + compile, ] ;
2760: see foo
2761: @end example
2762:
2763: This is non-standard, because @code{compile,} has no compilation
2764: semantics in the standard, but it works in good Forth systems. For the
2765: broken ones, use
2766:
2767: @example
2768: : [compile,] compile, ; immediate
2769:
2770: : foo1 ( n1 n2 -- n )
2771: [ ' + ] [compile,] ;
2772: see foo
2773: @end example
2774:
2775: @code{'} is a word with default compilation semantics; it parses the
2776: next word when its interpretation semantics are executed, not during
2777: compilation:
2778:
2779: @example
2780: : foo ( -- xt )
2781: ' ;
2782: see foo
2783: : bar ( ... "word" -- ... )
2784: ' execute ;
2785: see bar
1.60 anton 2786: 1 2 bar + .
1.48 anton 2787: @end example
2788:
2789: You often want to parse a word during compilation and compile its XT so
2790: it will be pushed on the stack at run-time. @code{[']} does this:
2791:
2792: @example
2793: : xt-+ ( -- xt )
2794: ['] + ;
2795: see xt-+
2796: 1 2 xt-+ execute .
2797: @end example
2798:
2799: Many programmers tend to see @code{'} and the word it parses as one
2800: unit, and expect it to behave like @code{[']} when compiled, and are
2801: confused by the actual behaviour. If you are, just remember that the
2802: Forth system just takes @code{'} as one unit and has no idea that it is
2803: a parsing word (attempts to convenience programmers in this issue have
2804: usually resulted in even worse pitfalls, see
1.66 anton 2805: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2806: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2807:
2808: Note that the state of the interpreter does not come into play when
1.51 pazsan 2809: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2810: compile state, it still gives you the interpretation semantics. And
2811: whatever that state is, @code{execute} performs the semantics
1.66 anton 2812: represented by the XT (i.e., for XTs produced with @code{'} the
2813: interpretation semantics).
2814:
2815: Reference: @ref{Tokens for Words}.
1.48 anton 2816:
2817:
2818: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2819: @section Exceptions
1.66 anton 2820: @cindex exceptions tutorial
1.48 anton 2821:
2822: @code{throw ( n -- )} causes an exception unless n is zero.
2823:
2824: @example
2825: 100 throw .s
2826: 0 throw .s
2827: @end example
2828:
2829: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2830: it catches exceptions and pushes the number of the exception on the
2831: stack (or 0, if the xt executed without exception). If there was an
2832: exception, the stacks have the same depth as when entering @code{catch}:
2833:
2834: @example
2835: .s
2836: 3 0 ' / catch .s
2837: 3 2 ' / catch .s
2838: @end example
2839:
1.141 anton 2840: @quotation Assignment
1.48 anton 2841: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2842: @end quotation
1.48 anton 2843:
2844: @code{Throw} always jumps to the dynamically next enclosing
2845: @code{catch}, even if it has to leave several call levels to achieve
2846: this:
2847:
2848: @example
2849: : foo 100 throw ;
2850: : foo1 foo ." after foo" ;
1.51 pazsan 2851: : bar ['] foo1 catch ;
1.60 anton 2852: bar .
1.48 anton 2853: @end example
2854:
2855: It is often important to restore a value upon leaving a definition, even
2856: if the definition is left through an exception. You can ensure this
2857: like this:
2858:
2859: @example
2860: : ...
2861: save-x
1.51 pazsan 2862: ['] word-changing-x catch ( ... n )
1.48 anton 2863: restore-x
2864: ( ... n ) throw ;
2865: @end example
2866:
1.172 anton 2867: However, this is still not safe against, e.g., the user pressing
2868: @kbd{Ctrl-C} when execution is between the @code{catch} and
2869: @code{restore-x}.
2870:
2871: Gforth provides an alternative exception handling syntax that is safe
2872: against such cases: @code{try ... restore ... endtry}. If the code
2873: between @code{try} and @code{endtry} has an exception, the stack
2874: depths are restored, the exception number is pushed on the stack, and
2875: the execution continues right after @code{restore}.
1.48 anton 2876:
1.172 anton 2877: The safer equivalent to the restoration code above is
1.48 anton 2878:
2879: @example
2880: : ...
2881: save-x
2882: try
1.92 anton 2883: word-changing-x 0
1.172 anton 2884: restore
2885: restore-x
2886: endtry
1.48 anton 2887: throw ;
2888: @end example
2889:
1.66 anton 2890: Reference: @ref{Exception Handling}.
2891:
1.48 anton 2892:
2893: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2894: @section Defining Words
1.66 anton 2895: @cindex defining words tutorial
2896: @cindex does> tutorial
2897: @cindex create...does> tutorial
2898:
2899: @c before semantics?
1.48 anton 2900:
2901: @code{:}, @code{create}, and @code{variable} are definition words: They
2902: define other words. @code{Constant} is another definition word:
2903:
2904: @example
2905: 5 constant foo
2906: foo .
2907: @end example
2908:
2909: You can also use the prefixes @code{2} (double-cell) and @code{f}
2910: (floating point) with @code{variable} and @code{constant}.
2911:
2912: You can also define your own defining words. E.g.:
2913:
2914: @example
2915: : variable ( "name" -- )
2916: create 0 , ;
2917: @end example
2918:
2919: You can also define defining words that create words that do something
2920: other than just producing their address:
2921:
2922: @example
2923: : constant ( n "name" -- )
2924: create ,
2925: does> ( -- n )
1.50 anton 2926: ( addr ) @@ ;
1.48 anton 2927:
2928: 5 constant foo
2929: foo .
2930: @end example
2931:
2932: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2933: @code{does>} replaces @code{;}, but it also does something else: It
2934: changes the last defined word such that it pushes the address of the
2935: body of the word and then performs the code after the @code{does>}
2936: whenever it is called.
2937:
2938: In the example above, @code{constant} uses @code{,} to store 5 into the
2939: body of @code{foo}. When @code{foo} executes, it pushes the address of
2940: the body onto the stack, then (in the code after the @code{does>})
2941: fetches the 5 from there.
2942:
2943: The stack comment near the @code{does>} reflects the stack effect of the
2944: defined word, not the stack effect of the code after the @code{does>}
2945: (the difference is that the code expects the address of the body that
2946: the stack comment does not show).
2947:
2948: You can use these definition words to do factoring in cases that involve
2949: (other) definition words. E.g., a field offset is always added to an
2950: address. Instead of defining
2951:
2952: @example
2953: 2 cells constant offset-field1
2954: @end example
2955:
2956: and using this like
2957:
2958: @example
2959: ( addr ) offset-field1 +
2960: @end example
2961:
2962: you can define a definition word
2963:
2964: @example
2965: : simple-field ( n "name" -- )
2966: create ,
2967: does> ( n1 -- n1+n )
1.50 anton 2968: ( addr ) @@ + ;
1.48 anton 2969: @end example
1.21 crook 2970:
1.48 anton 2971: Definition and use of field offsets now look like this:
1.21 crook 2972:
1.48 anton 2973: @example
2974: 2 cells simple-field field1
1.60 anton 2975: create mystruct 4 cells allot
2976: mystruct .s field1 .s drop
1.48 anton 2977: @end example
1.21 crook 2978:
1.48 anton 2979: If you want to do something with the word without performing the code
2980: after the @code{does>}, you can access the body of a @code{create}d word
2981: with @code{>body ( xt -- addr )}:
1.21 crook 2982:
1.48 anton 2983: @example
2984: : value ( n "name" -- )
2985: create ,
2986: does> ( -- n1 )
1.50 anton 2987: @@ ;
1.48 anton 2988: : to ( n "name" -- )
2989: ' >body ! ;
1.21 crook 2990:
1.48 anton 2991: 5 value foo
2992: foo .
2993: 7 to foo
2994: foo .
2995: @end example
1.21 crook 2996:
1.141 anton 2997: @quotation Assignment
1.48 anton 2998: Define @code{defer ( "name" -- )}, which creates a word that stores an
2999: XT (at the start the XT of @code{abort}), and upon execution
3000: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3001: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3002: recursion is one application of @code{defer}.
1.141 anton 3003: @end quotation
1.29 crook 3004:
1.66 anton 3005: Reference: @ref{User-defined Defining Words}.
3006:
3007:
1.48 anton 3008: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3009: @section Arrays and Records
1.66 anton 3010: @cindex arrays tutorial
3011: @cindex records tutorial
3012: @cindex structs tutorial
1.29 crook 3013:
1.48 anton 3014: Forth has no standard words for defining data structures such as arrays
3015: and records (structs in C terminology), but you can build them yourself
3016: based on address arithmetic. You can also define words for defining
3017: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3018:
1.48 anton 3019: One of the first projects a Forth newcomer sets out upon when learning
3020: about defining words is an array defining word (possibly for
3021: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3022: learn something from it. However, don't be disappointed when you later
3023: learn that you have little use for these words (inappropriate use would
3024: be even worse). I have not yet found a set of useful array words yet;
3025: the needs are just too diverse, and named, global arrays (the result of
3026: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3027: consider how to pass them as parameters). Another such project is a set
3028: of words to help dealing with strings.
1.29 crook 3029:
1.48 anton 3030: On the other hand, there is a useful set of record words, and it has
3031: been defined in @file{compat/struct.fs}; these words are predefined in
3032: Gforth. They are explained in depth elsewhere in this manual (see
3033: @pxref{Structures}). The @code{simple-field} example above is
3034: simplified variant of fields in this package.
1.21 crook 3035:
3036:
1.48 anton 3037: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3038: @section @code{POSTPONE}
1.66 anton 3039: @cindex postpone tutorial
1.21 crook 3040:
1.48 anton 3041: You can compile the compilation semantics (instead of compiling the
3042: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3043:
1.48 anton 3044: @example
3045: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3046: POSTPONE + ; immediate
1.48 anton 3047: : foo ( n1 n2 -- n )
3048: MY-+ ;
3049: 1 2 foo .
3050: see foo
3051: @end example
1.21 crook 3052:
1.48 anton 3053: During the definition of @code{foo} the text interpreter performs the
3054: compilation semantics of @code{MY-+}, which performs the compilation
3055: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3056:
3057: This example also displays separate stack comments for the compilation
3058: semantics and for the stack effect of the compiled code. For words with
3059: default compilation semantics these stack effects are usually not
3060: displayed; the stack effect of the compilation semantics is always
3061: @code{( -- )} for these words, the stack effect for the compiled code is
3062: the stack effect of the interpretation semantics.
3063:
3064: Note that the state of the interpreter does not come into play when
3065: performing the compilation semantics in this way. You can also perform
3066: it interpretively, e.g.:
3067:
3068: @example
3069: : foo2 ( n1 n2 -- n )
3070: [ MY-+ ] ;
3071: 1 2 foo .
3072: see foo
3073: @end example
1.21 crook 3074:
1.48 anton 3075: However, there are some broken Forth systems where this does not always
1.62 crook 3076: work, and therefore this practice was been declared non-standard in
1.48 anton 3077: 1999.
3078: @c !! repair.fs
3079:
3080: Here is another example for using @code{POSTPONE}:
1.44 crook 3081:
1.48 anton 3082: @example
3083: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3084: POSTPONE negate POSTPONE + ; immediate compile-only
3085: : bar ( n1 n2 -- n )
3086: MY-- ;
3087: 2 1 bar .
3088: see bar
3089: @end example
1.21 crook 3090:
1.48 anton 3091: You can define @code{ENDIF} in this way:
1.21 crook 3092:
1.48 anton 3093: @example
3094: : ENDIF ( Compilation: orig -- )
3095: POSTPONE then ; immediate
3096: @end example
1.21 crook 3097:
1.141 anton 3098: @quotation Assignment
1.48 anton 3099: Write @code{MY-2DUP} that has compilation semantics equivalent to
3100: @code{2dup}, but compiles @code{over over}.
1.141 anton 3101: @end quotation
1.29 crook 3102:
1.66 anton 3103: @c !! @xref{Macros} for reference
3104:
3105:
1.48 anton 3106: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3107: @section @code{Literal}
1.66 anton 3108: @cindex literal tutorial
1.29 crook 3109:
1.48 anton 3110: You cannot @code{POSTPONE} numbers:
1.21 crook 3111:
1.48 anton 3112: @example
3113: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3114: @end example
3115:
1.48 anton 3116: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3117:
1.48 anton 3118: @example
3119: : [FOO] ( compilation: --; run-time: -- n )
3120: 500 POSTPONE literal ; immediate
1.29 crook 3121:
1.60 anton 3122: : flip [FOO] ;
1.48 anton 3123: flip .
3124: see flip
3125: @end example
1.29 crook 3126:
1.48 anton 3127: @code{LITERAL} consumes a number at compile-time (when it's compilation
3128: semantics are executed) and pushes it at run-time (when the code it
3129: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3130: number computed at compile time into the current word:
1.29 crook 3131:
1.48 anton 3132: @example
3133: : bar ( -- n )
3134: [ 2 2 + ] literal ;
3135: see bar
3136: @end example
1.29 crook 3137:
1.141 anton 3138: @quotation Assignment
1.48 anton 3139: Write @code{]L} which allows writing the example above as @code{: bar (
3140: -- n ) [ 2 2 + ]L ;}
1.141 anton 3141: @end quotation
1.48 anton 3142:
1.66 anton 3143: @c !! @xref{Macros} for reference
3144:
1.48 anton 3145:
3146: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3147: @section Advanced macros
1.66 anton 3148: @cindex macros, advanced tutorial
3149: @cindex run-time code generation, tutorial
1.48 anton 3150:
1.66 anton 3151: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3152: Execution Tokens}. It frequently performs @code{execute}, a relatively
3153: expensive operation in some Forth implementations. You can use
1.48 anton 3154: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3155: and produce a word that contains the word to be performed directly:
3156:
3157: @c use ]] ... [[
3158: @example
3159: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3160: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3161: \ array beginning at addr and containing u elements
3162: @{ xt @}
3163: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3164: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3165: 1 cells POSTPONE literal POSTPONE +loop ;
3166:
3167: : sum-array ( addr u -- n )
3168: 0 rot rot [ ' + compile-map-array ] ;
3169: see sum-array
3170: a 5 sum-array .
3171: @end example
3172:
3173: You can use the full power of Forth for generating the code; here's an
3174: example where the code is generated in a loop:
3175:
3176: @example
3177: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3178: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3179: POSTPONE tuck POSTPONE @@
1.48 anton 3180: POSTPONE literal POSTPONE * POSTPONE +
3181: POSTPONE swap POSTPONE cell+ ;
3182:
3183: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3184: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3185: 0 postpone literal postpone swap
3186: [ ' compile-vmul-step compile-map-array ]
3187: postpone drop ;
3188: see compile-vmul
3189:
3190: : a-vmul ( addr -- n )
1.51 pazsan 3191: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3192: [ a 5 compile-vmul ] ;
3193: see a-vmul
3194: a a-vmul .
3195: @end example
3196:
3197: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3198: also use @code{map-array} instead (try it now!).
1.48 anton 3199:
3200: You can use this technique for efficient multiplication of large
3201: matrices. In matrix multiplication, you multiply every line of one
3202: matrix with every column of the other matrix. You can generate the code
3203: for one line once, and use it for every column. The only downside of
3204: this technique is that it is cumbersome to recover the memory consumed
3205: by the generated code when you are done (and in more complicated cases
3206: it is not possible portably).
3207:
1.66 anton 3208: @c !! @xref{Macros} for reference
3209:
3210:
1.48 anton 3211: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3212: @section Compilation Tokens
1.66 anton 3213: @cindex compilation tokens, tutorial
3214: @cindex CT, tutorial
1.48 anton 3215:
3216: This section is Gforth-specific. You can skip it.
3217:
3218: @code{' word compile,} compiles the interpretation semantics. For words
3219: with default compilation semantics this is the same as performing the
3220: compilation semantics. To represent the compilation semantics of other
3221: words (e.g., words like @code{if} that have no interpretation
3222: semantics), Gforth has the concept of a compilation token (CT,
3223: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3224: You can perform the compilation semantics represented by a CT with
3225: @code{execute}:
1.29 crook 3226:
1.48 anton 3227: @example
3228: : foo2 ( n1 n2 -- n )
3229: [ comp' + execute ] ;
3230: see foo
3231: @end example
1.29 crook 3232:
1.48 anton 3233: You can compile the compilation semantics represented by a CT with
3234: @code{postpone,}:
1.30 anton 3235:
1.48 anton 3236: @example
3237: : foo3 ( -- )
3238: [ comp' + postpone, ] ;
3239: see foo3
3240: @end example
1.30 anton 3241:
1.51 pazsan 3242: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3243: @code{comp'} is particularly useful for words that have no
3244: interpretation semantics:
1.29 crook 3245:
1.30 anton 3246: @example
1.48 anton 3247: ' if
1.60 anton 3248: comp' if .s 2drop
1.30 anton 3249: @end example
3250:
1.66 anton 3251: Reference: @ref{Tokens for Words}.
3252:
1.29 crook 3253:
1.48 anton 3254: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3255: @section Wordlists and Search Order
1.66 anton 3256: @cindex wordlists tutorial
3257: @cindex search order, tutorial
1.48 anton 3258:
3259: The dictionary is not just a memory area that allows you to allocate
3260: memory with @code{allot}, it also contains the Forth words, arranged in
3261: several wordlists. When searching for a word in a wordlist,
3262: conceptually you start searching at the youngest and proceed towards
3263: older words (in reality most systems nowadays use hash-tables); i.e., if
3264: you define a word with the same name as an older word, the new word
3265: shadows the older word.
3266:
3267: Which wordlists are searched in which order is determined by the search
3268: order. You can display the search order with @code{order}. It displays
3269: first the search order, starting with the wordlist searched first, then
3270: it displays the wordlist that will contain newly defined words.
1.21 crook 3271:
1.48 anton 3272: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3273:
1.48 anton 3274: @example
3275: wordlist constant mywords
3276: @end example
1.21 crook 3277:
1.48 anton 3278: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3279: defined words (the @emph{current} wordlist):
1.21 crook 3280:
1.48 anton 3281: @example
3282: mywords set-current
3283: order
3284: @end example
1.26 crook 3285:
1.48 anton 3286: Gforth does not display a name for the wordlist in @code{mywords}
3287: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3288:
1.48 anton 3289: You can get the current wordlist with @code{get-current ( -- wid)}. If
3290: you want to put something into a specific wordlist without overall
3291: effect on the current wordlist, this typically looks like this:
1.21 crook 3292:
1.48 anton 3293: @example
3294: get-current mywords set-current ( wid )
3295: create someword
3296: ( wid ) set-current
3297: @end example
1.21 crook 3298:
1.48 anton 3299: You can write the search order with @code{set-order ( wid1 .. widn n --
3300: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3301: searched wordlist is topmost.
1.21 crook 3302:
1.48 anton 3303: @example
3304: get-order mywords swap 1+ set-order
3305: order
3306: @end example
1.21 crook 3307:
1.48 anton 3308: Yes, the order of wordlists in the output of @code{order} is reversed
3309: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3310:
1.141 anton 3311: @quotation Assignment
1.48 anton 3312: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3313: wordlist to the search order. Define @code{previous ( -- )}, which
3314: removes the first searched wordlist from the search order. Experiment
3315: with boundary conditions (you will see some crashes or situations that
3316: are hard or impossible to leave).
1.141 anton 3317: @end quotation
1.21 crook 3318:
1.48 anton 3319: The search order is a powerful foundation for providing features similar
3320: to Modula-2 modules and C++ namespaces. However, trying to modularize
3321: programs in this way has disadvantages for debugging and reuse/factoring
3322: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3323: though). These disadvantages are not so clear in other
1.82 anton 3324: languages/programming environments, because these languages are not so
1.48 anton 3325: strong in debugging and reuse.
1.21 crook 3326:
1.66 anton 3327: @c !! example
3328:
3329: Reference: @ref{Word Lists}.
1.21 crook 3330:
1.29 crook 3331: @c ******************************************************************
1.48 anton 3332: @node Introduction, Words, Tutorial, Top
1.29 crook 3333: @comment node-name, next, previous, up
3334: @chapter An Introduction to ANS Forth
3335: @cindex Forth - an introduction
1.21 crook 3336:
1.83 anton 3337: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3338: that it is slower-paced in its examples, but uses them to dive deep into
3339: explaining Forth internals (not covered by the Tutorial). Apart from
3340: that, this chapter covers far less material. It is suitable for reading
3341: without using a computer.
3342:
1.29 crook 3343: The primary purpose of this manual is to document Gforth. However, since
3344: Forth is not a widely-known language and there is a lack of up-to-date
3345: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3346: material. For other sources of Forth-related
3347: information, see @ref{Forth-related information}.
1.21 crook 3348:
1.29 crook 3349: The examples in this section should work on any ANS Forth; the
3350: output shown was produced using Gforth. Each example attempts to
3351: reproduce the exact output that Gforth produces. If you try out the
3352: examples (and you should), what you should type is shown @kbd{like this}
3353: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3354: that, where the example shows @key{RET} it means that you should
1.29 crook 3355: press the ``carriage return'' key. Unfortunately, some output formats for
3356: this manual cannot show the difference between @kbd{this} and
3357: @code{this} which will make trying out the examples harder (but not
3358: impossible).
1.21 crook 3359:
1.29 crook 3360: Forth is an unusual language. It provides an interactive development
3361: environment which includes both an interpreter and compiler. Forth
3362: programming style encourages you to break a problem down into many
3363: @cindex factoring
3364: small fragments (@dfn{factoring}), and then to develop and test each
3365: fragment interactively. Forth advocates assert that breaking the
3366: edit-compile-test cycle used by conventional programming languages can
3367: lead to great productivity improvements.
1.21 crook 3368:
1.29 crook 3369: @menu
1.67 anton 3370: * Introducing the Text Interpreter::
3371: * Stacks and Postfix notation::
3372: * Your first definition::
3373: * How does that work?::
3374: * Forth is written in Forth::
3375: * Review - elements of a Forth system::
3376: * Where to go next::
3377: * Exercises::
1.29 crook 3378: @end menu
1.21 crook 3379:
1.29 crook 3380: @comment ----------------------------------------------
3381: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3382: @section Introducing the Text Interpreter
3383: @cindex text interpreter
3384: @cindex outer interpreter
1.21 crook 3385:
1.30 anton 3386: @c IMO this is too detailed and the pace is too slow for
3387: @c an introduction. If you know German, take a look at
3388: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3389: @c to see how I do it - anton
3390:
1.44 crook 3391: @c nac-> Where I have accepted your comments 100% and modified the text
3392: @c accordingly, I have deleted your comments. Elsewhere I have added a
3393: @c response like this to attempt to rationalise what I have done. Of
3394: @c course, this is a very clumsy mechanism for something that would be
3395: @c done far more efficiently over a beer. Please delete any dialogue
3396: @c you consider closed.
3397:
1.29 crook 3398: When you invoke the Forth image, you will see a startup banner printed
3399: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3400: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3401: its command line interpreter, which is called the @dfn{Text Interpreter}
3402: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3403: about the text interpreter as you read through this chapter, for more
3404: detail @pxref{The Text Interpreter}).
1.21 crook 3405:
1.29 crook 3406: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3407: input. Type a number and press the @key{RET} key:
1.21 crook 3408:
1.26 crook 3409: @example
1.30 anton 3410: @kbd{45@key{RET}} ok
1.26 crook 3411: @end example
1.21 crook 3412:
1.29 crook 3413: Rather than give you a prompt to invite you to input something, the text
3414: interpreter prints a status message @i{after} it has processed a line
3415: of input. The status message in this case (``@code{ ok}'' followed by
3416: carriage-return) indicates that the text interpreter was able to process
3417: all of your input successfully. Now type something illegal:
3418:
3419: @example
1.30 anton 3420: @kbd{qwer341@key{RET}}
1.134 anton 3421: *the terminal*:2: Undefined word
3422: >>>qwer341<<<
3423: Backtrace:
3424: $2A95B42A20 throw
3425: $2A95B57FB8 no.extensions
1.29 crook 3426: @end example
1.23 crook 3427:
1.134 anton 3428: The exact text, other than the ``Undefined word'' may differ slightly
3429: on your system, but the effect is the same; when the text interpreter
1.29 crook 3430: detects an error, it discards any remaining text on a line, resets
1.134 anton 3431: certain internal state and prints an error message. For a detailed
3432: description of error messages see @ref{Error messages}.
1.23 crook 3433:
1.29 crook 3434: The text interpreter waits for you to press carriage-return, and then
3435: processes your input line. Starting at the beginning of the line, it
3436: breaks the line into groups of characters separated by spaces. For each
3437: group of characters in turn, it makes two attempts to do something:
1.23 crook 3438:
1.29 crook 3439: @itemize @bullet
3440: @item
1.44 crook 3441: @cindex name dictionary
1.29 crook 3442: It tries to treat it as a command. It does this by searching a @dfn{name
3443: dictionary}. If the group of characters matches an entry in the name
3444: dictionary, the name dictionary provides the text interpreter with
3445: information that allows the text interpreter perform some actions. In
3446: Forth jargon, we say that the group
3447: @cindex word
3448: @cindex definition
3449: @cindex execution token
3450: @cindex xt
3451: of characters names a @dfn{word}, that the dictionary search returns an
3452: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3453: word, and that the text interpreter executes the xt. Often, the terms
3454: @dfn{word} and @dfn{definition} are used interchangeably.
3455: @item
3456: If the text interpreter fails to find a match in the name dictionary, it
3457: tries to treat the group of characters as a number in the current number
3458: base (when you start up Forth, the current number base is base 10). If
3459: the group of characters legitimately represents a number, the text
3460: interpreter pushes the number onto a stack (we'll learn more about that
3461: in the next section).
3462: @end itemize
1.23 crook 3463:
1.29 crook 3464: If the text interpreter is unable to do either of these things with any
3465: group of characters, it discards the group of characters and the rest of
3466: the line, then prints an error message. If the text interpreter reaches
3467: the end of the line without error, it prints the status message ``@code{ ok}''
3468: followed by carriage-return.
1.21 crook 3469:
1.29 crook 3470: This is the simplest command we can give to the text interpreter:
1.23 crook 3471:
3472: @example
1.30 anton 3473: @key{RET} ok
1.23 crook 3474: @end example
1.21 crook 3475:
1.29 crook 3476: The text interpreter did everything we asked it to do (nothing) without
3477: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3478: command:
1.21 crook 3479:
1.23 crook 3480: @example
1.30 anton 3481: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3482: *the terminal*:3: Undefined word
3483: 12 dup >>>fred<<< dup
3484: Backtrace:
3485: $2A95B42A20 throw
3486: $2A95B57FB8 no.extensions
1.23 crook 3487: @end example
1.21 crook 3488:
1.29 crook 3489: When you press the carriage-return key, the text interpreter starts to
3490: work its way along the line:
1.21 crook 3491:
1.29 crook 3492: @itemize @bullet
3493: @item
3494: When it gets to the space after the @code{2}, it takes the group of
3495: characters @code{12} and looks them up in the name
3496: dictionary@footnote{We can't tell if it found them or not, but assume
3497: for now that it did not}. There is no match for this group of characters
3498: in the name dictionary, so it tries to treat them as a number. It is
3499: able to do this successfully, so it puts the number, 12, ``on the stack''
3500: (whatever that means).
3501: @item
3502: The text interpreter resumes scanning the line and gets the next group
3503: of characters, @code{dup}. It looks it up in the name dictionary and
3504: (you'll have to take my word for this) finds it, and executes the word
3505: @code{dup} (whatever that means).
3506: @item
3507: Once again, the text interpreter resumes scanning the line and gets the
3508: group of characters @code{fred}. It looks them up in the name
3509: dictionary, but can't find them. It tries to treat them as a number, but
3510: they don't represent any legal number.
3511: @end itemize
1.21 crook 3512:
1.29 crook 3513: At this point, the text interpreter gives up and prints an error
3514: message. The error message shows exactly how far the text interpreter
3515: got in processing the line. In particular, it shows that the text
3516: interpreter made no attempt to do anything with the final character
3517: group, @code{dup}, even though we have good reason to believe that the
3518: text interpreter would have no problem looking that word up and
3519: executing it a second time.
1.21 crook 3520:
3521:
1.29 crook 3522: @comment ----------------------------------------------
3523: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3524: @section Stacks, postfix notation and parameter passing
3525: @cindex text interpreter
3526: @cindex outer interpreter
1.21 crook 3527:
1.29 crook 3528: In procedural programming languages (like C and Pascal), the
3529: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3530: functions or procedures are called with @dfn{explicit parameters}. For
3531: example, in C we might write:
1.21 crook 3532:
1.23 crook 3533: @example
1.29 crook 3534: total = total + new_volume(length,height,depth);
1.23 crook 3535: @end example
1.21 crook 3536:
1.23 crook 3537: @noindent
1.29 crook 3538: where new_volume is a function-call to another piece of code, and total,
3539: length, height and depth are all variables. length, height and depth are
3540: parameters to the function-call.
1.21 crook 3541:
1.29 crook 3542: In Forth, the equivalent of the function or procedure is the
3543: @dfn{definition} and parameters are implicitly passed between
3544: definitions using a shared stack that is visible to the
3545: programmer. Although Forth does support variables, the existence of the
3546: stack means that they are used far less often than in most other
3547: programming languages. When the text interpreter encounters a number, it
3548: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3549: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3550: used for any operation is implied unambiguously by the operation being
3551: performed. The stack used for all integer operations is called the @dfn{data
3552: stack} and, since this is the stack used most commonly, references to
3553: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3554:
1.29 crook 3555: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3556:
1.23 crook 3557: @example
1.30 anton 3558: @kbd{1 2 3@key{RET}} ok
1.23 crook 3559: @end example
1.21 crook 3560:
1.29 crook 3561: Then this instructs the text interpreter to placed three numbers on the
3562: (data) stack. An analogy for the behaviour of the stack is to take a
3563: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3564: the table. The 3 was the last card onto the pile (``last-in'') and if
3565: you take a card off the pile then, unless you're prepared to fiddle a
3566: bit, the card that you take off will be the 3 (``first-out''). The
3567: number that will be first-out of the stack is called the @dfn{top of
3568: stack}, which
3569: @cindex TOS definition
3570: is often abbreviated to @dfn{TOS}.
1.21 crook 3571:
1.29 crook 3572: To understand how parameters are passed in Forth, consider the
3573: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3574: be surprised to learn that this definition performs addition. More
3575: precisely, it adds two number together and produces a result. Where does
3576: it get the two numbers from? It takes the top two numbers off the
3577: stack. Where does it place the result? On the stack. You can act-out the
3578: behaviour of @code{+} with your playing cards like this:
1.21 crook 3579:
3580: @itemize @bullet
3581: @item
1.29 crook 3582: Pick up two cards from the stack on the table
1.21 crook 3583: @item
1.29 crook 3584: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3585: numbers''
1.21 crook 3586: @item
1.29 crook 3587: Decide that the answer is 5
1.21 crook 3588: @item
1.29 crook 3589: Shuffle the two cards back into the pack and find a 5
1.21 crook 3590: @item
1.29 crook 3591: Put a 5 on the remaining ace that's on the table.
1.21 crook 3592: @end itemize
3593:
1.29 crook 3594: If you don't have a pack of cards handy but you do have Forth running,
3595: you can use the definition @code{.s} to show the current state of the stack,
3596: without affecting the stack. Type:
1.21 crook 3597:
3598: @example
1.124 anton 3599: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3600: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3601: @end example
3602:
1.124 anton 3603: The text interpreter looks up the word @code{clearstacks} and executes
3604: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3605: left on it by earlier examples. The text interpreter pushes each of the
3606: three numbers in turn onto the stack. Finally, the text interpreter
3607: looks up the word @code{.s} and executes it. The effect of executing
3608: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3609: followed by a list of all the items on the stack; the item on the far
3610: right-hand side is the TOS.
1.21 crook 3611:
1.29 crook 3612: You can now type:
1.21 crook 3613:
1.29 crook 3614: @example
1.30 anton 3615: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3616: @end example
1.21 crook 3617:
1.29 crook 3618: @noindent
3619: which is correct; there are now 2 items on the stack and the result of
3620: the addition is 5.
1.23 crook 3621:
1.29 crook 3622: If you're playing with cards, try doing a second addition: pick up the
3623: two cards, work out that their sum is 6, shuffle them into the pack,
3624: look for a 6 and place that on the table. You now have just one item on
3625: the stack. What happens if you try to do a third addition? Pick up the
3626: first card, pick up the second card -- ah! There is no second card. This
3627: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3628: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3629: Underflow or an Invalid Memory Address error).
1.23 crook 3630:
1.29 crook 3631: The opposite situation to a stack underflow is a @dfn{stack overflow},
3632: which simply accepts that there is a finite amount of storage space
3633: reserved for the stack. To stretch the playing card analogy, if you had
3634: enough packs of cards and you piled the cards up on the table, you would
3635: eventually be unable to add another card; you'd hit the ceiling. Gforth
3636: allows you to set the maximum size of the stacks. In general, the only
3637: time that you will get a stack overflow is because a definition has a
3638: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3639:
1.29 crook 3640: There's one final use for the playing card analogy. If you model your
3641: stack using a pack of playing cards, the maximum number of items on
3642: your stack will be 52 (I assume you didn't use the Joker). The maximum
3643: @i{value} of any item on the stack is 13 (the King). In fact, the only
3644: possible numbers are positive integer numbers 1 through 13; you can't
3645: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3646: think about some of the cards, you can accommodate different
3647: numbers. For example, you could think of the Jack as representing 0,
3648: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3649: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3650: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3651:
1.29 crook 3652: In that analogy, the limit was the amount of information that a single
3653: stack entry could hold, and Forth has a similar limit. In Forth, the
3654: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3655: implementation dependent and affects the maximum value that a stack
3656: entry can hold. A Standard Forth provides a cell size of at least
3657: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3658:
1.29 crook 3659: Forth does not do any type checking for you, so you are free to
3660: manipulate and combine stack items in any way you wish. A convenient way
3661: of treating stack items is as 2's complement signed integers, and that
3662: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3663:
1.29 crook 3664: @example
1.30 anton 3665: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3666: @end example
1.21 crook 3667:
1.29 crook 3668: If you use numbers and definitions like @code{+} in order to turn Forth
3669: into a great big pocket calculator, you will realise that it's rather
3670: different from a normal calculator. Rather than typing 2 + 3 = you had
3671: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3672: result). The terminology used to describe this difference is to say that
3673: your calculator uses @dfn{Infix Notation} (parameters and operators are
3674: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3675: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3676:
1.29 crook 3677: Whilst postfix notation might look confusing to begin with, it has
3678: several important advantages:
1.21 crook 3679:
1.23 crook 3680: @itemize @bullet
3681: @item
1.29 crook 3682: it is unambiguous
1.23 crook 3683: @item
1.29 crook 3684: it is more concise
1.23 crook 3685: @item
1.29 crook 3686: it fits naturally with a stack-based system
1.23 crook 3687: @end itemize
1.21 crook 3688:
1.29 crook 3689: To examine these claims in more detail, consider these sums:
1.21 crook 3690:
1.29 crook 3691: @example
3692: 6 + 5 * 4 =
3693: 4 * 5 + 6 =
3694: @end example
1.21 crook 3695:
1.29 crook 3696: If you're just learning maths or your maths is very rusty, you will
3697: probably come up with the answer 44 for the first and 26 for the
3698: second. If you are a bit of a whizz at maths you will remember the
3699: @i{convention} that multiplication takes precendence over addition, and
3700: you'd come up with the answer 26 both times. To explain the answer 26
3701: to someone who got the answer 44, you'd probably rewrite the first sum
3702: like this:
1.21 crook 3703:
1.29 crook 3704: @example
3705: 6 + (5 * 4) =
3706: @end example
1.21 crook 3707:
1.29 crook 3708: If what you really wanted was to perform the addition before the
3709: multiplication, you would have to use parentheses to force it.
1.21 crook 3710:
1.29 crook 3711: If you did the first two sums on a pocket calculator you would probably
3712: get the right answers, unless you were very cautious and entered them using
3713: these keystroke sequences:
1.21 crook 3714:
1.29 crook 3715: 6 + 5 = * 4 =
3716: 4 * 5 = + 6 =
1.21 crook 3717:
1.29 crook 3718: Postfix notation is unambiguous because the order that the operators
3719: are applied is always explicit; that also means that parentheses are
3720: never required. The operators are @i{active} (the act of quoting the
3721: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3722:
1.29 crook 3723: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3724: equivalent ways:
1.26 crook 3725:
3726: @example
1.29 crook 3727: 6 5 4 * + or:
3728: 5 4 * 6 +
1.26 crook 3729: @end example
1.23 crook 3730:
1.29 crook 3731: An important thing that you should notice about this notation is that
3732: the @i{order} of the numbers does not change; if you want to subtract
3733: 2 from 10 you type @code{10 2 -}.
1.1 anton 3734:
1.29 crook 3735: The reason that Forth uses postfix notation is very simple to explain: it
3736: makes the implementation extremely simple, and it follows naturally from
3737: using the stack as a mechanism for passing parameters. Another way of
3738: thinking about this is to realise that all Forth definitions are
3739: @i{active}; they execute as they are encountered by the text
3740: interpreter. The result of this is that the syntax of Forth is trivially
3741: simple.
1.1 anton 3742:
3743:
3744:
1.29 crook 3745: @comment ----------------------------------------------
3746: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3747: @section Your first Forth definition
3748: @cindex first definition
1.1 anton 3749:
1.29 crook 3750: Until now, the examples we've seen have been trivial; we've just been
3751: using Forth as a bigger-than-pocket calculator. Also, each calculation
3752: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3753: again@footnote{That's not quite true. If you press the up-arrow key on
3754: your keyboard you should be able to scroll back to any earlier command,
3755: edit it and re-enter it.} In this section we'll see how to add new
3756: words to Forth's vocabulary.
1.1 anton 3757:
1.29 crook 3758: The easiest way to create a new word is to use a @dfn{colon
3759: definition}. We'll define a few and try them out before worrying too
3760: much about how they work. Try typing in these examples; be careful to
3761: copy the spaces accurately:
1.1 anton 3762:
1.29 crook 3763: @example
3764: : add-two 2 + . ;
3765: : greet ." Hello and welcome" ;
3766: : demo 5 add-two ;
3767: @end example
1.1 anton 3768:
1.29 crook 3769: @noindent
3770: Now try them out:
1.1 anton 3771:
1.29 crook 3772: @example
1.30 anton 3773: @kbd{greet@key{RET}} Hello and welcome ok
3774: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3775: @kbd{4 add-two@key{RET}} 6 ok
3776: @kbd{demo@key{RET}} 7 ok
3777: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3778: @end example
1.1 anton 3779:
1.29 crook 3780: The first new thing that we've introduced here is the pair of words
3781: @code{:} and @code{;}. These are used to start and terminate a new
3782: definition, respectively. The first word after the @code{:} is the name
3783: for the new definition.
1.1 anton 3784:
1.29 crook 3785: As you can see from the examples, a definition is built up of words that
3786: have already been defined; Forth makes no distinction between
3787: definitions that existed when you started the system up, and those that
3788: you define yourself.
1.1 anton 3789:
1.29 crook 3790: The examples also introduce the words @code{.} (dot), @code{."}
3791: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3792: the stack and displays it. It's like @code{.s} except that it only
3793: displays the top item of the stack and it is destructive; after it has
3794: executed, the number is no longer on the stack. There is always one
3795: space printed after the number, and no spaces before it. Dot-quote
3796: defines a string (a sequence of characters) that will be printed when
3797: the word is executed. The string can contain any printable characters
3798: except @code{"}. A @code{"} has a special function; it is not a Forth
3799: word but it acts as a delimiter (the way that delimiters work is
3800: described in the next section). Finally, @code{dup} duplicates the value
3801: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3802:
1.29 crook 3803: We already know that the text interpreter searches through the
3804: dictionary to locate names. If you've followed the examples earlier, you
3805: will already have a definition called @code{add-two}. Lets try modifying
3806: it by typing in a new definition:
1.1 anton 3807:
1.29 crook 3808: @example
1.30 anton 3809: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3810: @end example
1.5 anton 3811:
1.29 crook 3812: Forth recognised that we were defining a word that already exists, and
3813: printed a message to warn us of that fact. Let's try out the new
3814: definition:
1.5 anton 3815:
1.29 crook 3816: @example
1.30 anton 3817: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3818: @end example
1.1 anton 3819:
1.29 crook 3820: @noindent
3821: All that we've actually done here, though, is to create a new
3822: definition, with a particular name. The fact that there was already a
3823: definition with the same name did not make any difference to the way
3824: that the new definition was created (except that Forth printed a warning
3825: message). The old definition of add-two still exists (try @code{demo}
3826: again to see that this is true). Any new definition will use the new
3827: definition of @code{add-two}, but old definitions continue to use the
3828: version that already existed at the time that they were @code{compiled}.
1.1 anton 3829:
1.29 crook 3830: Before you go on to the next section, try defining and redefining some
3831: words of your own.
1.1 anton 3832:
1.29 crook 3833: @comment ----------------------------------------------
3834: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3835: @section How does that work?
3836: @cindex parsing words
1.1 anton 3837:
1.30 anton 3838: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3839:
3840: @c Is it a good idea to talk about the interpretation semantics of a
3841: @c number? We don't have an xt to go along with it. - anton
3842:
3843: @c Now that I have eliminated execution semantics, I wonder if it would not
3844: @c be better to keep them (or add run-time semantics), to make it easier to
3845: @c explain what compilation semantics usually does. - anton
3846:
1.44 crook 3847: @c nac-> I removed the term ``default compilation sematics'' from the
3848: @c introductory chapter. Removing ``execution semantics'' was making
3849: @c everything simpler to explain, then I think the use of this term made
3850: @c everything more complex again. I replaced it with ``default
3851: @c semantics'' (which is used elsewhere in the manual) by which I mean
3852: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3853: @c flag set''.
3854:
3855: @c anton: I have eliminated default semantics (except in one place where it
3856: @c means "default interpretation and compilation semantics"), because it
3857: @c makes no sense in the presence of combined words. I reverted to
3858: @c "execution semantics" where necessary.
3859:
3860: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3861: @c section (and, unusually for me, I think I even made it shorter!). See
3862: @c what you think -- I know I have not addressed your primary concern
3863: @c that it is too heavy-going for an introduction. From what I understood
3864: @c of your course notes it looks as though they might be a good framework.
3865: @c Things that I've tried to capture here are some things that came as a
3866: @c great revelation here when I first understood them. Also, I like the
3867: @c fact that a very simple code example shows up almost all of the issues
3868: @c that you need to understand to see how Forth works. That's unique and
3869: @c worthwhile to emphasise.
3870:
1.83 anton 3871: @c anton: I think it's a good idea to present the details, especially those
3872: @c that you found to be a revelation, and probably the tutorial tries to be
3873: @c too superficial and does not get some of the things across that make
3874: @c Forth special. I do believe that most of the time these things should
3875: @c be discussed at the end of a section or in separate sections instead of
3876: @c in the middle of a section (e.g., the stuff you added in "User-defined
3877: @c defining words" leads in a completely different direction from the rest
3878: @c of the section).
3879:
1.29 crook 3880: Now we're going to take another look at the definition of @code{add-two}
3881: from the previous section. From our knowledge of the way that the text
3882: interpreter works, we would have expected this result when we tried to
3883: define @code{add-two}:
1.21 crook 3884:
1.29 crook 3885: @example
1.44 crook 3886: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3887: *the terminal*:4: Undefined word
3888: : >>>add-two<<< 2 + . ;
1.29 crook 3889: @end example
1.28 crook 3890:
1.29 crook 3891: The reason that this didn't happen is bound up in the way that @code{:}
3892: works. The word @code{:} does two special things. The first special
3893: thing that it does prevents the text interpreter from ever seeing the
3894: characters @code{add-two}. The text interpreter uses a variable called
3895: @cindex modifying >IN
1.44 crook 3896: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3897: input line. When it encounters the word @code{:} it behaves in exactly
3898: the same way as it does for any other word; it looks it up in the name
3899: dictionary, finds its xt and executes it. When @code{:} executes, it
3900: looks at the input buffer, finds the word @code{add-two} and advances the
3901: value of @code{>IN} to point past it. It then does some other stuff
3902: associated with creating the new definition (including creating an entry
3903: for @code{add-two} in the name dictionary). When the execution of @code{:}
3904: completes, control returns to the text interpreter, which is oblivious
3905: to the fact that it has been tricked into ignoring part of the input
3906: line.
1.21 crook 3907:
1.29 crook 3908: @cindex parsing words
3909: Words like @code{:} -- words that advance the value of @code{>IN} and so
3910: prevent the text interpreter from acting on the whole of the input line
3911: -- are called @dfn{parsing words}.
1.21 crook 3912:
1.29 crook 3913: @cindex @code{state} - effect on the text interpreter
3914: @cindex text interpreter - effect of state
3915: The second special thing that @code{:} does is change the value of a
3916: variable called @code{state}, which affects the way that the text
3917: interpreter behaves. When Gforth starts up, @code{state} has the value
3918: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3919: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3920: the text interpreter is said to be @dfn{compiling}.
3921:
3922: In this example, the text interpreter is compiling when it processes the
3923: string ``@code{2 + . ;}''. It still breaks the string down into
3924: character sequences in the same way. However, instead of pushing the
3925: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3926: into the definition of @code{add-two} that will make the number @code{2} get
3927: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3928: the behaviours of @code{+} and @code{.} are also compiled into the
3929: definition.
3930:
3931: One category of words don't get compiled. These so-called @dfn{immediate
3932: words} get executed (performed @i{now}) regardless of whether the text
3933: interpreter is interpreting or compiling. The word @code{;} is an
3934: immediate word. Rather than being compiled into the definition, it
3935: executes. Its effect is to terminate the current definition, which
3936: includes changing the value of @code{state} back to 0.
3937:
3938: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3939: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3940: definition.
1.28 crook 3941:
1.30 anton 3942: In Forth, every word or number can be described in terms of two
1.29 crook 3943: properties:
1.28 crook 3944:
3945: @itemize @bullet
3946: @item
1.29 crook 3947: @cindex interpretation semantics
1.44 crook 3948: Its @dfn{interpretation semantics} describe how it will behave when the
3949: text interpreter encounters it in @dfn{interpret} state. The
3950: interpretation semantics of a word are represented by an @dfn{execution
3951: token}.
1.28 crook 3952: @item
1.29 crook 3953: @cindex compilation semantics
1.44 crook 3954: Its @dfn{compilation semantics} describe how it will behave when the
3955: text interpreter encounters it in @dfn{compile} state. The compilation
3956: semantics of a word are represented in an implementation-dependent way;
3957: Gforth uses a @dfn{compilation token}.
1.29 crook 3958: @end itemize
3959:
3960: @noindent
3961: Numbers are always treated in a fixed way:
3962:
3963: @itemize @bullet
1.28 crook 3964: @item
1.44 crook 3965: When the number is @dfn{interpreted}, its behaviour is to push the
3966: number onto the stack.
1.28 crook 3967: @item
1.30 anton 3968: When the number is @dfn{compiled}, a piece of code is appended to the
3969: current definition that pushes the number when it runs. (In other words,
3970: the compilation semantics of a number are to postpone its interpretation
3971: semantics until the run-time of the definition that it is being compiled
3972: into.)
1.29 crook 3973: @end itemize
3974:
1.44 crook 3975: Words don't behave in such a regular way, but most have @i{default
3976: semantics} which means that they behave like this:
1.29 crook 3977:
3978: @itemize @bullet
1.28 crook 3979: @item
1.30 anton 3980: The @dfn{interpretation semantics} of the word are to do something useful.
3981: @item
1.29 crook 3982: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3983: @dfn{interpretation semantics} to the current definition (so that its
3984: run-time behaviour is to do something useful).
1.28 crook 3985: @end itemize
3986:
1.30 anton 3987: @cindex immediate words
1.44 crook 3988: The actual behaviour of any particular word can be controlled by using
3989: the words @code{immediate} and @code{compile-only} when the word is
3990: defined. These words set flags in the name dictionary entry of the most
3991: recently defined word, and these flags are retrieved by the text
3992: interpreter when it finds the word in the name dictionary.
3993:
3994: A word that is marked as @dfn{immediate} has compilation semantics that
3995: are identical to its interpretation semantics. In other words, it
3996: behaves like this:
1.29 crook 3997:
3998: @itemize @bullet
3999: @item
1.30 anton 4000: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4001: @item
1.30 anton 4002: The @dfn{compilation semantics} of the word are to do something useful
4003: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4004: @end itemize
1.28 crook 4005:
1.44 crook 4006: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4007: performing the interpretation semantics of the word directly; an attempt
4008: to do so will generate an error. It is never necessary to use
4009: @code{compile-only} (and it is not even part of ANS Forth, though it is
4010: provided by many implementations) but it is good etiquette to apply it
4011: to a word that will not behave correctly (and might have unexpected
4012: side-effects) in interpret state. For example, it is only legal to use
4013: the conditional word @code{IF} within a definition. If you forget this
4014: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4015: @code{compile-only} allows the text interpreter to generate a helpful
4016: error message rather than subjecting you to the consequences of your
4017: folly.
4018:
1.29 crook 4019: This example shows the difference between an immediate and a
4020: non-immediate word:
1.28 crook 4021:
1.29 crook 4022: @example
4023: : show-state state @@ . ;
4024: : show-state-now show-state ; immediate
4025: : word1 show-state ;
4026: : word2 show-state-now ;
1.28 crook 4027: @end example
1.23 crook 4028:
1.29 crook 4029: The word @code{immediate} after the definition of @code{show-state-now}
4030: makes that word an immediate word. These definitions introduce a new
4031: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4032: variable, and leaves it on the stack. Therefore, the behaviour of
4033: @code{show-state} is to print a number that represents the current value
4034: of @code{state}.
1.28 crook 4035:
1.29 crook 4036: When you execute @code{word1}, it prints the number 0, indicating that
4037: the system is interpreting. When the text interpreter compiled the
4038: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4039: compilation semantics are to append its interpretation semantics to the
1.29 crook 4040: current definition. When you execute @code{word1}, it performs the
1.30 anton 4041: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4042: (and therefore @code{show-state}) are executed, the system is
4043: interpreting.
1.28 crook 4044:
1.30 anton 4045: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4046: you should have seen the number -1 printed, followed by ``@code{
4047: ok}''. When the text interpreter compiled the definition of
4048: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4049: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4050: semantics. It is executed straight away (even before the text
4051: interpreter has moved on to process another group of characters; the
4052: @code{;} in this example). The effect of executing it are to display the
4053: value of @code{state} @i{at the time that the definition of}
4054: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4055: system is compiling at this time. If you execute @code{word2} it does
4056: nothing at all.
1.28 crook 4057:
1.29 crook 4058: @cindex @code{."}, how it works
4059: Before leaving the subject of immediate words, consider the behaviour of
4060: @code{."} in the definition of @code{greet}, in the previous
4061: section. This word is both a parsing word and an immediate word. Notice
4062: that there is a space between @code{."} and the start of the text
4063: @code{Hello and welcome}, but that there is no space between the last
4064: letter of @code{welcome} and the @code{"} character. The reason for this
4065: is that @code{."} is a Forth word; it must have a space after it so that
4066: the text interpreter can identify it. The @code{"} is not a Forth word;
4067: it is a @dfn{delimiter}. The examples earlier show that, when the string
4068: is displayed, there is neither a space before the @code{H} nor after the
4069: @code{e}. Since @code{."} is an immediate word, it executes at the time
4070: that @code{greet} is defined. When it executes, its behaviour is to
4071: search forward in the input line looking for the delimiter. When it
4072: finds the delimiter, it updates @code{>IN} to point past the
4073: delimiter. It also compiles some magic code into the definition of
4074: @code{greet}; the xt of a run-time routine that prints a text string. It
4075: compiles the string @code{Hello and welcome} into memory so that it is
4076: available to be printed later. When the text interpreter gains control,
4077: the next word it finds in the input stream is @code{;} and so it
4078: terminates the definition of @code{greet}.
1.28 crook 4079:
4080:
4081: @comment ----------------------------------------------
1.29 crook 4082: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4083: @section Forth is written in Forth
4084: @cindex structure of Forth programs
4085:
4086: When you start up a Forth compiler, a large number of definitions
4087: already exist. In Forth, you develop a new application using bottom-up
4088: programming techniques to create new definitions that are defined in
4089: terms of existing definitions. As you create each definition you can
4090: test and debug it interactively.
4091:
4092: If you have tried out the examples in this section, you will probably
4093: have typed them in by hand; when you leave Gforth, your definitions will
4094: be lost. You can avoid this by using a text editor to enter Forth source
4095: code into a file, and then loading code from the file using
1.49 anton 4096: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4097: processed by the text interpreter, just as though you had typed it in by
4098: hand@footnote{Actually, there are some subtle differences -- see
4099: @ref{The Text Interpreter}.}.
4100:
4101: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4102: files for program entry (@pxref{Blocks}).
1.28 crook 4103:
1.29 crook 4104: In common with many, if not most, Forth compilers, most of Gforth is
4105: actually written in Forth. All of the @file{.fs} files in the
4106: installation directory@footnote{For example,
1.30 anton 4107: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4108: study to see examples of Forth programming.
1.28 crook 4109:
1.29 crook 4110: Gforth maintains a history file that records every line that you type to
4111: the text interpreter. This file is preserved between sessions, and is
4112: used to provide a command-line recall facility. If you enter long
4113: definitions by hand, you can use a text editor to paste them out of the
4114: history file into a Forth source file for reuse at a later time
1.49 anton 4115: (for more information @pxref{Command-line editing}).
1.28 crook 4116:
4117:
4118: @comment ----------------------------------------------
1.29 crook 4119: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4120: @section Review - elements of a Forth system
4121: @cindex elements of a Forth system
1.28 crook 4122:
1.29 crook 4123: To summarise this chapter:
1.28 crook 4124:
4125: @itemize @bullet
4126: @item
1.29 crook 4127: Forth programs use @dfn{factoring} to break a problem down into small
4128: fragments called @dfn{words} or @dfn{definitions}.
4129: @item
4130: Forth program development is an interactive process.
4131: @item
4132: The main command loop that accepts input, and controls both
4133: interpretation and compilation, is called the @dfn{text interpreter}
4134: (also known as the @dfn{outer interpreter}).
4135: @item
4136: Forth has a very simple syntax, consisting of words and numbers
4137: separated by spaces or carriage-return characters. Any additional syntax
4138: is imposed by @dfn{parsing words}.
4139: @item
4140: Forth uses a stack to pass parameters between words. As a result, it
4141: uses postfix notation.
4142: @item
4143: To use a word that has previously been defined, the text interpreter
4144: searches for the word in the @dfn{name dictionary}.
4145: @item
1.30 anton 4146: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4147: @item
1.29 crook 4148: The text interpreter uses the value of @code{state} to select between
4149: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4150: semantics} of a word that it encounters.
1.28 crook 4151: @item
1.30 anton 4152: The relationship between the @dfn{interpretation semantics} and
4153: @dfn{compilation semantics} for a word
1.29 crook 4154: depend upon the way in which the word was defined (for example, whether
4155: it is an @dfn{immediate} word).
1.28 crook 4156: @item
1.29 crook 4157: Forth definitions can be implemented in Forth (called @dfn{high-level
4158: definitions}) or in some other way (usually a lower-level language and
4159: as a result often called @dfn{low-level definitions}, @dfn{code
4160: definitions} or @dfn{primitives}).
1.28 crook 4161: @item
1.29 crook 4162: Many Forth systems are implemented mainly in Forth.
1.28 crook 4163: @end itemize
4164:
4165:
1.29 crook 4166: @comment ----------------------------------------------
1.48 anton 4167: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4168: @section Where To Go Next
4169: @cindex where to go next
1.28 crook 4170:
1.29 crook 4171: Amazing as it may seem, if you have read (and understood) this far, you
4172: know almost all the fundamentals about the inner workings of a Forth
4173: system. You certainly know enough to be able to read and understand the
4174: rest of this manual and the ANS Forth document, to learn more about the
4175: facilities that Forth in general and Gforth in particular provide. Even
4176: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4177: However, that's not a good idea just yet... better to try writing some
1.29 crook 4178: programs in Gforth.
1.28 crook 4179:
1.29 crook 4180: Forth has such a rich vocabulary that it can be hard to know where to
4181: start in learning it. This section suggests a few sets of words that are
4182: enough to write small but useful programs. Use the word index in this
4183: document to learn more about each word, then try it out and try to write
4184: small definitions using it. Start by experimenting with these words:
1.28 crook 4185:
4186: @itemize @bullet
4187: @item
1.29 crook 4188: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4189: @item
4190: Comparison: @code{MIN MAX =}
4191: @item
4192: Logic: @code{AND OR XOR NOT}
4193: @item
4194: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4195: @item
1.29 crook 4196: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4197: @item
1.29 crook 4198: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4199: @item
1.29 crook 4200: Defining words: @code{: ; CREATE}
1.28 crook 4201: @item
1.29 crook 4202: Memory allocation words: @code{ALLOT ,}
1.28 crook 4203: @item
1.29 crook 4204: Tools: @code{SEE WORDS .S MARKER}
4205: @end itemize
4206:
4207: When you have mastered those, go on to:
4208:
4209: @itemize @bullet
1.28 crook 4210: @item
1.29 crook 4211: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4212: @item
1.29 crook 4213: Memory access: @code{@@ !}
1.28 crook 4214: @end itemize
1.23 crook 4215:
1.29 crook 4216: When you have mastered these, there's nothing for it but to read through
4217: the whole of this manual and find out what you've missed.
4218:
4219: @comment ----------------------------------------------
1.48 anton 4220: @node Exercises, , Where to go next, Introduction
1.29 crook 4221: @section Exercises
4222: @cindex exercises
4223:
4224: TODO: provide a set of programming excercises linked into the stuff done
4225: already and into other sections of the manual. Provide solutions to all
4226: the exercises in a .fs file in the distribution.
4227:
4228: @c Get some inspiration from Starting Forth and Kelly&Spies.
4229:
4230: @c excercises:
4231: @c 1. take inches and convert to feet and inches.
4232: @c 2. take temperature and convert from fahrenheight to celcius;
4233: @c may need to care about symmetric vs floored??
4234: @c 3. take input line and do character substitution
4235: @c to encipher or decipher
4236: @c 4. as above but work on a file for in and out
4237: @c 5. take input line and convert to pig-latin
4238: @c
4239: @c thing of sets of things to exercise then come up with
4240: @c problems that need those things.
4241:
4242:
1.26 crook 4243: @c ******************************************************************
1.29 crook 4244: @node Words, Error messages, Introduction, Top
1.1 anton 4245: @chapter Forth Words
1.26 crook 4246: @cindex words
1.1 anton 4247:
4248: @menu
4249: * Notation::
1.65 anton 4250: * Case insensitivity::
4251: * Comments::
4252: * Boolean Flags::
1.1 anton 4253: * Arithmetic::
4254: * Stack Manipulation::
1.5 anton 4255: * Memory::
1.1 anton 4256: * Control Structures::
4257: * Defining Words::
1.65 anton 4258: * Interpretation and Compilation Semantics::
1.47 crook 4259: * Tokens for Words::
1.81 anton 4260: * Compiling words::
1.65 anton 4261: * The Text Interpreter::
1.111 anton 4262: * The Input Stream::
1.65 anton 4263: * Word Lists::
4264: * Environmental Queries::
1.12 anton 4265: * Files::
4266: * Blocks::
4267: * Other I/O::
1.121 anton 4268: * OS command line arguments::
1.78 anton 4269: * Locals::
4270: * Structures::
4271: * Object-oriented Forth::
1.12 anton 4272: * Programming Tools::
1.150 anton 4273: * C Interface::
1.12 anton 4274: * Assembler and Code Words::
4275: * Threading Words::
1.65 anton 4276: * Passing Commands to the OS::
4277: * Keeping track of Time::
4278: * Miscellaneous Words::
1.1 anton 4279: @end menu
4280:
1.65 anton 4281: @node Notation, Case insensitivity, Words, Words
1.1 anton 4282: @section Notation
4283: @cindex notation of glossary entries
4284: @cindex format of glossary entries
4285: @cindex glossary notation format
4286: @cindex word glossary entry format
4287:
4288: The Forth words are described in this section in the glossary notation
1.67 anton 4289: that has become a de-facto standard for Forth texts:
1.1 anton 4290:
4291: @format
1.29 crook 4292: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4293: @end format
1.29 crook 4294: @i{Description}
1.1 anton 4295:
4296: @table @var
4297: @item word
1.28 crook 4298: The name of the word.
1.1 anton 4299:
4300: @item Stack effect
4301: @cindex stack effect
1.29 crook 4302: The stack effect is written in the notation @code{@i{before} --
4303: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4304: stack entries before and after the execution of the word. The rest of
4305: the stack is not touched by the word. The top of stack is rightmost,
4306: i.e., a stack sequence is written as it is typed in. Note that Gforth
4307: uses a separate floating point stack, but a unified stack
1.29 crook 4308: notation. Also, return stack effects are not shown in @i{stack
4309: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4310: the type and/or the function of the item. See below for a discussion of
4311: the types.
4312:
4313: All words have two stack effects: A compile-time stack effect and a
4314: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4315: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4316: this standard behaviour, or the word does other unusual things at
4317: compile time, both stack effects are shown; otherwise only the run-time
4318: stack effect is shown.
4319:
4320: @cindex pronounciation of words
4321: @item pronunciation
4322: How the word is pronounced.
4323:
4324: @cindex wordset
1.67 anton 4325: @cindex environment wordset
1.1 anton 4326: @item wordset
1.21 crook 4327: The ANS Forth standard is divided into several word sets. A standard
4328: system need not support all of them. Therefore, in theory, the fewer
4329: word sets your program uses the more portable it will be. However, we
4330: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4331: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4332: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4333: describes words that will work in future releases of Gforth;
4334: @code{gforth-internal} words are more volatile. Environmental query
4335: strings are also displayed like words; you can recognize them by the
1.21 crook 4336: @code{environment} in the word set field.
1.1 anton 4337:
4338: @item Description
4339: A description of the behaviour of the word.
4340: @end table
4341:
4342: @cindex types of stack items
4343: @cindex stack item types
4344: The type of a stack item is specified by the character(s) the name
4345: starts with:
4346:
4347: @table @code
4348: @item f
4349: @cindex @code{f}, stack item type
4350: Boolean flags, i.e. @code{false} or @code{true}.
4351: @item c
4352: @cindex @code{c}, stack item type
4353: Char
4354: @item w
4355: @cindex @code{w}, stack item type
4356: Cell, can contain an integer or an address
4357: @item n
4358: @cindex @code{n}, stack item type
4359: signed integer
4360: @item u
4361: @cindex @code{u}, stack item type
4362: unsigned integer
4363: @item d
4364: @cindex @code{d}, stack item type
4365: double sized signed integer
4366: @item ud
4367: @cindex @code{ud}, stack item type
4368: double sized unsigned integer
4369: @item r
4370: @cindex @code{r}, stack item type
4371: Float (on the FP stack)
1.21 crook 4372: @item a-
1.1 anton 4373: @cindex @code{a_}, stack item type
4374: Cell-aligned address
1.21 crook 4375: @item c-
1.1 anton 4376: @cindex @code{c_}, stack item type
4377: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4378: @item f-
1.1 anton 4379: @cindex @code{f_}, stack item type
4380: Float-aligned address
1.21 crook 4381: @item df-
1.1 anton 4382: @cindex @code{df_}, stack item type
4383: Address aligned for IEEE double precision float
1.21 crook 4384: @item sf-
1.1 anton 4385: @cindex @code{sf_}, stack item type
4386: Address aligned for IEEE single precision float
4387: @item xt
4388: @cindex @code{xt}, stack item type
4389: Execution token, same size as Cell
4390: @item wid
4391: @cindex @code{wid}, stack item type
1.21 crook 4392: Word list ID, same size as Cell
1.68 anton 4393: @item ior, wior
4394: @cindex ior type description
4395: @cindex wior type description
4396: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4397: @item f83name
4398: @cindex @code{f83name}, stack item type
4399: Pointer to a name structure
4400: @item "
4401: @cindex @code{"}, stack item type
1.12 anton 4402: string in the input stream (not on the stack). The terminating character
4403: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4404: quotes.
4405: @end table
4406:
1.65 anton 4407: @comment ----------------------------------------------
4408: @node Case insensitivity, Comments, Notation, Words
4409: @section Case insensitivity
4410: @cindex case sensitivity
4411: @cindex upper and lower case
4412:
4413: Gforth is case-insensitive; you can enter definitions and invoke
4414: Standard words using upper, lower or mixed case (however,
4415: @pxref{core-idef, Implementation-defined options, Implementation-defined
4416: options}).
4417:
4418: ANS Forth only @i{requires} implementations to recognise Standard words
4419: when they are typed entirely in upper case. Therefore, a Standard
4420: program must use upper case for all Standard words. You can use whatever
4421: case you like for words that you define, but in a Standard program you
4422: have to use the words in the same case that you defined them.
4423:
4424: Gforth supports case sensitivity through @code{table}s (case-sensitive
4425: wordlists, @pxref{Word Lists}).
4426:
4427: Two people have asked how to convert Gforth to be case-sensitive; while
4428: we think this is a bad idea, you can change all wordlists into tables
4429: like this:
4430:
4431: @example
4432: ' table-find forth-wordlist wordlist-map @ !
4433: @end example
4434:
4435: Note that you now have to type the predefined words in the same case
4436: that we defined them, which are varying. You may want to convert them
4437: to your favourite case before doing this operation (I won't explain how,
4438: because if you are even contemplating doing this, you'd better have
4439: enough knowledge of Forth systems to know this already).
4440:
4441: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4442: @section Comments
1.26 crook 4443: @cindex comments
1.21 crook 4444:
1.29 crook 4445: Forth supports two styles of comment; the traditional @i{in-line} comment,
4446: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4447:
1.44 crook 4448:
1.23 crook 4449: doc-(
1.21 crook 4450: doc-\
1.23 crook 4451: doc-\G
1.21 crook 4452:
1.44 crook 4453:
1.21 crook 4454: @node Boolean Flags, Arithmetic, Comments, Words
4455: @section Boolean Flags
1.26 crook 4456: @cindex Boolean flags
1.21 crook 4457:
4458: A Boolean flag is cell-sized. A cell with all bits clear represents the
4459: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4460: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4461: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4462: @c on and off to Memory?
4463: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4464:
1.21 crook 4465: doc-true
4466: doc-false
1.29 crook 4467: doc-on
4468: doc-off
1.21 crook 4469:
1.44 crook 4470:
1.21 crook 4471: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4472: @section Arithmetic
4473: @cindex arithmetic words
4474:
4475: @cindex division with potentially negative operands
4476: Forth arithmetic is not checked, i.e., you will not hear about integer
4477: overflow on addition or multiplication, you may hear about division by
4478: zero if you are lucky. The operator is written after the operands, but
4479: the operands are still in the original order. I.e., the infix @code{2-1}
4480: corresponds to @code{2 1 -}. Forth offers a variety of division
4481: operators. If you perform division with potentially negative operands,
4482: you do not want to use @code{/} or @code{/mod} with its undefined
4483: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4484: former, @pxref{Mixed precision}).
1.26 crook 4485: @comment TODO discuss the different division forms and the std approach
1.1 anton 4486:
4487: @menu
4488: * Single precision::
1.67 anton 4489: * Double precision:: Double-cell integer arithmetic
1.1 anton 4490: * Bitwise operations::
1.67 anton 4491: * Numeric comparison::
1.29 crook 4492: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4493: * Floating Point::
4494: @end menu
4495:
1.67 anton 4496: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4497: @subsection Single precision
4498: @cindex single precision arithmetic words
4499:
1.67 anton 4500: @c !! cell undefined
4501:
4502: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4503: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4504: treat them. For the rules used by the text interpreter for recognising
4505: single-precision integers see @ref{Number Conversion}.
1.21 crook 4506:
1.67 anton 4507: These words are all defined for signed operands, but some of them also
4508: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4509: @code{*}.
1.44 crook 4510:
1.1 anton 4511: doc-+
1.21 crook 4512: doc-1+
1.128 anton 4513: doc-under+
1.1 anton 4514: doc--
1.21 crook 4515: doc-1-
1.1 anton 4516: doc-*
4517: doc-/
4518: doc-mod
4519: doc-/mod
4520: doc-negate
4521: doc-abs
4522: doc-min
4523: doc-max
1.27 crook 4524: doc-floored
1.1 anton 4525:
1.44 crook 4526:
1.67 anton 4527: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4528: @subsection Double precision
4529: @cindex double precision arithmetic words
4530:
1.49 anton 4531: For the rules used by the text interpreter for
4532: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4533:
4534: A double precision number is represented by a cell pair, with the most
1.67 anton 4535: significant cell at the TOS. It is trivial to convert an unsigned single
4536: to a double: simply push a @code{0} onto the TOS. Since numbers are
4537: represented by Gforth using 2's complement arithmetic, converting a
4538: signed single to a (signed) double requires sign-extension across the
4539: most significant cell. This can be achieved using @code{s>d}. The moral
4540: of the story is that you cannot convert a number without knowing whether
4541: it represents an unsigned or a signed number.
1.21 crook 4542:
1.67 anton 4543: These words are all defined for signed operands, but some of them also
4544: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4545:
1.21 crook 4546: doc-s>d
1.67 anton 4547: doc-d>s
1.21 crook 4548: doc-d+
4549: doc-d-
4550: doc-dnegate
4551: doc-dabs
4552: doc-dmin
4553: doc-dmax
4554:
1.44 crook 4555:
1.67 anton 4556: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4557: @subsection Bitwise operations
4558: @cindex bitwise operation words
4559:
4560:
4561: doc-and
4562: doc-or
4563: doc-xor
4564: doc-invert
4565: doc-lshift
4566: doc-rshift
4567: doc-2*
4568: doc-d2*
4569: doc-2/
4570: doc-d2/
4571:
4572:
4573: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4574: @subsection Numeric comparison
4575: @cindex numeric comparison words
4576:
1.67 anton 4577: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4578: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4579:
1.28 crook 4580: doc-<
4581: doc-<=
4582: doc-<>
4583: doc-=
4584: doc->
4585: doc->=
4586:
1.21 crook 4587: doc-0<
1.23 crook 4588: doc-0<=
1.21 crook 4589: doc-0<>
4590: doc-0=
1.23 crook 4591: doc-0>
4592: doc-0>=
1.28 crook 4593:
4594: doc-u<
4595: doc-u<=
1.44 crook 4596: @c u<> and u= exist but are the same as <> and =
1.31 anton 4597: @c doc-u<>
4598: @c doc-u=
1.28 crook 4599: doc-u>
4600: doc-u>=
4601:
4602: doc-within
4603:
4604: doc-d<
4605: doc-d<=
4606: doc-d<>
4607: doc-d=
4608: doc-d>
4609: doc-d>=
1.23 crook 4610:
1.21 crook 4611: doc-d0<
1.23 crook 4612: doc-d0<=
4613: doc-d0<>
1.21 crook 4614: doc-d0=
1.23 crook 4615: doc-d0>
4616: doc-d0>=
4617:
1.21 crook 4618: doc-du<
1.28 crook 4619: doc-du<=
1.44 crook 4620: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4621: @c doc-du<>
4622: @c doc-du=
1.28 crook 4623: doc-du>
4624: doc-du>=
1.1 anton 4625:
1.44 crook 4626:
1.21 crook 4627: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4628: @subsection Mixed precision
4629: @cindex mixed precision arithmetic words
4630:
1.44 crook 4631:
1.1 anton 4632: doc-m+
4633: doc-*/
4634: doc-*/mod
4635: doc-m*
4636: doc-um*
4637: doc-m*/
4638: doc-um/mod
4639: doc-fm/mod
4640: doc-sm/rem
4641:
1.44 crook 4642:
1.21 crook 4643: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4644: @subsection Floating Point
4645: @cindex floating point arithmetic words
4646:
1.49 anton 4647: For the rules used by the text interpreter for
4648: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4649:
1.67 anton 4650: Gforth has a separate floating point stack, but the documentation uses
4651: the unified notation.@footnote{It's easy to generate the separate
4652: notation from that by just separating the floating-point numbers out:
4653: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4654: r3 )}.}
1.1 anton 4655:
4656: @cindex floating-point arithmetic, pitfalls
4657: Floating point numbers have a number of unpleasant surprises for the
4658: unwary (e.g., floating point addition is not associative) and even a few
4659: for the wary. You should not use them unless you know what you are doing
4660: or you don't care that the results you get are totally bogus. If you
4661: want to learn about the problems of floating point numbers (and how to
1.66 anton 4662: avoid them), you might start with @cite{David Goldberg,
4663: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4664: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4665: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4666:
1.44 crook 4667:
1.21 crook 4668: doc-d>f
4669: doc-f>d
1.1 anton 4670: doc-f+
4671: doc-f-
4672: doc-f*
4673: doc-f/
4674: doc-fnegate
4675: doc-fabs
4676: doc-fmax
4677: doc-fmin
4678: doc-floor
4679: doc-fround
4680: doc-f**
4681: doc-fsqrt
4682: doc-fexp
4683: doc-fexpm1
4684: doc-fln
4685: doc-flnp1
4686: doc-flog
4687: doc-falog
1.32 anton 4688: doc-f2*
4689: doc-f2/
4690: doc-1/f
4691: doc-precision
4692: doc-set-precision
4693:
4694: @cindex angles in trigonometric operations
4695: @cindex trigonometric operations
4696: Angles in floating point operations are given in radians (a full circle
4697: has 2 pi radians).
4698:
1.1 anton 4699: doc-fsin
4700: doc-fcos
4701: doc-fsincos
4702: doc-ftan
4703: doc-fasin
4704: doc-facos
4705: doc-fatan
4706: doc-fatan2
4707: doc-fsinh
4708: doc-fcosh
4709: doc-ftanh
4710: doc-fasinh
4711: doc-facosh
4712: doc-fatanh
1.21 crook 4713: doc-pi
1.28 crook 4714:
1.32 anton 4715: @cindex equality of floats
4716: @cindex floating-point comparisons
1.31 anton 4717: One particular problem with floating-point arithmetic is that comparison
4718: for equality often fails when you would expect it to succeed. For this
4719: reason approximate equality is often preferred (but you still have to
1.67 anton 4720: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4721: differently from what you might expect. The comparison words are:
1.31 anton 4722:
4723: doc-f~rel
4724: doc-f~abs
1.68 anton 4725: doc-f~
1.31 anton 4726: doc-f=
4727: doc-f<>
4728:
4729: doc-f<
4730: doc-f<=
4731: doc-f>
4732: doc-f>=
4733:
1.21 crook 4734: doc-f0<
1.28 crook 4735: doc-f0<=
4736: doc-f0<>
1.21 crook 4737: doc-f0=
1.28 crook 4738: doc-f0>
4739: doc-f0>=
4740:
1.1 anton 4741:
4742: @node Stack Manipulation, Memory, Arithmetic, Words
4743: @section Stack Manipulation
4744: @cindex stack manipulation words
4745:
4746: @cindex floating-point stack in the standard
1.21 crook 4747: Gforth maintains a number of separate stacks:
4748:
1.29 crook 4749: @cindex data stack
4750: @cindex parameter stack
1.21 crook 4751: @itemize @bullet
4752: @item
1.29 crook 4753: A data stack (also known as the @dfn{parameter stack}) -- for
4754: characters, cells, addresses, and double cells.
1.21 crook 4755:
1.29 crook 4756: @cindex floating-point stack
1.21 crook 4757: @item
1.44 crook 4758: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4759:
1.29 crook 4760: @cindex return stack
1.21 crook 4761: @item
1.44 crook 4762: A return stack -- for holding the return addresses of colon
1.32 anton 4763: definitions and other (non-FP) data.
1.21 crook 4764:
1.29 crook 4765: @cindex locals stack
1.21 crook 4766: @item
1.44 crook 4767: A locals stack -- for holding local variables.
1.21 crook 4768: @end itemize
4769:
1.1 anton 4770: @menu
4771: * Data stack::
4772: * Floating point stack::
4773: * Return stack::
4774: * Locals stack::
4775: * Stack pointer manipulation::
4776: @end menu
4777:
4778: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4779: @subsection Data stack
4780: @cindex data stack manipulation words
4781: @cindex stack manipulations words, data stack
4782:
1.44 crook 4783:
1.1 anton 4784: doc-drop
4785: doc-nip
4786: doc-dup
4787: doc-over
4788: doc-tuck
4789: doc-swap
1.21 crook 4790: doc-pick
1.1 anton 4791: doc-rot
4792: doc--rot
4793: doc-?dup
4794: doc-roll
4795: doc-2drop
4796: doc-2nip
4797: doc-2dup
4798: doc-2over
4799: doc-2tuck
4800: doc-2swap
4801: doc-2rot
4802:
1.44 crook 4803:
1.1 anton 4804: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4805: @subsection Floating point stack
4806: @cindex floating-point stack manipulation words
4807: @cindex stack manipulation words, floating-point stack
4808:
1.32 anton 4809: Whilst every sane Forth has a separate floating-point stack, it is not
4810: strictly required; an ANS Forth system could theoretically keep
4811: floating-point numbers on the data stack. As an additional difficulty,
4812: you don't know how many cells a floating-point number takes. It is
4813: reportedly possible to write words in a way that they work also for a
4814: unified stack model, but we do not recommend trying it. Instead, just
4815: say that your program has an environmental dependency on a separate
4816: floating-point stack.
4817:
4818: doc-floating-stack
4819:
1.1 anton 4820: doc-fdrop
4821: doc-fnip
4822: doc-fdup
4823: doc-fover
4824: doc-ftuck
4825: doc-fswap
1.21 crook 4826: doc-fpick
1.1 anton 4827: doc-frot
4828:
1.44 crook 4829:
1.1 anton 4830: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4831: @subsection Return stack
4832: @cindex return stack manipulation words
4833: @cindex stack manipulation words, return stack
4834:
1.32 anton 4835: @cindex return stack and locals
4836: @cindex locals and return stack
4837: A Forth system is allowed to keep local variables on the
4838: return stack. This is reasonable, as local variables usually eliminate
4839: the need to use the return stack explicitly. So, if you want to produce
4840: a standard compliant program and you are using local variables in a
4841: word, forget about return stack manipulations in that word (refer to the
4842: standard document for the exact rules).
4843:
1.1 anton 4844: doc->r
4845: doc-r>
4846: doc-r@
4847: doc-rdrop
4848: doc-2>r
4849: doc-2r>
4850: doc-2r@
4851: doc-2rdrop
4852:
1.44 crook 4853:
1.1 anton 4854: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4855: @subsection Locals stack
4856:
1.78 anton 4857: Gforth uses an extra locals stack. It is described, along with the
4858: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4859:
1.1 anton 4860: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4861: @subsection Stack pointer manipulation
4862: @cindex stack pointer manipulation words
4863:
1.44 crook 4864: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4865: doc-sp0
1.1 anton 4866: doc-sp@
4867: doc-sp!
1.21 crook 4868: doc-fp0
1.1 anton 4869: doc-fp@
4870: doc-fp!
1.21 crook 4871: doc-rp0
1.1 anton 4872: doc-rp@
4873: doc-rp!
1.21 crook 4874: doc-lp0
1.1 anton 4875: doc-lp@
4876: doc-lp!
4877:
1.44 crook 4878:
1.1 anton 4879: @node Memory, Control Structures, Stack Manipulation, Words
4880: @section Memory
1.26 crook 4881: @cindex memory words
1.1 anton 4882:
1.32 anton 4883: @menu
4884: * Memory model::
4885: * Dictionary allocation::
4886: * Heap Allocation::
4887: * Memory Access::
4888: * Address arithmetic::
4889: * Memory Blocks::
4890: @end menu
4891:
1.67 anton 4892: In addition to the standard Forth memory allocation words, there is also
4893: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4894: garbage collector}.
4895:
1.32 anton 4896: @node Memory model, Dictionary allocation, Memory, Memory
4897: @subsection ANS Forth and Gforth memory models
4898:
4899: @c The ANS Forth description is a mess (e.g., is the heap part of
4900: @c the dictionary?), so let's not stick to closely with it.
4901:
1.67 anton 4902: ANS Forth considers a Forth system as consisting of several address
4903: spaces, of which only @dfn{data space} is managed and accessible with
4904: the memory words. Memory not necessarily in data space includes the
4905: stacks, the code (called code space) and the headers (called name
4906: space). In Gforth everything is in data space, but the code for the
4907: primitives is usually read-only.
1.32 anton 4908:
4909: Data space is divided into a number of areas: The (data space portion of
4910: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4911: refer to the search data structure embodied in word lists and headers,
4912: because it is used for looking up names, just as you would in a
4913: conventional dictionary.}, the heap, and a number of system-allocated
4914: buffers.
4915:
1.68 anton 4916: @cindex address arithmetic restrictions, ANS vs. Gforth
4917: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4918: In ANS Forth data space is also divided into contiguous regions. You
4919: can only use address arithmetic within a contiguous region, not between
4920: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4921: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4922: allocation}).
4923:
4924: Gforth provides one big address space, and address arithmetic can be
4925: performed between any addresses. However, in the dictionary headers or
4926: code are interleaved with data, so almost the only contiguous data space
4927: regions there are those described by ANS Forth as contiguous; but you
4928: can be sure that the dictionary is allocated towards increasing
4929: addresses even between contiguous regions. The memory order of
4930: allocations in the heap is platform-dependent (and possibly different
4931: from one run to the next).
4932:
1.27 crook 4933:
1.32 anton 4934: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4935: @subsection Dictionary allocation
1.27 crook 4936: @cindex reserving data space
4937: @cindex data space - reserving some
4938:
1.32 anton 4939: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4940: you want to deallocate X, you also deallocate everything
4941: allocated after X.
4942:
1.68 anton 4943: @cindex contiguous regions in dictionary allocation
1.32 anton 4944: The allocations using the words below are contiguous and grow the region
4945: towards increasing addresses. Other words that allocate dictionary
4946: memory of any kind (i.e., defining words including @code{:noname}) end
4947: the contiguous region and start a new one.
4948:
4949: In ANS Forth only @code{create}d words are guaranteed to produce an
4950: address that is the start of the following contiguous region. In
4951: particular, the cell allocated by @code{variable} is not guaranteed to
4952: be contiguous with following @code{allot}ed memory.
4953:
4954: You can deallocate memory by using @code{allot} with a negative argument
4955: (with some restrictions, see @code{allot}). For larger deallocations use
4956: @code{marker}.
1.27 crook 4957:
1.29 crook 4958:
1.27 crook 4959: doc-here
4960: doc-unused
4961: doc-allot
4962: doc-c,
1.29 crook 4963: doc-f,
1.27 crook 4964: doc-,
4965: doc-2,
4966:
1.32 anton 4967: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4968: course you should allocate memory in an aligned way, too. I.e., before
4969: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4970: The words below align @code{here} if it is not already. Basically it is
4971: only already aligned for a type, if the last allocation was a multiple
4972: of the size of this type and if @code{here} was aligned for this type
4973: before.
4974:
4975: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4976: ANS Forth (@code{maxalign}ed in Gforth).
4977:
4978: doc-align
4979: doc-falign
4980: doc-sfalign
4981: doc-dfalign
4982: doc-maxalign
4983: doc-cfalign
4984:
4985:
4986: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4987: @subsection Heap allocation
4988: @cindex heap allocation
4989: @cindex dynamic allocation of memory
4990: @cindex memory-allocation word set
4991:
1.68 anton 4992: @cindex contiguous regions and heap allocation
1.32 anton 4993: Heap allocation supports deallocation of allocated memory in any
4994: order. Dictionary allocation is not affected by it (i.e., it does not
4995: end a contiguous region). In Gforth, these words are implemented using
4996: the standard C library calls malloc(), free() and resize().
4997:
1.68 anton 4998: The memory region produced by one invocation of @code{allocate} or
4999: @code{resize} is internally contiguous. There is no contiguity between
5000: such a region and any other region (including others allocated from the
5001: heap).
5002:
1.32 anton 5003: doc-allocate
5004: doc-free
5005: doc-resize
5006:
1.27 crook 5007:
1.32 anton 5008: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5009: @subsection Memory Access
5010: @cindex memory access words
5011:
5012: doc-@
5013: doc-!
5014: doc-+!
5015: doc-c@
5016: doc-c!
5017: doc-2@
5018: doc-2!
5019: doc-f@
5020: doc-f!
5021: doc-sf@
5022: doc-sf!
5023: doc-df@
5024: doc-df!
1.144 anton 5025: doc-sw@
5026: doc-uw@
5027: doc-w!
5028: doc-sl@
5029: doc-ul@
5030: doc-l!
1.68 anton 5031:
1.32 anton 5032: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5033: @subsection Address arithmetic
1.1 anton 5034: @cindex address arithmetic words
5035:
1.67 anton 5036: Address arithmetic is the foundation on which you can build data
5037: structures like arrays, records (@pxref{Structures}) and objects
5038: (@pxref{Object-oriented Forth}).
1.32 anton 5039:
1.68 anton 5040: @cindex address unit
5041: @cindex au (address unit)
1.1 anton 5042: ANS Forth does not specify the sizes of the data types. Instead, it
5043: offers a number of words for computing sizes and doing address
1.29 crook 5044: arithmetic. Address arithmetic is performed in terms of address units
5045: (aus); on most systems the address unit is one byte. Note that a
5046: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5047: platforms where it is a noop, it compiles to nothing).
1.1 anton 5048:
1.67 anton 5049: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5050: you have the address of a cell, perform @code{1 cells +}, and you will
5051: have the address of the next cell.
5052:
1.68 anton 5053: @cindex contiguous regions and address arithmetic
1.67 anton 5054: In ANS Forth you can perform address arithmetic only within a contiguous
5055: region, i.e., if you have an address into one region, you can only add
5056: and subtract such that the result is still within the region; you can
5057: only subtract or compare addresses from within the same contiguous
5058: region. Reasons: several contiguous regions can be arranged in memory
5059: in any way; on segmented systems addresses may have unusual
5060: representations, such that address arithmetic only works within a
5061: region. Gforth provides a few more guarantees (linear address space,
5062: dictionary grows upwards), but in general I have found it easy to stay
5063: within contiguous regions (exception: computing and comparing to the
5064: address just beyond the end of an array).
5065:
1.1 anton 5066: @cindex alignment of addresses for types
5067: ANS Forth also defines words for aligning addresses for specific
5068: types. Many computers require that accesses to specific data types
5069: must only occur at specific addresses; e.g., that cells may only be
5070: accessed at addresses divisible by 4. Even if a machine allows unaligned
5071: accesses, it can usually perform aligned accesses faster.
5072:
5073: For the performance-conscious: alignment operations are usually only
5074: necessary during the definition of a data structure, not during the
5075: (more frequent) accesses to it.
5076:
5077: ANS Forth defines no words for character-aligning addresses. This is not
5078: an oversight, but reflects the fact that addresses that are not
5079: char-aligned have no use in the standard and therefore will not be
5080: created.
5081:
5082: @cindex @code{CREATE} and alignment
1.29 crook 5083: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5084: are cell-aligned; in addition, Gforth guarantees that these addresses
5085: are aligned for all purposes.
5086:
1.26 crook 5087: Note that the ANS Forth word @code{char} has nothing to do with address
5088: arithmetic.
1.1 anton 5089:
1.44 crook 5090:
1.1 anton 5091: doc-chars
5092: doc-char+
5093: doc-cells
5094: doc-cell+
5095: doc-cell
5096: doc-aligned
5097: doc-floats
5098: doc-float+
5099: doc-float
5100: doc-faligned
5101: doc-sfloats
5102: doc-sfloat+
5103: doc-sfaligned
5104: doc-dfloats
5105: doc-dfloat+
5106: doc-dfaligned
5107: doc-maxaligned
5108: doc-cfaligned
5109: doc-address-unit-bits
1.145 anton 5110: doc-/w
5111: doc-/l
1.44 crook 5112:
1.32 anton 5113: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5114: @subsection Memory Blocks
5115: @cindex memory block words
1.27 crook 5116: @cindex character strings - moving and copying
5117:
1.49 anton 5118: Memory blocks often represent character strings; For ways of storing
5119: character strings in memory see @ref{String Formats}. For other
5120: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5121:
1.67 anton 5122: A few of these words work on address unit blocks. In that case, you
5123: usually have to insert @code{CHARS} before the word when working on
5124: character strings. Most words work on character blocks, and expect a
5125: char-aligned address.
5126:
5127: When copying characters between overlapping memory regions, use
5128: @code{chars move} or choose carefully between @code{cmove} and
5129: @code{cmove>}.
1.44 crook 5130:
1.1 anton 5131: doc-move
5132: doc-erase
5133: doc-cmove
5134: doc-cmove>
5135: doc-fill
5136: doc-blank
1.21 crook 5137: doc-compare
1.111 anton 5138: doc-str=
5139: doc-str<
5140: doc-string-prefix?
1.21 crook 5141: doc-search
1.27 crook 5142: doc--trailing
5143: doc-/string
1.82 anton 5144: doc-bounds
1.141 anton 5145: doc-pad
1.111 anton 5146:
1.27 crook 5147: @comment TODO examples
5148:
1.1 anton 5149:
1.26 crook 5150: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5151: @section Control Structures
5152: @cindex control structures
5153:
1.33 anton 5154: Control structures in Forth cannot be used interpretively, only in a
5155: colon definition@footnote{To be precise, they have no interpretation
5156: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5157: not like this limitation, but have not seen a satisfying way around it
5158: yet, although many schemes have been proposed.
1.1 anton 5159:
5160: @menu
1.33 anton 5161: * Selection:: IF ... ELSE ... ENDIF
5162: * Simple Loops:: BEGIN ...
1.29 crook 5163: * Counted Loops:: DO
1.67 anton 5164: * Arbitrary control structures::
5165: * Calls and returns::
1.1 anton 5166: * Exception Handling::
5167: @end menu
5168:
5169: @node Selection, Simple Loops, Control Structures, Control Structures
5170: @subsection Selection
5171: @cindex selection control structures
5172: @cindex control structures for selection
5173:
5174: @cindex @code{IF} control structure
5175: @example
1.29 crook 5176: @i{flag}
1.1 anton 5177: IF
1.29 crook 5178: @i{code}
1.1 anton 5179: ENDIF
5180: @end example
1.21 crook 5181: @noindent
1.33 anton 5182:
1.44 crook 5183: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5184: with any bit set represents truth) @i{code} is executed.
1.33 anton 5185:
1.1 anton 5186: @example
1.29 crook 5187: @i{flag}
1.1 anton 5188: IF
1.29 crook 5189: @i{code1}
1.1 anton 5190: ELSE
1.29 crook 5191: @i{code2}
1.1 anton 5192: ENDIF
5193: @end example
5194:
1.44 crook 5195: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5196: executed.
1.33 anton 5197:
1.1 anton 5198: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5199: standard, and @code{ENDIF} is not, although it is quite popular. We
5200: recommend using @code{ENDIF}, because it is less confusing for people
5201: who also know other languages (and is not prone to reinforcing negative
5202: prejudices against Forth in these people). Adding @code{ENDIF} to a
5203: system that only supplies @code{THEN} is simple:
5204: @example
1.82 anton 5205: : ENDIF POSTPONE then ; immediate
1.1 anton 5206: @end example
5207:
5208: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5209: (adv.)} has the following meanings:
5210: @quotation
5211: ... 2b: following next after in order ... 3d: as a necessary consequence
5212: (if you were there, then you saw them).
5213: @end quotation
5214: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5215: and many other programming languages has the meaning 3d.]
5216:
1.21 crook 5217: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5218: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5219: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5220: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5221: @file{compat/control.fs}.
5222:
5223: @cindex @code{CASE} control structure
5224: @example
1.29 crook 5225: @i{n}
1.1 anton 5226: CASE
1.29 crook 5227: @i{n1} OF @i{code1} ENDOF
5228: @i{n2} OF @i{code2} ENDOF
1.1 anton 5229: @dots{}
1.68 anton 5230: ( n ) @i{default-code} ( n )
1.131 anton 5231: ENDCASE ( )
1.1 anton 5232: @end example
5233:
1.131 anton 5234: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5235: no @i{ni} matches, the optional @i{default-code} is executed. The
5236: optional default case can be added by simply writing the code after
5237: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5238: but must not consume it. The value @i{n} is consumed by this
5239: construction (either by a OF that matches, or by the ENDCASE, if no OF
5240: matches).
1.1 anton 5241:
1.69 anton 5242: @progstyle
1.131 anton 5243: To keep the code understandable, you should ensure that you change the
5244: stack in the same way (wrt. number and types of stack items consumed
5245: and pushed) on all paths through a selection construct.
1.69 anton 5246:
1.1 anton 5247: @node Simple Loops, Counted Loops, Selection, Control Structures
5248: @subsection Simple Loops
5249: @cindex simple loops
5250: @cindex loops without count
5251:
5252: @cindex @code{WHILE} loop
5253: @example
5254: BEGIN
1.29 crook 5255: @i{code1}
5256: @i{flag}
1.1 anton 5257: WHILE
1.29 crook 5258: @i{code2}
1.1 anton 5259: REPEAT
5260: @end example
5261:
1.29 crook 5262: @i{code1} is executed and @i{flag} is computed. If it is true,
5263: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5264: false, execution continues after the @code{REPEAT}.
5265:
5266: @cindex @code{UNTIL} loop
5267: @example
5268: BEGIN
1.29 crook 5269: @i{code}
5270: @i{flag}
1.1 anton 5271: UNTIL
5272: @end example
5273:
1.29 crook 5274: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5275:
1.69 anton 5276: @progstyle
5277: To keep the code understandable, a complete iteration of the loop should
5278: not change the number and types of the items on the stacks.
5279:
1.1 anton 5280: @cindex endless loop
5281: @cindex loops, endless
5282: @example
5283: BEGIN
1.29 crook 5284: @i{code}
1.1 anton 5285: AGAIN
5286: @end example
5287:
5288: This is an endless loop.
5289:
5290: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5291: @subsection Counted Loops
5292: @cindex counted loops
5293: @cindex loops, counted
5294: @cindex @code{DO} loops
5295:
5296: The basic counted loop is:
5297: @example
1.29 crook 5298: @i{limit} @i{start}
1.1 anton 5299: ?DO
1.29 crook 5300: @i{body}
1.1 anton 5301: LOOP
5302: @end example
5303:
1.29 crook 5304: This performs one iteration for every integer, starting from @i{start}
5305: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5306: accessed with @code{i}. For example, the loop:
1.1 anton 5307: @example
5308: 10 0 ?DO
5309: i .
5310: LOOP
5311: @end example
1.21 crook 5312: @noindent
5313: prints @code{0 1 2 3 4 5 6 7 8 9}
5314:
1.1 anton 5315: The index of the innermost loop can be accessed with @code{i}, the index
5316: of the next loop with @code{j}, and the index of the third loop with
5317: @code{k}.
5318:
1.44 crook 5319:
1.1 anton 5320: doc-i
5321: doc-j
5322: doc-k
5323:
1.44 crook 5324:
1.1 anton 5325: The loop control data are kept on the return stack, so there are some
1.21 crook 5326: restrictions on mixing return stack accesses and counted loop words. In
5327: particuler, if you put values on the return stack outside the loop, you
5328: cannot read them inside the loop@footnote{well, not in a way that is
5329: portable.}. If you put values on the return stack within a loop, you
5330: have to remove them before the end of the loop and before accessing the
5331: index of the loop.
1.1 anton 5332:
5333: There are several variations on the counted loop:
5334:
1.21 crook 5335: @itemize @bullet
5336: @item
5337: @code{LEAVE} leaves the innermost counted loop immediately; execution
5338: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5339:
5340: @example
5341: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5342: @end example
5343: prints @code{0 1 2 3}
5344:
1.1 anton 5345:
1.21 crook 5346: @item
5347: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5348: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5349: return stack so @code{EXIT} can get to its return address. For example:
5350:
5351: @example
5352: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5353: @end example
5354: prints @code{0 1 2 3}
5355:
5356:
5357: @item
1.29 crook 5358: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5359: (and @code{LOOP} iterates until they become equal by wrap-around
5360: arithmetic). This behaviour is usually not what you want. Therefore,
5361: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5362: @code{?DO}), which do not enter the loop if @i{start} is greater than
5363: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5364: unsigned loop parameters.
5365:
1.21 crook 5366: @item
5367: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5368: the loop, independent of the loop parameters. Do not use @code{DO}, even
5369: if you know that the loop is entered in any case. Such knowledge tends
5370: to become invalid during maintenance of a program, and then the
5371: @code{DO} will make trouble.
5372:
5373: @item
1.29 crook 5374: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5375: index by @i{n} instead of by 1. The loop is terminated when the border
5376: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5377:
1.21 crook 5378: @example
5379: 4 0 +DO i . 2 +LOOP
5380: @end example
5381: @noindent
5382: prints @code{0 2}
5383:
5384: @example
5385: 4 1 +DO i . 2 +LOOP
5386: @end example
5387: @noindent
5388: prints @code{1 3}
1.1 anton 5389:
1.68 anton 5390: @item
1.1 anton 5391: @cindex negative increment for counted loops
5392: @cindex counted loops with negative increment
1.29 crook 5393: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5394:
1.21 crook 5395: @example
5396: -1 0 ?DO i . -1 +LOOP
5397: @end example
5398: @noindent
5399: prints @code{0 -1}
1.1 anton 5400:
1.21 crook 5401: @example
5402: 0 0 ?DO i . -1 +LOOP
5403: @end example
5404: prints nothing.
1.1 anton 5405:
1.29 crook 5406: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5407: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5408: index by @i{u} each iteration. The loop is terminated when the border
5409: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5410: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5411:
1.21 crook 5412: @example
5413: -2 0 -DO i . 1 -LOOP
5414: @end example
5415: @noindent
5416: prints @code{0 -1}
1.1 anton 5417:
1.21 crook 5418: @example
5419: -1 0 -DO i . 1 -LOOP
5420: @end example
5421: @noindent
5422: prints @code{0}
5423:
5424: @example
5425: 0 0 -DO i . 1 -LOOP
5426: @end example
5427: @noindent
5428: prints nothing.
1.1 anton 5429:
1.21 crook 5430: @end itemize
1.1 anton 5431:
5432: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5433: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5434: for these words that uses only standard words is provided in
5435: @file{compat/loops.fs}.
1.1 anton 5436:
5437:
5438: @cindex @code{FOR} loops
1.26 crook 5439: Another counted loop is:
1.1 anton 5440: @example
1.29 crook 5441: @i{n}
1.1 anton 5442: FOR
1.29 crook 5443: @i{body}
1.1 anton 5444: NEXT
5445: @end example
5446: This is the preferred loop of native code compiler writers who are too
1.26 crook 5447: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5448: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5449: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5450: Forth systems may behave differently, even if they support @code{FOR}
5451: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5452:
5453: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5454: @subsection Arbitrary control structures
5455: @cindex control structures, user-defined
5456:
5457: @cindex control-flow stack
5458: ANS Forth permits and supports using control structures in a non-nested
5459: way. Information about incomplete control structures is stored on the
5460: control-flow stack. This stack may be implemented on the Forth data
5461: stack, and this is what we have done in Gforth.
5462:
5463: @cindex @code{orig}, control-flow stack item
5464: @cindex @code{dest}, control-flow stack item
5465: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5466: entry represents a backward branch target. A few words are the basis for
5467: building any control structure possible (except control structures that
5468: need storage, like calls, coroutines, and backtracking).
5469:
1.44 crook 5470:
1.1 anton 5471: doc-if
5472: doc-ahead
5473: doc-then
5474: doc-begin
5475: doc-until
5476: doc-again
5477: doc-cs-pick
5478: doc-cs-roll
5479:
1.44 crook 5480:
1.21 crook 5481: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5482: manipulate the control-flow stack in a portable way. Without them, you
5483: would need to know how many stack items are occupied by a control-flow
5484: entry (many systems use one cell. In Gforth they currently take three,
5485: but this may change in the future).
5486:
1.1 anton 5487: Some standard control structure words are built from these words:
5488:
1.44 crook 5489:
1.1 anton 5490: doc-else
5491: doc-while
5492: doc-repeat
5493:
1.44 crook 5494:
5495: @noindent
1.1 anton 5496: Gforth adds some more control-structure words:
5497:
1.44 crook 5498:
1.1 anton 5499: doc-endif
5500: doc-?dup-if
5501: doc-?dup-0=-if
5502:
1.44 crook 5503:
5504: @noindent
1.1 anton 5505: Counted loop words constitute a separate group of words:
5506:
1.44 crook 5507:
1.1 anton 5508: doc-?do
5509: doc-+do
5510: doc-u+do
5511: doc--do
5512: doc-u-do
5513: doc-do
5514: doc-for
5515: doc-loop
5516: doc-+loop
5517: doc--loop
5518: doc-next
5519: doc-leave
5520: doc-?leave
5521: doc-unloop
5522: doc-done
5523:
1.44 crook 5524:
1.21 crook 5525: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5526: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5527: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5528: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5529: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5530: resolved (by using one of the loop-ending words or @code{DONE}).
5531:
1.44 crook 5532: @noindent
1.26 crook 5533: Another group of control structure words are:
1.1 anton 5534:
1.44 crook 5535:
1.1 anton 5536: doc-case
5537: doc-endcase
5538: doc-of
5539: doc-endof
5540:
1.44 crook 5541:
1.21 crook 5542: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5543: @code{CS-ROLL}.
1.1 anton 5544:
5545: @subsubsection Programming Style
1.47 crook 5546: @cindex control structures programming style
5547: @cindex programming style, arbitrary control structures
1.1 anton 5548:
5549: In order to ensure readability we recommend that you do not create
5550: arbitrary control structures directly, but define new control structure
5551: words for the control structure you want and use these words in your
1.26 crook 5552: program. For example, instead of writing:
1.1 anton 5553:
5554: @example
1.26 crook 5555: BEGIN
1.1 anton 5556: ...
1.26 crook 5557: IF [ 1 CS-ROLL ]
1.1 anton 5558: ...
1.26 crook 5559: AGAIN THEN
1.1 anton 5560: @end example
5561:
1.21 crook 5562: @noindent
1.1 anton 5563: we recommend defining control structure words, e.g.,
5564:
5565: @example
1.26 crook 5566: : WHILE ( DEST -- ORIG DEST )
5567: POSTPONE IF
5568: 1 CS-ROLL ; immediate
5569:
5570: : REPEAT ( orig dest -- )
5571: POSTPONE AGAIN
5572: POSTPONE THEN ; immediate
1.1 anton 5573: @end example
5574:
1.21 crook 5575: @noindent
1.1 anton 5576: and then using these to create the control structure:
5577:
5578: @example
1.26 crook 5579: BEGIN
1.1 anton 5580: ...
1.26 crook 5581: WHILE
1.1 anton 5582: ...
1.26 crook 5583: REPEAT
1.1 anton 5584: @end example
5585:
5586: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5587: @code{WHILE} are predefined, so in this example it would not be
5588: necessary to define them.
5589:
5590: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5591: @subsection Calls and returns
5592: @cindex calling a definition
5593: @cindex returning from a definition
5594:
1.3 anton 5595: @cindex recursive definitions
5596: A definition can be called simply be writing the name of the definition
1.26 crook 5597: to be called. Normally a definition is invisible during its own
1.3 anton 5598: definition. If you want to write a directly recursive definition, you
1.26 crook 5599: can use @code{recursive} to make the current definition visible, or
5600: @code{recurse} to call the current definition directly.
1.3 anton 5601:
1.44 crook 5602:
1.3 anton 5603: doc-recursive
5604: doc-recurse
5605:
1.44 crook 5606:
1.21 crook 5607: @comment TODO add example of the two recursion methods
1.12 anton 5608: @quotation
5609: @progstyle
5610: I prefer using @code{recursive} to @code{recurse}, because calling the
5611: definition by name is more descriptive (if the name is well-chosen) than
5612: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5613: implementation, it is much better to read (and think) ``now sort the
5614: partitions'' than to read ``now do a recursive call''.
5615: @end quotation
1.3 anton 5616:
1.29 crook 5617: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5618:
5619: @example
1.28 crook 5620: Defer foo
1.3 anton 5621:
5622: : bar ( ... -- ... )
5623: ... foo ... ;
5624:
5625: :noname ( ... -- ... )
5626: ... bar ... ;
5627: IS foo
5628: @end example
5629:
1.170 pazsan 5630: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5631:
1.26 crook 5632: The current definition returns control to the calling definition when
1.33 anton 5633: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5634:
5635: doc-exit
5636: doc-;s
5637:
1.44 crook 5638:
1.1 anton 5639: @node Exception Handling, , Calls and returns, Control Structures
5640: @subsection Exception Handling
1.26 crook 5641: @cindex exceptions
1.1 anton 5642:
1.68 anton 5643: @c quit is a very bad idea for error handling,
5644: @c because it does not translate into a THROW
5645: @c it also does not belong into this chapter
5646:
5647: If a word detects an error condition that it cannot handle, it can
5648: @code{throw} an exception. In the simplest case, this will terminate
5649: your program, and report an appropriate error.
1.21 crook 5650:
1.68 anton 5651: doc-throw
1.1 anton 5652:
1.69 anton 5653: @code{Throw} consumes a cell-sized error number on the stack. There are
5654: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5655: Gforth (and most other systems) you can use the iors produced by various
5656: words as error numbers (e.g., a typical use of @code{allocate} is
5657: @code{allocate throw}). Gforth also provides the word @code{exception}
5658: to define your own error numbers (with decent error reporting); an ANS
5659: Forth version of this word (but without the error messages) is available
5660: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5661: numbers (anything outside the range -4095..0), but won't get nice error
5662: messages, only numbers. For example, try:
5663:
5664: @example
1.69 anton 5665: -10 throw \ ANS defined
5666: -267 throw \ system defined
5667: s" my error" exception throw \ user defined
5668: 7 throw \ arbitrary number
1.68 anton 5669: @end example
5670:
5671: doc---exception-exception
1.1 anton 5672:
1.69 anton 5673: A common idiom to @code{THROW} a specific error if a flag is true is
5674: this:
5675:
5676: @example
5677: @code{( flag ) 0<> @i{errno} and throw}
5678: @end example
5679:
5680: Your program can provide exception handlers to catch exceptions. An
5681: exception handler can be used to correct the problem, or to clean up
5682: some data structures and just throw the exception to the next exception
5683: handler. Note that @code{throw} jumps to the dynamically innermost
5684: exception handler. The system's exception handler is outermost, and just
5685: prints an error and restarts command-line interpretation (or, in batch
5686: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5687:
1.68 anton 5688: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5689:
1.68 anton 5690: doc-catch
1.160 anton 5691: doc-nothrow
1.68 anton 5692:
5693: The most common use of exception handlers is to clean up the state when
5694: an error happens. E.g.,
1.1 anton 5695:
1.26 crook 5696: @example
1.68 anton 5697: base @ >r hex \ actually the hex should be inside foo, or we h
5698: ['] foo catch ( nerror|0 )
5699: r> base !
1.69 anton 5700: ( nerror|0 ) throw \ pass it on
1.26 crook 5701: @end example
1.1 anton 5702:
1.69 anton 5703: A use of @code{catch} for handling the error @code{myerror} might look
5704: like this:
1.44 crook 5705:
1.68 anton 5706: @example
1.69 anton 5707: ['] foo catch
5708: CASE
1.160 anton 5709: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5710: dup throw \ default: pass other errors on, do nothing on non-errors
5711: ENDCASE
1.68 anton 5712: @end example
1.44 crook 5713:
1.68 anton 5714: Having to wrap the code into a separate word is often cumbersome,
5715: therefore Gforth provides an alternative syntax:
1.1 anton 5716:
5717: @example
1.69 anton 5718: TRY
1.68 anton 5719: @i{code1}
1.172 anton 5720: IFERROR
5721: @i{code2}
5722: THEN
5723: @i{code3}
1.69 anton 5724: ENDTRY
1.1 anton 5725: @end example
5726:
1.172 anton 5727: This performs @i{code1}. If @i{code1} completes normally, execution
5728: continues with @i{code3}. If @i{code1} or there is an exception
5729: before @code{endtry}, the stacks are reset to the state during
5730: @code{try}, the throw value is pushed on the data stack, and execution
5731: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26 crook 5732:
1.68 anton 5733: doc-try
5734: doc-endtry
1.172 anton 5735: doc-iferror
5736:
5737: If you don't need @i{code2}, you can write @code{restore} instead of
5738: @code{iferror then}:
5739:
5740: @example
5741: TRY
5742: @i{code1}
5743: RESTORE
5744: @i{code3}
5745: ENDTRY
5746: @end example
1.26 crook 5747:
1.172 anton 5748: @cindex unwind-protect
1.69 anton 5749: The cleanup example from above in this syntax:
1.26 crook 5750:
1.68 anton 5751: @example
1.174 anton 5752: base @@ @{ oldbase @}
1.172 anton 5753: TRY
1.68 anton 5754: hex foo \ now the hex is placed correctly
1.69 anton 5755: 0 \ value for throw
1.172 anton 5756: RESTORE
5757: oldbase base !
5758: ENDTRY
5759: throw
1.1 anton 5760: @end example
5761:
1.172 anton 5762: An additional advantage of this variant is that an exception between
5763: @code{restore} and @code{endtry} (e.g., from the user pressing
5764: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5765: so the base will be restored under all circumstances.
5766:
5767: However, you have to ensure that this code does not cause an exception
5768: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5769: Moreover, you should also make sure that the stack contents needed by
5770: the @code{iferror}/@code{restore} code exist everywhere between
5771: @code{try} and @code{endtry}; in our example this is achived by
5772: putting the data in a local before the @code{try} (you cannot use the
5773: return stack because the exception frame (@i{sys1}) is in the way
5774: there).
5775:
5776: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5777:
5778: @cindex @code{recover} (old Gforth versions)
5779: If you do not want this exception-restarting behaviour, you achieve
5780: this as follows:
5781:
5782: @example
5783: TRY
5784: @i{code1}
5785: ENDTRY-IFERROR
5786: @i{code2}
5787: THEN
5788: @end example
5789:
5790: If there is an exception in @i{code1}, then @i{code2} is executed,
5791: otherwise execution continues behind the @code{then} (or in a possible
5792: @code{else} branch). This corresponds to the construct
5793:
5794: @example
5795: TRY
5796: @i{code1}
5797: RECOVER
5798: @i{code2}
5799: ENDTRY
5800: @end example
5801:
5802: in Gforth before version 0.7. So you can directly replace
5803: @code{recover}-using code; however, we recommend that you check if it
5804: would not be better to use one of the other @code{try} variants while
5805: you are at it.
5806:
1.173 anton 5807: To ease the transition, Gforth provides two compatibility files:
5808: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5809: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5810: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5811: ... endtry} syntax on new systems, so you can use that file as a
5812: stopgap to run old programs. Both files work on any system (they just
5813: do nothing if the system already has the syntax it implements), so you
5814: can unconditionally @code{require} one of these files, even if you use
5815: a mix old and new systems.
5816:
1.172 anton 5817: doc-restore
5818: doc-endtry-iferror
5819:
5820: Here's the error handling example:
1.1 anton 5821:
1.68 anton 5822: @example
1.69 anton 5823: TRY
1.68 anton 5824: foo
1.172 anton 5825: ENDTRY-IFERROR
1.69 anton 5826: CASE
1.160 anton 5827: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5828: throw \ pass other errors on
5829: ENDCASE
1.172 anton 5830: THEN
1.68 anton 5831: @end example
1.1 anton 5832:
1.69 anton 5833: @progstyle
5834: As usual, you should ensure that the stack depth is statically known at
5835: the end: either after the @code{throw} for passing on errors, or after
5836: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5837: selection construct for handling the error).
5838:
1.68 anton 5839: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5840: and you can provide an error message. @code{Abort} just produces an
5841: ``Aborted'' error.
1.1 anton 5842:
1.68 anton 5843: The problem with these words is that exception handlers cannot
5844: differentiate between different @code{abort"}s; they just look like
5845: @code{-2 throw} to them (the error message cannot be accessed by
5846: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5847: exception handlers.
1.44 crook 5848:
1.68 anton 5849: doc-abort"
1.26 crook 5850: doc-abort
1.29 crook 5851:
5852:
1.44 crook 5853:
1.29 crook 5854: @c -------------------------------------------------------------
1.47 crook 5855: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5856: @section Defining Words
5857: @cindex defining words
5858:
1.47 crook 5859: Defining words are used to extend Forth by creating new entries in the dictionary.
5860:
1.29 crook 5861: @menu
1.67 anton 5862: * CREATE::
1.44 crook 5863: * Variables:: Variables and user variables
1.67 anton 5864: * Constants::
1.44 crook 5865: * Values:: Initialised variables
1.67 anton 5866: * Colon Definitions::
1.44 crook 5867: * Anonymous Definitions:: Definitions without names
1.69 anton 5868: * Supplying names:: Passing definition names as strings
1.67 anton 5869: * User-defined Defining Words::
1.170 pazsan 5870: * Deferred Words:: Allow forward references
1.67 anton 5871: * Aliases::
1.29 crook 5872: @end menu
5873:
1.44 crook 5874: @node CREATE, Variables, Defining Words, Defining Words
5875: @subsection @code{CREATE}
1.29 crook 5876: @cindex simple defining words
5877: @cindex defining words, simple
5878:
5879: Defining words are used to create new entries in the dictionary. The
5880: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5881: this:
5882:
5883: @example
5884: CREATE new-word1
5885: @end example
5886:
1.69 anton 5887: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5888: input stream (@code{new-word1} in our example). It generates a
5889: dictionary entry for @code{new-word1}. When @code{new-word1} is
5890: executed, all that it does is leave an address on the stack. The address
5891: represents the value of the data space pointer (@code{HERE}) at the time
5892: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5893: associating a name with the address of a region of memory.
1.29 crook 5894:
1.34 anton 5895: doc-create
5896:
1.69 anton 5897: Note that in ANS Forth guarantees only for @code{create} that its body
5898: is in dictionary data space (i.e., where @code{here}, @code{allot}
5899: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5900: @code{create}d words can be modified with @code{does>}
5901: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5902: can only be applied to @code{create}d words.
5903:
1.29 crook 5904: By extending this example to reserve some memory in data space, we end
1.69 anton 5905: up with something like a @i{variable}. Here are two different ways to do
5906: it:
1.29 crook 5907:
5908: @example
5909: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5910: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5911: @end example
5912:
5913: The variable can be examined and modified using @code{@@} (``fetch'') and
5914: @code{!} (``store'') like this:
5915:
5916: @example
5917: new-word2 @@ . \ get address, fetch from it and display
5918: 1234 new-word2 ! \ new value, get address, store to it
5919: @end example
5920:
1.44 crook 5921: @cindex arrays
5922: A similar mechanism can be used to create arrays. For example, an
5923: 80-character text input buffer:
1.29 crook 5924:
5925: @example
1.44 crook 5926: CREATE text-buf 80 chars allot
5927:
1.168 anton 5928: text-buf 0 chars + c@@ \ the 1st character (offset 0)
5929: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 5930: @end example
1.29 crook 5931:
1.44 crook 5932: You can build arbitrarily complex data structures by allocating
1.49 anton 5933: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5934: learn about some Gforth tools that make it easier,
1.49 anton 5935: @xref{Structures}.
1.44 crook 5936:
5937:
5938: @node Variables, Constants, CREATE, Defining Words
5939: @subsection Variables
5940: @cindex variables
5941:
5942: The previous section showed how a sequence of commands could be used to
5943: generate a variable. As a final refinement, the whole code sequence can
5944: be wrapped up in a defining word (pre-empting the subject of the next
5945: section), making it easier to create new variables:
5946:
5947: @example
5948: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5949: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5950:
5951: myvariableX foo \ variable foo starts off with an unknown value
5952: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5953:
5954: 45 3 * foo ! \ set foo to 135
5955: 1234 joe ! \ set joe to 1234
5956: 3 joe +! \ increment joe by 3.. to 1237
5957: @end example
5958:
5959: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5960: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5961: guarantee that a @code{Variable} is initialised when it is created
5962: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5963: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5964: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5965: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5966: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5967: store a boolean, you can use @code{on} and @code{off} to toggle its
5968: state.
1.29 crook 5969:
1.34 anton 5970: doc-variable
5971: doc-2variable
5972: doc-fvariable
5973:
1.29 crook 5974: @cindex user variables
5975: @cindex user space
5976: The defining word @code{User} behaves in the same way as @code{Variable}.
5977: The difference is that it reserves space in @i{user (data) space} rather
5978: than normal data space. In a Forth system that has a multi-tasker, each
5979: task has its own set of user variables.
5980:
1.34 anton 5981: doc-user
1.67 anton 5982: @c doc-udp
5983: @c doc-uallot
1.34 anton 5984:
1.29 crook 5985: @comment TODO is that stuff about user variables strictly correct? Is it
5986: @comment just terminal tasks that have user variables?
5987: @comment should document tasker.fs (with some examples) elsewhere
5988: @comment in this manual, then expand on user space and user variables.
5989:
1.44 crook 5990: @node Constants, Values, Variables, Defining Words
5991: @subsection Constants
5992: @cindex constants
5993:
5994: @code{Constant} allows you to declare a fixed value and refer to it by
5995: name. For example:
1.29 crook 5996:
5997: @example
5998: 12 Constant INCHES-PER-FOOT
5999: 3E+08 fconstant SPEED-O-LIGHT
6000: @end example
6001:
6002: A @code{Variable} can be both read and written, so its run-time
6003: behaviour is to supply an address through which its current value can be
6004: manipulated. In contrast, the value of a @code{Constant} cannot be
6005: changed once it has been declared@footnote{Well, often it can be -- but
6006: not in a Standard, portable way. It's safer to use a @code{Value} (read
6007: on).} so it's not necessary to supply the address -- it is more
6008: efficient to return the value of the constant directly. That's exactly
6009: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6010: the top of the stack (You can find one
6011: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6012:
1.69 anton 6013: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6014: double and floating-point constants, respectively.
6015:
1.34 anton 6016: doc-constant
6017: doc-2constant
6018: doc-fconstant
6019:
6020: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6021: @c nac-> How could that not be true in an ANS Forth? You can't define a
6022: @c constant, use it and then delete the definition of the constant..
1.69 anton 6023:
6024: @c anton->An ANS Forth system can compile a constant to a literal; On
6025: @c decompilation you would see only the number, just as if it had been used
6026: @c in the first place. The word will stay, of course, but it will only be
6027: @c used by the text interpreter (no run-time duties, except when it is
6028: @c POSTPONEd or somesuch).
6029:
6030: @c nac:
1.44 crook 6031: @c I agree that it's rather deep, but IMO it is an important difference
6032: @c relative to other programming languages.. often it's annoying: it
6033: @c certainly changes my programming style relative to C.
6034:
1.69 anton 6035: @c anton: In what way?
6036:
1.29 crook 6037: Constants in Forth behave differently from their equivalents in other
6038: programming languages. In other languages, a constant (such as an EQU in
6039: assembler or a #define in C) only exists at compile-time; in the
6040: executable program the constant has been translated into an absolute
6041: number and, unless you are using a symbolic debugger, it's impossible to
6042: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6043: an entry in the header space and remains there after the code that uses
6044: it has been defined. In fact, it must remain in the dictionary since it
6045: has run-time duties to perform. For example:
1.29 crook 6046:
6047: @example
6048: 12 Constant INCHES-PER-FOOT
6049: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6050: @end example
6051:
6052: @cindex in-lining of constants
6053: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6054: associated with the constant @code{INCHES-PER-FOOT}. If you use
6055: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6056: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6057: attempt to optimise constants by in-lining them where they are used. You
6058: can force Gforth to in-line a constant like this:
6059:
6060: @example
6061: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6062: @end example
6063:
6064: If you use @code{see} to decompile @i{this} version of
6065: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6066: longer present. To understand how this works, read
6067: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6068:
6069: In-lining constants in this way might improve execution time
6070: fractionally, and can ensure that a constant is now only referenced at
6071: compile-time. However, the definition of the constant still remains in
6072: the dictionary. Some Forth compilers provide a mechanism for controlling
6073: a second dictionary for holding transient words such that this second
6074: dictionary can be deleted later in order to recover memory
6075: space. However, there is no standard way of doing this.
6076:
6077:
1.44 crook 6078: @node Values, Colon Definitions, Constants, Defining Words
6079: @subsection Values
6080: @cindex values
1.34 anton 6081:
1.69 anton 6082: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6083: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6084: (not in ANS Forth) you can access (and change) a @code{value} also with
6085: @code{>body}.
6086:
6087: Here are some
6088: examples:
1.29 crook 6089:
6090: @example
1.69 anton 6091: 12 Value APPLES \ Define APPLES with an initial value of 12
6092: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6093: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6094: APPLES \ puts 35 on the top of the stack.
1.29 crook 6095: @end example
6096:
1.44 crook 6097: doc-value
6098: doc-to
1.29 crook 6099:
1.35 anton 6100:
1.69 anton 6101:
1.44 crook 6102: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6103: @subsection Colon Definitions
6104: @cindex colon definitions
1.35 anton 6105:
6106: @example
1.44 crook 6107: : name ( ... -- ... )
6108: word1 word2 word3 ;
1.29 crook 6109: @end example
6110:
1.44 crook 6111: @noindent
6112: Creates a word called @code{name} that, upon execution, executes
6113: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6114:
1.49 anton 6115: The explanation above is somewhat superficial. For simple examples of
6116: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6117: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6118: Compilation Semantics}.
1.29 crook 6119:
1.44 crook 6120: doc-:
6121: doc-;
1.1 anton 6122:
1.34 anton 6123:
1.69 anton 6124: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6125: @subsection Anonymous Definitions
6126: @cindex colon definitions
6127: @cindex defining words without name
1.34 anton 6128:
1.44 crook 6129: Sometimes you want to define an @dfn{anonymous word}; a word without a
6130: name. You can do this with:
1.1 anton 6131:
1.44 crook 6132: doc-:noname
1.1 anton 6133:
1.44 crook 6134: This leaves the execution token for the word on the stack after the
6135: closing @code{;}. Here's an example in which a deferred word is
6136: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6137:
1.29 crook 6138: @example
1.44 crook 6139: Defer deferred
6140: :noname ( ... -- ... )
6141: ... ;
6142: IS deferred
1.29 crook 6143: @end example
1.26 crook 6144:
1.44 crook 6145: @noindent
6146: Gforth provides an alternative way of doing this, using two separate
6147: words:
1.27 crook 6148:
1.44 crook 6149: doc-noname
6150: @cindex execution token of last defined word
1.116 anton 6151: doc-latestxt
1.1 anton 6152:
1.44 crook 6153: @noindent
6154: The previous example can be rewritten using @code{noname} and
1.116 anton 6155: @code{latestxt}:
1.1 anton 6156:
1.26 crook 6157: @example
1.44 crook 6158: Defer deferred
6159: noname : ( ... -- ... )
6160: ... ;
1.116 anton 6161: latestxt IS deferred
1.26 crook 6162: @end example
1.1 anton 6163:
1.29 crook 6164: @noindent
1.44 crook 6165: @code{noname} works with any defining word, not just @code{:}.
6166:
1.116 anton 6167: @code{latestxt} also works when the last word was not defined as
1.71 anton 6168: @code{noname}. It does not work for combined words, though. It also has
6169: the useful property that is is valid as soon as the header for a
6170: definition has been built. Thus:
1.44 crook 6171:
6172: @example
1.116 anton 6173: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6174: @end example
1.1 anton 6175:
1.44 crook 6176: @noindent
6177: prints 3 numbers; the last two are the same.
1.26 crook 6178:
1.69 anton 6179: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6180: @subsection Supplying the name of a defined word
6181: @cindex names for defined words
6182: @cindex defining words, name given in a string
6183:
6184: By default, a defining word takes the name for the defined word from the
6185: input stream. Sometimes you want to supply the name from a string. You
6186: can do this with:
6187:
6188: doc-nextname
6189:
6190: For example:
6191:
6192: @example
6193: s" foo" nextname create
6194: @end example
6195:
6196: @noindent
6197: is equivalent to:
6198:
6199: @example
6200: create foo
6201: @end example
6202:
6203: @noindent
6204: @code{nextname} works with any defining word.
6205:
1.1 anton 6206:
1.170 pazsan 6207: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6208: @subsection User-defined Defining Words
6209: @cindex user-defined defining words
6210: @cindex defining words, user-defined
1.1 anton 6211:
1.29 crook 6212: You can create a new defining word by wrapping defining-time code around
6213: an existing defining word and putting the sequence in a colon
1.69 anton 6214: definition.
6215:
6216: @c anton: This example is very complex and leads in a quite different
6217: @c direction from the CREATE-DOES> stuff that follows. It should probably
6218: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6219: @c subsection of Defining Words)
6220:
6221: For example, suppose that you have a word @code{stats} that
1.29 crook 6222: gathers statistics about colon definitions given the @i{xt} of the
6223: definition, and you want every colon definition in your application to
6224: make a call to @code{stats}. You can define and use a new version of
6225: @code{:} like this:
6226:
6227: @example
6228: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6229: ... ; \ other code
6230:
1.116 anton 6231: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6232:
6233: my: foo + - ;
6234: @end example
6235:
6236: When @code{foo} is defined using @code{my:} these steps occur:
6237:
6238: @itemize @bullet
6239: @item
6240: @code{my:} is executed.
6241: @item
6242: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6243: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6244: the input stream for a name, builds a dictionary header for the name
6245: @code{foo} and switches @code{state} from interpret to compile.
6246: @item
1.116 anton 6247: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6248: being defined -- @code{foo} -- onto the stack.
6249: @item
6250: The code that was produced by @code{postpone literal} is executed; this
6251: causes the value on the stack to be compiled as a literal in the code
6252: area of @code{foo}.
6253: @item
6254: The code @code{['] stats} compiles a literal into the definition of
6255: @code{my:}. When @code{compile,} is executed, that literal -- the
6256: execution token for @code{stats} -- is layed down in the code area of
6257: @code{foo} , following the literal@footnote{Strictly speaking, the
6258: mechanism that @code{compile,} uses to convert an @i{xt} into something
6259: in the code area is implementation-dependent. A threaded implementation
6260: might spit out the execution token directly whilst another
6261: implementation might spit out a native code sequence.}.
6262: @item
6263: At this point, the execution of @code{my:} is complete, and control
6264: returns to the text interpreter. The text interpreter is in compile
6265: state, so subsequent text @code{+ -} is compiled into the definition of
6266: @code{foo} and the @code{;} terminates the definition as always.
6267: @end itemize
6268:
6269: You can use @code{see} to decompile a word that was defined using
6270: @code{my:} and see how it is different from a normal @code{:}
6271: definition. For example:
6272:
6273: @example
6274: : bar + - ; \ like foo but using : rather than my:
6275: see bar
6276: : bar
6277: + - ;
6278: see foo
6279: : foo
6280: 107645672 stats + - ;
6281:
1.140 anton 6282: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6283: @end example
6284:
6285: You can use techniques like this to make new defining words in terms of
6286: @i{any} existing defining word.
1.1 anton 6287:
6288:
1.29 crook 6289: @cindex defining defining words
1.26 crook 6290: @cindex @code{CREATE} ... @code{DOES>}
6291: If you want the words defined with your defining words to behave
6292: differently from words defined with standard defining words, you can
6293: write your defining word like this:
1.1 anton 6294:
6295: @example
1.26 crook 6296: : def-word ( "name" -- )
1.29 crook 6297: CREATE @i{code1}
1.26 crook 6298: DOES> ( ... -- ... )
1.29 crook 6299: @i{code2} ;
1.26 crook 6300:
6301: def-word name
1.1 anton 6302: @end example
6303:
1.29 crook 6304: @cindex child words
6305: This fragment defines a @dfn{defining word} @code{def-word} and then
6306: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6307: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6308: is not executed at this time. The word @code{name} is sometimes called a
6309: @dfn{child} of @code{def-word}.
6310:
6311: When you execute @code{name}, the address of the body of @code{name} is
6312: put on the data stack and @i{code2} is executed (the address of the body
6313: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6314: @code{CREATE}, i.e., the address a @code{create}d word returns by
6315: default).
6316:
6317: @c anton:
6318: @c www.dictionary.com says:
6319: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6320: @c several generations of absence, usually caused by the chance
6321: @c recombination of genes. 2.An individual or a part that exhibits
6322: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6323: @c of previous behavior after a period of absence.
6324: @c
6325: @c Doesn't seem to fit.
1.29 crook 6326:
1.69 anton 6327: @c @cindex atavism in child words
1.33 anton 6328: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6329: similarly; they all have a common run-time behaviour determined by
6330: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6331: body of the child word. The structure of the data is common to all
6332: children of @code{def-word}, but the data values are specific -- and
6333: private -- to each child word. When a child word is executed, the
6334: address of its private data area is passed as a parameter on TOS to be
6335: used and manipulated@footnote{It is legitimate both to read and write to
6336: this data area.} by @i{code2}.
1.29 crook 6337:
6338: The two fragments of code that make up the defining words act (are
6339: executed) at two completely separate times:
1.1 anton 6340:
1.29 crook 6341: @itemize @bullet
6342: @item
6343: At @i{define time}, the defining word executes @i{code1} to generate a
6344: child word
6345: @item
6346: At @i{child execution time}, when a child word is invoked, @i{code2}
6347: is executed, using parameters (data) that are private and specific to
6348: the child word.
6349: @end itemize
6350:
1.44 crook 6351: Another way of understanding the behaviour of @code{def-word} and
6352: @code{name} is to say that, if you make the following definitions:
1.33 anton 6353: @example
6354: : def-word1 ( "name" -- )
6355: CREATE @i{code1} ;
6356:
6357: : action1 ( ... -- ... )
6358: @i{code2} ;
6359:
6360: def-word1 name1
6361: @end example
6362:
1.44 crook 6363: @noindent
6364: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6365:
1.29 crook 6366: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6367:
1.1 anton 6368: @example
1.29 crook 6369: : CONSTANT ( w "name" -- )
6370: CREATE ,
1.26 crook 6371: DOES> ( -- w )
6372: @@ ;
1.1 anton 6373: @end example
6374:
1.29 crook 6375: @comment There is a beautiful description of how this works and what
6376: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6377: @comment commentary on the Counting Fruits problem.
6378:
6379: When you create a constant with @code{5 CONSTANT five}, a set of
6380: define-time actions take place; first a new word @code{five} is created,
6381: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6382: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6383: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6384: no code of its own; it simply contains a data field and a pointer to the
6385: code that follows @code{DOES>} in its defining word. That makes words
6386: created in this way very compact.
6387:
6388: The final example in this section is intended to remind you that space
6389: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6390: both read and written by a Standard program@footnote{Exercise: use this
6391: example as a starting point for your own implementation of @code{Value}
6392: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6393: @code{[']}.}:
6394:
6395: @example
6396: : foo ( "name" -- )
6397: CREATE -1 ,
6398: DOES> ( -- )
1.33 anton 6399: @@ . ;
1.29 crook 6400:
6401: foo first-word
6402: foo second-word
6403:
6404: 123 ' first-word >BODY !
6405: @end example
6406:
6407: If @code{first-word} had been a @code{CREATE}d word, we could simply
6408: have executed it to get the address of its data field. However, since it
6409: was defined to have @code{DOES>} actions, its execution semantics are to
6410: perform those @code{DOES>} actions. To get the address of its data field
6411: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6412: translate the xt into the address of the data field. When you execute
6413: @code{first-word}, it will display @code{123}. When you execute
6414: @code{second-word} it will display @code{-1}.
1.26 crook 6415:
6416: @cindex stack effect of @code{DOES>}-parts
6417: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6418: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6419: the stack effect of the defined words, not the stack effect of the
6420: following code (the following code expects the address of the body on
6421: the top of stack, which is not reflected in the stack comment). This is
6422: the convention that I use and recommend (it clashes a bit with using
6423: locals declarations for stack effect specification, though).
1.1 anton 6424:
1.53 anton 6425: @menu
6426: * CREATE..DOES> applications::
6427: * CREATE..DOES> details::
1.63 anton 6428: * Advanced does> usage example::
1.155 anton 6429: * Const-does>::
1.53 anton 6430: @end menu
6431:
6432: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6433: @subsubsection Applications of @code{CREATE..DOES>}
6434: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6435:
1.26 crook 6436: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6437:
1.26 crook 6438: @cindex factoring similar colon definitions
6439: When you see a sequence of code occurring several times, and you can
6440: identify a meaning, you will factor it out as a colon definition. When
6441: you see similar colon definitions, you can factor them using
6442: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6443: that look very similar:
1.1 anton 6444: @example
1.26 crook 6445: : ori, ( reg-target reg-source n -- )
6446: 0 asm-reg-reg-imm ;
6447: : andi, ( reg-target reg-source n -- )
6448: 1 asm-reg-reg-imm ;
1.1 anton 6449: @end example
6450:
1.26 crook 6451: @noindent
6452: This could be factored with:
6453: @example
6454: : reg-reg-imm ( op-code -- )
6455: CREATE ,
6456: DOES> ( reg-target reg-source n -- )
6457: @@ asm-reg-reg-imm ;
6458:
6459: 0 reg-reg-imm ori,
6460: 1 reg-reg-imm andi,
6461: @end example
1.1 anton 6462:
1.26 crook 6463: @cindex currying
6464: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6465: supply a part of the parameters for a word (known as @dfn{currying} in
6466: the functional language community). E.g., @code{+} needs two
6467: parameters. Creating versions of @code{+} with one parameter fixed can
6468: be done like this:
1.82 anton 6469:
1.1 anton 6470: @example
1.82 anton 6471: : curry+ ( n1 "name" -- )
1.26 crook 6472: CREATE ,
6473: DOES> ( n2 -- n1+n2 )
6474: @@ + ;
6475:
6476: 3 curry+ 3+
6477: -2 curry+ 2-
1.1 anton 6478: @end example
6479:
1.91 anton 6480:
1.63 anton 6481: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6482: @subsubsection The gory details of @code{CREATE..DOES>}
6483: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6484:
1.26 crook 6485: doc-does>
1.1 anton 6486:
1.26 crook 6487: @cindex @code{DOES>} in a separate definition
6488: This means that you need not use @code{CREATE} and @code{DOES>} in the
6489: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6490: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6491: @example
6492: : does1
6493: DOES> ( ... -- ... )
1.44 crook 6494: ... ;
6495:
6496: : does2
6497: DOES> ( ... -- ... )
6498: ... ;
6499:
6500: : def-word ( ... -- ... )
6501: create ...
6502: IF
6503: does1
6504: ELSE
6505: does2
6506: ENDIF ;
6507: @end example
6508:
6509: In this example, the selection of whether to use @code{does1} or
1.69 anton 6510: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6511: @code{CREATE}d.
6512:
6513: @cindex @code{DOES>} in interpretation state
6514: In a standard program you can apply a @code{DOES>}-part only if the last
6515: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6516: will override the behaviour of the last word defined in any case. In a
6517: standard program, you can use @code{DOES>} only in a colon
6518: definition. In Gforth, you can also use it in interpretation state, in a
6519: kind of one-shot mode; for example:
6520: @example
6521: CREATE name ( ... -- ... )
6522: @i{initialization}
6523: DOES>
6524: @i{code} ;
6525: @end example
6526:
6527: @noindent
6528: is equivalent to the standard:
6529: @example
6530: :noname
6531: DOES>
6532: @i{code} ;
6533: CREATE name EXECUTE ( ... -- ... )
6534: @i{initialization}
6535: @end example
6536:
1.53 anton 6537: doc->body
6538:
1.152 pazsan 6539: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6540: @subsubsection Advanced does> usage example
6541:
6542: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6543: for disassembling instructions, that follow a very repetetive scheme:
6544:
6545: @example
6546: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6547: @var{entry-num} cells @var{table} + !
6548: @end example
6549:
6550: Of course, this inspires the idea to factor out the commonalities to
6551: allow a definition like
6552:
6553: @example
6554: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6555: @end example
6556:
6557: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6558: correlated. Moreover, before I wrote the disassembler, there already
6559: existed code that defines instructions like this:
1.63 anton 6560:
6561: @example
6562: @var{entry-num} @var{inst-format} @var{inst-name}
6563: @end example
6564:
6565: This code comes from the assembler and resides in
6566: @file{arch/mips/insts.fs}.
6567:
6568: So I had to define the @var{inst-format} words that performed the scheme
6569: above when executed. At first I chose to use run-time code-generation:
6570:
6571: @example
6572: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6573: :noname Postpone @var{disasm-operands}
6574: name Postpone sliteral Postpone type Postpone ;
6575: swap cells @var{table} + ! ;
6576: @end example
6577:
6578: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6579:
1.63 anton 6580: An alternative would have been to write this using
6581: @code{create}/@code{does>}:
6582:
6583: @example
6584: : @var{inst-format} ( entry-num "name" -- )
6585: here name string, ( entry-num c-addr ) \ parse and save "name"
6586: noname create , ( entry-num )
1.116 anton 6587: latestxt swap cells @var{table} + !
1.63 anton 6588: does> ( addr w -- )
6589: \ disassemble instruction w at addr
6590: @@ >r
6591: @var{disasm-operands}
6592: r> count type ;
6593: @end example
6594:
6595: Somehow the first solution is simpler, mainly because it's simpler to
6596: shift a string from definition-time to use-time with @code{sliteral}
6597: than with @code{string,} and friends.
6598:
6599: I wrote a lot of words following this scheme and soon thought about
6600: factoring out the commonalities among them. Note that this uses a
6601: two-level defining word, i.e., a word that defines ordinary defining
6602: words.
6603:
6604: This time a solution involving @code{postpone} and friends seemed more
6605: difficult (try it as an exercise), so I decided to use a
6606: @code{create}/@code{does>} word; since I was already at it, I also used
6607: @code{create}/@code{does>} for the lower level (try using
6608: @code{postpone} etc. as an exercise), resulting in the following
6609: definition:
6610:
6611: @example
6612: : define-format ( disasm-xt table-xt -- )
6613: \ define an instruction format that uses disasm-xt for
6614: \ disassembling and enters the defined instructions into table
6615: \ table-xt
6616: create 2,
6617: does> ( u "inst" -- )
6618: \ defines an anonymous word for disassembling instruction inst,
6619: \ and enters it as u-th entry into table-xt
6620: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6621: noname create 2, \ define anonymous word
1.116 anton 6622: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6623: does> ( addr w -- )
6624: \ disassemble instruction w at addr
6625: 2@@ >r ( addr w disasm-xt R: c-addr )
6626: execute ( R: c-addr ) \ disassemble operands
6627: r> count type ; \ print name
6628: @end example
6629:
6630: Note that the tables here (in contrast to above) do the @code{cells +}
6631: by themselves (that's why you have to pass an xt). This word is used in
6632: the following way:
6633:
6634: @example
6635: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6636: @end example
6637:
1.71 anton 6638: As shown above, the defined instruction format is then used like this:
6639:
6640: @example
6641: @var{entry-num} @var{inst-format} @var{inst-name}
6642: @end example
6643:
1.63 anton 6644: In terms of currying, this kind of two-level defining word provides the
6645: parameters in three stages: first @var{disasm-operands} and @var{table},
6646: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6647: the instruction to be disassembled.
6648:
6649: Of course this did not quite fit all the instruction format names used
6650: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6651: the parameters into the right form.
6652:
6653: If you have trouble following this section, don't worry. First, this is
6654: involved and takes time (and probably some playing around) to
6655: understand; second, this is the first two-level
6656: @code{create}/@code{does>} word I have written in seventeen years of
6657: Forth; and if I did not have @file{insts.fs} to start with, I may well
6658: have elected to use just a one-level defining word (with some repeating
6659: of parameters when using the defining word). So it is not necessary to
6660: understand this, but it may improve your understanding of Forth.
1.44 crook 6661:
6662:
1.152 pazsan 6663: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6664: @subsubsection @code{Const-does>}
6665:
6666: A frequent use of @code{create}...@code{does>} is for transferring some
6667: values from definition-time to run-time. Gforth supports this use with
6668:
6669: doc-const-does>
6670:
6671: A typical use of this word is:
6672:
6673: @example
6674: : curry+ ( n1 "name" -- )
6675: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6676: + ;
6677:
6678: 3 curry+ 3+
6679: @end example
6680:
6681: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6682: definition to run-time.
6683:
6684: The advantages of using @code{const-does>} are:
6685:
6686: @itemize
6687:
6688: @item
6689: You don't have to deal with storing and retrieving the values, i.e.,
6690: your program becomes more writable and readable.
6691:
6692: @item
6693: When using @code{does>}, you have to introduce a @code{@@} that cannot
6694: be optimized away (because you could change the data using
6695: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6696:
6697: @end itemize
6698:
6699: An ANS Forth implementation of @code{const-does>} is available in
6700: @file{compat/const-does.fs}.
6701:
6702:
1.170 pazsan 6703: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6704: @subsection Deferred Words
1.44 crook 6705: @cindex deferred words
6706:
6707: The defining word @code{Defer} allows you to define a word by name
6708: without defining its behaviour; the definition of its behaviour is
6709: deferred. Here are two situation where this can be useful:
6710:
6711: @itemize @bullet
6712: @item
6713: Where you want to allow the behaviour of a word to be altered later, and
6714: for all precompiled references to the word to change when its behaviour
6715: is changed.
6716: @item
6717: For mutual recursion; @xref{Calls and returns}.
6718: @end itemize
6719:
6720: In the following example, @code{foo} always invokes the version of
6721: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6722: always invokes the version that prints ``@code{Hello}''. There is no way
6723: of getting @code{foo} to use the later version without re-ordering the
6724: source code and recompiling it.
6725:
6726: @example
6727: : greet ." Good morning" ;
6728: : foo ... greet ... ;
6729: : greet ." Hello" ;
6730: : bar ... greet ... ;
6731: @end example
6732:
6733: This problem can be solved by defining @code{greet} as a @code{Defer}red
6734: word. The behaviour of a @code{Defer}red word can be defined and
6735: redefined at any time by using @code{IS} to associate the xt of a
6736: previously-defined word with it. The previous example becomes:
6737:
6738: @example
1.69 anton 6739: Defer greet ( -- )
1.44 crook 6740: : foo ... greet ... ;
6741: : bar ... greet ... ;
1.69 anton 6742: : greet1 ( -- ) ." Good morning" ;
6743: : greet2 ( -- ) ." Hello" ;
1.132 anton 6744: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6745: @end example
6746:
1.69 anton 6747: @progstyle
6748: You should write a stack comment for every deferred word, and put only
6749: XTs into deferred words that conform to this stack effect. Otherwise
6750: it's too difficult to use the deferred word.
6751:
1.44 crook 6752: A deferred word can be used to improve the statistics-gathering example
6753: from @ref{User-defined Defining Words}; rather than edit the
6754: application's source code to change every @code{:} to a @code{my:}, do
6755: this:
6756:
6757: @example
6758: : real: : ; \ retain access to the original
6759: defer : \ redefine as a deferred word
1.132 anton 6760: ' my: IS : \ use special version of :
1.44 crook 6761: \
6762: \ load application here
6763: \
1.132 anton 6764: ' real: IS : \ go back to the original
1.44 crook 6765: @end example
6766:
6767:
1.132 anton 6768: One thing to note is that @code{IS} has special compilation semantics,
6769: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6770:
6771: @example
6772: : set-greet ( xt -- )
1.132 anton 6773: IS greet ;
1.44 crook 6774:
6775: ' greet1 set-greet
6776: @end example
6777:
1.132 anton 6778: In situations where @code{IS} does not fit, use @code{defer!} instead.
6779:
1.69 anton 6780: A deferred word can only inherit execution semantics from the xt
6781: (because that is all that an xt can represent -- for more discussion of
6782: this @pxref{Tokens for Words}); by default it will have default
6783: interpretation and compilation semantics deriving from this execution
6784: semantics. However, you can change the interpretation and compilation
6785: semantics of the deferred word in the usual ways:
1.44 crook 6786:
6787: @example
1.132 anton 6788: : bar .... ; immediate
1.44 crook 6789: Defer fred immediate
6790: Defer jim
6791:
1.132 anton 6792: ' bar IS jim \ jim has default semantics
6793: ' bar IS fred \ fred is immediate
1.44 crook 6794: @end example
6795:
6796: doc-defer
1.132 anton 6797: doc-defer!
1.44 crook 6798: doc-is
1.132 anton 6799: doc-defer@
6800: doc-action-of
1.44 crook 6801: @comment TODO document these: what's defers [is]
6802: doc-defers
6803:
6804: @c Use @code{words-deferred} to see a list of deferred words.
6805:
1.132 anton 6806: Definitions of these words (except @code{defers}) in ANS Forth are
6807: provided in @file{compat/defer.fs}.
1.44 crook 6808:
6809:
1.170 pazsan 6810: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6811: @subsection Aliases
6812: @cindex aliases
1.1 anton 6813:
1.44 crook 6814: The defining word @code{Alias} allows you to define a word by name that
6815: has the same behaviour as some other word. Here are two situation where
6816: this can be useful:
1.1 anton 6817:
1.44 crook 6818: @itemize @bullet
6819: @item
6820: When you want access to a word's definition from a different word list
6821: (for an example of this, see the definition of the @code{Root} word list
6822: in the Gforth source).
6823: @item
6824: When you want to create a synonym; a definition that can be known by
6825: either of two names (for example, @code{THEN} and @code{ENDIF} are
6826: aliases).
6827: @end itemize
1.1 anton 6828:
1.69 anton 6829: Like deferred words, an alias has default compilation and interpretation
6830: semantics at the beginning (not the modifications of the other word),
6831: but you can change them in the usual ways (@code{immediate},
6832: @code{compile-only}). For example:
1.1 anton 6833:
6834: @example
1.44 crook 6835: : foo ... ; immediate
6836:
6837: ' foo Alias bar \ bar is not an immediate word
6838: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6839: @end example
6840:
1.44 crook 6841: Words that are aliases have the same xt, different headers in the
6842: dictionary, and consequently different name tokens (@pxref{Tokens for
6843: Words}) and possibly different immediate flags. An alias can only have
6844: default or immediate compilation semantics; you can define aliases for
6845: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6846:
1.44 crook 6847: doc-alias
1.1 anton 6848:
6849:
1.47 crook 6850: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6851: @section Interpretation and Compilation Semantics
1.26 crook 6852: @cindex semantics, interpretation and compilation
1.1 anton 6853:
1.71 anton 6854: @c !! state and ' are used without explanation
6855: @c example for immediate/compile-only? or is the tutorial enough
6856:
1.26 crook 6857: @cindex interpretation semantics
1.71 anton 6858: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6859: interpreter does when it encounters the word in interpret state. It also
6860: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6861: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6862: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6863: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6864:
1.26 crook 6865: @cindex compilation semantics
1.71 anton 6866: The @dfn{compilation semantics} of a (named) word are what the text
6867: interpreter does when it encounters the word in compile state. It also
6868: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6869: compiles@footnote{In standard terminology, ``appends to the current
6870: definition''.} the compilation semantics of @i{word}.
1.1 anton 6871:
1.26 crook 6872: @cindex execution semantics
6873: The standard also talks about @dfn{execution semantics}. They are used
6874: only for defining the interpretation and compilation semantics of many
6875: words. By default, the interpretation semantics of a word are to
6876: @code{execute} its execution semantics, and the compilation semantics of
6877: a word are to @code{compile,} its execution semantics.@footnote{In
6878: standard terminology: The default interpretation semantics are its
6879: execution semantics; the default compilation semantics are to append its
6880: execution semantics to the execution semantics of the current
6881: definition.}
6882:
1.71 anton 6883: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6884: the text interpreter, ticked, or @code{postpone}d, so they have no
6885: interpretation or compilation semantics. Their behaviour is represented
6886: by their XT (@pxref{Tokens for Words}), and we call it execution
6887: semantics, too.
6888:
1.26 crook 6889: @comment TODO expand, make it co-operate with new sections on text interpreter.
6890:
6891: @cindex immediate words
6892: @cindex compile-only words
6893: You can change the semantics of the most-recently defined word:
6894:
1.44 crook 6895:
1.26 crook 6896: doc-immediate
6897: doc-compile-only
6898: doc-restrict
6899:
1.82 anton 6900: By convention, words with non-default compilation semantics (e.g.,
6901: immediate words) often have names surrounded with brackets (e.g.,
6902: @code{[']}, @pxref{Execution token}).
1.44 crook 6903:
1.26 crook 6904: Note that ticking (@code{'}) a compile-only word gives an error
6905: (``Interpreting a compile-only word'').
1.1 anton 6906:
1.47 crook 6907: @menu
1.67 anton 6908: * Combined words::
1.47 crook 6909: @end menu
1.44 crook 6910:
1.71 anton 6911:
1.48 anton 6912: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6913: @subsection Combined Words
6914: @cindex combined words
6915:
6916: Gforth allows you to define @dfn{combined words} -- words that have an
6917: arbitrary combination of interpretation and compilation semantics.
6918:
1.26 crook 6919: doc-interpret/compile:
1.1 anton 6920:
1.26 crook 6921: This feature was introduced for implementing @code{TO} and @code{S"}. I
6922: recommend that you do not define such words, as cute as they may be:
6923: they make it hard to get at both parts of the word in some contexts.
6924: E.g., assume you want to get an execution token for the compilation
6925: part. Instead, define two words, one that embodies the interpretation
6926: part, and one that embodies the compilation part. Once you have done
6927: that, you can define a combined word with @code{interpret/compile:} for
6928: the convenience of your users.
1.1 anton 6929:
1.26 crook 6930: You might try to use this feature to provide an optimizing
6931: implementation of the default compilation semantics of a word. For
6932: example, by defining:
1.1 anton 6933: @example
1.26 crook 6934: :noname
6935: foo bar ;
6936: :noname
6937: POSTPONE foo POSTPONE bar ;
1.29 crook 6938: interpret/compile: opti-foobar
1.1 anton 6939: @end example
1.26 crook 6940:
1.23 crook 6941: @noindent
1.26 crook 6942: as an optimizing version of:
6943:
1.1 anton 6944: @example
1.26 crook 6945: : foobar
6946: foo bar ;
1.1 anton 6947: @end example
6948:
1.26 crook 6949: Unfortunately, this does not work correctly with @code{[compile]},
6950: because @code{[compile]} assumes that the compilation semantics of all
6951: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6952: opti-foobar} would compile compilation semantics, whereas
6953: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6954:
1.26 crook 6955: @cindex state-smart words (are a bad idea)
1.82 anton 6956: @anchor{state-smartness}
1.29 crook 6957: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6958: by @code{interpret/compile:} (words are state-smart if they check
6959: @code{STATE} during execution). E.g., they would try to code
6960: @code{foobar} like this:
1.1 anton 6961:
1.26 crook 6962: @example
6963: : foobar
6964: STATE @@
6965: IF ( compilation state )
6966: POSTPONE foo POSTPONE bar
6967: ELSE
6968: foo bar
6969: ENDIF ; immediate
6970: @end example
1.1 anton 6971:
1.26 crook 6972: Although this works if @code{foobar} is only processed by the text
6973: interpreter, it does not work in other contexts (like @code{'} or
6974: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6975: for a state-smart word, not for the interpretation semantics of the
6976: original @code{foobar}; when you execute this execution token (directly
6977: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6978: state, the result will not be what you expected (i.e., it will not
6979: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6980: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6981: M. Anton Ertl,
6982: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6983: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6984:
1.26 crook 6985: @cindex defining words with arbitrary semantics combinations
6986: It is also possible to write defining words that define words with
6987: arbitrary combinations of interpretation and compilation semantics. In
6988: general, they look like this:
1.1 anton 6989:
1.26 crook 6990: @example
6991: : def-word
6992: create-interpret/compile
1.29 crook 6993: @i{code1}
1.26 crook 6994: interpretation>
1.29 crook 6995: @i{code2}
1.26 crook 6996: <interpretation
6997: compilation>
1.29 crook 6998: @i{code3}
1.26 crook 6999: <compilation ;
7000: @end example
1.1 anton 7001:
1.29 crook 7002: For a @i{word} defined with @code{def-word}, the interpretation
7003: semantics are to push the address of the body of @i{word} and perform
7004: @i{code2}, and the compilation semantics are to push the address of
7005: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7006: can also be defined like this (except that the defined constants don't
7007: behave correctly when @code{[compile]}d):
1.1 anton 7008:
1.26 crook 7009: @example
7010: : constant ( n "name" -- )
7011: create-interpret/compile
7012: ,
7013: interpretation> ( -- n )
7014: @@
7015: <interpretation
7016: compilation> ( compilation. -- ; run-time. -- n )
7017: @@ postpone literal
7018: <compilation ;
7019: @end example
1.1 anton 7020:
1.44 crook 7021:
1.26 crook 7022: doc-create-interpret/compile
7023: doc-interpretation>
7024: doc-<interpretation
7025: doc-compilation>
7026: doc-<compilation
1.1 anton 7027:
1.44 crook 7028:
1.29 crook 7029: Words defined with @code{interpret/compile:} and
1.26 crook 7030: @code{create-interpret/compile} have an extended header structure that
7031: differs from other words; however, unless you try to access them with
7032: plain address arithmetic, you should not notice this. Words for
7033: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7034: @code{'} @i{word} @code{>body} also gives you the body of a word created
7035: with @code{create-interpret/compile}.
1.1 anton 7036:
1.44 crook 7037:
1.47 crook 7038: @c -------------------------------------------------------------
1.81 anton 7039: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7040: @section Tokens for Words
7041: @cindex tokens for words
7042:
7043: This section describes the creation and use of tokens that represent
7044: words.
7045:
1.71 anton 7046: @menu
7047: * Execution token:: represents execution/interpretation semantics
7048: * Compilation token:: represents compilation semantics
7049: * Name token:: represents named words
7050: @end menu
1.47 crook 7051:
1.71 anton 7052: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7053: @subsection Execution token
1.47 crook 7054:
7055: @cindex xt
7056: @cindex execution token
1.71 anton 7057: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7058: You can use @code{execute} to invoke this behaviour.
1.47 crook 7059:
1.71 anton 7060: @cindex tick (')
7061: You can use @code{'} to get an execution token that represents the
7062: interpretation semantics of a named word:
1.47 crook 7063:
7064: @example
1.97 anton 7065: 5 ' . ( n xt )
7066: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7067: @end example
1.47 crook 7068:
1.71 anton 7069: doc-'
7070:
7071: @code{'} parses at run-time; there is also a word @code{[']} that parses
7072: when it is compiled, and compiles the resulting XT:
7073:
7074: @example
7075: : foo ['] . execute ;
7076: 5 foo
7077: : bar ' execute ; \ by contrast,
7078: 5 bar . \ ' parses "." when bar executes
7079: @end example
7080:
7081: doc-[']
7082:
7083: If you want the execution token of @i{word}, write @code{['] @i{word}}
7084: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7085: @code{'} and @code{[']} behave somewhat unusually by complaining about
7086: compile-only words (because these words have no interpretation
7087: semantics). You might get what you want by using @code{COMP' @i{word}
7088: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7089: token}).
7090:
1.116 anton 7091: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7092: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7093: for the only behaviour the word has (the execution semantics). For
1.116 anton 7094: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7095: would produce if the word was defined anonymously.
7096:
7097: @example
7098: :noname ." hello" ;
7099: execute
1.47 crook 7100: @end example
7101:
1.71 anton 7102: An XT occupies one cell and can be manipulated like any other cell.
7103:
1.47 crook 7104: @cindex code field address
7105: @cindex CFA
1.71 anton 7106: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7107: operations that produce or consume it). For old hands: In Gforth, the
7108: XT is implemented as a code field address (CFA).
7109:
7110: doc-execute
7111: doc-perform
7112:
7113: @node Compilation token, Name token, Execution token, Tokens for Words
7114: @subsection Compilation token
1.47 crook 7115:
7116: @cindex compilation token
1.71 anton 7117: @cindex CT (compilation token)
7118: Gforth represents the compilation semantics of a named word by a
1.47 crook 7119: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7120: @i{xt} is an execution token. The compilation semantics represented by
7121: the compilation token can be performed with @code{execute}, which
7122: consumes the whole compilation token, with an additional stack effect
7123: determined by the represented compilation semantics.
7124:
7125: At present, the @i{w} part of a compilation token is an execution token,
7126: and the @i{xt} part represents either @code{execute} or
7127: @code{compile,}@footnote{Depending upon the compilation semantics of the
7128: word. If the word has default compilation semantics, the @i{xt} will
7129: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7130: @i{xt} will represent @code{execute}.}. However, don't rely on that
7131: knowledge, unless necessary; future versions of Gforth may introduce
7132: unusual compilation tokens (e.g., a compilation token that represents
7133: the compilation semantics of a literal).
7134:
1.71 anton 7135: You can perform the compilation semantics represented by the compilation
7136: token with @code{execute}. You can compile the compilation semantics
7137: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7138: equivalent to @code{postpone @i{word}}.
7139:
7140: doc-[comp']
7141: doc-comp'
7142: doc-postpone,
7143:
7144: @node Name token, , Compilation token, Tokens for Words
7145: @subsection Name token
1.47 crook 7146:
7147: @cindex name token
1.116 anton 7148: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7149: token is an abstract data type that occurs as argument or result of the
7150: words below.
7151:
7152: @c !! put this elswhere?
1.47 crook 7153: @cindex name field address
7154: @cindex NFA
1.116 anton 7155: The closest thing to the nt in older Forth systems is the name field
7156: address (NFA), but there are significant differences: in older Forth
7157: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7158: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7159: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7160: is a link field in the structure identified by the name token, but
7161: searching usually uses a hash table external to these structures; the
7162: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7163: implemented as the address of that count field.
1.47 crook 7164:
7165: doc-find-name
1.116 anton 7166: doc-latest
7167: doc->name
1.47 crook 7168: doc-name>int
7169: doc-name?int
7170: doc-name>comp
7171: doc-name>string
1.109 anton 7172: doc-id.
7173: doc-.name
7174: doc-.id
1.47 crook 7175:
1.81 anton 7176: @c ----------------------------------------------------------
7177: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7178: @section Compiling words
7179: @cindex compiling words
7180: @cindex macros
7181:
7182: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7183: between compilation and run-time. E.g., you can run arbitrary code
7184: between defining words (or for computing data used by defining words
7185: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7186: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7187: running arbitrary code while compiling a colon definition (exception:
7188: you must not allot dictionary space).
7189:
7190: @menu
7191: * Literals:: Compiling data values
7192: * Macros:: Compiling words
7193: @end menu
7194:
7195: @node Literals, Macros, Compiling words, Compiling words
7196: @subsection Literals
7197: @cindex Literals
7198:
7199: The simplest and most frequent example is to compute a literal during
7200: compilation. E.g., the following definition prints an array of strings,
7201: one string per line:
7202:
7203: @example
7204: : .strings ( addr u -- ) \ gforth
7205: 2* cells bounds U+DO
7206: cr i 2@@ type
7207: 2 cells +LOOP ;
7208: @end example
1.81 anton 7209:
1.82 anton 7210: With a simple-minded compiler like Gforth's, this computes @code{2
7211: cells} on every loop iteration. You can compute this value once and for
7212: all at compile time and compile it into the definition like this:
7213:
7214: @example
7215: : .strings ( addr u -- ) \ gforth
7216: 2* cells bounds U+DO
7217: cr i 2@@ type
7218: [ 2 cells ] literal +LOOP ;
7219: @end example
7220:
7221: @code{[} switches the text interpreter to interpret state (you will get
7222: an @code{ok} prompt if you type this example interactively and insert a
7223: newline between @code{[} and @code{]}), so it performs the
7224: interpretation semantics of @code{2 cells}; this computes a number.
7225: @code{]} switches the text interpreter back into compile state. It then
7226: performs @code{Literal}'s compilation semantics, which are to compile
7227: this number into the current word. You can decompile the word with
7228: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7229:
1.82 anton 7230: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7231: *} in this way.
1.81 anton 7232:
1.82 anton 7233: doc-[
7234: doc-]
1.81 anton 7235: doc-literal
7236: doc-]L
1.82 anton 7237:
7238: There are also words for compiling other data types than single cells as
7239: literals:
7240:
1.81 anton 7241: doc-2literal
7242: doc-fliteral
1.82 anton 7243: doc-sliteral
7244:
7245: @cindex colon-sys, passing data across @code{:}
7246: @cindex @code{:}, passing data across
7247: You might be tempted to pass data from outside a colon definition to the
7248: inside on the data stack. This does not work, because @code{:} puhes a
7249: colon-sys, making stuff below unaccessible. E.g., this does not work:
7250:
7251: @example
7252: 5 : foo literal ; \ error: "unstructured"
7253: @end example
7254:
7255: Instead, you have to pass the value in some other way, e.g., through a
7256: variable:
7257:
7258: @example
7259: variable temp
7260: 5 temp !
7261: : foo [ temp @@ ] literal ;
7262: @end example
7263:
7264:
7265: @node Macros, , Literals, Compiling words
7266: @subsection Macros
7267: @cindex Macros
7268: @cindex compiling compilation semantics
7269:
7270: @code{Literal} and friends compile data values into the current
7271: definition. You can also write words that compile other words into the
7272: current definition. E.g.,
7273:
7274: @example
7275: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7276: POSTPONE + ;
7277:
7278: : foo ( n1 n2 -- n )
7279: [ compile-+ ] ;
7280: 1 2 foo .
7281: @end example
7282:
7283: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7284: What happens in this example? @code{Postpone} compiles the compilation
7285: semantics of @code{+} into @code{compile-+}; later the text interpreter
7286: executes @code{compile-+} and thus the compilation semantics of +, which
7287: compile (the execution semantics of) @code{+} into
7288: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7289: should only be executed in compile state, so this example is not
7290: guaranteed to work on all standard systems, but on any decent system it
7291: will work.}
7292:
7293: doc-postpone
7294: doc-[compile]
7295:
7296: Compiling words like @code{compile-+} are usually immediate (or similar)
7297: so you do not have to switch to interpret state to execute them;
7298: mopifying the last example accordingly produces:
7299:
7300: @example
7301: : [compile-+] ( compilation: --; interpretation: -- )
7302: \ compiled code: ( n1 n2 -- n )
7303: POSTPONE + ; immediate
7304:
7305: : foo ( n1 n2 -- n )
7306: [compile-+] ;
7307: 1 2 foo .
7308: @end example
7309:
7310: Immediate compiling words are similar to macros in other languages (in
7311: particular, Lisp). The important differences to macros in, e.g., C are:
7312:
7313: @itemize @bullet
7314:
7315: @item
7316: You use the same language for defining and processing macros, not a
7317: separate preprocessing language and processor.
7318:
7319: @item
7320: Consequently, the full power of Forth is available in macro definitions.
7321: E.g., you can perform arbitrarily complex computations, or generate
7322: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7323: Tutorial}). This power is very useful when writing a parser generators
7324: or other code-generating software.
7325:
7326: @item
7327: Macros defined using @code{postpone} etc. deal with the language at a
7328: higher level than strings; name binding happens at macro definition
7329: time, so you can avoid the pitfalls of name collisions that can happen
7330: in C macros. Of course, Forth is a liberal language and also allows to
7331: shoot yourself in the foot with text-interpreted macros like
7332:
7333: @example
7334: : [compile-+] s" +" evaluate ; immediate
7335: @end example
7336:
7337: Apart from binding the name at macro use time, using @code{evaluate}
7338: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7339: @end itemize
7340:
7341: You may want the macro to compile a number into a word. The word to do
7342: it is @code{literal}, but you have to @code{postpone} it, so its
7343: compilation semantics take effect when the macro is executed, not when
7344: it is compiled:
7345:
7346: @example
7347: : [compile-5] ( -- ) \ compiled code: ( -- n )
7348: 5 POSTPONE literal ; immediate
7349:
7350: : foo [compile-5] ;
7351: foo .
7352: @end example
7353:
7354: You may want to pass parameters to a macro, that the macro should
7355: compile into the current definition. If the parameter is a number, then
7356: you can use @code{postpone literal} (similar for other values).
7357:
7358: If you want to pass a word that is to be compiled, the usual way is to
7359: pass an execution token and @code{compile,} it:
7360:
7361: @example
7362: : twice1 ( xt -- ) \ compiled code: ... -- ...
7363: dup compile, compile, ;
7364:
7365: : 2+ ( n1 -- n2 )
7366: [ ' 1+ twice1 ] ;
7367: @end example
7368:
7369: doc-compile,
7370:
7371: An alternative available in Gforth, that allows you to pass compile-only
7372: words as parameters is to use the compilation token (@pxref{Compilation
7373: token}). The same example in this technique:
7374:
7375: @example
7376: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7377: 2dup 2>r execute 2r> execute ;
7378:
7379: : 2+ ( n1 -- n2 )
7380: [ comp' 1+ twice ] ;
7381: @end example
7382:
7383: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7384: works even if the executed compilation semantics has an effect on the
7385: data stack.
7386:
7387: You can also define complete definitions with these words; this provides
7388: an alternative to using @code{does>} (@pxref{User-defined Defining
7389: Words}). E.g., instead of
7390:
7391: @example
7392: : curry+ ( n1 "name" -- )
7393: CREATE ,
7394: DOES> ( n2 -- n1+n2 )
7395: @@ + ;
7396: @end example
7397:
7398: you could define
7399:
7400: @example
7401: : curry+ ( n1 "name" -- )
7402: \ name execution: ( n2 -- n1+n2 )
7403: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7404:
1.82 anton 7405: -3 curry+ 3-
7406: see 3-
7407: @end example
1.81 anton 7408:
1.82 anton 7409: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7410: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7411:
1.82 anton 7412: This way of writing defining words is sometimes more, sometimes less
7413: convenient than using @code{does>} (@pxref{Advanced does> usage
7414: example}). One advantage of this method is that it can be optimized
7415: better, because the compiler knows that the value compiled with
7416: @code{literal} is fixed, whereas the data associated with a
7417: @code{create}d word can be changed.
1.47 crook 7418:
1.26 crook 7419: @c ----------------------------------------------------------
1.111 anton 7420: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7421: @section The Text Interpreter
7422: @cindex interpreter - outer
7423: @cindex text interpreter
7424: @cindex outer interpreter
1.1 anton 7425:
1.34 anton 7426: @c Should we really describe all these ugly details? IMO the text
7427: @c interpreter should be much cleaner, but that may not be possible within
7428: @c ANS Forth. - anton
1.44 crook 7429: @c nac-> I wanted to explain how it works to show how you can exploit
7430: @c it in your own programs. When I was writing a cross-compiler, figuring out
7431: @c some of these gory details was very helpful to me. None of the textbooks
7432: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7433: @c seems to positively avoid going into too much detail for some of
7434: @c the internals.
1.34 anton 7435:
1.71 anton 7436: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7437: @c it is; for the ugly details, I would prefer another place. I wonder
7438: @c whether we should have a chapter before "Words" that describes some
7439: @c basic concepts referred to in words, and a chapter after "Words" that
7440: @c describes implementation details.
7441:
1.29 crook 7442: The text interpreter@footnote{This is an expanded version of the
7443: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7444: that processes input from the current input device. It is also called
7445: the outer interpreter, in contrast to the inner interpreter
7446: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7447: implementations.
1.27 crook 7448:
1.29 crook 7449: @cindex interpret state
7450: @cindex compile state
7451: The text interpreter operates in one of two states: @dfn{interpret
7452: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7453: aptly-named variable @code{state}.
1.29 crook 7454:
7455: This section starts by describing how the text interpreter behaves when
7456: it is in interpret state, processing input from the user input device --
7457: the keyboard. This is the mode that a Forth system is in after it starts
7458: up.
7459:
7460: @cindex input buffer
7461: @cindex terminal input buffer
7462: The text interpreter works from an area of memory called the @dfn{input
7463: buffer}@footnote{When the text interpreter is processing input from the
7464: keyboard, this area of memory is called the @dfn{terminal input buffer}
7465: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7466: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7467: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7468: leading spaces (called @dfn{delimiters}) then parses a string (a
7469: sequence of non-space characters) until it reaches either a space
7470: character or the end of the buffer. Having parsed a string, it makes two
7471: attempts to process it:
1.27 crook 7472:
1.29 crook 7473: @cindex dictionary
1.27 crook 7474: @itemize @bullet
7475: @item
1.29 crook 7476: It looks for the string in a @dfn{dictionary} of definitions. If the
7477: string is found, the string names a @dfn{definition} (also known as a
7478: @dfn{word}) and the dictionary search returns information that allows
7479: the text interpreter to perform the word's @dfn{interpretation
7480: semantics}. In most cases, this simply means that the word will be
7481: executed.
1.27 crook 7482: @item
7483: If the string is not found in the dictionary, the text interpreter
1.29 crook 7484: attempts to treat it as a number, using the rules described in
7485: @ref{Number Conversion}. If the string represents a legal number in the
7486: current radix, the number is pushed onto a parameter stack (the data
7487: stack for integers, the floating-point stack for floating-point
7488: numbers).
7489: @end itemize
7490:
7491: If both attempts fail, or if the word is found in the dictionary but has
7492: no interpretation semantics@footnote{This happens if the word was
7493: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7494: remainder of the input buffer, issues an error message and waits for
7495: more input. If one of the attempts succeeds, the text interpreter
7496: repeats the parsing process until the whole of the input buffer has been
7497: processed, at which point it prints the status message ``@code{ ok}''
7498: and waits for more input.
7499:
1.71 anton 7500: @c anton: this should be in the input stream subsection (or below it)
7501:
1.29 crook 7502: @cindex parse area
7503: The text interpreter keeps track of its position in the input buffer by
7504: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7505: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7506: of the input buffer. The region from offset @code{>IN @@} to the end of
7507: the input buffer is called the @dfn{parse area}@footnote{In other words,
7508: the text interpreter processes the contents of the input buffer by
7509: parsing strings from the parse area until the parse area is empty.}.
7510: This example shows how @code{>IN} changes as the text interpreter parses
7511: the input buffer:
7512:
7513: @example
7514: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7515: CR ." ->" TYPE ." <-" ; IMMEDIATE
7516:
7517: 1 2 3 remaining + remaining .
7518:
7519: : foo 1 2 3 remaining SWAP remaining ;
7520: @end example
7521:
7522: @noindent
7523: The result is:
7524:
7525: @example
7526: ->+ remaining .<-
7527: ->.<-5 ok
7528:
7529: ->SWAP remaining ;-<
7530: ->;<- ok
7531: @end example
7532:
7533: @cindex parsing words
7534: The value of @code{>IN} can also be modified by a word in the input
7535: buffer that is executed by the text interpreter. This means that a word
7536: can ``trick'' the text interpreter into either skipping a section of the
7537: input buffer@footnote{This is how parsing words work.} or into parsing a
7538: section twice. For example:
1.27 crook 7539:
1.29 crook 7540: @example
1.71 anton 7541: : lat ." <<foo>>" ;
7542: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7543: @end example
7544:
7545: @noindent
7546: When @code{flat} is executed, this output is produced@footnote{Exercise
7547: for the reader: what would happen if the @code{3} were replaced with
7548: @code{4}?}:
7549:
7550: @example
1.71 anton 7551: <<bar>><<foo>>
1.29 crook 7552: @end example
7553:
1.71 anton 7554: This technique can be used to work around some of the interoperability
7555: problems of parsing words. Of course, it's better to avoid parsing
7556: words where possible.
7557:
1.29 crook 7558: @noindent
7559: Two important notes about the behaviour of the text interpreter:
1.27 crook 7560:
7561: @itemize @bullet
7562: @item
7563: It processes each input string to completion before parsing additional
1.29 crook 7564: characters from the input buffer.
7565: @item
7566: It treats the input buffer as a read-only region (and so must your code).
7567: @end itemize
7568:
7569: @noindent
7570: When the text interpreter is in compile state, its behaviour changes in
7571: these ways:
7572:
7573: @itemize @bullet
7574: @item
7575: If a parsed string is found in the dictionary, the text interpreter will
7576: perform the word's @dfn{compilation semantics}. In most cases, this
7577: simply means that the execution semantics of the word will be appended
7578: to the current definition.
1.27 crook 7579: @item
1.29 crook 7580: When a number is encountered, it is compiled into the current definition
7581: (as a literal) rather than being pushed onto a parameter stack.
7582: @item
7583: If an error occurs, @code{state} is modified to put the text interpreter
7584: back into interpret state.
7585: @item
7586: Each time a line is entered from the keyboard, Gforth prints
7587: ``@code{ compiled}'' rather than `` @code{ok}''.
7588: @end itemize
7589:
7590: @cindex text interpreter - input sources
7591: When the text interpreter is using an input device other than the
7592: keyboard, its behaviour changes in these ways:
7593:
7594: @itemize @bullet
7595: @item
7596: When the parse area is empty, the text interpreter attempts to refill
7597: the input buffer from the input source. When the input source is
1.71 anton 7598: exhausted, the input source is set back to the previous input source.
1.29 crook 7599: @item
7600: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7601: time the parse area is emptied.
7602: @item
7603: If an error occurs, the input source is set back to the user input
7604: device.
1.27 crook 7605: @end itemize
1.21 crook 7606:
1.49 anton 7607: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7608:
1.26 crook 7609: doc->in
1.27 crook 7610: doc-source
7611:
1.26 crook 7612: doc-tib
7613: doc-#tib
1.1 anton 7614:
1.44 crook 7615:
1.26 crook 7616: @menu
1.67 anton 7617: * Input Sources::
7618: * Number Conversion::
7619: * Interpret/Compile states::
7620: * Interpreter Directives::
1.26 crook 7621: @end menu
1.1 anton 7622:
1.29 crook 7623: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7624: @subsection Input Sources
7625: @cindex input sources
7626: @cindex text interpreter - input sources
7627:
1.44 crook 7628: By default, the text interpreter processes input from the user input
1.29 crook 7629: device (the keyboard) when Forth starts up. The text interpreter can
7630: process input from any of these sources:
7631:
7632: @itemize @bullet
7633: @item
7634: The user input device -- the keyboard.
7635: @item
7636: A file, using the words described in @ref{Forth source files}.
7637: @item
7638: A block, using the words described in @ref{Blocks}.
7639: @item
7640: A text string, using @code{evaluate}.
7641: @end itemize
7642:
7643: A program can identify the current input device from the values of
7644: @code{source-id} and @code{blk}.
7645:
1.44 crook 7646:
1.29 crook 7647: doc-source-id
7648: doc-blk
7649:
7650: doc-save-input
7651: doc-restore-input
7652:
7653: doc-evaluate
1.111 anton 7654: doc-query
1.1 anton 7655:
1.29 crook 7656:
1.44 crook 7657:
1.29 crook 7658: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7659: @subsection Number Conversion
7660: @cindex number conversion
7661: @cindex double-cell numbers, input format
7662: @cindex input format for double-cell numbers
7663: @cindex single-cell numbers, input format
7664: @cindex input format for single-cell numbers
7665: @cindex floating-point numbers, input format
7666: @cindex input format for floating-point numbers
1.1 anton 7667:
1.29 crook 7668: This section describes the rules that the text interpreter uses when it
7669: tries to convert a string into a number.
1.1 anton 7670:
1.26 crook 7671: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7672: number base@footnote{For example, 0-9 when the number base is decimal or
7673: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7674:
1.26 crook 7675: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7676:
1.29 crook 7677: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7678: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7679:
1.26 crook 7680: Let * represent any number of instances of the previous character
7681: (including none).
1.1 anton 7682:
1.26 crook 7683: Let any other character represent itself.
1.1 anton 7684:
1.29 crook 7685: @noindent
1.26 crook 7686: Now, the conversion rules are:
1.21 crook 7687:
1.26 crook 7688: @itemize @bullet
7689: @item
7690: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7691: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7692: @item
7693: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7694: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7695: arithmetic. Examples are -45 -5681 -0
7696: @item
7697: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7698: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7699: (all three of these represent the same number).
1.26 crook 7700: @item
7701: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7702: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7703: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7704: -34.65 (all three of these represent the same number).
1.26 crook 7705: @item
1.29 crook 7706: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7707: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7708: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7709: number) +12.E-4
1.26 crook 7710: @end itemize
1.1 anton 7711:
1.174 anton 7712: By default, the number base used for integer number conversion is
7713: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7714: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7715: change @code{base} anywhere, make sure to save the old value and
7716: restore it afterwards; better yet, use @code{base-execute}, which does
7717: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7718: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7719:
1.29 crook 7720: doc-dpl
1.174 anton 7721: doc-base-execute
1.26 crook 7722: doc-base
7723: doc-hex
7724: doc-decimal
1.1 anton 7725:
1.26 crook 7726: @cindex '-prefix for character strings
7727: @cindex &-prefix for decimal numbers
1.133 anton 7728: @cindex #-prefix for decimal numbers
1.26 crook 7729: @cindex %-prefix for binary numbers
7730: @cindex $-prefix for hexadecimal numbers
1.133 anton 7731: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7732: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7733: prefix@footnote{Some Forth implementations provide a similar scheme by
7734: implementing @code{$} etc. as parsing words that process the subsequent
7735: number in the input stream and push it onto the stack. For example, see
7736: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7737: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7738: is required between the prefix and the number.} before the first digit
1.133 anton 7739: of an (integer) number. The following prefixes are supported:
1.1 anton 7740:
1.26 crook 7741: @itemize @bullet
7742: @item
1.35 anton 7743: @code{&} -- decimal
1.26 crook 7744: @item
1.133 anton 7745: @code{#} -- decimal
7746: @item
1.35 anton 7747: @code{%} -- binary
1.26 crook 7748: @item
1.35 anton 7749: @code{$} -- hexadecimal
1.26 crook 7750: @item
1.133 anton 7751: @code{0x} -- hexadecimal, if base<33.
7752: @item
7753: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7754: optional @code{'} may be present after the character.
1.26 crook 7755: @end itemize
1.1 anton 7756:
1.26 crook 7757: Here are some examples, with the equivalent decimal number shown after
7758: in braces:
1.1 anton 7759:
1.26 crook 7760: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7761: 'A (65),
7762: -'a' (-97),
1.26 crook 7763: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7764:
1.26 crook 7765: @cindex number conversion - traps for the unwary
1.29 crook 7766: @noindent
1.26 crook 7767: Number conversion has a number of traps for the unwary:
1.1 anton 7768:
1.26 crook 7769: @itemize @bullet
7770: @item
7771: You cannot determine the current number base using the code sequence
1.35 anton 7772: @code{base @@ .} -- the number base is always 10 in the current number
7773: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7774: @item
7775: If the number base is set to a value greater than 14 (for example,
7776: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7777: it to be intepreted as either a single-precision integer or a
7778: floating-point number (Gforth treats it as an integer). The ambiguity
7779: can be resolved by explicitly stating the sign of the mantissa and/or
7780: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7781: ambiguity arises; either representation will be treated as a
7782: floating-point number.
7783: @item
1.29 crook 7784: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7785: It is used to specify file types.
7786: @item
1.72 anton 7787: ANS Forth requires the @code{.} of a double-precision number to be the
7788: final character in the string. Gforth allows the @code{.} to be
7789: anywhere after the first digit.
1.26 crook 7790: @item
7791: The number conversion process does not check for overflow.
7792: @item
1.72 anton 7793: In an ANS Forth program @code{base} is required to be decimal when
7794: converting floating-point numbers. In Gforth, number conversion to
7795: floating-point numbers always uses base &10, irrespective of the value
7796: of @code{base}.
1.26 crook 7797: @end itemize
1.1 anton 7798:
1.49 anton 7799: You can read numbers into your programs with the words described in
7800: @ref{Input}.
1.1 anton 7801:
1.82 anton 7802: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7803: @subsection Interpret/Compile states
7804: @cindex Interpret/Compile states
1.1 anton 7805:
1.29 crook 7806: A standard program is not permitted to change @code{state}
7807: explicitly. However, it can change @code{state} implicitly, using the
7808: words @code{[} and @code{]}. When @code{[} is executed it switches
7809: @code{state} to interpret state, and therefore the text interpreter
7810: starts interpreting. When @code{]} is executed it switches @code{state}
7811: to compile state and therefore the text interpreter starts
1.44 crook 7812: compiling. The most common usage for these words is for switching into
7813: interpret state and back from within a colon definition; this technique
1.49 anton 7814: can be used to compile a literal (for an example, @pxref{Literals}) or
7815: for conditional compilation (for an example, @pxref{Interpreter
7816: Directives}).
1.44 crook 7817:
1.35 anton 7818:
7819: @c This is a bad example: It's non-standard, and it's not necessary.
7820: @c However, I can't think of a good example for switching into compile
7821: @c state when there is no current word (@code{state}-smart words are not a
7822: @c good reason). So maybe we should use an example for switching into
7823: @c interpret @code{state} in a colon def. - anton
1.44 crook 7824: @c nac-> I agree. I started out by putting in the example, then realised
7825: @c that it was non-ANS, so wrote more words around it. I hope this
7826: @c re-written version is acceptable to you. I do want to keep the example
7827: @c as it is helpful for showing what is and what is not portable, particularly
7828: @c where it outlaws a style in common use.
7829:
1.72 anton 7830: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7831: @c that, we can also show what's not. In any case, I have written a
7832: @c section Compiling Words which also deals with [ ].
1.35 anton 7833:
1.95 anton 7834: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7835:
1.95 anton 7836: @c @code{[} and @code{]} also give you the ability to switch into compile
7837: @c state and back, but we cannot think of any useful Standard application
7838: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7839:
7840: @c @example
7841: @c : AA ." this is A" ;
7842: @c : BB ." this is B" ;
7843: @c : CC ." this is C" ;
7844:
7845: @c create table ] aa bb cc [
7846:
7847: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7848: @c cells table + @@ execute ;
7849: @c @end example
7850:
7851: @c This example builds a jump table; @code{0 go} will display ``@code{this
7852: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7853: @c defining @code{table} like this:
7854:
7855: @c @example
7856: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7857: @c @end example
7858:
7859: @c The problem with this code is that the definition of @code{table} is not
7860: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7861: @c @i{may} work on systems where code space and data space co-incide, the
7862: @c Standard only allows data space to be assigned for a @code{CREATE}d
7863: @c word. In addition, the Standard only allows @code{@@} to access data
7864: @c space, whilst this example is using it to access code space. The only
7865: @c portable, Standard way to build this table is to build it in data space,
7866: @c like this:
7867:
7868: @c @example
7869: @c create table ' aa , ' bb , ' cc ,
7870: @c @end example
1.29 crook 7871:
1.95 anton 7872: @c doc-state
1.44 crook 7873:
1.29 crook 7874:
1.82 anton 7875: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7876: @subsection Interpreter Directives
7877: @cindex interpreter directives
1.72 anton 7878: @cindex conditional compilation
1.1 anton 7879:
1.29 crook 7880: These words are usually used in interpret state; typically to control
7881: which parts of a source file are processed by the text
1.26 crook 7882: interpreter. There are only a few ANS Forth Standard words, but Gforth
7883: supplements these with a rich set of immediate control structure words
7884: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7885: used in compile state (@pxref{Control Structures}). Typical usages:
7886:
7887: @example
1.72 anton 7888: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7889: .
7890: .
1.72 anton 7891: HAVE-ASSEMBLER [IF]
1.29 crook 7892: : ASSEMBLER-FEATURE
7893: ...
7894: ;
7895: [ENDIF]
7896: .
7897: .
7898: : SEE
7899: ... \ general-purpose SEE code
1.72 anton 7900: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7901: ... \ assembler-specific SEE code
7902: [ [ENDIF] ]
7903: ;
7904: @end example
1.1 anton 7905:
1.44 crook 7906:
1.26 crook 7907: doc-[IF]
7908: doc-[ELSE]
7909: doc-[THEN]
7910: doc-[ENDIF]
1.1 anton 7911:
1.26 crook 7912: doc-[IFDEF]
7913: doc-[IFUNDEF]
1.1 anton 7914:
1.26 crook 7915: doc-[?DO]
7916: doc-[DO]
7917: doc-[FOR]
7918: doc-[LOOP]
7919: doc-[+LOOP]
7920: doc-[NEXT]
1.1 anton 7921:
1.26 crook 7922: doc-[BEGIN]
7923: doc-[UNTIL]
7924: doc-[AGAIN]
7925: doc-[WHILE]
7926: doc-[REPEAT]
1.1 anton 7927:
1.27 crook 7928:
1.26 crook 7929: @c -------------------------------------------------------------
1.111 anton 7930: @node The Input Stream, Word Lists, The Text Interpreter, Words
7931: @section The Input Stream
7932: @cindex input stream
7933:
7934: @c !! integrate this better with the "Text Interpreter" section
7935: The text interpreter reads from the input stream, which can come from
7936: several sources (@pxref{Input Sources}). Some words, in particular
7937: defining words, but also words like @code{'}, read parameters from the
7938: input stream instead of from the stack.
7939:
7940: Such words are called parsing words, because they parse the input
7941: stream. Parsing words are hard to use in other words, because it is
7942: hard to pass program-generated parameters through the input stream.
7943: They also usually have an unintuitive combination of interpretation and
7944: compilation semantics when implemented naively, leading to various
7945: approaches that try to produce a more intuitive behaviour
7946: (@pxref{Combined words}).
7947:
7948: It should be obvious by now that parsing words are a bad idea. If you
7949: want to implement a parsing word for convenience, also provide a factor
7950: of the word that does not parse, but takes the parameters on the stack.
7951: To implement the parsing word on top if it, you can use the following
7952: words:
7953:
7954: @c anton: these belong in the input stream section
7955: doc-parse
1.138 anton 7956: doc-parse-name
1.111 anton 7957: doc-parse-word
7958: doc-name
7959: doc-word
7960: doc-\"-parse
7961: doc-refill
7962:
7963: Conversely, if you have the bad luck (or lack of foresight) to have to
7964: deal with parsing words without having such factors, how do you pass a
7965: string that is not in the input stream to it?
7966:
7967: doc-execute-parsing
7968:
1.146 anton 7969: A definition of this word in ANS Forth is provided in
7970: @file{compat/execute-parsing.fs}.
7971:
1.111 anton 7972: If you want to run a parsing word on a file, the following word should
7973: help:
7974:
7975: doc-execute-parsing-file
7976:
7977: @c -------------------------------------------------------------
7978: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7979: @section Word Lists
7980: @cindex word lists
1.32 anton 7981: @cindex header space
1.1 anton 7982:
1.36 anton 7983: A wordlist is a list of named words; you can add new words and look up
7984: words by name (and you can remove words in a restricted way with
7985: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7986:
7987: @cindex search order stack
7988: The text interpreter searches the wordlists present in the search order
7989: (a stack of wordlists), from the top to the bottom. Within each
7990: wordlist, the search starts conceptually at the newest word; i.e., if
7991: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7992:
1.26 crook 7993: @cindex compilation word list
1.36 anton 7994: New words are added to the @dfn{compilation wordlist} (aka current
7995: wordlist).
1.1 anton 7996:
1.36 anton 7997: @cindex wid
7998: A word list is identified by a cell-sized word list identifier (@i{wid})
7999: in much the same way as a file is identified by a file handle. The
8000: numerical value of the wid has no (portable) meaning, and might change
8001: from session to session.
1.1 anton 8002:
1.29 crook 8003: The ANS Forth ``Search order'' word set is intended to provide a set of
8004: low-level tools that allow various different schemes to be
1.74 anton 8005: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8006: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8007: Forth.
1.1 anton 8008:
1.27 crook 8009: @comment TODO: locals section refers to here, saying that every word list (aka
8010: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8011: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8012:
1.45 crook 8013: @comment TODO: document markers, reveal, tables, mappedwordlist
8014:
8015: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8016: @comment word from the source files, rather than some alias.
1.44 crook 8017:
1.26 crook 8018: doc-forth-wordlist
8019: doc-definitions
8020: doc-get-current
8021: doc-set-current
8022: doc-get-order
1.45 crook 8023: doc---gforthman-set-order
1.26 crook 8024: doc-wordlist
1.30 anton 8025: doc-table
1.79 anton 8026: doc->order
1.36 anton 8027: doc-previous
1.26 crook 8028: doc-also
1.45 crook 8029: doc---gforthman-forth
1.26 crook 8030: doc-only
1.45 crook 8031: doc---gforthman-order
1.15 anton 8032:
1.26 crook 8033: doc-find
8034: doc-search-wordlist
1.15 anton 8035:
1.26 crook 8036: doc-words
8037: doc-vlist
1.44 crook 8038: @c doc-words-deferred
1.1 anton 8039:
1.74 anton 8040: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8041: doc-root
8042: doc-vocabulary
8043: doc-seal
8044: doc-vocs
8045: doc-current
8046: doc-context
1.1 anton 8047:
1.44 crook 8048:
1.26 crook 8049: @menu
1.75 anton 8050: * Vocabularies::
1.67 anton 8051: * Why use word lists?::
1.75 anton 8052: * Word list example::
1.26 crook 8053: @end menu
8054:
1.75 anton 8055: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8056: @subsection Vocabularies
8057: @cindex Vocabularies, detailed explanation
8058:
8059: Here is an example of creating and using a new wordlist using ANS
8060: Forth words:
8061:
8062: @example
8063: wordlist constant my-new-words-wordlist
8064: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8065:
8066: \ add it to the search order
8067: also my-new-words
8068:
8069: \ alternatively, add it to the search order and make it
8070: \ the compilation word list
8071: also my-new-words definitions
8072: \ type "order" to see the problem
8073: @end example
8074:
8075: The problem with this example is that @code{order} has no way to
8076: associate the name @code{my-new-words} with the wid of the word list (in
8077: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8078: that has no associated name). There is no Standard way of associating a
8079: name with a wid.
8080:
8081: In Gforth, this example can be re-coded using @code{vocabulary}, which
8082: associates a name with a wid:
8083:
8084: @example
8085: vocabulary my-new-words
8086:
8087: \ add it to the search order
8088: also my-new-words
8089:
8090: \ alternatively, add it to the search order and make it
8091: \ the compilation word list
8092: my-new-words definitions
8093: \ type "order" to see that the problem is solved
8094: @end example
8095:
8096:
8097: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8098: @subsection Why use word lists?
8099: @cindex word lists - why use them?
8100:
1.74 anton 8101: Here are some reasons why people use wordlists:
1.26 crook 8102:
8103: @itemize @bullet
1.74 anton 8104:
8105: @c anton: Gforth's hashing implementation makes the search speed
8106: @c independent from the number of words. But it is linear with the number
8107: @c of wordlists that have to be searched, so in effect using more wordlists
8108: @c actually slows down compilation.
8109:
8110: @c @item
8111: @c To improve compilation speed by reducing the number of header space
8112: @c entries that must be searched. This is achieved by creating a new
8113: @c word list that contains all of the definitions that are used in the
8114: @c definition of a Forth system but which would not usually be used by
8115: @c programs running on that system. That word list would be on the search
8116: @c list when the Forth system was compiled but would be removed from the
8117: @c search list for normal operation. This can be a useful technique for
8118: @c low-performance systems (for example, 8-bit processors in embedded
8119: @c systems) but is unlikely to be necessary in high-performance desktop
8120: @c systems.
8121:
1.26 crook 8122: @item
8123: To prevent a set of words from being used outside the context in which
8124: they are valid. Two classic examples of this are an integrated editor
8125: (all of the edit commands are defined in a separate word list; the
8126: search order is set to the editor word list when the editor is invoked;
8127: the old search order is restored when the editor is terminated) and an
8128: integrated assembler (the op-codes for the machine are defined in a
8129: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8130:
8131: @item
8132: To organize the words of an application or library into a user-visible
8133: set (in @code{forth-wordlist} or some other common wordlist) and a set
8134: of helper words used just for the implementation (hidden in a separate
1.75 anton 8135: wordlist). This keeps @code{words}' output smaller, separates
8136: implementation and interface, and reduces the chance of name conflicts
8137: within the common wordlist.
1.74 anton 8138:
1.26 crook 8139: @item
8140: To prevent a name-space clash between multiple definitions with the same
8141: name. For example, when building a cross-compiler you might have a word
8142: @code{IF} that generates conditional code for your target system. By
8143: placing this definition in a different word list you can control whether
8144: the host system's @code{IF} or the target system's @code{IF} get used in
8145: any particular context by controlling the order of the word lists on the
8146: search order stack.
1.74 anton 8147:
1.26 crook 8148: @end itemize
1.1 anton 8149:
1.74 anton 8150: The downsides of using wordlists are:
8151:
8152: @itemize
8153:
8154: @item
8155: Debugging becomes more cumbersome.
8156:
8157: @item
8158: Name conflicts worked around with wordlists are still there, and you
8159: have to arrange the search order carefully to get the desired results;
8160: if you forget to do that, you get hard-to-find errors (as in any case
8161: where you read the code differently from the compiler; @code{see} can
1.75 anton 8162: help seeing which of several possible words the name resolves to in such
8163: cases). @code{See} displays just the name of the words, not what
8164: wordlist they belong to, so it might be misleading. Using unique names
8165: is a better approach to avoid name conflicts.
1.74 anton 8166:
8167: @item
8168: You have to explicitly undo any changes to the search order. In many
8169: cases it would be more convenient if this happened implicitly. Gforth
8170: currently does not provide such a feature, but it may do so in the
8171: future.
8172: @end itemize
8173:
8174:
1.75 anton 8175: @node Word list example, , Why use word lists?, Word Lists
8176: @subsection Word list example
8177: @cindex word lists - example
1.1 anton 8178:
1.74 anton 8179: The following example is from the
8180: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8181: garbage collector} and uses wordlists to separate public words from
8182: helper words:
8183:
8184: @example
8185: get-current ( wid )
8186: vocabulary garbage-collector also garbage-collector definitions
8187: ... \ define helper words
8188: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8189: ... \ define the public (i.e., API) words
8190: \ they can refer to the helper words
8191: previous \ restore original search order (helper words become invisible)
8192: @end example
8193:
1.26 crook 8194: @c -------------------------------------------------------------
8195: @node Environmental Queries, Files, Word Lists, Words
8196: @section Environmental Queries
8197: @cindex environmental queries
1.21 crook 8198:
1.26 crook 8199: ANS Forth introduced the idea of ``environmental queries'' as a way
8200: for a program running on a system to determine certain characteristics of the system.
8201: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8202:
1.32 anton 8203: The Standard requires that the header space used for environmental queries
8204: be distinct from the header space used for definitions.
1.21 crook 8205:
1.26 crook 8206: Typically, environmental queries are supported by creating a set of
1.29 crook 8207: definitions in a word list that is @i{only} used during environmental
1.26 crook 8208: queries; that is what Gforth does. There is no Standard way of adding
8209: definitions to the set of recognised environmental queries, but any
8210: implementation that supports the loading of optional word sets must have
8211: some mechanism for doing this (after loading the word set, the
8212: associated environmental query string must return @code{true}). In
8213: Gforth, the word list used to honour environmental queries can be
8214: manipulated just like any other word list.
1.21 crook 8215:
1.44 crook 8216:
1.26 crook 8217: doc-environment?
8218: doc-environment-wordlist
1.21 crook 8219:
1.26 crook 8220: doc-gforth
8221: doc-os-class
1.21 crook 8222:
1.44 crook 8223:
1.26 crook 8224: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8225: returning two items on the stack, querying it using @code{environment?}
8226: will return an additional item; the @code{true} flag that shows that the
8227: string was recognised.
1.21 crook 8228:
1.26 crook 8229: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8230:
1.26 crook 8231: Here are some examples of using environmental queries:
1.21 crook 8232:
1.26 crook 8233: @example
8234: s" address-unit-bits" environment? 0=
8235: [IF]
8236: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8237: [ELSE]
8238: drop \ ensure balanced stack effect
1.26 crook 8239: [THEN]
1.21 crook 8240:
1.75 anton 8241: \ this might occur in the prelude of a standard program that uses THROW
8242: s" exception" environment? [IF]
8243: 0= [IF]
8244: : throw abort" exception thrown" ;
8245: [THEN]
8246: [ELSE] \ we don't know, so make sure
8247: : throw abort" exception thrown" ;
8248: [THEN]
1.21 crook 8249:
1.26 crook 8250: s" gforth" environment? [IF] .( Gforth version ) TYPE
8251: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8252:
8253: \ a program using v*
8254: s" gforth" environment? [IF]
8255: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8256: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8257: >r swap 2swap swap 0e r> 0 ?DO
8258: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8259: LOOP
8260: 2drop 2drop ;
8261: [THEN]
8262: [ELSE] \
8263: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8264: ...
8265: [THEN]
1.26 crook 8266: @end example
1.21 crook 8267:
1.26 crook 8268: Here is an example of adding a definition to the environment word list:
1.21 crook 8269:
1.26 crook 8270: @example
8271: get-current environment-wordlist set-current
8272: true constant block
8273: true constant block-ext
8274: set-current
8275: @end example
1.21 crook 8276:
1.26 crook 8277: You can see what definitions are in the environment word list like this:
1.21 crook 8278:
1.26 crook 8279: @example
1.79 anton 8280: environment-wordlist >order words previous
1.26 crook 8281: @end example
1.21 crook 8282:
8283:
1.26 crook 8284: @c -------------------------------------------------------------
8285: @node Files, Blocks, Environmental Queries, Words
8286: @section Files
1.28 crook 8287: @cindex files
8288: @cindex I/O - file-handling
1.21 crook 8289:
1.26 crook 8290: Gforth provides facilities for accessing files that are stored in the
8291: host operating system's file-system. Files that are processed by Gforth
8292: can be divided into two categories:
1.21 crook 8293:
1.23 crook 8294: @itemize @bullet
8295: @item
1.29 crook 8296: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8297: @item
1.29 crook 8298: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8299: @end itemize
8300:
8301: @menu
1.48 anton 8302: * Forth source files::
8303: * General files::
1.167 anton 8304: * Redirection::
1.48 anton 8305: * Search Paths::
1.26 crook 8306: @end menu
8307:
8308: @c -------------------------------------------------------------
8309: @node Forth source files, General files, Files, Files
8310: @subsection Forth source files
8311: @cindex including files
8312: @cindex Forth source files
1.21 crook 8313:
1.26 crook 8314: The simplest way to interpret the contents of a file is to use one of
8315: these two formats:
1.21 crook 8316:
1.26 crook 8317: @example
8318: include mysource.fs
8319: s" mysource.fs" included
8320: @end example
1.21 crook 8321:
1.75 anton 8322: You usually want to include a file only if it is not included already
1.26 crook 8323: (by, say, another source file). In that case, you can use one of these
1.45 crook 8324: three formats:
1.21 crook 8325:
1.26 crook 8326: @example
8327: require mysource.fs
8328: needs mysource.fs
8329: s" mysource.fs" required
8330: @end example
1.21 crook 8331:
1.26 crook 8332: @cindex stack effect of included files
8333: @cindex including files, stack effect
1.45 crook 8334: It is good practice to write your source files such that interpreting them
8335: does not change the stack. Source files designed in this way can be used with
1.26 crook 8336: @code{required} and friends without complications. For example:
1.21 crook 8337:
1.26 crook 8338: @example
1.75 anton 8339: 1024 require foo.fs drop
1.26 crook 8340: @end example
1.21 crook 8341:
1.75 anton 8342: Here you want to pass the argument 1024 (e.g., a buffer size) to
8343: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8344: ), which allows its use with @code{require}. Of course with such
8345: parameters to required files, you have to ensure that the first
8346: @code{require} fits for all uses (i.e., @code{require} it early in the
8347: master load file).
1.44 crook 8348:
1.26 crook 8349: doc-include-file
8350: doc-included
1.28 crook 8351: doc-included?
1.26 crook 8352: doc-include
8353: doc-required
8354: doc-require
8355: doc-needs
1.75 anton 8356: @c doc-init-included-files @c internal
8357: doc-sourcefilename
8358: doc-sourceline#
1.44 crook 8359:
1.26 crook 8360: A definition in ANS Forth for @code{required} is provided in
8361: @file{compat/required.fs}.
1.21 crook 8362:
1.26 crook 8363: @c -------------------------------------------------------------
1.167 anton 8364: @node General files, Redirection, Forth source files, Files
1.26 crook 8365: @subsection General files
8366: @cindex general files
8367: @cindex file-handling
1.21 crook 8368:
1.75 anton 8369: Files are opened/created by name and type. The following file access
8370: methods (FAMs) are recognised:
1.44 crook 8371:
1.75 anton 8372: @cindex fam (file access method)
1.26 crook 8373: doc-r/o
8374: doc-r/w
8375: doc-w/o
8376: doc-bin
1.1 anton 8377:
1.44 crook 8378:
1.26 crook 8379: When a file is opened/created, it returns a file identifier,
1.29 crook 8380: @i{wfileid} that is used for all other file commands. All file
8381: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8382: successful operation and an implementation-defined non-zero value in the
8383: case of an error.
1.21 crook 8384:
1.44 crook 8385:
1.26 crook 8386: doc-open-file
8387: doc-create-file
1.21 crook 8388:
1.26 crook 8389: doc-close-file
8390: doc-delete-file
8391: doc-rename-file
8392: doc-read-file
8393: doc-read-line
1.154 anton 8394: doc-key-file
8395: doc-key?-file
1.26 crook 8396: doc-write-file
8397: doc-write-line
8398: doc-emit-file
8399: doc-flush-file
1.21 crook 8400:
1.26 crook 8401: doc-file-status
8402: doc-file-position
8403: doc-reposition-file
8404: doc-file-size
8405: doc-resize-file
1.21 crook 8406:
1.93 anton 8407: doc-slurp-file
8408: doc-slurp-fid
1.112 anton 8409: doc-stdin
8410: doc-stdout
8411: doc-stderr
1.44 crook 8412:
1.26 crook 8413: @c ---------------------------------------------------------
1.167 anton 8414: @node Redirection, Search Paths, General files, Files
8415: @subsection Redirection
8416: @cindex Redirection
8417: @cindex Input Redirection
8418: @cindex Output Redirection
8419:
8420: You can redirect the output of @code{type} and @code{emit} and all the
8421: words that use them (all output words that don't have an explicit
1.174 anton 8422: target file) to an arbitrary file with the @code{outfile-execute},
8423: used like this:
1.167 anton 8424:
8425: @example
1.174 anton 8426: : some-warning ( n -- )
8427: cr ." warning# " . ;
8428:
1.167 anton 8429: : print-some-warning ( n -- )
1.174 anton 8430: ['] some-warning stderr outfile-execute ;
1.167 anton 8431: @end example
8432:
1.174 anton 8433: After @code{some-warning} is executed, the original output direction
8434: is restored; this construct is safe against exceptions. Similarly,
8435: there is @code{infile-execute} for redirecting the input of @code{key}
8436: and its users (any input word that does not take a file explicitly).
8437:
8438: doc-outfile-execute
8439: doc-infile-execute
1.167 anton 8440:
8441: If you do not want to redirect the input or output to a file, you can
8442: also make use of the fact that @code{key}, @code{emit} and @code{type}
8443: are deferred words (@pxref{Deferred Words}). However, in that case
8444: you have to worry about the restoration and the protection against
8445: exceptions yourself; also, note that for redirecting the output in
8446: this way, you have to redirect both @code{emit} and @code{type}.
8447:
8448: @c ---------------------------------------------------------
8449: @node Search Paths, , Redirection, Files
1.26 crook 8450: @subsection Search Paths
8451: @cindex path for @code{included}
8452: @cindex file search path
8453: @cindex @code{include} search path
8454: @cindex search path for files
1.21 crook 8455:
1.26 crook 8456: If you specify an absolute filename (i.e., a filename starting with
8457: @file{/} or @file{~}, or with @file{:} in the second position (as in
8458: @samp{C:...})) for @code{included} and friends, that file is included
8459: just as you would expect.
1.21 crook 8460:
1.75 anton 8461: If the filename starts with @file{./}, this refers to the directory that
8462: the present file was @code{included} from. This allows files to include
8463: other files relative to their own position (irrespective of the current
8464: working directory or the absolute position). This feature is essential
8465: for libraries consisting of several files, where a file may include
8466: other files from the library. It corresponds to @code{#include "..."}
8467: in C. If the current input source is not a file, @file{.} refers to the
8468: directory of the innermost file being included, or, if there is no file
8469: being included, to the current working directory.
8470:
8471: For relative filenames (not starting with @file{./}), Gforth uses a
8472: search path similar to Forth's search order (@pxref{Word Lists}). It
8473: tries to find the given filename in the directories present in the path,
8474: and includes the first one it finds. There are separate search paths for
8475: Forth source files and general files. If the search path contains the
8476: directory @file{.}, this refers to the directory of the current file, or
8477: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8478:
1.26 crook 8479: Use @file{~+} to refer to the current working directory (as in the
8480: @code{bash}).
1.1 anton 8481:
1.75 anton 8482: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8483:
1.48 anton 8484: @menu
1.75 anton 8485: * Source Search Paths::
1.48 anton 8486: * General Search Paths::
8487: @end menu
8488:
1.26 crook 8489: @c ---------------------------------------------------------
1.75 anton 8490: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8491: @subsubsection Source Search Paths
8492: @cindex search path control, source files
1.5 anton 8493:
1.26 crook 8494: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8495: Gforth}). You can display it and change it using @code{fpath} in
8496: combination with the general path handling words.
1.5 anton 8497:
1.75 anton 8498: doc-fpath
8499: @c the functionality of the following words is easily available through
8500: @c fpath and the general path words. The may go away.
8501: @c doc-.fpath
8502: @c doc-fpath+
8503: @c doc-fpath=
8504: @c doc-open-fpath-file
1.44 crook 8505:
8506: @noindent
1.26 crook 8507: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8508:
1.26 crook 8509: @example
1.75 anton 8510: fpath path= /usr/lib/forth/|./
1.26 crook 8511: require timer.fs
8512: @end example
1.5 anton 8513:
1.75 anton 8514:
1.26 crook 8515: @c ---------------------------------------------------------
1.75 anton 8516: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8517: @subsubsection General Search Paths
1.75 anton 8518: @cindex search path control, source files
1.5 anton 8519:
1.26 crook 8520: Your application may need to search files in several directories, like
8521: @code{included} does. To facilitate this, Gforth allows you to define
8522: and use your own search paths, by providing generic equivalents of the
8523: Forth search path words:
1.5 anton 8524:
1.75 anton 8525: doc-open-path-file
8526: doc-path-allot
8527: doc-clear-path
8528: doc-also-path
1.26 crook 8529: doc-.path
8530: doc-path+
8531: doc-path=
1.5 anton 8532:
1.75 anton 8533: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8534:
1.75 anton 8535: Here's an example of creating an empty search path:
8536: @c
1.26 crook 8537: @example
1.75 anton 8538: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8539: @end example
1.5 anton 8540:
1.26 crook 8541: @c -------------------------------------------------------------
8542: @node Blocks, Other I/O, Files, Words
8543: @section Blocks
1.28 crook 8544: @cindex I/O - blocks
8545: @cindex blocks
8546:
8547: When you run Gforth on a modern desk-top computer, it runs under the
8548: control of an operating system which provides certain services. One of
8549: these services is @var{file services}, which allows Forth source code
8550: and data to be stored in files and read into Gforth (@pxref{Files}).
8551:
8552: Traditionally, Forth has been an important programming language on
8553: systems where it has interfaced directly to the underlying hardware with
8554: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8555: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8556:
8557: A block is a 1024-byte data area, which can be used to hold data or
8558: Forth source code. No structure is imposed on the contents of the
8559: block. A block is identified by its number; blocks are numbered
8560: contiguously from 1 to an implementation-defined maximum.
8561:
8562: A typical system that used blocks but no operating system might use a
8563: single floppy-disk drive for mass storage, with the disks formatted to
8564: provide 256-byte sectors. Blocks would be implemented by assigning the
8565: first four sectors of the disk to block 1, the second four sectors to
8566: block 2 and so on, up to the limit of the capacity of the disk. The disk
8567: would not contain any file system information, just the set of blocks.
8568:
1.29 crook 8569: @cindex blocks file
1.28 crook 8570: On systems that do provide file services, blocks are typically
1.29 crook 8571: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8572: file}. The size of the blocks file will be an exact multiple of 1024
8573: bytes, corresponding to the number of blocks it contains. This is the
8574: mechanism that Gforth uses.
8575:
1.29 crook 8576: @cindex @file{blocks.fb}
1.75 anton 8577: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8578: having specified a blocks file, Gforth defaults to the blocks file
8579: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8580: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8581:
1.29 crook 8582: @cindex block buffers
1.28 crook 8583: When you read and write blocks under program control, Gforth uses a
1.29 crook 8584: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8585: not used when you use @code{load} to interpret the contents of a block.
8586:
1.75 anton 8587: The behaviour of the block buffers is analagous to that of a cache.
8588: Each block buffer has three states:
1.28 crook 8589:
8590: @itemize @bullet
8591: @item
8592: Unassigned
8593: @item
8594: Assigned-clean
8595: @item
8596: Assigned-dirty
8597: @end itemize
8598:
1.29 crook 8599: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8600: block, the block (specified by its block number) must be assigned to a
8601: block buffer.
8602:
8603: The assignment of a block to a block buffer is performed by @code{block}
8604: or @code{buffer}. Use @code{block} when you wish to modify the existing
8605: contents of a block. Use @code{buffer} when you don't care about the
8606: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8607: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8608: with the particular block is already stored in a block buffer due to an
8609: earlier @code{block} command, @code{buffer} will return that block
8610: buffer and the existing contents of the block will be
8611: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8612: block buffer for the block.}.
1.28 crook 8613:
1.47 crook 8614: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8615: @code{buffer}, that block buffer becomes the @i{current block
8616: buffer}. Data may only be manipulated (read or written) within the
8617: current block buffer.
1.47 crook 8618:
8619: When the contents of the current block buffer has been modified it is
1.48 anton 8620: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8621: either abandon the changes (by doing nothing) or mark the block as
8622: changed (assigned-dirty), using @code{update}. Using @code{update} does
8623: not change the blocks file; it simply changes a block buffer's state to
8624: @i{assigned-dirty}. The block will be written implicitly when it's
8625: buffer is needed for another block, or explicitly by @code{flush} or
8626: @code{save-buffers}.
8627:
8628: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8629: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8630: @code{flush}.
1.28 crook 8631:
1.29 crook 8632: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8633: algorithm to assign a block buffer to a block. That means that any
8634: particular block can only be assigned to one specific block buffer,
1.29 crook 8635: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8636: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8637: the new block immediately. If it is @i{assigned-dirty} its current
8638: contents are written back to the blocks file on disk before it is
1.28 crook 8639: allocated to the new block.
8640:
8641: Although no structure is imposed on the contents of a block, it is
8642: traditional to display the contents as 16 lines each of 64 characters. A
8643: block provides a single, continuous stream of input (for example, it
8644: acts as a single parse area) -- there are no end-of-line characters
8645: within a block, and no end-of-file character at the end of a
8646: block. There are two consequences of this:
1.26 crook 8647:
1.28 crook 8648: @itemize @bullet
8649: @item
8650: The last character of one line wraps straight into the first character
8651: of the following line
8652: @item
8653: The word @code{\} -- comment to end of line -- requires special
8654: treatment; in the context of a block it causes all characters until the
8655: end of the current 64-character ``line'' to be ignored.
8656: @end itemize
8657:
8658: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8659: the current blocks file will be extended to the appropriate size and the
1.28 crook 8660: block buffer will be initialised with spaces.
8661:
1.47 crook 8662: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8663: for details) but doesn't encourage the use of blocks; the mechanism is
8664: only provided for backward compatibility -- ANS Forth requires blocks to
8665: be available when files are.
1.28 crook 8666:
8667: Common techniques that are used when working with blocks include:
8668:
8669: @itemize @bullet
8670: @item
8671: A screen editor that allows you to edit blocks without leaving the Forth
8672: environment.
8673: @item
8674: Shadow screens; where every code block has an associated block
8675: containing comments (for example: code in odd block numbers, comments in
8676: even block numbers). Typically, the block editor provides a convenient
8677: mechanism to toggle between code and comments.
8678: @item
8679: Load blocks; a single block (typically block 1) contains a number of
8680: @code{thru} commands which @code{load} the whole of the application.
8681: @end itemize
1.26 crook 8682:
1.29 crook 8683: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8684: integrated into a Forth programming environment.
1.26 crook 8685:
8686: @comment TODO what about errors on open-blocks?
1.44 crook 8687:
1.26 crook 8688: doc-open-blocks
8689: doc-use
1.75 anton 8690: doc-block-offset
1.26 crook 8691: doc-get-block-fid
8692: doc-block-position
1.28 crook 8693:
1.75 anton 8694: doc-list
1.28 crook 8695: doc-scr
8696:
1.45 crook 8697: doc---gforthman-block
1.28 crook 8698: doc-buffer
8699:
1.75 anton 8700: doc-empty-buffers
8701: doc-empty-buffer
1.26 crook 8702: doc-update
1.28 crook 8703: doc-updated?
1.26 crook 8704: doc-save-buffers
1.75 anton 8705: doc-save-buffer
1.26 crook 8706: doc-flush
1.28 crook 8707:
1.26 crook 8708: doc-load
8709: doc-thru
8710: doc-+load
8711: doc-+thru
1.45 crook 8712: doc---gforthman--->
1.26 crook 8713: doc-block-included
8714:
1.44 crook 8715:
1.26 crook 8716: @c -------------------------------------------------------------
1.126 pazsan 8717: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8718: @section Other I/O
1.28 crook 8719: @cindex I/O - keyboard and display
1.26 crook 8720:
8721: @menu
8722: * Simple numeric output:: Predefined formats
8723: * Formatted numeric output:: Formatted (pictured) output
8724: * String Formats:: How Forth stores strings in memory
1.67 anton 8725: * Displaying characters and strings:: Other stuff
1.175 anton 8726: * Terminal output:: Cursor positioning etc.
1.26 crook 8727: * Input:: Input
1.112 anton 8728: * Pipes:: How to create your own pipes
1.149 pazsan 8729: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8730: @end menu
8731:
8732: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8733: @subsection Simple numeric output
1.28 crook 8734: @cindex numeric output - simple/free-format
1.5 anton 8735:
1.26 crook 8736: The simplest output functions are those that display numbers from the
8737: data or floating-point stacks. Floating-point output is always displayed
8738: using base 10. Numbers displayed from the data stack use the value stored
8739: in @code{base}.
1.5 anton 8740:
1.44 crook 8741:
1.26 crook 8742: doc-.
8743: doc-dec.
8744: doc-hex.
8745: doc-u.
8746: doc-.r
8747: doc-u.r
8748: doc-d.
8749: doc-ud.
8750: doc-d.r
8751: doc-ud.r
8752: doc-f.
8753: doc-fe.
8754: doc-fs.
1.111 anton 8755: doc-f.rdp
1.44 crook 8756:
1.26 crook 8757: Examples of printing the number 1234.5678E23 in the different floating-point output
8758: formats are shown below:
1.5 anton 8759:
8760: @example
1.26 crook 8761: f. 123456779999999000000000000.
8762: fe. 123.456779999999E24
8763: fs. 1.23456779999999E26
1.5 anton 8764: @end example
8765:
8766:
1.26 crook 8767: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8768: @subsection Formatted numeric output
1.28 crook 8769: @cindex formatted numeric output
1.26 crook 8770: @cindex pictured numeric output
1.28 crook 8771: @cindex numeric output - formatted
1.26 crook 8772:
1.29 crook 8773: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8774: output} for formatted printing of integers. In this technique, digits
8775: are extracted from the number (using the current output radix defined by
8776: @code{base}), converted to ASCII codes and appended to a string that is
8777: built in a scratch-pad area of memory (@pxref{core-idef,
8778: Implementation-defined options, Implementation-defined
8779: options}). Arbitrary characters can be appended to the string during the
8780: extraction process. The completed string is specified by an address
8781: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8782: under program control.
1.5 anton 8783:
1.75 anton 8784: All of the integer output words described in the previous section
8785: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8786: numeric output.
1.5 anton 8787:
1.47 crook 8788: Three important things to remember about pictured numeric output:
1.5 anton 8789:
1.26 crook 8790: @itemize @bullet
8791: @item
1.28 crook 8792: It always operates on double-precision numbers; to display a
1.49 anton 8793: single-precision number, convert it first (for ways of doing this
8794: @pxref{Double precision}).
1.26 crook 8795: @item
1.28 crook 8796: It always treats the double-precision number as though it were
8797: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8798: @item
8799: The string is built up from right to left; least significant digit first.
8800: @end itemize
1.5 anton 8801:
1.44 crook 8802:
1.26 crook 8803: doc-<#
1.47 crook 8804: doc-<<#
1.26 crook 8805: doc-#
8806: doc-#s
8807: doc-hold
8808: doc-sign
8809: doc-#>
1.47 crook 8810: doc-#>>
1.5 anton 8811:
1.26 crook 8812: doc-represent
1.111 anton 8813: doc-f>str-rdp
8814: doc-f>buf-rdp
1.5 anton 8815:
1.44 crook 8816:
8817: @noindent
1.26 crook 8818: Here are some examples of using pictured numeric output:
1.5 anton 8819:
8820: @example
1.26 crook 8821: : my-u. ( u -- )
8822: \ Simplest use of pns.. behaves like Standard u.
8823: 0 \ convert to unsigned double
1.75 anton 8824: <<# \ start conversion
1.26 crook 8825: #s \ convert all digits
8826: #> \ complete conversion
1.75 anton 8827: TYPE SPACE \ display, with trailing space
8828: #>> ; \ release hold area
1.5 anton 8829:
1.26 crook 8830: : cents-only ( u -- )
8831: 0 \ convert to unsigned double
1.75 anton 8832: <<# \ start conversion
1.26 crook 8833: # # \ convert two least-significant digits
8834: #> \ complete conversion, discard other digits
1.75 anton 8835: TYPE SPACE \ display, with trailing space
8836: #>> ; \ release hold area
1.5 anton 8837:
1.26 crook 8838: : dollars-and-cents ( u -- )
8839: 0 \ convert to unsigned double
1.75 anton 8840: <<# \ start conversion
1.26 crook 8841: # # \ convert two least-significant digits
8842: [char] . hold \ insert decimal point
8843: #s \ convert remaining digits
8844: [char] $ hold \ append currency symbol
8845: #> \ complete conversion
1.75 anton 8846: TYPE SPACE \ display, with trailing space
8847: #>> ; \ release hold area
1.5 anton 8848:
1.26 crook 8849: : my-. ( n -- )
8850: \ handling negatives.. behaves like Standard .
8851: s>d \ convert to signed double
8852: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8853: <<# \ start conversion
1.26 crook 8854: #s \ convert all digits
8855: rot sign \ get at sign byte, append "-" if needed
8856: #> \ complete conversion
1.75 anton 8857: TYPE SPACE \ display, with trailing space
8858: #>> ; \ release hold area
1.5 anton 8859:
1.26 crook 8860: : account. ( n -- )
1.75 anton 8861: \ accountants don't like minus signs, they use parentheses
1.26 crook 8862: \ for negative numbers
8863: s>d \ convert to signed double
8864: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8865: <<# \ start conversion
1.26 crook 8866: 2 pick \ get copy of sign byte
8867: 0< IF [char] ) hold THEN \ right-most character of output
8868: #s \ convert all digits
8869: rot \ get at sign byte
8870: 0< IF [char] ( hold THEN
8871: #> \ complete conversion
1.75 anton 8872: TYPE SPACE \ display, with trailing space
8873: #>> ; \ release hold area
8874:
1.5 anton 8875: @end example
8876:
1.26 crook 8877: Here are some examples of using these words:
1.5 anton 8878:
8879: @example
1.26 crook 8880: 1 my-u. 1
8881: hex -1 my-u. decimal FFFFFFFF
8882: 1 cents-only 01
8883: 1234 cents-only 34
8884: 2 dollars-and-cents $0.02
8885: 1234 dollars-and-cents $12.34
8886: 123 my-. 123
8887: -123 my. -123
8888: 123 account. 123
8889: -456 account. (456)
1.5 anton 8890: @end example
8891:
8892:
1.26 crook 8893: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8894: @subsection String Formats
1.27 crook 8895: @cindex strings - see character strings
8896: @cindex character strings - formats
1.28 crook 8897: @cindex I/O - see character strings
1.75 anton 8898: @cindex counted strings
8899:
8900: @c anton: this does not really belong here; maybe the memory section,
8901: @c or the principles chapter
1.26 crook 8902:
1.27 crook 8903: Forth commonly uses two different methods for representing character
8904: strings:
1.26 crook 8905:
8906: @itemize @bullet
8907: @item
8908: @cindex address of counted string
1.45 crook 8909: @cindex counted string
1.29 crook 8910: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8911: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8912: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8913: memory.
8914: @item
1.29 crook 8915: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8916: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8917: first byte of the string.
8918: @end itemize
8919:
8920: ANS Forth encourages the use of the second format when representing
1.75 anton 8921: strings.
1.26 crook 8922:
1.44 crook 8923:
1.26 crook 8924: doc-count
8925:
1.44 crook 8926:
1.49 anton 8927: For words that move, copy and search for strings see @ref{Memory
8928: Blocks}. For words that display characters and strings see
8929: @ref{Displaying characters and strings}.
1.26 crook 8930:
1.175 anton 8931: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 8932: @subsection Displaying characters and strings
1.27 crook 8933: @cindex characters - compiling and displaying
8934: @cindex character strings - compiling and displaying
1.26 crook 8935:
8936: This section starts with a glossary of Forth words and ends with a set
8937: of examples.
8938:
8939: doc-bl
8940: doc-space
8941: doc-spaces
8942: doc-emit
8943: doc-toupper
8944: doc-."
8945: doc-.(
1.98 anton 8946: doc-.\"
1.26 crook 8947: doc-type
1.44 crook 8948: doc-typewhite
1.26 crook 8949: doc-cr
1.27 crook 8950: @cindex cursor control
1.26 crook 8951: doc-s"
1.98 anton 8952: doc-s\"
1.26 crook 8953: doc-c"
8954: doc-char
8955: doc-[char]
8956:
1.44 crook 8957:
8958: @noindent
1.26 crook 8959: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8960:
8961: @example
1.26 crook 8962: .( text-1)
8963: : my-word
8964: ." text-2" cr
8965: .( text-3)
8966: ;
8967:
8968: ." text-4"
8969:
8970: : my-char
8971: [char] ALPHABET emit
8972: char emit
8973: ;
1.5 anton 8974: @end example
8975:
1.26 crook 8976: When you load this code into Gforth, the following output is generated:
1.5 anton 8977:
1.26 crook 8978: @example
1.30 anton 8979: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8980: @end example
1.5 anton 8981:
1.26 crook 8982: @itemize @bullet
8983: @item
8984: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8985: is an immediate word; it behaves in the same way whether it is used inside
8986: or outside a colon definition.
8987: @item
8988: Message @code{text-4} is displayed because of Gforth's added interpretation
8989: semantics for @code{."}.
8990: @item
1.29 crook 8991: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8992: performs the compilation semantics for @code{."} within the definition of
8993: @code{my-word}.
8994: @end itemize
1.5 anton 8995:
1.26 crook 8996: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8997:
1.26 crook 8998: @example
1.30 anton 8999: @kbd{my-word @key{RET}} text-2
1.26 crook 9000: ok
1.30 anton 9001: @kbd{my-char fred @key{RET}} Af ok
9002: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9003: @end example
1.5 anton 9004:
9005: @itemize @bullet
9006: @item
1.26 crook 9007: Message @code{text-2} is displayed because of the run-time behaviour of
9008: @code{."}.
9009: @item
9010: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9011: on the stack at run-time. @code{emit} always displays the character
9012: when @code{my-char} is executed.
9013: @item
9014: @code{char} parses a string at run-time and the second @code{emit} displays
9015: the first character of the string.
1.5 anton 9016: @item
1.26 crook 9017: If you type @code{see my-char} you can see that @code{[char]} discarded
9018: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9019: definition of @code{my-char}.
1.5 anton 9020: @end itemize
9021:
9022:
1.175 anton 9023: @node Terminal output, Input, Displaying characters and strings, Other I/O
9024: @subsection Terminal output
9025: @cindex output to terminal
9026: @cindex terminal output
9027:
9028: If you are outputting to a terminal, you may want to control the
9029: positioning of the cursor:
9030: @cindex cursor positioning
9031:
9032: doc-at-xy
9033:
9034: In order to know where to position the cursor, it is often helpful to
9035: know the size of the screen:
9036: @cindex terminal size
9037:
9038: doc-form
9039:
9040: And sometimes you want to use:
9041: @cindex clear screen
9042:
9043: doc-page
9044:
9045: Note that on non-terminals you should use @code{12 emit}, not
9046: @code{page}, to get a form feed.
9047:
1.5 anton 9048:
1.175 anton 9049: @node Input, Pipes, Terminal output, Other I/O
1.26 crook 9050: @subsection Input
9051: @cindex input
1.28 crook 9052: @cindex I/O - see input
9053: @cindex parsing a string
1.5 anton 9054:
1.49 anton 9055: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 9056:
1.27 crook 9057: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 9058: @comment then index them
1.27 crook 9059:
1.44 crook 9060:
1.27 crook 9061: doc-key
9062: doc-key?
1.45 crook 9063: doc-ekey
1.141 anton 9064: doc-ekey>char
1.45 crook 9065: doc-ekey?
1.141 anton 9066:
9067: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9068: you need the ANSI.SYS driver to get that behaviour). These are the
9069: keyboard events produced by various common keys:
9070:
9071: doc-k-left
9072: doc-k-right
9073: doc-k-up
9074: doc-k-down
9075: doc-k-home
9076: doc-k-end
9077: doc-k-prior
9078: doc-k-next
9079: doc-k-insert
9080: doc-k-delete
9081:
9082: The function keys (aka keypad keys) are:
9083:
9084: doc-k1
9085: doc-k2
9086: doc-k3
9087: doc-k4
9088: doc-k5
9089: doc-k6
9090: doc-k7
9091: doc-k8
9092: doc-k9
9093: doc-k10
9094: doc-k11
9095: doc-k12
9096:
9097: Note that K11 and K12 are not as widely available. The shifted
9098: function keys are also not very widely available:
9099:
9100: doc-s-k1
9101: doc-s-k2
9102: doc-s-k3
9103: doc-s-k4
9104: doc-s-k5
9105: doc-s-k6
9106: doc-s-k7
9107: doc-s-k8
9108: doc-s-k9
9109: doc-s-k10
9110: doc-s-k11
9111: doc-s-k12
9112:
9113: Words for inputting one line from the keyboard:
9114:
9115: doc-accept
9116: doc-edit-line
9117:
9118: Conversion words:
9119:
1.143 anton 9120: doc-s>number?
9121: doc-s>unumber?
1.26 crook 9122: doc->number
9123: doc->float
1.143 anton 9124:
1.141 anton 9125:
1.27 crook 9126: @comment obsolescent words..
1.141 anton 9127: Obsolescent input and conversion words:
9128:
1.27 crook 9129: doc-convert
1.26 crook 9130: doc-expect
1.27 crook 9131: doc-span
1.5 anton 9132:
9133:
1.149 pazsan 9134: @node Pipes, Xchars and Unicode, Input, Other I/O
1.112 anton 9135: @subsection Pipes
9136: @cindex pipes, creating your own
9137:
9138: In addition to using Gforth in pipes created by other processes
9139: (@pxref{Gforth in pipes}), you can create your own pipe with
9140: @code{open-pipe}, and read from or write to it.
9141:
9142: doc-open-pipe
9143: doc-close-pipe
9144:
9145: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9146: you don't catch this exception, Gforth will catch it and exit, usually
9147: silently (@pxref{Gforth in pipes}). Since you probably do not want
9148: this, you should wrap a @code{catch} or @code{try} block around the code
9149: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9150: problem yourself, and then return to regular processing.
9151:
9152: doc-broken-pipe-error
9153:
1.155 anton 9154: @node Xchars and Unicode, , Pipes, Other I/O
9155: @subsection Xchars and Unicode
1.149 pazsan 9156:
9157: This chapter needs completion
1.112 anton 9158:
1.121 anton 9159: @node OS command line arguments, Locals, Other I/O, Words
9160: @section OS command line arguments
9161: @cindex OS command line arguments
9162: @cindex command line arguments, OS
9163: @cindex arguments, OS command line
9164:
9165: The usual way to pass arguments to Gforth programs on the command line
9166: is via the @option{-e} option, e.g.
9167:
9168: @example
9169: gforth -e "123 456" foo.fs -e bye
9170: @end example
9171:
9172: However, you may want to interpret the command-line arguments directly.
9173: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9174: through @code{next-arg}:
1.121 anton 9175:
1.123 anton 9176: doc-next-arg
1.121 anton 9177:
1.123 anton 9178: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9179:
9180: @example
9181: : echo ( -- )
1.122 anton 9182: begin
1.123 anton 9183: next-arg 2dup 0 0 d<> while
9184: type space
9185: repeat
9186: 2drop ;
1.121 anton 9187:
9188: echo cr bye
9189: @end example
9190:
9191: This can be invoked with
9192:
9193: @example
9194: gforth echo.fs hello world
9195: @end example
1.123 anton 9196:
9197: and it will print
9198:
9199: @example
9200: hello world
9201: @end example
9202:
9203: The next lower level of dealing with the OS command line are the
9204: following words:
9205:
9206: doc-arg
9207: doc-shift-args
9208:
9209: Finally, at the lowest level Gforth provides the following words:
9210:
9211: doc-argc
9212: doc-argv
1.121 anton 9213:
1.78 anton 9214: @c -------------------------------------------------------------
1.126 pazsan 9215: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9216: @section Locals
9217: @cindex locals
9218:
9219: Local variables can make Forth programming more enjoyable and Forth
9220: programs easier to read. Unfortunately, the locals of ANS Forth are
9221: laden with restrictions. Therefore, we provide not only the ANS Forth
9222: locals wordset, but also our own, more powerful locals wordset (we
9223: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9224:
1.78 anton 9225: The ideas in this section have also been published in M. Anton Ertl,
9226: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9227: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9228:
9229: @menu
1.78 anton 9230: * Gforth locals::
9231: * ANS Forth locals::
1.5 anton 9232: @end menu
9233:
1.78 anton 9234: @node Gforth locals, ANS Forth locals, Locals, Locals
9235: @subsection Gforth locals
9236: @cindex Gforth locals
9237: @cindex locals, Gforth style
1.5 anton 9238:
1.78 anton 9239: Locals can be defined with
1.44 crook 9240:
1.78 anton 9241: @example
9242: @{ local1 local2 ... -- comment @}
9243: @end example
9244: or
9245: @example
9246: @{ local1 local2 ... @}
9247: @end example
1.5 anton 9248:
1.78 anton 9249: E.g.,
9250: @example
9251: : max @{ n1 n2 -- n3 @}
9252: n1 n2 > if
9253: n1
9254: else
9255: n2
9256: endif ;
9257: @end example
1.44 crook 9258:
1.78 anton 9259: The similarity of locals definitions with stack comments is intended. A
9260: locals definition often replaces the stack comment of a word. The order
9261: of the locals corresponds to the order in a stack comment and everything
9262: after the @code{--} is really a comment.
1.77 anton 9263:
1.78 anton 9264: This similarity has one disadvantage: It is too easy to confuse locals
9265: declarations with stack comments, causing bugs and making them hard to
9266: find. However, this problem can be avoided by appropriate coding
9267: conventions: Do not use both notations in the same program. If you do,
9268: they should be distinguished using additional means, e.g. by position.
1.77 anton 9269:
1.78 anton 9270: @cindex types of locals
9271: @cindex locals types
9272: The name of the local may be preceded by a type specifier, e.g.,
9273: @code{F:} for a floating point value:
1.5 anton 9274:
1.78 anton 9275: @example
9276: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9277: \ complex multiplication
9278: Ar Br f* Ai Bi f* f-
9279: Ar Bi f* Ai Br f* f+ ;
9280: @end example
1.44 crook 9281:
1.78 anton 9282: @cindex flavours of locals
9283: @cindex locals flavours
9284: @cindex value-flavoured locals
9285: @cindex variable-flavoured locals
9286: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9287: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9288: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9289: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9290: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9291: produces its address (which becomes invalid when the variable's scope is
9292: left). E.g., the standard word @code{emit} can be defined in terms of
9293: @code{type} like this:
1.5 anton 9294:
1.78 anton 9295: @example
9296: : emit @{ C^ char* -- @}
9297: char* 1 type ;
9298: @end example
1.5 anton 9299:
1.78 anton 9300: @cindex default type of locals
9301: @cindex locals, default type
9302: A local without type specifier is a @code{W:} local. Both flavours of
9303: locals are initialized with values from the data or FP stack.
1.44 crook 9304:
1.78 anton 9305: Currently there is no way to define locals with user-defined data
9306: structures, but we are working on it.
1.5 anton 9307:
1.78 anton 9308: Gforth allows defining locals everywhere in a colon definition. This
9309: poses the following questions:
1.5 anton 9310:
1.78 anton 9311: @menu
9312: * Where are locals visible by name?::
9313: * How long do locals live?::
9314: * Locals programming style::
9315: * Locals implementation::
9316: @end menu
1.44 crook 9317:
1.78 anton 9318: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9319: @subsubsection Where are locals visible by name?
9320: @cindex locals visibility
9321: @cindex visibility of locals
9322: @cindex scope of locals
1.5 anton 9323:
1.78 anton 9324: Basically, the answer is that locals are visible where you would expect
9325: it in block-structured languages, and sometimes a little longer. If you
9326: want to restrict the scope of a local, enclose its definition in
9327: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9328:
9329:
1.78 anton 9330: doc-scope
9331: doc-endscope
1.5 anton 9332:
9333:
1.78 anton 9334: These words behave like control structure words, so you can use them
9335: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9336: arbitrary ways.
1.77 anton 9337:
1.78 anton 9338: If you want a more exact answer to the visibility question, here's the
9339: basic principle: A local is visible in all places that can only be
9340: reached through the definition of the local@footnote{In compiler
9341: construction terminology, all places dominated by the definition of the
9342: local.}. In other words, it is not visible in places that can be reached
9343: without going through the definition of the local. E.g., locals defined
9344: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9345: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9346: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9347:
1.78 anton 9348: The reasoning behind this solution is: We want to have the locals
9349: visible as long as it is meaningful. The user can always make the
9350: visibility shorter by using explicit scoping. In a place that can
9351: only be reached through the definition of a local, the meaning of a
9352: local name is clear. In other places it is not: How is the local
9353: initialized at the control flow path that does not contain the
9354: definition? Which local is meant, if the same name is defined twice in
9355: two independent control flow paths?
1.77 anton 9356:
1.78 anton 9357: This should be enough detail for nearly all users, so you can skip the
9358: rest of this section. If you really must know all the gory details and
9359: options, read on.
1.77 anton 9360:
1.78 anton 9361: In order to implement this rule, the compiler has to know which places
9362: are unreachable. It knows this automatically after @code{AHEAD},
9363: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9364: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9365: compiler that the control flow never reaches that place. If
9366: @code{UNREACHABLE} is not used where it could, the only consequence is
9367: that the visibility of some locals is more limited than the rule above
9368: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9369: lie to the compiler), buggy code will be produced.
1.77 anton 9370:
1.5 anton 9371:
1.78 anton 9372: doc-unreachable
1.5 anton 9373:
1.23 crook 9374:
1.78 anton 9375: Another problem with this rule is that at @code{BEGIN}, the compiler
9376: does not know which locals will be visible on the incoming
9377: back-edge. All problems discussed in the following are due to this
9378: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9379: loops as examples; the discussion also applies to @code{?DO} and other
9380: loops). Perhaps the most insidious example is:
1.26 crook 9381: @example
1.78 anton 9382: AHEAD
9383: BEGIN
9384: x
9385: [ 1 CS-ROLL ] THEN
9386: @{ x @}
9387: ...
9388: UNTIL
1.26 crook 9389: @end example
1.23 crook 9390:
1.78 anton 9391: This should be legal according to the visibility rule. The use of
9392: @code{x} can only be reached through the definition; but that appears
9393: textually below the use.
9394:
9395: From this example it is clear that the visibility rules cannot be fully
9396: implemented without major headaches. Our implementation treats common
9397: cases as advertised and the exceptions are treated in a safe way: The
9398: compiler makes a reasonable guess about the locals visible after a
9399: @code{BEGIN}; if it is too pessimistic, the
9400: user will get a spurious error about the local not being defined; if the
9401: compiler is too optimistic, it will notice this later and issue a
9402: warning. In the case above the compiler would complain about @code{x}
9403: being undefined at its use. You can see from the obscure examples in
9404: this section that it takes quite unusual control structures to get the
9405: compiler into trouble, and even then it will often do fine.
1.23 crook 9406:
1.78 anton 9407: If the @code{BEGIN} is reachable from above, the most optimistic guess
9408: is that all locals visible before the @code{BEGIN} will also be
9409: visible after the @code{BEGIN}. This guess is valid for all loops that
9410: are entered only through the @code{BEGIN}, in particular, for normal
9411: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9412: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9413: compiler. When the branch to the @code{BEGIN} is finally generated by
9414: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9415: warns the user if it was too optimistic:
1.26 crook 9416: @example
1.78 anton 9417: IF
9418: @{ x @}
9419: BEGIN
9420: \ x ?
9421: [ 1 cs-roll ] THEN
9422: ...
9423: UNTIL
1.26 crook 9424: @end example
1.23 crook 9425:
1.78 anton 9426: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9427: optimistically assumes that it lives until the @code{THEN}. It notices
9428: this difference when it compiles the @code{UNTIL} and issues a
9429: warning. The user can avoid the warning, and make sure that @code{x}
9430: is not used in the wrong area by using explicit scoping:
9431: @example
9432: IF
9433: SCOPE
9434: @{ x @}
9435: ENDSCOPE
9436: BEGIN
9437: [ 1 cs-roll ] THEN
9438: ...
9439: UNTIL
9440: @end example
1.23 crook 9441:
1.78 anton 9442: Since the guess is optimistic, there will be no spurious error messages
9443: about undefined locals.
1.44 crook 9444:
1.78 anton 9445: If the @code{BEGIN} is not reachable from above (e.g., after
9446: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9447: optimistic guess, as the locals visible after the @code{BEGIN} may be
9448: defined later. Therefore, the compiler assumes that no locals are
9449: visible after the @code{BEGIN}. However, the user can use
9450: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9451: visible at the BEGIN as at the point where the top control-flow stack
9452: item was created.
1.23 crook 9453:
1.44 crook 9454:
1.78 anton 9455: doc-assume-live
1.26 crook 9456:
1.23 crook 9457:
1.78 anton 9458: @noindent
9459: E.g.,
9460: @example
9461: @{ x @}
9462: AHEAD
9463: ASSUME-LIVE
9464: BEGIN
9465: x
9466: [ 1 CS-ROLL ] THEN
9467: ...
9468: UNTIL
9469: @end example
1.44 crook 9470:
1.78 anton 9471: Other cases where the locals are defined before the @code{BEGIN} can be
9472: handled by inserting an appropriate @code{CS-ROLL} before the
9473: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9474: behind the @code{ASSUME-LIVE}).
1.23 crook 9475:
1.78 anton 9476: Cases where locals are defined after the @code{BEGIN} (but should be
9477: visible immediately after the @code{BEGIN}) can only be handled by
9478: rearranging the loop. E.g., the ``most insidious'' example above can be
9479: arranged into:
9480: @example
9481: BEGIN
9482: @{ x @}
9483: ... 0=
9484: WHILE
9485: x
9486: REPEAT
9487: @end example
1.44 crook 9488:
1.78 anton 9489: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9490: @subsubsection How long do locals live?
9491: @cindex locals lifetime
9492: @cindex lifetime of locals
1.23 crook 9493:
1.78 anton 9494: The right answer for the lifetime question would be: A local lives at
9495: least as long as it can be accessed. For a value-flavoured local this
9496: means: until the end of its visibility. However, a variable-flavoured
9497: local could be accessed through its address far beyond its visibility
9498: scope. Ultimately, this would mean that such locals would have to be
9499: garbage collected. Since this entails un-Forth-like implementation
9500: complexities, I adopted the same cowardly solution as some other
9501: languages (e.g., C): The local lives only as long as it is visible;
9502: afterwards its address is invalid (and programs that access it
9503: afterwards are erroneous).
1.23 crook 9504:
1.78 anton 9505: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9506: @subsubsection Locals programming style
9507: @cindex locals programming style
9508: @cindex programming style, locals
1.23 crook 9509:
1.78 anton 9510: The freedom to define locals anywhere has the potential to change
9511: programming styles dramatically. In particular, the need to use the
9512: return stack for intermediate storage vanishes. Moreover, all stack
9513: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9514: determined arguments) can be eliminated: If the stack items are in the
9515: wrong order, just write a locals definition for all of them; then
9516: write the items in the order you want.
1.23 crook 9517:
1.78 anton 9518: This seems a little far-fetched and eliminating stack manipulations is
9519: unlikely to become a conscious programming objective. Still, the number
9520: of stack manipulations will be reduced dramatically if local variables
9521: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9522: a traditional implementation of @code{max}).
1.23 crook 9523:
1.78 anton 9524: This shows one potential benefit of locals: making Forth programs more
9525: readable. Of course, this benefit will only be realized if the
9526: programmers continue to honour the principle of factoring instead of
9527: using the added latitude to make the words longer.
1.23 crook 9528:
1.78 anton 9529: @cindex single-assignment style for locals
9530: Using @code{TO} can and should be avoided. Without @code{TO},
9531: every value-flavoured local has only a single assignment and many
9532: advantages of functional languages apply to Forth. I.e., programs are
9533: easier to analyse, to optimize and to read: It is clear from the
9534: definition what the local stands for, it does not turn into something
9535: different later.
1.23 crook 9536:
1.78 anton 9537: E.g., a definition using @code{TO} might look like this:
9538: @example
9539: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9540: u1 u2 min 0
9541: ?do
9542: addr1 c@@ addr2 c@@ -
9543: ?dup-if
9544: unloop exit
9545: then
9546: addr1 char+ TO addr1
9547: addr2 char+ TO addr2
9548: loop
9549: u1 u2 - ;
1.26 crook 9550: @end example
1.78 anton 9551: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9552: every loop iteration. @code{strcmp} is a typical example of the
9553: readability problems of using @code{TO}. When you start reading
9554: @code{strcmp}, you think that @code{addr1} refers to the start of the
9555: string. Only near the end of the loop you realize that it is something
9556: else.
1.23 crook 9557:
1.78 anton 9558: This can be avoided by defining two locals at the start of the loop that
9559: are initialized with the right value for the current iteration.
9560: @example
9561: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9562: addr1 addr2
9563: u1 u2 min 0
9564: ?do @{ s1 s2 @}
9565: s1 c@@ s2 c@@ -
9566: ?dup-if
9567: unloop exit
9568: then
9569: s1 char+ s2 char+
9570: loop
9571: 2drop
9572: u1 u2 - ;
9573: @end example
9574: Here it is clear from the start that @code{s1} has a different value
9575: in every loop iteration.
1.23 crook 9576:
1.78 anton 9577: @node Locals implementation, , Locals programming style, Gforth locals
9578: @subsubsection Locals implementation
9579: @cindex locals implementation
9580: @cindex implementation of locals
1.23 crook 9581:
1.78 anton 9582: @cindex locals stack
9583: Gforth uses an extra locals stack. The most compelling reason for
9584: this is that the return stack is not float-aligned; using an extra stack
9585: also eliminates the problems and restrictions of using the return stack
9586: as locals stack. Like the other stacks, the locals stack grows toward
9587: lower addresses. A few primitives allow an efficient implementation:
9588:
9589:
9590: doc-@local#
9591: doc-f@local#
9592: doc-laddr#
9593: doc-lp+!#
9594: doc-lp!
9595: doc->l
9596: doc-f>l
9597:
9598:
9599: In addition to these primitives, some specializations of these
9600: primitives for commonly occurring inline arguments are provided for
9601: efficiency reasons, e.g., @code{@@local0} as specialization of
9602: @code{@@local#} for the inline argument 0. The following compiling words
9603: compile the right specialized version, or the general version, as
9604: appropriate:
1.23 crook 9605:
1.5 anton 9606:
1.107 dvdkhlng 9607: @c doc-compile-@local
9608: @c doc-compile-f@local
1.78 anton 9609: doc-compile-lp+!
1.5 anton 9610:
9611:
1.78 anton 9612: Combinations of conditional branches and @code{lp+!#} like
9613: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9614: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9615:
1.78 anton 9616: A special area in the dictionary space is reserved for keeping the
9617: local variable names. @code{@{} switches the dictionary pointer to this
9618: area and @code{@}} switches it back and generates the locals
9619: initializing code. @code{W:} etc.@ are normal defining words. This
9620: special area is cleared at the start of every colon definition.
1.5 anton 9621:
1.78 anton 9622: @cindex word list for defining locals
9623: A special feature of Gforth's dictionary is used to implement the
9624: definition of locals without type specifiers: every word list (aka
9625: vocabulary) has its own methods for searching
9626: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9627: with a special search method: When it is searched for a word, it
9628: actually creates that word using @code{W:}. @code{@{} changes the search
9629: order to first search the word list containing @code{@}}, @code{W:} etc.,
9630: and then the word list for defining locals without type specifiers.
1.5 anton 9631:
1.78 anton 9632: The lifetime rules support a stack discipline within a colon
9633: definition: The lifetime of a local is either nested with other locals
9634: lifetimes or it does not overlap them.
1.23 crook 9635:
1.78 anton 9636: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9637: pointer manipulation is generated. Between control structure words
9638: locals definitions can push locals onto the locals stack. @code{AGAIN}
9639: is the simplest of the other three control flow words. It has to
9640: restore the locals stack depth of the corresponding @code{BEGIN}
9641: before branching. The code looks like this:
9642: @format
9643: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9644: @code{branch} <begin>
9645: @end format
1.26 crook 9646:
1.78 anton 9647: @code{UNTIL} is a little more complicated: If it branches back, it
9648: must adjust the stack just like @code{AGAIN}. But if it falls through,
9649: the locals stack must not be changed. The compiler generates the
9650: following code:
9651: @format
9652: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9653: @end format
9654: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9655:
1.78 anton 9656: @code{THEN} can produce somewhat inefficient code:
9657: @format
9658: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9659: <orig target>:
9660: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9661: @end format
9662: The second @code{lp+!#} adjusts the locals stack pointer from the
9663: level at the @i{orig} point to the level after the @code{THEN}. The
9664: first @code{lp+!#} adjusts the locals stack pointer from the current
9665: level to the level at the orig point, so the complete effect is an
9666: adjustment from the current level to the right level after the
9667: @code{THEN}.
1.26 crook 9668:
1.78 anton 9669: @cindex locals information on the control-flow stack
9670: @cindex control-flow stack items, locals information
9671: In a conventional Forth implementation a dest control-flow stack entry
9672: is just the target address and an orig entry is just the address to be
9673: patched. Our locals implementation adds a word list to every orig or dest
9674: item. It is the list of locals visible (or assumed visible) at the point
9675: described by the entry. Our implementation also adds a tag to identify
9676: the kind of entry, in particular to differentiate between live and dead
9677: (reachable and unreachable) orig entries.
1.26 crook 9678:
1.78 anton 9679: A few unusual operations have to be performed on locals word lists:
1.44 crook 9680:
1.5 anton 9681:
1.78 anton 9682: doc-common-list
9683: doc-sub-list?
9684: doc-list-size
1.52 anton 9685:
9686:
1.78 anton 9687: Several features of our locals word list implementation make these
9688: operations easy to implement: The locals word lists are organised as
9689: linked lists; the tails of these lists are shared, if the lists
9690: contain some of the same locals; and the address of a name is greater
9691: than the address of the names behind it in the list.
1.5 anton 9692:
1.78 anton 9693: Another important implementation detail is the variable
9694: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9695: determine if they can be reached directly or only through the branch
9696: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9697: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9698: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9699:
1.78 anton 9700: Counted loops are similar to other loops in most respects, but
9701: @code{LEAVE} requires special attention: It performs basically the same
9702: service as @code{AHEAD}, but it does not create a control-flow stack
9703: entry. Therefore the information has to be stored elsewhere;
9704: traditionally, the information was stored in the target fields of the
9705: branches created by the @code{LEAVE}s, by organizing these fields into a
9706: linked list. Unfortunately, this clever trick does not provide enough
9707: space for storing our extended control flow information. Therefore, we
9708: introduce another stack, the leave stack. It contains the control-flow
9709: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9710:
1.78 anton 9711: Local names are kept until the end of the colon definition, even if
9712: they are no longer visible in any control-flow path. In a few cases
9713: this may lead to increased space needs for the locals name area, but
9714: usually less than reclaiming this space would cost in code size.
1.5 anton 9715:
1.44 crook 9716:
1.78 anton 9717: @node ANS Forth locals, , Gforth locals, Locals
9718: @subsection ANS Forth locals
9719: @cindex locals, ANS Forth style
1.5 anton 9720:
1.78 anton 9721: The ANS Forth locals wordset does not define a syntax for locals, but
9722: words that make it possible to define various syntaxes. One of the
9723: possible syntaxes is a subset of the syntax we used in the Gforth locals
9724: wordset, i.e.:
1.29 crook 9725:
9726: @example
1.78 anton 9727: @{ local1 local2 ... -- comment @}
9728: @end example
9729: @noindent
9730: or
9731: @example
9732: @{ local1 local2 ... @}
1.29 crook 9733: @end example
9734:
1.78 anton 9735: The order of the locals corresponds to the order in a stack comment. The
9736: restrictions are:
1.5 anton 9737:
1.78 anton 9738: @itemize @bullet
9739: @item
9740: Locals can only be cell-sized values (no type specifiers are allowed).
9741: @item
9742: Locals can be defined only outside control structures.
9743: @item
9744: Locals can interfere with explicit usage of the return stack. For the
9745: exact (and long) rules, see the standard. If you don't use return stack
9746: accessing words in a definition using locals, you will be all right. The
9747: purpose of this rule is to make locals implementation on the return
9748: stack easier.
9749: @item
9750: The whole definition must be in one line.
9751: @end itemize
1.5 anton 9752:
1.78 anton 9753: Locals defined in ANS Forth behave like @code{VALUE}s
9754: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9755: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9756:
1.78 anton 9757: Since the syntax above is supported by Gforth directly, you need not do
9758: anything to use it. If you want to port a program using this syntax to
9759: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9760: syntax on the other system.
1.5 anton 9761:
1.78 anton 9762: Note that a syntax shown in the standard, section A.13 looks
9763: similar, but is quite different in having the order of locals
9764: reversed. Beware!
1.5 anton 9765:
1.78 anton 9766: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9767:
1.78 anton 9768: doc-(local)
1.5 anton 9769:
1.78 anton 9770: The ANS Forth locals extension wordset defines a syntax using
9771: @code{locals|}, but it is so awful that we strongly recommend not to use
9772: it. We have implemented this syntax to make porting to Gforth easy, but
9773: do not document it here. The problem with this syntax is that the locals
9774: are defined in an order reversed with respect to the standard stack
9775: comment notation, making programs harder to read, and easier to misread
9776: and miswrite. The only merit of this syntax is that it is easy to
9777: implement using the ANS Forth locals wordset.
1.53 anton 9778:
9779:
1.78 anton 9780: @c ----------------------------------------------------------
9781: @node Structures, Object-oriented Forth, Locals, Words
9782: @section Structures
9783: @cindex structures
9784: @cindex records
1.53 anton 9785:
1.78 anton 9786: This section presents the structure package that comes with Gforth. A
9787: version of the package implemented in ANS Forth is available in
9788: @file{compat/struct.fs}. This package was inspired by a posting on
9789: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9790: possibly John Hayes). A version of this section has been published in
9791: M. Anton Ertl,
9792: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9793: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9794: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9795:
1.78 anton 9796: @menu
9797: * Why explicit structure support?::
9798: * Structure Usage::
9799: * Structure Naming Convention::
9800: * Structure Implementation::
9801: * Structure Glossary::
9802: @end menu
1.55 anton 9803:
1.78 anton 9804: @node Why explicit structure support?, Structure Usage, Structures, Structures
9805: @subsection Why explicit structure support?
1.53 anton 9806:
1.78 anton 9807: @cindex address arithmetic for structures
9808: @cindex structures using address arithmetic
9809: If we want to use a structure containing several fields, we could simply
9810: reserve memory for it, and access the fields using address arithmetic
9811: (@pxref{Address arithmetic}). As an example, consider a structure with
9812: the following fields
1.57 anton 9813:
1.78 anton 9814: @table @code
9815: @item a
9816: is a float
9817: @item b
9818: is a cell
9819: @item c
9820: is a float
9821: @end table
1.57 anton 9822:
1.78 anton 9823: Given the (float-aligned) base address of the structure we get the
9824: address of the field
1.52 anton 9825:
1.78 anton 9826: @table @code
9827: @item a
9828: without doing anything further.
9829: @item b
9830: with @code{float+}
9831: @item c
9832: with @code{float+ cell+ faligned}
9833: @end table
1.52 anton 9834:
1.78 anton 9835: It is easy to see that this can become quite tiring.
1.52 anton 9836:
1.78 anton 9837: Moreover, it is not very readable, because seeing a
9838: @code{cell+} tells us neither which kind of structure is
9839: accessed nor what field is accessed; we have to somehow infer the kind
9840: of structure, and then look up in the documentation, which field of
9841: that structure corresponds to that offset.
1.53 anton 9842:
1.78 anton 9843: Finally, this kind of address arithmetic also causes maintenance
9844: troubles: If you add or delete a field somewhere in the middle of the
9845: structure, you have to find and change all computations for the fields
9846: afterwards.
1.52 anton 9847:
1.78 anton 9848: So, instead of using @code{cell+} and friends directly, how
9849: about storing the offsets in constants:
1.52 anton 9850:
1.78 anton 9851: @example
9852: 0 constant a-offset
9853: 0 float+ constant b-offset
9854: 0 float+ cell+ faligned c-offset
9855: @end example
1.64 pazsan 9856:
1.78 anton 9857: Now we can get the address of field @code{x} with @code{x-offset
9858: +}. This is much better in all respects. Of course, you still
9859: have to change all later offset definitions if you add a field. You can
9860: fix this by declaring the offsets in the following way:
1.57 anton 9861:
1.78 anton 9862: @example
9863: 0 constant a-offset
9864: a-offset float+ constant b-offset
9865: b-offset cell+ faligned constant c-offset
9866: @end example
1.57 anton 9867:
1.78 anton 9868: Since we always use the offsets with @code{+}, we could use a defining
9869: word @code{cfield} that includes the @code{+} in the action of the
9870: defined word:
1.64 pazsan 9871:
1.78 anton 9872: @example
9873: : cfield ( n "name" -- )
9874: create ,
9875: does> ( name execution: addr1 -- addr2 )
9876: @@ + ;
1.64 pazsan 9877:
1.78 anton 9878: 0 cfield a
9879: 0 a float+ cfield b
9880: 0 b cell+ faligned cfield c
9881: @end example
1.64 pazsan 9882:
1.78 anton 9883: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9884:
1.78 anton 9885: The structure field words now can be used quite nicely. However,
9886: their definition is still a bit cumbersome: We have to repeat the
9887: name, the information about size and alignment is distributed before
9888: and after the field definitions etc. The structure package presented
9889: here addresses these problems.
1.64 pazsan 9890:
1.78 anton 9891: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9892: @subsection Structure Usage
9893: @cindex structure usage
1.57 anton 9894:
1.78 anton 9895: @cindex @code{field} usage
9896: @cindex @code{struct} usage
9897: @cindex @code{end-struct} usage
9898: You can define a structure for a (data-less) linked list with:
1.57 anton 9899: @example
1.78 anton 9900: struct
9901: cell% field list-next
9902: end-struct list%
1.57 anton 9903: @end example
9904:
1.78 anton 9905: With the address of the list node on the stack, you can compute the
9906: address of the field that contains the address of the next node with
9907: @code{list-next}. E.g., you can determine the length of a list
9908: with:
1.57 anton 9909:
9910: @example
1.78 anton 9911: : list-length ( list -- n )
9912: \ "list" is a pointer to the first element of a linked list
9913: \ "n" is the length of the list
9914: 0 BEGIN ( list1 n1 )
9915: over
9916: WHILE ( list1 n1 )
9917: 1+ swap list-next @@ swap
9918: REPEAT
9919: nip ;
1.57 anton 9920: @end example
9921:
1.78 anton 9922: You can reserve memory for a list node in the dictionary with
9923: @code{list% %allot}, which leaves the address of the list node on the
9924: stack. For the equivalent allocation on the heap you can use @code{list%
9925: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9926: use @code{list% %allocate}). You can get the the size of a list
9927: node with @code{list% %size} and its alignment with @code{list%
9928: %alignment}.
9929:
9930: Note that in ANS Forth the body of a @code{create}d word is
9931: @code{aligned} but not necessarily @code{faligned};
9932: therefore, if you do a:
1.57 anton 9933:
9934: @example
1.78 anton 9935: create @emph{name} foo% %allot drop
1.57 anton 9936: @end example
9937:
1.78 anton 9938: @noindent
9939: then the memory alloted for @code{foo%} is guaranteed to start at the
9940: body of @code{@emph{name}} only if @code{foo%} contains only character,
9941: cell and double fields. Therefore, if your structure contains floats,
9942: better use
1.57 anton 9943:
9944: @example
1.78 anton 9945: foo% %allot constant @emph{name}
1.57 anton 9946: @end example
9947:
1.78 anton 9948: @cindex structures containing structures
9949: You can include a structure @code{foo%} as a field of
9950: another structure, like this:
1.65 anton 9951: @example
1.78 anton 9952: struct
9953: ...
9954: foo% field ...
9955: ...
9956: end-struct ...
1.65 anton 9957: @end example
1.52 anton 9958:
1.78 anton 9959: @cindex structure extension
9960: @cindex extended records
9961: Instead of starting with an empty structure, you can extend an
9962: existing structure. E.g., a plain linked list without data, as defined
9963: above, is hardly useful; You can extend it to a linked list of integers,
9964: like this:@footnote{This feature is also known as @emph{extended
9965: records}. It is the main innovation in the Oberon language; in other
9966: words, adding this feature to Modula-2 led Wirth to create a new
9967: language, write a new compiler etc. Adding this feature to Forth just
9968: required a few lines of code.}
1.52 anton 9969:
1.78 anton 9970: @example
9971: list%
9972: cell% field intlist-int
9973: end-struct intlist%
9974: @end example
1.55 anton 9975:
1.78 anton 9976: @code{intlist%} is a structure with two fields:
9977: @code{list-next} and @code{intlist-int}.
1.55 anton 9978:
1.78 anton 9979: @cindex structures containing arrays
9980: You can specify an array type containing @emph{n} elements of
9981: type @code{foo%} like this:
1.55 anton 9982:
9983: @example
1.78 anton 9984: foo% @emph{n} *
1.56 anton 9985: @end example
1.55 anton 9986:
1.78 anton 9987: You can use this array type in any place where you can use a normal
9988: type, e.g., when defining a @code{field}, or with
9989: @code{%allot}.
9990:
9991: @cindex first field optimization
9992: The first field is at the base address of a structure and the word for
9993: this field (e.g., @code{list-next}) actually does not change the address
9994: on the stack. You may be tempted to leave it away in the interest of
9995: run-time and space efficiency. This is not necessary, because the
9996: structure package optimizes this case: If you compile a first-field
9997: words, no code is generated. So, in the interest of readability and
9998: maintainability you should include the word for the field when accessing
9999: the field.
1.52 anton 10000:
10001:
1.78 anton 10002: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10003: @subsection Structure Naming Convention
10004: @cindex structure naming convention
1.52 anton 10005:
1.78 anton 10006: The field names that come to (my) mind are often quite generic, and,
10007: if used, would cause frequent name clashes. E.g., many structures
10008: probably contain a @code{counter} field. The structure names
10009: that come to (my) mind are often also the logical choice for the names
10010: of words that create such a structure.
1.52 anton 10011:
1.78 anton 10012: Therefore, I have adopted the following naming conventions:
1.52 anton 10013:
1.78 anton 10014: @itemize @bullet
10015: @cindex field naming convention
10016: @item
10017: The names of fields are of the form
10018: @code{@emph{struct}-@emph{field}}, where
10019: @code{@emph{struct}} is the basic name of the structure, and
10020: @code{@emph{field}} is the basic name of the field. You can
10021: think of field words as converting the (address of the)
10022: structure into the (address of the) field.
1.52 anton 10023:
1.78 anton 10024: @cindex structure naming convention
10025: @item
10026: The names of structures are of the form
10027: @code{@emph{struct}%}, where
10028: @code{@emph{struct}} is the basic name of the structure.
10029: @end itemize
1.52 anton 10030:
1.78 anton 10031: This naming convention does not work that well for fields of extended
10032: structures; e.g., the integer list structure has a field
10033: @code{intlist-int}, but has @code{list-next}, not
10034: @code{intlist-next}.
1.53 anton 10035:
1.78 anton 10036: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10037: @subsection Structure Implementation
10038: @cindex structure implementation
10039: @cindex implementation of structures
1.52 anton 10040:
1.78 anton 10041: The central idea in the implementation is to pass the data about the
10042: structure being built on the stack, not in some global
10043: variable. Everything else falls into place naturally once this design
10044: decision is made.
1.53 anton 10045:
1.78 anton 10046: The type description on the stack is of the form @emph{align
10047: size}. Keeping the size on the top-of-stack makes dealing with arrays
10048: very simple.
1.53 anton 10049:
1.78 anton 10050: @code{field} is a defining word that uses @code{Create}
10051: and @code{DOES>}. The body of the field contains the offset
10052: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10053:
10054: @example
1.78 anton 10055: @@ +
1.53 anton 10056: @end example
10057:
1.78 anton 10058: @noindent
10059: i.e., add the offset to the address, giving the stack effect
10060: @i{addr1 -- addr2} for a field.
10061:
10062: @cindex first field optimization, implementation
10063: This simple structure is slightly complicated by the optimization
10064: for fields with offset 0, which requires a different
10065: @code{DOES>}-part (because we cannot rely on there being
10066: something on the stack if such a field is invoked during
10067: compilation). Therefore, we put the different @code{DOES>}-parts
10068: in separate words, and decide which one to invoke based on the
10069: offset. For a zero offset, the field is basically a noop; it is
10070: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10071:
1.78 anton 10072: @node Structure Glossary, , Structure Implementation, Structures
10073: @subsection Structure Glossary
10074: @cindex structure glossary
1.53 anton 10075:
1.5 anton 10076:
1.78 anton 10077: doc-%align
10078: doc-%alignment
10079: doc-%alloc
10080: doc-%allocate
10081: doc-%allot
10082: doc-cell%
10083: doc-char%
10084: doc-dfloat%
10085: doc-double%
10086: doc-end-struct
10087: doc-field
10088: doc-float%
10089: doc-naligned
10090: doc-sfloat%
10091: doc-%size
10092: doc-struct
1.54 anton 10093:
10094:
1.26 crook 10095: @c -------------------------------------------------------------
1.78 anton 10096: @node Object-oriented Forth, Programming Tools, Structures, Words
10097: @section Object-oriented Forth
10098:
10099: Gforth comes with three packages for object-oriented programming:
10100: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10101: is preloaded, so you have to @code{include} them before use. The most
10102: important differences between these packages (and others) are discussed
10103: in @ref{Comparison with other object models}. All packages are written
10104: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10105:
1.78 anton 10106: @menu
10107: * Why object-oriented programming?::
10108: * Object-Oriented Terminology::
10109: * Objects::
10110: * OOF::
10111: * Mini-OOF::
10112: * Comparison with other object models::
10113: @end menu
1.5 anton 10114:
1.78 anton 10115: @c ----------------------------------------------------------------
10116: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10117: @subsection Why object-oriented programming?
10118: @cindex object-oriented programming motivation
10119: @cindex motivation for object-oriented programming
1.44 crook 10120:
1.78 anton 10121: Often we have to deal with several data structures (@emph{objects}),
10122: that have to be treated similarly in some respects, but differently in
10123: others. Graphical objects are the textbook example: circles, triangles,
10124: dinosaurs, icons, and others, and we may want to add more during program
10125: development. We want to apply some operations to any graphical object,
10126: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10127: has to do something different for every kind of object.
10128: @comment TODO add some other operations eg perimeter, area
10129: @comment and tie in to concrete examples later..
1.5 anton 10130:
1.78 anton 10131: We could implement @code{draw} as a big @code{CASE}
10132: control structure that executes the appropriate code depending on the
10133: kind of object to be drawn. This would be not be very elegant, and,
10134: moreover, we would have to change @code{draw} every time we add
10135: a new kind of graphical object (say, a spaceship).
1.44 crook 10136:
1.78 anton 10137: What we would rather do is: When defining spaceships, we would tell
10138: the system: ``Here's how you @code{draw} a spaceship; you figure
10139: out the rest''.
1.5 anton 10140:
1.78 anton 10141: This is the problem that all systems solve that (rightfully) call
10142: themselves object-oriented; the object-oriented packages presented here
10143: solve this problem (and not much else).
10144: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10145:
1.78 anton 10146: @c ------------------------------------------------------------------------
10147: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10148: @subsection Object-Oriented Terminology
10149: @cindex object-oriented terminology
10150: @cindex terminology for object-oriented programming
1.5 anton 10151:
1.78 anton 10152: This section is mainly for reference, so you don't have to understand
10153: all of it right away. The terminology is mainly Smalltalk-inspired. In
10154: short:
1.44 crook 10155:
1.78 anton 10156: @table @emph
10157: @cindex class
10158: @item class
10159: a data structure definition with some extras.
1.5 anton 10160:
1.78 anton 10161: @cindex object
10162: @item object
10163: an instance of the data structure described by the class definition.
1.5 anton 10164:
1.78 anton 10165: @cindex instance variables
10166: @item instance variables
10167: fields of the data structure.
1.5 anton 10168:
1.78 anton 10169: @cindex selector
10170: @cindex method selector
10171: @cindex virtual function
10172: @item selector
10173: (or @emph{method selector}) a word (e.g.,
10174: @code{draw}) that performs an operation on a variety of data
10175: structures (classes). A selector describes @emph{what} operation to
10176: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10177:
1.78 anton 10178: @cindex method
10179: @item method
10180: the concrete definition that performs the operation
10181: described by the selector for a specific class. A method specifies
10182: @emph{how} the operation is performed for a specific class.
1.5 anton 10183:
1.78 anton 10184: @cindex selector invocation
10185: @cindex message send
10186: @cindex invoking a selector
10187: @item selector invocation
10188: a call of a selector. One argument of the call (the TOS (top-of-stack))
10189: is used for determining which method is used. In Smalltalk terminology:
10190: a message (consisting of the selector and the other arguments) is sent
10191: to the object.
1.5 anton 10192:
1.78 anton 10193: @cindex receiving object
10194: @item receiving object
10195: the object used for determining the method executed by a selector
10196: invocation. In the @file{objects.fs} model, it is the object that is on
10197: the TOS when the selector is invoked. (@emph{Receiving} comes from
10198: the Smalltalk @emph{message} terminology.)
1.5 anton 10199:
1.78 anton 10200: @cindex child class
10201: @cindex parent class
10202: @cindex inheritance
10203: @item child class
10204: a class that has (@emph{inherits}) all properties (instance variables,
10205: selectors, methods) from a @emph{parent class}. In Smalltalk
10206: terminology: The subclass inherits from the superclass. In C++
10207: terminology: The derived class inherits from the base class.
1.5 anton 10208:
1.78 anton 10209: @end table
1.5 anton 10210:
1.78 anton 10211: @c If you wonder about the message sending terminology, it comes from
10212: @c a time when each object had it's own task and objects communicated via
10213: @c message passing; eventually the Smalltalk developers realized that
10214: @c they can do most things through simple (indirect) calls. They kept the
10215: @c terminology.
1.5 anton 10216:
1.78 anton 10217: @c --------------------------------------------------------------
10218: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10219: @subsection The @file{objects.fs} model
10220: @cindex objects
10221: @cindex object-oriented programming
1.26 crook 10222:
1.78 anton 10223: @cindex @file{objects.fs}
10224: @cindex @file{oof.fs}
1.26 crook 10225:
1.78 anton 10226: This section describes the @file{objects.fs} package. This material also
10227: has been published in M. Anton Ertl,
10228: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10229: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10230: 37--43.
10231: @c McKewan's and Zsoter's packages
1.26 crook 10232:
1.78 anton 10233: This section assumes that you have read @ref{Structures}.
1.5 anton 10234:
1.78 anton 10235: The techniques on which this model is based have been used to implement
10236: the parser generator, Gray, and have also been used in Gforth for
10237: implementing the various flavours of word lists (hashed or not,
10238: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10239:
10240:
1.26 crook 10241: @menu
1.78 anton 10242: * Properties of the Objects model::
10243: * Basic Objects Usage::
10244: * The Objects base class::
10245: * Creating objects::
10246: * Object-Oriented Programming Style::
10247: * Class Binding::
10248: * Method conveniences::
10249: * Classes and Scoping::
10250: * Dividing classes::
10251: * Object Interfaces::
10252: * Objects Implementation::
10253: * Objects Glossary::
1.26 crook 10254: @end menu
1.5 anton 10255:
1.78 anton 10256: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10257:
1.78 anton 10258: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10259: @subsubsection Properties of the @file{objects.fs} model
10260: @cindex @file{objects.fs} properties
1.5 anton 10261:
1.78 anton 10262: @itemize @bullet
10263: @item
10264: It is straightforward to pass objects on the stack. Passing
10265: selectors on the stack is a little less convenient, but possible.
1.44 crook 10266:
1.78 anton 10267: @item
10268: Objects are just data structures in memory, and are referenced by their
10269: address. You can create words for objects with normal defining words
10270: like @code{constant}. Likewise, there is no difference between instance
10271: variables that contain objects and those that contain other data.
1.5 anton 10272:
1.78 anton 10273: @item
10274: Late binding is efficient and easy to use.
1.44 crook 10275:
1.78 anton 10276: @item
10277: It avoids parsing, and thus avoids problems with state-smartness
10278: and reduced extensibility; for convenience there are a few parsing
10279: words, but they have non-parsing counterparts. There are also a few
10280: defining words that parse. This is hard to avoid, because all standard
10281: defining words parse (except @code{:noname}); however, such
10282: words are not as bad as many other parsing words, because they are not
10283: state-smart.
1.5 anton 10284:
1.78 anton 10285: @item
10286: It does not try to incorporate everything. It does a few things and does
10287: them well (IMO). In particular, this model was not designed to support
10288: information hiding (although it has features that may help); you can use
10289: a separate package for achieving this.
1.5 anton 10290:
1.78 anton 10291: @item
10292: It is layered; you don't have to learn and use all features to use this
10293: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10294: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10295: are optional and independent of each other.
1.5 anton 10296:
1.78 anton 10297: @item
10298: An implementation in ANS Forth is available.
1.5 anton 10299:
1.78 anton 10300: @end itemize
1.5 anton 10301:
1.44 crook 10302:
1.78 anton 10303: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10304: @subsubsection Basic @file{objects.fs} Usage
10305: @cindex basic objects usage
10306: @cindex objects, basic usage
1.5 anton 10307:
1.78 anton 10308: You can define a class for graphical objects like this:
1.44 crook 10309:
1.78 anton 10310: @cindex @code{class} usage
10311: @cindex @code{end-class} usage
10312: @cindex @code{selector} usage
1.5 anton 10313: @example
1.78 anton 10314: object class \ "object" is the parent class
10315: selector draw ( x y graphical -- )
10316: end-class graphical
10317: @end example
10318:
10319: This code defines a class @code{graphical} with an
10320: operation @code{draw}. We can perform the operation
10321: @code{draw} on any @code{graphical} object, e.g.:
10322:
10323: @example
10324: 100 100 t-rex draw
1.26 crook 10325: @end example
1.5 anton 10326:
1.78 anton 10327: @noindent
10328: where @code{t-rex} is a word (say, a constant) that produces a
10329: graphical object.
10330:
10331: @comment TODO add a 2nd operation eg perimeter.. and use for
10332: @comment a concrete example
1.5 anton 10333:
1.78 anton 10334: @cindex abstract class
10335: How do we create a graphical object? With the present definitions,
10336: we cannot create a useful graphical object. The class
10337: @code{graphical} describes graphical objects in general, but not
10338: any concrete graphical object type (C++ users would call it an
10339: @emph{abstract class}); e.g., there is no method for the selector
10340: @code{draw} in the class @code{graphical}.
1.5 anton 10341:
1.78 anton 10342: For concrete graphical objects, we define child classes of the
10343: class @code{graphical}, e.g.:
1.5 anton 10344:
1.78 anton 10345: @cindex @code{overrides} usage
10346: @cindex @code{field} usage in class definition
1.26 crook 10347: @example
1.78 anton 10348: graphical class \ "graphical" is the parent class
10349: cell% field circle-radius
1.5 anton 10350:
1.78 anton 10351: :noname ( x y circle -- )
10352: circle-radius @@ draw-circle ;
10353: overrides draw
1.5 anton 10354:
1.78 anton 10355: :noname ( n-radius circle -- )
10356: circle-radius ! ;
10357: overrides construct
1.5 anton 10358:
1.78 anton 10359: end-class circle
10360: @end example
1.44 crook 10361:
1.78 anton 10362: Here we define a class @code{circle} as a child of @code{graphical},
10363: with field @code{circle-radius} (which behaves just like a field
10364: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10365: for the selectors @code{draw} and @code{construct} (@code{construct} is
10366: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10367:
1.78 anton 10368: Now we can create a circle on the heap (i.e.,
10369: @code{allocate}d memory) with:
1.44 crook 10370:
1.78 anton 10371: @cindex @code{heap-new} usage
1.5 anton 10372: @example
1.78 anton 10373: 50 circle heap-new constant my-circle
1.5 anton 10374: @end example
10375:
1.78 anton 10376: @noindent
10377: @code{heap-new} invokes @code{construct}, thus
10378: initializing the field @code{circle-radius} with 50. We can draw
10379: this new circle at (100,100) with:
1.5 anton 10380:
10381: @example
1.78 anton 10382: 100 100 my-circle draw
1.5 anton 10383: @end example
10384:
1.78 anton 10385: @cindex selector invocation, restrictions
10386: @cindex class definition, restrictions
10387: Note: You can only invoke a selector if the object on the TOS
10388: (the receiving object) belongs to the class where the selector was
10389: defined or one of its descendents; e.g., you can invoke
10390: @code{draw} only for objects belonging to @code{graphical}
10391: or its descendents (e.g., @code{circle}). Immediately before
10392: @code{end-class}, the search order has to be the same as
10393: immediately after @code{class}.
10394:
10395: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10396: @subsubsection The @file{object.fs} base class
10397: @cindex @code{object} class
10398:
10399: When you define a class, you have to specify a parent class. So how do
10400: you start defining classes? There is one class available from the start:
10401: @code{object}. It is ancestor for all classes and so is the
10402: only class that has no parent. It has two selectors: @code{construct}
10403: and @code{print}.
10404:
10405: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10406: @subsubsection Creating objects
10407: @cindex creating objects
10408: @cindex object creation
10409: @cindex object allocation options
10410:
10411: @cindex @code{heap-new} discussion
10412: @cindex @code{dict-new} discussion
10413: @cindex @code{construct} discussion
10414: You can create and initialize an object of a class on the heap with
10415: @code{heap-new} ( ... class -- object ) and in the dictionary
10416: (allocation with @code{allot}) with @code{dict-new} (
10417: ... class -- object ). Both words invoke @code{construct}, which
10418: consumes the stack items indicated by "..." above.
10419:
10420: @cindex @code{init-object} discussion
10421: @cindex @code{class-inst-size} discussion
10422: If you want to allocate memory for an object yourself, you can get its
10423: alignment and size with @code{class-inst-size 2@@} ( class --
10424: align size ). Once you have memory for an object, you can initialize
10425: it with @code{init-object} ( ... class object -- );
10426: @code{construct} does only a part of the necessary work.
10427:
10428: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10429: @subsubsection Object-Oriented Programming Style
10430: @cindex object-oriented programming style
10431: @cindex programming style, object-oriented
1.5 anton 10432:
1.78 anton 10433: This section is not exhaustive.
1.5 anton 10434:
1.78 anton 10435: @cindex stack effects of selectors
10436: @cindex selectors and stack effects
10437: In general, it is a good idea to ensure that all methods for the
10438: same selector have the same stack effect: when you invoke a selector,
10439: you often have no idea which method will be invoked, so, unless all
10440: methods have the same stack effect, you will not know the stack effect
10441: of the selector invocation.
1.5 anton 10442:
1.78 anton 10443: One exception to this rule is methods for the selector
10444: @code{construct}. We know which method is invoked, because we
10445: specify the class to be constructed at the same place. Actually, I
10446: defined @code{construct} as a selector only to give the users a
10447: convenient way to specify initialization. The way it is used, a
10448: mechanism different from selector invocation would be more natural
10449: (but probably would take more code and more space to explain).
1.5 anton 10450:
1.78 anton 10451: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10452: @subsubsection Class Binding
10453: @cindex class binding
10454: @cindex early binding
1.5 anton 10455:
1.78 anton 10456: @cindex late binding
10457: Normal selector invocations determine the method at run-time depending
10458: on the class of the receiving object. This run-time selection is called
10459: @i{late binding}.
1.5 anton 10460:
1.78 anton 10461: Sometimes it's preferable to invoke a different method. For example,
10462: you might want to use the simple method for @code{print}ing
10463: @code{object}s instead of the possibly long-winded @code{print} method
10464: of the receiver class. You can achieve this by replacing the invocation
10465: of @code{print} with:
1.5 anton 10466:
1.78 anton 10467: @cindex @code{[bind]} usage
1.5 anton 10468: @example
1.78 anton 10469: [bind] object print
1.5 anton 10470: @end example
10471:
1.78 anton 10472: @noindent
10473: in compiled code or:
10474:
10475: @cindex @code{bind} usage
1.5 anton 10476: @example
1.78 anton 10477: bind object print
1.5 anton 10478: @end example
10479:
1.78 anton 10480: @cindex class binding, alternative to
10481: @noindent
10482: in interpreted code. Alternatively, you can define the method with a
10483: name (e.g., @code{print-object}), and then invoke it through the
10484: name. Class binding is just a (often more convenient) way to achieve
10485: the same effect; it avoids name clutter and allows you to invoke
10486: methods directly without naming them first.
1.5 anton 10487:
1.78 anton 10488: @cindex superclass binding
10489: @cindex parent class binding
10490: A frequent use of class binding is this: When we define a method
10491: for a selector, we often want the method to do what the selector does
10492: in the parent class, and a little more. There is a special word for
10493: this purpose: @code{[parent]}; @code{[parent]
10494: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10495: selector}}, where @code{@emph{parent}} is the parent
10496: class of the current class. E.g., a method definition might look like:
1.44 crook 10497:
1.78 anton 10498: @cindex @code{[parent]} usage
10499: @example
10500: :noname
10501: dup [parent] foo \ do parent's foo on the receiving object
10502: ... \ do some more
10503: ; overrides foo
10504: @end example
1.6 pazsan 10505:
1.78 anton 10506: @cindex class binding as optimization
10507: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10508: March 1997), Andrew McKewan presents class binding as an optimization
10509: technique. I recommend not using it for this purpose unless you are in
10510: an emergency. Late binding is pretty fast with this model anyway, so the
10511: benefit of using class binding is small; the cost of using class binding
10512: where it is not appropriate is reduced maintainability.
1.44 crook 10513:
1.78 anton 10514: While we are at programming style questions: You should bind
10515: selectors only to ancestor classes of the receiving object. E.g., say,
10516: you know that the receiving object is of class @code{foo} or its
10517: descendents; then you should bind only to @code{foo} and its
10518: ancestors.
1.12 anton 10519:
1.78 anton 10520: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10521: @subsubsection Method conveniences
10522: @cindex method conveniences
1.44 crook 10523:
1.78 anton 10524: In a method you usually access the receiving object pretty often. If
10525: you define the method as a plain colon definition (e.g., with
10526: @code{:noname}), you may have to do a lot of stack
10527: gymnastics. To avoid this, you can define the method with @code{m:
10528: ... ;m}. E.g., you could define the method for
10529: @code{draw}ing a @code{circle} with
1.6 pazsan 10530:
1.78 anton 10531: @cindex @code{this} usage
10532: @cindex @code{m:} usage
10533: @cindex @code{;m} usage
10534: @example
10535: m: ( x y circle -- )
10536: ( x y ) this circle-radius @@ draw-circle ;m
10537: @end example
1.6 pazsan 10538:
1.78 anton 10539: @cindex @code{exit} in @code{m: ... ;m}
10540: @cindex @code{exitm} discussion
10541: @cindex @code{catch} in @code{m: ... ;m}
10542: When this method is executed, the receiver object is removed from the
10543: stack; you can access it with @code{this} (admittedly, in this
10544: example the use of @code{m: ... ;m} offers no advantage). Note
10545: that I specify the stack effect for the whole method (i.e. including
10546: the receiver object), not just for the code between @code{m:}
10547: and @code{;m}. You cannot use @code{exit} in
10548: @code{m:...;m}; instead, use
10549: @code{exitm}.@footnote{Moreover, for any word that calls
10550: @code{catch} and was defined before loading
10551: @code{objects.fs}, you have to redefine it like I redefined
10552: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10553:
1.78 anton 10554: @cindex @code{inst-var} usage
10555: You will frequently use sequences of the form @code{this
10556: @emph{field}} (in the example above: @code{this
10557: circle-radius}). If you use the field only in this way, you can
10558: define it with @code{inst-var} and eliminate the
10559: @code{this} before the field name. E.g., the @code{circle}
10560: class above could also be defined with:
1.6 pazsan 10561:
1.78 anton 10562: @example
10563: graphical class
10564: cell% inst-var radius
1.6 pazsan 10565:
1.78 anton 10566: m: ( x y circle -- )
10567: radius @@ draw-circle ;m
10568: overrides draw
1.6 pazsan 10569:
1.78 anton 10570: m: ( n-radius circle -- )
10571: radius ! ;m
10572: overrides construct
1.6 pazsan 10573:
1.78 anton 10574: end-class circle
10575: @end example
1.6 pazsan 10576:
1.78 anton 10577: @code{radius} can only be used in @code{circle} and its
10578: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10579:
1.78 anton 10580: @cindex @code{inst-value} usage
10581: You can also define fields with @code{inst-value}, which is
10582: to @code{inst-var} what @code{value} is to
10583: @code{variable}. You can change the value of such a field with
10584: @code{[to-inst]}. E.g., we could also define the class
10585: @code{circle} like this:
1.44 crook 10586:
1.78 anton 10587: @example
10588: graphical class
10589: inst-value radius
1.6 pazsan 10590:
1.78 anton 10591: m: ( x y circle -- )
10592: radius draw-circle ;m
10593: overrides draw
1.44 crook 10594:
1.78 anton 10595: m: ( n-radius circle -- )
10596: [to-inst] radius ;m
10597: overrides construct
1.6 pazsan 10598:
1.78 anton 10599: end-class circle
10600: @end example
1.6 pazsan 10601:
1.78 anton 10602: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10603:
1.78 anton 10604: @c Finally, you can define named methods with @code{:m}. One use of this
10605: @c feature is the definition of words that occur only in one class and are
10606: @c not intended to be overridden, but which still need method context
10607: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10608: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10609:
10610:
1.78 anton 10611: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10612: @subsubsection Classes and Scoping
10613: @cindex classes and scoping
10614: @cindex scoping and classes
1.6 pazsan 10615:
1.78 anton 10616: Inheritance is frequent, unlike structure extension. This exacerbates
10617: the problem with the field name convention (@pxref{Structure Naming
10618: Convention}): One always has to remember in which class the field was
10619: originally defined; changing a part of the class structure would require
10620: changes for renaming in otherwise unaffected code.
1.6 pazsan 10621:
1.78 anton 10622: @cindex @code{inst-var} visibility
10623: @cindex @code{inst-value} visibility
10624: To solve this problem, I added a scoping mechanism (which was not in my
10625: original charter): A field defined with @code{inst-var} (or
10626: @code{inst-value}) is visible only in the class where it is defined and in
10627: the descendent classes of this class. Using such fields only makes
10628: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10629:
1.78 anton 10630: This scoping mechanism allows us to use the unadorned field name,
10631: because name clashes with unrelated words become much less likely.
1.6 pazsan 10632:
1.78 anton 10633: @cindex @code{protected} discussion
10634: @cindex @code{private} discussion
10635: Once we have this mechanism, we can also use it for controlling the
10636: visibility of other words: All words defined after
10637: @code{protected} are visible only in the current class and its
10638: descendents. @code{public} restores the compilation
10639: (i.e. @code{current}) word list that was in effect before. If you
10640: have several @code{protected}s without an intervening
10641: @code{public} or @code{set-current}, @code{public}
10642: will restore the compilation word list in effect before the first of
10643: these @code{protected}s.
1.6 pazsan 10644:
1.78 anton 10645: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10646: @subsubsection Dividing classes
10647: @cindex Dividing classes
10648: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10649:
1.78 anton 10650: You may want to do the definition of methods separate from the
10651: definition of the class, its selectors, fields, and instance variables,
10652: i.e., separate the implementation from the definition. You can do this
10653: in the following way:
1.6 pazsan 10654:
1.78 anton 10655: @example
10656: graphical class
10657: inst-value radius
10658: end-class circle
1.6 pazsan 10659:
1.78 anton 10660: ... \ do some other stuff
1.6 pazsan 10661:
1.78 anton 10662: circle methods \ now we are ready
1.44 crook 10663:
1.78 anton 10664: m: ( x y circle -- )
10665: radius draw-circle ;m
10666: overrides draw
1.6 pazsan 10667:
1.78 anton 10668: m: ( n-radius circle -- )
10669: [to-inst] radius ;m
10670: overrides construct
1.44 crook 10671:
1.78 anton 10672: end-methods
10673: @end example
1.7 pazsan 10674:
1.78 anton 10675: You can use several @code{methods}...@code{end-methods} sections. The
10676: only things you can do to the class in these sections are: defining
10677: methods, and overriding the class's selectors. You must not define new
10678: selectors or fields.
1.7 pazsan 10679:
1.78 anton 10680: Note that you often have to override a selector before using it. In
10681: particular, you usually have to override @code{construct} with a new
10682: method before you can invoke @code{heap-new} and friends. E.g., you
10683: must not create a circle before the @code{overrides construct} sequence
10684: in the example above.
1.7 pazsan 10685:
1.78 anton 10686: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10687: @subsubsection Object Interfaces
10688: @cindex object interfaces
10689: @cindex interfaces for objects
1.7 pazsan 10690:
1.78 anton 10691: In this model you can only call selectors defined in the class of the
10692: receiving objects or in one of its ancestors. If you call a selector
10693: with a receiving object that is not in one of these classes, the
10694: result is undefined; if you are lucky, the program crashes
10695: immediately.
1.7 pazsan 10696:
1.78 anton 10697: @cindex selectors common to hardly-related classes
10698: Now consider the case when you want to have a selector (or several)
10699: available in two classes: You would have to add the selector to a
10700: common ancestor class, in the worst case to @code{object}. You
10701: may not want to do this, e.g., because someone else is responsible for
10702: this ancestor class.
1.7 pazsan 10703:
1.78 anton 10704: The solution for this problem is interfaces. An interface is a
10705: collection of selectors. If a class implements an interface, the
10706: selectors become available to the class and its descendents. A class
10707: can implement an unlimited number of interfaces. For the problem
10708: discussed above, we would define an interface for the selector(s), and
10709: both classes would implement the interface.
1.7 pazsan 10710:
1.78 anton 10711: As an example, consider an interface @code{storage} for
10712: writing objects to disk and getting them back, and a class
10713: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10714:
1.78 anton 10715: @cindex @code{interface} usage
10716: @cindex @code{end-interface} usage
10717: @cindex @code{implementation} usage
10718: @example
10719: interface
10720: selector write ( file object -- )
10721: selector read1 ( file object -- )
10722: end-interface storage
1.13 pazsan 10723:
1.78 anton 10724: bar class
10725: storage implementation
1.13 pazsan 10726:
1.78 anton 10727: ... overrides write
10728: ... overrides read1
10729: ...
10730: end-class foo
10731: @end example
1.13 pazsan 10732:
1.78 anton 10733: @noindent
10734: (I would add a word @code{read} @i{( file -- object )} that uses
10735: @code{read1} internally, but that's beyond the point illustrated
10736: here.)
1.13 pazsan 10737:
1.78 anton 10738: Note that you cannot use @code{protected} in an interface; and
10739: of course you cannot define fields.
1.13 pazsan 10740:
1.78 anton 10741: In the Neon model, all selectors are available for all classes;
10742: therefore it does not need interfaces. The price you pay in this model
10743: is slower late binding, and therefore, added complexity to avoid late
10744: binding.
1.13 pazsan 10745:
1.78 anton 10746: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10747: @subsubsection @file{objects.fs} Implementation
10748: @cindex @file{objects.fs} implementation
1.13 pazsan 10749:
1.78 anton 10750: @cindex @code{object-map} discussion
10751: An object is a piece of memory, like one of the data structures
10752: described with @code{struct...end-struct}. It has a field
10753: @code{object-map} that points to the method map for the object's
10754: class.
1.13 pazsan 10755:
1.78 anton 10756: @cindex method map
10757: @cindex virtual function table
10758: The @emph{method map}@footnote{This is Self terminology; in C++
10759: terminology: virtual function table.} is an array that contains the
10760: execution tokens (@i{xt}s) of the methods for the object's class. Each
10761: selector contains an offset into a method map.
1.13 pazsan 10762:
1.78 anton 10763: @cindex @code{selector} implementation, class
10764: @code{selector} is a defining word that uses
10765: @code{CREATE} and @code{DOES>}. The body of the
10766: selector contains the offset; the @code{DOES>} action for a
10767: class selector is, basically:
1.8 pazsan 10768:
10769: @example
1.78 anton 10770: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10771: @end example
10772:
1.78 anton 10773: Since @code{object-map} is the first field of the object, it
10774: does not generate any code. As you can see, calling a selector has a
10775: small, constant cost.
1.26 crook 10776:
1.78 anton 10777: @cindex @code{current-interface} discussion
10778: @cindex class implementation and representation
10779: A class is basically a @code{struct} combined with a method
10780: map. During the class definition the alignment and size of the class
10781: are passed on the stack, just as with @code{struct}s, so
10782: @code{field} can also be used for defining class
10783: fields. However, passing more items on the stack would be
10784: inconvenient, so @code{class} builds a data structure in memory,
10785: which is accessed through the variable
10786: @code{current-interface}. After its definition is complete, the
10787: class is represented on the stack by a pointer (e.g., as parameter for
10788: a child class definition).
1.26 crook 10789:
1.78 anton 10790: A new class starts off with the alignment and size of its parent,
10791: and a copy of the parent's method map. Defining new fields extends the
10792: size and alignment; likewise, defining new selectors extends the
10793: method map. @code{overrides} just stores a new @i{xt} in the method
10794: map at the offset given by the selector.
1.13 pazsan 10795:
1.78 anton 10796: @cindex class binding, implementation
10797: Class binding just gets the @i{xt} at the offset given by the selector
10798: from the class's method map and @code{compile,}s (in the case of
10799: @code{[bind]}) it.
1.13 pazsan 10800:
1.78 anton 10801: @cindex @code{this} implementation
10802: @cindex @code{catch} and @code{this}
10803: @cindex @code{this} and @code{catch}
10804: I implemented @code{this} as a @code{value}. At the
10805: start of an @code{m:...;m} method the old @code{this} is
10806: stored to the return stack and restored at the end; and the object on
10807: the TOS is stored @code{TO this}. This technique has one
10808: disadvantage: If the user does not leave the method via
10809: @code{;m}, but via @code{throw} or @code{exit},
10810: @code{this} is not restored (and @code{exit} may
10811: crash). To deal with the @code{throw} problem, I have redefined
10812: @code{catch} to save and restore @code{this}; the same
10813: should be done with any word that can catch an exception. As for
10814: @code{exit}, I simply forbid it (as a replacement, there is
10815: @code{exitm}).
1.13 pazsan 10816:
1.78 anton 10817: @cindex @code{inst-var} implementation
10818: @code{inst-var} is just the same as @code{field}, with
10819: a different @code{DOES>} action:
1.13 pazsan 10820: @example
1.78 anton 10821: @@ this +
1.8 pazsan 10822: @end example
1.78 anton 10823: Similar for @code{inst-value}.
1.8 pazsan 10824:
1.78 anton 10825: @cindex class scoping implementation
10826: Each class also has a word list that contains the words defined with
10827: @code{inst-var} and @code{inst-value}, and its protected
10828: words. It also has a pointer to its parent. @code{class} pushes
10829: the word lists of the class and all its ancestors onto the search order stack,
10830: and @code{end-class} drops them.
1.20 pazsan 10831:
1.78 anton 10832: @cindex interface implementation
10833: An interface is like a class without fields, parent and protected
10834: words; i.e., it just has a method map. If a class implements an
10835: interface, its method map contains a pointer to the method map of the
10836: interface. The positive offsets in the map are reserved for class
10837: methods, therefore interface map pointers have negative
10838: offsets. Interfaces have offsets that are unique throughout the
10839: system, unlike class selectors, whose offsets are only unique for the
10840: classes where the selector is available (invokable).
1.20 pazsan 10841:
1.78 anton 10842: This structure means that interface selectors have to perform one
10843: indirection more than class selectors to find their method. Their body
10844: contains the interface map pointer offset in the class method map, and
10845: the method offset in the interface method map. The
10846: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10847:
10848: @example
1.78 anton 10849: ( object selector-body )
10850: 2dup selector-interface @@ ( object selector-body object interface-offset )
10851: swap object-map @@ + @@ ( object selector-body map )
10852: swap selector-offset @@ + @@ execute
1.20 pazsan 10853: @end example
10854:
1.78 anton 10855: where @code{object-map} and @code{selector-offset} are
10856: first fields and generate no code.
1.20 pazsan 10857:
1.78 anton 10858: As a concrete example, consider the following code:
1.20 pazsan 10859:
10860: @example
1.78 anton 10861: interface
10862: selector if1sel1
10863: selector if1sel2
10864: end-interface if1
1.20 pazsan 10865:
1.78 anton 10866: object class
10867: if1 implementation
10868: selector cl1sel1
10869: cell% inst-var cl1iv1
1.20 pazsan 10870:
1.78 anton 10871: ' m1 overrides construct
10872: ' m2 overrides if1sel1
10873: ' m3 overrides if1sel2
10874: ' m4 overrides cl1sel2
10875: end-class cl1
1.20 pazsan 10876:
1.78 anton 10877: create obj1 object dict-new drop
10878: create obj2 cl1 dict-new drop
10879: @end example
1.20 pazsan 10880:
1.78 anton 10881: The data structure created by this code (including the data structure
10882: for @code{object}) is shown in the
10883: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10884: @comment TODO add this diagram..
1.20 pazsan 10885:
1.78 anton 10886: @node Objects Glossary, , Objects Implementation, Objects
10887: @subsubsection @file{objects.fs} Glossary
10888: @cindex @file{objects.fs} Glossary
1.20 pazsan 10889:
10890:
1.78 anton 10891: doc---objects-bind
10892: doc---objects-<bind>
10893: doc---objects-bind'
10894: doc---objects-[bind]
10895: doc---objects-class
10896: doc---objects-class->map
10897: doc---objects-class-inst-size
10898: doc---objects-class-override!
1.79 anton 10899: doc---objects-class-previous
10900: doc---objects-class>order
1.78 anton 10901: doc---objects-construct
10902: doc---objects-current'
10903: doc---objects-[current]
10904: doc---objects-current-interface
10905: doc---objects-dict-new
10906: doc---objects-end-class
10907: doc---objects-end-class-noname
10908: doc---objects-end-interface
10909: doc---objects-end-interface-noname
10910: doc---objects-end-methods
10911: doc---objects-exitm
10912: doc---objects-heap-new
10913: doc---objects-implementation
10914: doc---objects-init-object
10915: doc---objects-inst-value
10916: doc---objects-inst-var
10917: doc---objects-interface
10918: doc---objects-m:
10919: doc---objects-:m
10920: doc---objects-;m
10921: doc---objects-method
10922: doc---objects-methods
10923: doc---objects-object
10924: doc---objects-overrides
10925: doc---objects-[parent]
10926: doc---objects-print
10927: doc---objects-protected
10928: doc---objects-public
10929: doc---objects-selector
10930: doc---objects-this
10931: doc---objects-<to-inst>
10932: doc---objects-[to-inst]
10933: doc---objects-to-this
10934: doc---objects-xt-new
1.20 pazsan 10935:
10936:
1.78 anton 10937: @c -------------------------------------------------------------
10938: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10939: @subsection The @file{oof.fs} model
10940: @cindex oof
10941: @cindex object-oriented programming
1.20 pazsan 10942:
1.78 anton 10943: @cindex @file{objects.fs}
10944: @cindex @file{oof.fs}
1.20 pazsan 10945:
1.78 anton 10946: This section describes the @file{oof.fs} package.
1.20 pazsan 10947:
1.78 anton 10948: The package described in this section has been used in bigFORTH since 1991, and
10949: used for two large applications: a chromatographic system used to
10950: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10951:
1.78 anton 10952: You can find a description (in German) of @file{oof.fs} in @cite{Object
10953: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10954: 10(2), 1994.
1.20 pazsan 10955:
1.78 anton 10956: @menu
10957: * Properties of the OOF model::
10958: * Basic OOF Usage::
10959: * The OOF base class::
10960: * Class Declaration::
10961: * Class Implementation::
10962: @end menu
1.20 pazsan 10963:
1.78 anton 10964: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10965: @subsubsection Properties of the @file{oof.fs} model
10966: @cindex @file{oof.fs} properties
1.20 pazsan 10967:
1.78 anton 10968: @itemize @bullet
10969: @item
10970: This model combines object oriented programming with information
10971: hiding. It helps you writing large application, where scoping is
10972: necessary, because it provides class-oriented scoping.
1.20 pazsan 10973:
1.78 anton 10974: @item
10975: Named objects, object pointers, and object arrays can be created,
10976: selector invocation uses the ``object selector'' syntax. Selector invocation
10977: to objects and/or selectors on the stack is a bit less convenient, but
10978: possible.
1.44 crook 10979:
1.78 anton 10980: @item
10981: Selector invocation and instance variable usage of the active object is
10982: straightforward, since both make use of the active object.
1.44 crook 10983:
1.78 anton 10984: @item
10985: Late binding is efficient and easy to use.
1.20 pazsan 10986:
1.78 anton 10987: @item
10988: State-smart objects parse selectors. However, extensibility is provided
10989: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10990:
1.78 anton 10991: @item
10992: An implementation in ANS Forth is available.
1.20 pazsan 10993:
1.78 anton 10994: @end itemize
1.23 crook 10995:
10996:
1.78 anton 10997: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10998: @subsubsection Basic @file{oof.fs} Usage
10999: @cindex @file{oof.fs} usage
1.23 crook 11000:
1.78 anton 11001: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11002:
1.78 anton 11003: You can define a class for graphical objects like this:
1.23 crook 11004:
1.78 anton 11005: @cindex @code{class} usage
11006: @cindex @code{class;} usage
11007: @cindex @code{method} usage
11008: @example
11009: object class graphical \ "object" is the parent class
1.139 pazsan 11010: method draw ( x y -- )
1.78 anton 11011: class;
11012: @end example
1.23 crook 11013:
1.78 anton 11014: This code defines a class @code{graphical} with an
11015: operation @code{draw}. We can perform the operation
11016: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11017:
1.78 anton 11018: @example
11019: 100 100 t-rex draw
11020: @end example
1.23 crook 11021:
1.78 anton 11022: @noindent
11023: where @code{t-rex} is an object or object pointer, created with e.g.
11024: @code{graphical : t-rex}.
1.23 crook 11025:
1.78 anton 11026: @cindex abstract class
11027: How do we create a graphical object? With the present definitions,
11028: we cannot create a useful graphical object. The class
11029: @code{graphical} describes graphical objects in general, but not
11030: any concrete graphical object type (C++ users would call it an
11031: @emph{abstract class}); e.g., there is no method for the selector
11032: @code{draw} in the class @code{graphical}.
1.23 crook 11033:
1.78 anton 11034: For concrete graphical objects, we define child classes of the
11035: class @code{graphical}, e.g.:
1.23 crook 11036:
1.78 anton 11037: @example
11038: graphical class circle \ "graphical" is the parent class
11039: cell var circle-radius
11040: how:
11041: : draw ( x y -- )
11042: circle-radius @@ draw-circle ;
1.23 crook 11043:
1.139 pazsan 11044: : init ( n-radius -- )
1.78 anton 11045: circle-radius ! ;
11046: class;
11047: @end example
1.1 anton 11048:
1.78 anton 11049: Here we define a class @code{circle} as a child of @code{graphical},
11050: with a field @code{circle-radius}; it defines new methods for the
11051: selectors @code{draw} and @code{init} (@code{init} is defined in
11052: @code{object}, the parent class of @code{graphical}).
1.1 anton 11053:
1.78 anton 11054: Now we can create a circle in the dictionary with:
1.1 anton 11055:
1.78 anton 11056: @example
11057: 50 circle : my-circle
11058: @end example
1.21 crook 11059:
1.78 anton 11060: @noindent
11061: @code{:} invokes @code{init}, thus initializing the field
11062: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11063: with:
1.1 anton 11064:
1.78 anton 11065: @example
11066: 100 100 my-circle draw
11067: @end example
1.1 anton 11068:
1.78 anton 11069: @cindex selector invocation, restrictions
11070: @cindex class definition, restrictions
11071: Note: You can only invoke a selector if the receiving object belongs to
11072: the class where the selector was defined or one of its descendents;
11073: e.g., you can invoke @code{draw} only for objects belonging to
11074: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11075: mechanism will check if you try to invoke a selector that is not
11076: defined in this class hierarchy, so you'll get an error at compilation
11077: time.
1.1 anton 11078:
11079:
1.78 anton 11080: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11081: @subsubsection The @file{oof.fs} base class
11082: @cindex @file{oof.fs} base class
1.1 anton 11083:
1.78 anton 11084: When you define a class, you have to specify a parent class. So how do
11085: you start defining classes? There is one class available from the start:
11086: @code{object}. You have to use it as ancestor for all classes. It is the
11087: only class that has no parent. Classes are also objects, except that
11088: they don't have instance variables; class manipulation such as
11089: inheritance or changing definitions of a class is handled through
11090: selectors of the class @code{object}.
1.1 anton 11091:
1.78 anton 11092: @code{object} provides a number of selectors:
1.1 anton 11093:
1.78 anton 11094: @itemize @bullet
11095: @item
11096: @code{class} for subclassing, @code{definitions} to add definitions
11097: later on, and @code{class?} to get type informations (is the class a
11098: subclass of the class passed on the stack?).
1.1 anton 11099:
1.78 anton 11100: doc---object-class
11101: doc---object-definitions
11102: doc---object-class?
1.1 anton 11103:
11104:
1.26 crook 11105: @item
1.78 anton 11106: @code{init} and @code{dispose} as constructor and destructor of the
11107: object. @code{init} is invocated after the object's memory is allocated,
11108: while @code{dispose} also handles deallocation. Thus if you redefine
11109: @code{dispose}, you have to call the parent's dispose with @code{super
11110: dispose}, too.
11111:
11112: doc---object-init
11113: doc---object-dispose
11114:
1.1 anton 11115:
1.26 crook 11116: @item
1.78 anton 11117: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11118: @code{[]} to create named and unnamed objects and object arrays or
11119: object pointers.
11120:
11121: doc---object-new
11122: doc---object-new[]
11123: doc---object-:
11124: doc---object-ptr
11125: doc---object-asptr
11126: doc---object-[]
11127:
1.1 anton 11128:
1.26 crook 11129: @item
1.78 anton 11130: @code{::} and @code{super} for explicit scoping. You should use explicit
11131: scoping only for super classes or classes with the same set of instance
11132: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11133:
1.78 anton 11134: doc---object-::
11135: doc---object-super
1.21 crook 11136:
11137:
1.26 crook 11138: @item
1.78 anton 11139: @code{self} to get the address of the object
1.21 crook 11140:
1.78 anton 11141: doc---object-self
1.21 crook 11142:
11143:
1.78 anton 11144: @item
11145: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11146: pointers and instance defers.
1.21 crook 11147:
1.78 anton 11148: doc---object-bind
11149: doc---object-bound
11150: doc---object-link
11151: doc---object-is
1.21 crook 11152:
11153:
1.78 anton 11154: @item
11155: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11156: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11157:
1.78 anton 11158: doc---object-'
11159: doc---object-postpone
1.21 crook 11160:
11161:
1.78 anton 11162: @item
11163: @code{with} and @code{endwith} to select the active object from the
11164: stack, and enable its scope. Using @code{with} and @code{endwith}
11165: also allows you to create code using selector @code{postpone} without being
11166: trapped by the state-smart objects.
1.21 crook 11167:
1.78 anton 11168: doc---object-with
11169: doc---object-endwith
1.21 crook 11170:
11171:
1.78 anton 11172: @end itemize
1.21 crook 11173:
1.78 anton 11174: @node Class Declaration, Class Implementation, The OOF base class, OOF
11175: @subsubsection Class Declaration
11176: @cindex class declaration
1.21 crook 11177:
1.78 anton 11178: @itemize @bullet
11179: @item
11180: Instance variables
1.21 crook 11181:
1.78 anton 11182: doc---oof-var
1.21 crook 11183:
11184:
1.78 anton 11185: @item
11186: Object pointers
1.21 crook 11187:
1.78 anton 11188: doc---oof-ptr
11189: doc---oof-asptr
1.21 crook 11190:
11191:
1.78 anton 11192: @item
11193: Instance defers
1.21 crook 11194:
1.78 anton 11195: doc---oof-defer
1.21 crook 11196:
11197:
1.78 anton 11198: @item
11199: Method selectors
1.21 crook 11200:
1.78 anton 11201: doc---oof-early
11202: doc---oof-method
1.21 crook 11203:
11204:
1.78 anton 11205: @item
11206: Class-wide variables
1.21 crook 11207:
1.78 anton 11208: doc---oof-static
1.21 crook 11209:
11210:
1.78 anton 11211: @item
11212: End declaration
1.1 anton 11213:
1.78 anton 11214: doc---oof-how:
11215: doc---oof-class;
1.21 crook 11216:
11217:
1.78 anton 11218: @end itemize
1.21 crook 11219:
1.78 anton 11220: @c -------------------------------------------------------------
11221: @node Class Implementation, , Class Declaration, OOF
11222: @subsubsection Class Implementation
11223: @cindex class implementation
1.21 crook 11224:
1.78 anton 11225: @c -------------------------------------------------------------
11226: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11227: @subsection The @file{mini-oof.fs} model
11228: @cindex mini-oof
1.21 crook 11229:
1.78 anton 11230: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11231: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11232: and reduces to the bare minimum of features. This is based on a posting
11233: of Bernd Paysan in comp.lang.forth.
1.21 crook 11234:
1.78 anton 11235: @menu
11236: * Basic Mini-OOF Usage::
11237: * Mini-OOF Example::
11238: * Mini-OOF Implementation::
11239: @end menu
1.21 crook 11240:
1.78 anton 11241: @c -------------------------------------------------------------
11242: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11243: @subsubsection Basic @file{mini-oof.fs} Usage
11244: @cindex mini-oof usage
1.21 crook 11245:
1.78 anton 11246: There is a base class (@code{class}, which allocates one cell for the
11247: object pointer) plus seven other words: to define a method, a variable,
11248: a class; to end a class, to resolve binding, to allocate an object and
11249: to compile a class method.
11250: @comment TODO better description of the last one
1.26 crook 11251:
1.21 crook 11252:
1.78 anton 11253: doc-object
11254: doc-method
11255: doc-var
11256: doc-class
11257: doc-end-class
11258: doc-defines
11259: doc-new
11260: doc-::
1.21 crook 11261:
11262:
11263:
1.78 anton 11264: @c -------------------------------------------------------------
11265: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11266: @subsubsection Mini-OOF Example
11267: @cindex mini-oof example
1.1 anton 11268:
1.78 anton 11269: A short example shows how to use this package. This example, in slightly
11270: extended form, is supplied as @file{moof-exm.fs}
11271: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11272:
1.26 crook 11273: @example
1.78 anton 11274: object class
11275: method init
11276: method draw
11277: end-class graphical
1.26 crook 11278: @end example
1.20 pazsan 11279:
1.78 anton 11280: This code defines a class @code{graphical} with an
11281: operation @code{draw}. We can perform the operation
11282: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11283:
1.26 crook 11284: @example
1.78 anton 11285: 100 100 t-rex draw
1.26 crook 11286: @end example
1.12 anton 11287:
1.78 anton 11288: where @code{t-rex} is an object or object pointer, created with e.g.
11289: @code{graphical new Constant t-rex}.
1.12 anton 11290:
1.78 anton 11291: For concrete graphical objects, we define child classes of the
11292: class @code{graphical}, e.g.:
1.12 anton 11293:
1.26 crook 11294: @example
11295: graphical class
1.78 anton 11296: cell var circle-radius
11297: end-class circle \ "graphical" is the parent class
1.12 anton 11298:
1.78 anton 11299: :noname ( x y -- )
11300: circle-radius @@ draw-circle ; circle defines draw
11301: :noname ( r -- )
11302: circle-radius ! ; circle defines init
11303: @end example
1.12 anton 11304:
1.78 anton 11305: There is no implicit init method, so we have to define one. The creation
11306: code of the object now has to call init explicitely.
1.21 crook 11307:
1.78 anton 11308: @example
11309: circle new Constant my-circle
11310: 50 my-circle init
1.12 anton 11311: @end example
11312:
1.78 anton 11313: It is also possible to add a function to create named objects with
11314: automatic call of @code{init}, given that all objects have @code{init}
11315: on the same place:
1.38 anton 11316:
1.78 anton 11317: @example
11318: : new: ( .. o "name" -- )
11319: new dup Constant init ;
11320: 80 circle new: large-circle
11321: @end example
1.12 anton 11322:
1.78 anton 11323: We can draw this new circle at (100,100) with:
1.12 anton 11324:
1.78 anton 11325: @example
11326: 100 100 my-circle draw
11327: @end example
1.12 anton 11328:
1.78 anton 11329: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11330: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11331:
1.78 anton 11332: Object-oriented systems with late binding typically use a
11333: ``vtable''-approach: the first variable in each object is a pointer to a
11334: table, which contains the methods as function pointers. The vtable
11335: may also contain other information.
1.12 anton 11336:
1.79 anton 11337: So first, let's declare selectors:
1.37 anton 11338:
11339: @example
1.79 anton 11340: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11341: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11342: @end example
1.37 anton 11343:
1.79 anton 11344: During selector declaration, the number of selectors and instance
11345: variables is on the stack (in address units). @code{method} creates one
11346: selector and increments the selector number. To execute a selector, it
1.78 anton 11347: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11348: executes the method @i{xt} stored there. Each selector takes the object
11349: it is invoked with as top of stack parameter; it passes the parameters
11350: (including the object) unchanged to the appropriate method which should
1.78 anton 11351: consume that object.
1.37 anton 11352:
1.78 anton 11353: Now, we also have to declare instance variables
1.37 anton 11354:
1.78 anton 11355: @example
1.79 anton 11356: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11357: DOES> ( o -- addr ) @@ + ;
1.37 anton 11358: @end example
11359:
1.78 anton 11360: As before, a word is created with the current offset. Instance
11361: variables can have different sizes (cells, floats, doubles, chars), so
11362: all we do is take the size and add it to the offset. If your machine
11363: has alignment restrictions, put the proper @code{aligned} or
11364: @code{faligned} before the variable, to adjust the variable
11365: offset. That's why it is on the top of stack.
1.37 anton 11366:
1.78 anton 11367: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11368:
1.78 anton 11369: @example
11370: Create object 1 cells , 2 cells ,
1.79 anton 11371: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11372: @end example
1.12 anton 11373:
1.78 anton 11374: For inheritance, the vtable of the parent object has to be
11375: copied when a new, derived class is declared. This gives all the
11376: methods of the parent class, which can be overridden, though.
1.12 anton 11377:
1.78 anton 11378: @example
1.79 anton 11379: : end-class ( class selectors vars "name" -- )
1.78 anton 11380: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11381: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11382: @end example
1.12 anton 11383:
1.78 anton 11384: The first line creates the vtable, initialized with
11385: @code{noop}s. The second line is the inheritance mechanism, it
11386: copies the xts from the parent vtable.
1.12 anton 11387:
1.78 anton 11388: We still have no way to define new methods, let's do that now:
1.12 anton 11389:
1.26 crook 11390: @example
1.79 anton 11391: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11392: @end example
1.12 anton 11393:
1.78 anton 11394: To allocate a new object, we need a word, too:
1.12 anton 11395:
1.78 anton 11396: @example
11397: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11398: @end example
11399:
1.78 anton 11400: Sometimes derived classes want to access the method of the
11401: parent object. There are two ways to achieve this with Mini-OOF:
11402: first, you could use named words, and second, you could look up the
11403: vtable of the parent object.
1.12 anton 11404:
1.78 anton 11405: @example
11406: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11407: @end example
1.12 anton 11408:
11409:
1.78 anton 11410: Nothing can be more confusing than a good example, so here is
11411: one. First let's declare a text object (called
11412: @code{button}), that stores text and position:
1.12 anton 11413:
1.78 anton 11414: @example
11415: object class
11416: cell var text
11417: cell var len
11418: cell var x
11419: cell var y
11420: method init
11421: method draw
11422: end-class button
11423: @end example
1.12 anton 11424:
1.78 anton 11425: @noindent
11426: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11427:
1.26 crook 11428: @example
1.78 anton 11429: :noname ( o -- )
11430: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11431: button defines draw
11432: :noname ( addr u o -- )
11433: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11434: button defines init
1.26 crook 11435: @end example
1.12 anton 11436:
1.78 anton 11437: @noindent
11438: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11439: new data and no new selectors:
1.78 anton 11440:
11441: @example
11442: button class
11443: end-class bold-button
1.12 anton 11444:
1.78 anton 11445: : bold 27 emit ." [1m" ;
11446: : normal 27 emit ." [0m" ;
11447: @end example
1.1 anton 11448:
1.78 anton 11449: @noindent
11450: The class @code{bold-button} has a different draw method to
11451: @code{button}, but the new method is defined in terms of the draw method
11452: for @code{button}:
1.20 pazsan 11453:
1.78 anton 11454: @example
11455: :noname bold [ button :: draw ] normal ; bold-button defines draw
11456: @end example
1.21 crook 11457:
1.78 anton 11458: @noindent
1.79 anton 11459: Finally, create two objects and apply selectors:
1.21 crook 11460:
1.26 crook 11461: @example
1.78 anton 11462: button new Constant foo
11463: s" thin foo" foo init
11464: page
11465: foo draw
11466: bold-button new Constant bar
11467: s" fat bar" bar init
11468: 1 bar y !
11469: bar draw
1.26 crook 11470: @end example
1.21 crook 11471:
11472:
1.78 anton 11473: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11474: @subsection Comparison with other object models
11475: @cindex comparison of object models
11476: @cindex object models, comparison
11477:
11478: Many object-oriented Forth extensions have been proposed (@cite{A survey
11479: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11480: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11481: relation of the object models described here to two well-known and two
11482: closely-related (by the use of method maps) models. Andras Zsoter
11483: helped us with this section.
11484:
11485: @cindex Neon model
11486: The most popular model currently seems to be the Neon model (see
11487: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11488: 1997) by Andrew McKewan) but this model has a number of limitations
11489: @footnote{A longer version of this critique can be
11490: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11491: Dimensions, May 1997) by Anton Ertl.}:
11492:
11493: @itemize @bullet
11494: @item
11495: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11496: to pass objects on the stack.
1.21 crook 11497:
1.78 anton 11498: @item
11499: It requires that the selector parses the input stream (at
1.79 anton 11500: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11501: hard to find.
1.21 crook 11502:
1.78 anton 11503: @item
1.79 anton 11504: It allows using every selector on every object; this eliminates the
11505: need for interfaces, but makes it harder to create efficient
11506: implementations.
1.78 anton 11507: @end itemize
1.21 crook 11508:
1.78 anton 11509: @cindex Pountain's object-oriented model
11510: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11511: Press, London, 1987) by Dick Pountain. However, it is not really about
11512: object-oriented programming, because it hardly deals with late
11513: binding. Instead, it focuses on features like information hiding and
11514: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11515:
1.78 anton 11516: @cindex Zsoter's object-oriented model
1.79 anton 11517: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11518: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11519: describes a model that makes heavy use of an active object (like
11520: @code{this} in @file{objects.fs}): The active object is not only used
11521: for accessing all fields, but also specifies the receiving object of
11522: every selector invocation; you have to change the active object
11523: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11524: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11525: the method entry point is unnecessary with Zsoter's model, because the
11526: receiving object is the active object already. On the other hand, the
11527: explicit change is absolutely necessary in that model, because otherwise
11528: no one could ever change the active object. An ANS Forth implementation
11529: of this model is available through
11530: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11531:
1.78 anton 11532: @cindex @file{oof.fs}, differences to other models
11533: The @file{oof.fs} model combines information hiding and overloading
11534: resolution (by keeping names in various word lists) with object-oriented
11535: programming. It sets the active object implicitly on method entry, but
11536: also allows explicit changing (with @code{>o...o>} or with
11537: @code{with...endwith}). It uses parsing and state-smart objects and
11538: classes for resolving overloading and for early binding: the object or
11539: class parses the selector and determines the method from this. If the
11540: selector is not parsed by an object or class, it performs a call to the
11541: selector for the active object (late binding), like Zsoter's model.
11542: Fields are always accessed through the active object. The big
11543: disadvantage of this model is the parsing and the state-smartness, which
11544: reduces extensibility and increases the opportunities for subtle bugs;
11545: essentially, you are only safe if you never tick or @code{postpone} an
11546: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11547:
1.78 anton 11548: @cindex @file{mini-oof.fs}, differences to other models
11549: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11550: version of the @file{objects.fs} model, but syntactically it is a
11551: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11552:
11553:
1.78 anton 11554: @c -------------------------------------------------------------
1.150 anton 11555: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11556: @section Programming Tools
11557: @cindex programming tools
1.21 crook 11558:
1.78 anton 11559: @c !! move this and assembler down below OO stuff.
1.21 crook 11560:
1.78 anton 11561: @menu
1.150 anton 11562: * Examining:: Data and Code.
11563: * Forgetting words:: Usually before reloading.
1.78 anton 11564: * Debugging:: Simple and quick.
11565: * Assertions:: Making your programs self-checking.
11566: * Singlestep Debugger:: Executing your program word by word.
11567: @end menu
1.21 crook 11568:
1.78 anton 11569: @node Examining, Forgetting words, Programming Tools, Programming Tools
11570: @subsection Examining data and code
11571: @cindex examining data and code
11572: @cindex data examination
11573: @cindex code examination
1.44 crook 11574:
1.78 anton 11575: The following words inspect the stack non-destructively:
1.21 crook 11576:
1.78 anton 11577: doc-.s
11578: doc-f.s
1.158 anton 11579: doc-maxdepth-.s
1.44 crook 11580:
1.78 anton 11581: There is a word @code{.r} but it does @i{not} display the return stack!
11582: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11583:
1.78 anton 11584: doc-depth
11585: doc-fdepth
11586: doc-clearstack
1.124 anton 11587: doc-clearstacks
1.21 crook 11588:
1.78 anton 11589: The following words inspect memory.
1.21 crook 11590:
1.78 anton 11591: doc-?
11592: doc-dump
1.21 crook 11593:
1.78 anton 11594: And finally, @code{see} allows to inspect code:
1.21 crook 11595:
1.78 anton 11596: doc-see
11597: doc-xt-see
1.111 anton 11598: doc-simple-see
11599: doc-simple-see-range
1.21 crook 11600:
1.78 anton 11601: @node Forgetting words, Debugging, Examining, Programming Tools
11602: @subsection Forgetting words
11603: @cindex words, forgetting
11604: @cindex forgeting words
1.21 crook 11605:
1.78 anton 11606: @c anton: other, maybe better places for this subsection: Defining Words;
11607: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11608:
1.78 anton 11609: Forth allows you to forget words (and everything that was alloted in the
11610: dictonary after them) in a LIFO manner.
1.21 crook 11611:
1.78 anton 11612: doc-marker
1.21 crook 11613:
1.78 anton 11614: The most common use of this feature is during progam development: when
11615: you change a source file, forget all the words it defined and load it
11616: again (since you also forget everything defined after the source file
11617: was loaded, you have to reload that, too). Note that effects like
11618: storing to variables and destroyed system words are not undone when you
11619: forget words. With a system like Gforth, that is fast enough at
11620: starting up and compiling, I find it more convenient to exit and restart
11621: Gforth, as this gives me a clean slate.
1.21 crook 11622:
1.78 anton 11623: Here's an example of using @code{marker} at the start of a source file
11624: that you are debugging; it ensures that you only ever have one copy of
11625: the file's definitions compiled at any time:
1.21 crook 11626:
1.78 anton 11627: @example
11628: [IFDEF] my-code
11629: my-code
11630: [ENDIF]
1.26 crook 11631:
1.78 anton 11632: marker my-code
11633: init-included-files
1.21 crook 11634:
1.78 anton 11635: \ .. definitions start here
11636: \ .
11637: \ .
11638: \ end
11639: @end example
1.21 crook 11640:
1.26 crook 11641:
1.78 anton 11642: @node Debugging, Assertions, Forgetting words, Programming Tools
11643: @subsection Debugging
11644: @cindex debugging
1.21 crook 11645:
1.78 anton 11646: Languages with a slow edit/compile/link/test development loop tend to
11647: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11648:
1.78 anton 11649: A much better (faster) way in fast-compiling languages is to add
11650: printing code at well-selected places, let the program run, look at
11651: the output, see where things went wrong, add more printing code, etc.,
11652: until the bug is found.
1.21 crook 11653:
1.78 anton 11654: The simple debugging aids provided in @file{debugs.fs}
11655: are meant to support this style of debugging.
1.21 crook 11656:
1.78 anton 11657: The word @code{~~} prints debugging information (by default the source
11658: location and the stack contents). It is easy to insert. If you use Emacs
11659: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11660: query-replace them with nothing). The deferred words
1.101 anton 11661: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11662: @code{~~}. The default source location output format works well with
11663: Emacs' compilation mode, so you can step through the program at the
11664: source level using @kbd{C-x `} (the advantage over a stepping debugger
11665: is that you can step in any direction and you know where the crash has
11666: happened or where the strange data has occurred).
1.21 crook 11667:
1.78 anton 11668: doc-~~
11669: doc-printdebugdata
1.101 anton 11670: doc-.debugline
1.21 crook 11671:
1.106 anton 11672: @cindex filenames in @code{~~} output
11673: @code{~~} (and assertions) will usually print the wrong file name if a
11674: marker is executed in the same file after their occurance. They will
11675: print @samp{*somewhere*} as file name if a marker is executed in the
11676: same file before their occurance.
11677:
11678:
1.78 anton 11679: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11680: @subsection Assertions
11681: @cindex assertions
1.21 crook 11682:
1.78 anton 11683: It is a good idea to make your programs self-checking, especially if you
11684: make an assumption that may become invalid during maintenance (for
11685: example, that a certain field of a data structure is never zero). Gforth
11686: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11687:
11688: @example
1.78 anton 11689: assert( @i{flag} )
1.26 crook 11690: @end example
11691:
1.78 anton 11692: The code between @code{assert(} and @code{)} should compute a flag, that
11693: should be true if everything is alright and false otherwise. It should
11694: not change anything else on the stack. The overall stack effect of the
11695: assertion is @code{( -- )}. E.g.
1.21 crook 11696:
1.26 crook 11697: @example
1.78 anton 11698: assert( 1 1 + 2 = ) \ what we learn in school
11699: assert( dup 0<> ) \ assert that the top of stack is not zero
11700: assert( false ) \ this code should not be reached
1.21 crook 11701: @end example
11702:
1.78 anton 11703: The need for assertions is different at different times. During
11704: debugging, we want more checking, in production we sometimes care more
11705: for speed. Therefore, assertions can be turned off, i.e., the assertion
11706: becomes a comment. Depending on the importance of an assertion and the
11707: time it takes to check it, you may want to turn off some assertions and
11708: keep others turned on. Gforth provides several levels of assertions for
11709: this purpose:
11710:
11711:
11712: doc-assert0(
11713: doc-assert1(
11714: doc-assert2(
11715: doc-assert3(
11716: doc-assert(
11717: doc-)
1.21 crook 11718:
11719:
1.78 anton 11720: The variable @code{assert-level} specifies the highest assertions that
11721: are turned on. I.e., at the default @code{assert-level} of one,
11722: @code{assert0(} and @code{assert1(} assertions perform checking, while
11723: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11724:
1.78 anton 11725: The value of @code{assert-level} is evaluated at compile-time, not at
11726: run-time. Therefore you cannot turn assertions on or off at run-time;
11727: you have to set the @code{assert-level} appropriately before compiling a
11728: piece of code. You can compile different pieces of code at different
11729: @code{assert-level}s (e.g., a trusted library at level 1 and
11730: newly-written code at level 3).
1.26 crook 11731:
11732:
1.78 anton 11733: doc-assert-level
1.26 crook 11734:
11735:
1.78 anton 11736: If an assertion fails, a message compatible with Emacs' compilation mode
11737: is produced and the execution is aborted (currently with @code{ABORT"}.
11738: If there is interest, we will introduce a special throw code. But if you
11739: intend to @code{catch} a specific condition, using @code{throw} is
11740: probably more appropriate than an assertion).
1.106 anton 11741:
11742: @cindex filenames in assertion output
11743: Assertions (and @code{~~}) will usually print the wrong file name if a
11744: marker is executed in the same file after their occurance. They will
11745: print @samp{*somewhere*} as file name if a marker is executed in the
11746: same file before their occurance.
1.44 crook 11747:
1.78 anton 11748: Definitions in ANS Forth for these assertion words are provided
11749: in @file{compat/assert.fs}.
1.26 crook 11750:
1.44 crook 11751:
1.78 anton 11752: @node Singlestep Debugger, , Assertions, Programming Tools
11753: @subsection Singlestep Debugger
11754: @cindex singlestep Debugger
11755: @cindex debugging Singlestep
1.44 crook 11756:
1.159 anton 11757: The singlestep debugger works only with the engine @code{gforth-ditc}.
1.112 anton 11758:
1.78 anton 11759: When you create a new word there's often the need to check whether it
11760: behaves correctly or not. You can do this by typing @code{dbg
11761: badword}. A debug session might look like this:
1.26 crook 11762:
1.78 anton 11763: @example
11764: : badword 0 DO i . LOOP ; ok
11765: 2 dbg badword
11766: : badword
11767: Scanning code...
1.44 crook 11768:
1.78 anton 11769: Nesting debugger ready!
1.44 crook 11770:
1.78 anton 11771: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11772: 400D4740 8049F68 DO -> [ 0 ]
11773: 400D4744 804A0C8 i -> [ 1 ] 00000
11774: 400D4748 400C5E60 . -> 0 [ 0 ]
11775: 400D474C 8049D0C LOOP -> [ 0 ]
11776: 400D4744 804A0C8 i -> [ 1 ] 00001
11777: 400D4748 400C5E60 . -> 1 [ 0 ]
11778: 400D474C 8049D0C LOOP -> [ 0 ]
11779: 400D4758 804B384 ; -> ok
11780: @end example
1.21 crook 11781:
1.78 anton 11782: Each line displayed is one step. You always have to hit return to
11783: execute the next word that is displayed. If you don't want to execute
11784: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11785: an overview what keys are available:
1.44 crook 11786:
1.78 anton 11787: @table @i
1.44 crook 11788:
1.78 anton 11789: @item @key{RET}
11790: Next; Execute the next word.
1.21 crook 11791:
1.78 anton 11792: @item n
11793: Nest; Single step through next word.
1.44 crook 11794:
1.78 anton 11795: @item u
11796: Unnest; Stop debugging and execute rest of word. If we got to this word
11797: with nest, continue debugging with the calling word.
1.44 crook 11798:
1.78 anton 11799: @item d
11800: Done; Stop debugging and execute rest.
1.21 crook 11801:
1.78 anton 11802: @item s
11803: Stop; Abort immediately.
1.44 crook 11804:
1.78 anton 11805: @end table
1.44 crook 11806:
1.78 anton 11807: Debugging large application with this mechanism is very difficult, because
11808: you have to nest very deeply into the program before the interesting part
11809: begins. This takes a lot of time.
1.26 crook 11810:
1.78 anton 11811: To do it more directly put a @code{BREAK:} command into your source code.
11812: When program execution reaches @code{BREAK:} the single step debugger is
11813: invoked and you have all the features described above.
1.44 crook 11814:
1.78 anton 11815: If you have more than one part to debug it is useful to know where the
11816: program has stopped at the moment. You can do this by the
11817: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11818: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11819:
1.26 crook 11820:
1.78 anton 11821: doc-dbg
11822: doc-break:
11823: doc-break"
1.44 crook 11824:
1.150 anton 11825: @c ------------------------------------------------------------
11826: @node C Interface, Assembler and Code Words, Programming Tools, Words
11827: @section C Interface
11828: @cindex C interface
11829: @cindex foreign language interface
11830: @cindex interface to C functions
11831:
1.178 ! anton 11832: Note that the C interface is not yet complete; callbacks are missing,
! 11833: as well as a way of declaring structs, unions, and their fields.
1.150 anton 11834:
11835: @menu
11836: * Calling C Functions::
11837: * Declaring C Functions::
11838: * Callbacks::
1.178 ! anton 11839: * C interface internals::
1.155 anton 11840: * Low-Level C Interface Words::
1.150 anton 11841: @end menu
11842:
1.151 pazsan 11843: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 11844: @subsection Calling C functions
1.155 anton 11845: @cindex C functions, calls to
11846: @cindex calling C functions
1.150 anton 11847:
1.151 pazsan 11848: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 11849: can call it as follows: You push the arguments on the stack(s), and
11850: then call the word for the C function. The arguments have to be
11851: pushed in the same order as the arguments appear in the C
11852: documentation (i.e., the first argument is deepest on the stack).
11853: Integer and pointer arguments have to be pushed on the data stack,
11854: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 11855: by the called C function.
1.150 anton 11856:
1.155 anton 11857: On returning from the C function, the return value, if any, resides on
11858: the appropriate stack: an integer return value is pushed on the data
11859: stack, an FP return value on the FP stack, and a void return value
11860: results in not pushing anything. Note that most C functions have a
11861: return value, even if that is often not used in C; in Forth, you have
11862: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 11863:
1.177 anton 11864: The C interface automatically converts between the C type and the
11865: Forth type as necessary, on a best-effort basis (in some cases, there
11866: may be some loss).
1.150 anton 11867:
11868: As an example, consider the POSIX function @code{lseek()}:
11869:
11870: @example
11871: off_t lseek(int fd, off_t offset, int whence);
11872: @end example
11873:
11874: This function takes three integer arguments, and returns an integer
11875: argument, so a Forth call for setting the current file offset to the
11876: start of the file could look like this:
11877:
11878: @example
11879: fd @@ 0 SEEK_SET lseek -1 = if
11880: ... \ error handling
11881: then
11882: @end example
11883:
11884: You might be worried that an @code{off_t} does not fit into a cell, so
11885: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 11886: of the return values. In that case, in your declaration of the
11887: function (@pxref{Declaring C Functions}) you should declare it to use
11888: double-cells for the off_t argument and return value, and maybe give
11889: the resulting Forth word a different name, like @code{dlseek}; the
11890: result could be called like this:
1.150 anton 11891:
11892: @example
11893: fd @@ 0. SEEK_SET dlseek -1. d= if
11894: ... \ error handling
11895: then
11896: @end example
11897:
11898: Passing and returning structs or unions is currently not supported by
11899: our interface@footnote{If you know the calling convention of your C
11900: compiler, you usually can call such functions in some way, but that
11901: way is usually not portable between platforms, and sometimes not even
11902: between C compilers.}.
11903:
1.177 anton 11904: Calling functions with a variable number of arguments (@emph{variadic}
11905: functions, e.g., @code{printf()}) is only supported by having you
11906: declare one function-calling word for each argument pattern, and
11907: calling the appropriate word for the desired pattern.
11908:
1.150 anton 11909:
1.155 anton 11910:
1.151 pazsan 11911: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
1.150 anton 11912: @subsection Declaring C Functions
1.155 anton 11913: @cindex C functions, declarations
11914: @cindex declaring C functions
1.150 anton 11915:
11916: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 11917: it. The declaration consists of two parts:
11918:
11919: @table @b
11920:
11921: @item The C part
11922: is the C declaration of the function, or more typically, a C-style
11923: @code{#include} of a file that contains the declaration of the C
11924: function.
11925:
11926: @item The Forth part
11927: declares the Forth types of the parameters and the Forth word name
11928: corresponding to the C function.
11929:
11930: @end table
11931:
11932: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
11933: declarations are:
11934:
11935: @example
11936: \c #define _FILE_OFFSET_BITS 64
11937: \c #include <sys/types.h>
11938: \c #include <unistd.h>
11939: c-function lseek lseek n n n -- n
11940: c-function dlseek lseek n d n -- d
11941: @end example
11942:
1.178 ! anton 11943: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 11944: of the line is ordinary C code. You can use as many lines of C
11945: declarations as you like, and they are visible for all further
11946: function declarations.
11947:
11948: The Forth part declares each interface word with @code{c-function},
11949: followed by the Forth name of the word, the C name of the called
11950: function, and the stack effect of the word. The stack effect contains
1.178 ! anton 11951: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 11952: exactly one type for the return value. The possible types are:
11953:
11954: @table @code
11955:
11956: @item n
11957: single-cell integer
11958:
11959: @item a
11960: address (single-cell)
11961:
11962: @item d
11963: double-cell integer
11964:
11965: @item r
11966: floating-point value
11967:
11968: @item func
11969: C function pointer
11970:
11971: @item void
11972: no value (used as return type for void functions)
11973:
11974: @end table
11975:
11976: @cindex variadic C functions
11977:
11978: To deal with variadic C functions, you can declare one Forth word for
11979: every pattern you want to use, e.g.:
11980:
11981: @example
11982: \c #include <stdio.h>
11983: c-function printf-nr printf a n r -- n
11984: c-function printf-rn printf a r n -- n
11985: @end example
11986:
11987: Note that with C functions declared as variadic (or if you don't
11988: provide a prototype), the C interface has no C type to convert to, so
11989: no automatic conversion happens, which may lead to portability
11990: problems in some cases. In such cases you can perform the conversion
11991: explicitly on the C level, e.g., as follows:
11992:
11993: @example
1.178 ! anton 11994: \c #define printfll(s,ll) printf(s,(long long)ll)
! 11995: c-function printfll printfll a n -- n
1.177 anton 11996: @end example
11997:
11998: Here, instead of calling @code{printf()} directly, we define a macro
1.178 ! anton 11999: that casts (converts) the Forth single-cell integer into a
! 12000: C @code{long long} before calling @code{printf()}.
1.177 anton 12001:
12002: doc-\c
12003: doc-c-function
12004:
12005: In order to work, this C interface invokes GCC at run-time and uses
1.178 ! anton 12006: dynamic linking. If these features are not available, there are
! 12007: other, less convenient and less portable C interfaces in @file{lib.fs}
! 12008: and @file{oldlib.fs}. These interfaces are mostly undocumented and
! 12009: mostly incompatible with each other and with the documented C
! 12010: interface; you can find some examples for the @file{lib.fs} interface
! 12011: in @file{lib.fs}.
1.177 anton 12012:
12013:
12014:
1.150 anton 12015:
1.155 anton 12016:
1.178 ! anton 12017: @node Callbacks, C interface internals, Declaring C Functions, C Interface
1.150 anton 12018: @subsection Callbacks
1.155 anton 12019: @cindex Callback functions written in Forth
12020: @cindex C function pointers to Forth words
12021:
1.177 anton 12022: Callbacks are not yet supported by the documented C interface. You
12023: can use the undocumented @file{lib.fs} interface for callbacks.
12024:
1.155 anton 12025: In some cases you have to pass a function pointer to a C function,
12026: i.e., the library wants to call back to your application (and the
12027: pointed-to function is called a callback function). You can pass the
12028: address of an existing C function (that you get with @code{lib-sym},
12029: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12030: function, you probably want to define the function as a Forth word.
12031:
12032: @c I don't understand the existing callback interface from the example - anton
12033:
1.165 anton 12034:
12035: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12036: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12037: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12038: @c > > C-Funktionsadresse auf dem TOS).
12039: @c >
12040: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12041: @c > gesehen habe, wozu das gut ist.
12042: @c
12043: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12044: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12045: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12046: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12047: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12048: @c demselben Prototyp.
12049:
12050:
1.178 ! anton 12051: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12052: @subsection How the C interface works
12053:
12054: The documented C interface works by generating a C code out of the
12055: declarations.
12056:
12057: In particular, for every Forth word declared with @code{c-function},
12058: it generates a wrapper function in C that takes the Forth data from
12059: the Forth stacks, and calls the target C function with these data as
12060: arguments. The C compiler then performs an implicit conversion
12061: between the Forth type from the stack, and the C type for the
12062: parameter, which is given by the C function prototype. After the C
12063: function returns, the return value is likewise implicitly converted to
12064: a Forth type and written back on the stack.
12065:
12066: The @code{\c} lines are literally included in the C code (but without
12067: the @code{\c}), and provide the necessary declarations so that the C
12068: compiler knows the C types and has enough information to perform the
12069: conversion.
12070:
12071: These wrapper functions are eventually compiled and dynamically linked
12072: into Gforth, and then they can be called.
12073:
12074:
1.178 ! anton 12075: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12076: @subsection Low-Level C Interface Words
1.44 crook 12077:
1.155 anton 12078: doc-open-lib
12079: doc-lib-sym
1.177 anton 12080: doc-call-c
1.26 crook 12081:
1.78 anton 12082: @c -------------------------------------------------------------
1.150 anton 12083: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12084: @section Assembler and Code Words
12085: @cindex assembler
12086: @cindex code words
1.44 crook 12087:
1.78 anton 12088: @menu
12089: * Code and ;code::
12090: * Common Assembler:: Assembler Syntax
12091: * Common Disassembler::
12092: * 386 Assembler:: Deviations and special cases
12093: * Alpha Assembler:: Deviations and special cases
12094: * MIPS assembler:: Deviations and special cases
1.161 anton 12095: * PowerPC assembler:: Deviations and special cases
1.78 anton 12096: * Other assemblers:: How to write them
12097: @end menu
1.21 crook 12098:
1.78 anton 12099: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12100: @subsection @code{Code} and @code{;code}
1.26 crook 12101:
1.78 anton 12102: Gforth provides some words for defining primitives (words written in
12103: machine code), and for defining the machine-code equivalent of
12104: @code{DOES>}-based defining words. However, the machine-independent
12105: nature of Gforth poses a few problems: First of all, Gforth runs on
12106: several architectures, so it can provide no standard assembler. What's
12107: worse is that the register allocation not only depends on the processor,
12108: but also on the @code{gcc} version and options used.
1.44 crook 12109:
1.78 anton 12110: The words that Gforth offers encapsulate some system dependences (e.g.,
12111: the header structure), so a system-independent assembler may be used in
12112: Gforth. If you do not have an assembler, you can compile machine code
12113: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12114: because these words emit stuff in @i{data} space; it works because
12115: Gforth has unified code/data spaces. Assembler isn't likely to be
12116: portable anyway.}.
1.21 crook 12117:
1.44 crook 12118:
1.78 anton 12119: doc-assembler
12120: doc-init-asm
12121: doc-code
12122: doc-end-code
12123: doc-;code
12124: doc-flush-icache
1.44 crook 12125:
1.21 crook 12126:
1.78 anton 12127: If @code{flush-icache} does not work correctly, @code{code} words
12128: etc. will not work (reliably), either.
1.44 crook 12129:
1.78 anton 12130: The typical usage of these @code{code} words can be shown most easily by
12131: analogy to the equivalent high-level defining words:
1.44 crook 12132:
1.78 anton 12133: @example
12134: : foo code foo
12135: <high-level Forth words> <assembler>
12136: ; end-code
12137:
12138: : bar : bar
12139: <high-level Forth words> <high-level Forth words>
12140: CREATE CREATE
12141: <high-level Forth words> <high-level Forth words>
12142: DOES> ;code
12143: <high-level Forth words> <assembler>
12144: ; end-code
12145: @end example
1.21 crook 12146:
1.78 anton 12147: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12148:
1.78 anton 12149: @cindex registers of the inner interpreter
12150: In the assembly code you will want to refer to the inner interpreter's
12151: registers (e.g., the data stack pointer) and you may want to use other
12152: registers for temporary storage. Unfortunately, the register allocation
12153: is installation-dependent.
1.44 crook 12154:
1.78 anton 12155: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12156: (return stack pointer) may be in different places in @code{gforth} and
12157: @code{gforth-fast}, or different installations. This means that you
12158: cannot write a @code{NEXT} routine that works reliably on both versions
12159: or different installations; so for doing @code{NEXT}, I recommend
12160: jumping to @code{' noop >code-address}, which contains nothing but a
12161: @code{NEXT}.
1.21 crook 12162:
1.78 anton 12163: For general accesses to the inner interpreter's registers, the easiest
12164: solution is to use explicit register declarations (@pxref{Explicit Reg
12165: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12166: all of the inner interpreter's registers: You have to compile Gforth
12167: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12168: the appropriate declarations must be present in the @code{machine.h}
12169: file (see @code{mips.h} for an example; you can find a full list of all
12170: declarable register symbols with @code{grep register engine.c}). If you
12171: give explicit registers to all variables that are declared at the
12172: beginning of @code{engine()}, you should be able to use the other
12173: caller-saved registers for temporary storage. Alternatively, you can use
12174: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12175: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12176: reserve a register (however, this restriction on register allocation may
12177: slow Gforth significantly).
1.44 crook 12178:
1.78 anton 12179: If this solution is not viable (e.g., because @code{gcc} does not allow
12180: you to explicitly declare all the registers you need), you have to find
12181: out by looking at the code where the inner interpreter's registers
12182: reside and which registers can be used for temporary storage. You can
12183: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12184:
1.78 anton 12185: In any case, it is good practice to abstract your assembly code from the
12186: actual register allocation. E.g., if the data stack pointer resides in
12187: register @code{$17}, create an alias for this register called @code{sp},
12188: and use that in your assembly code.
1.21 crook 12189:
1.78 anton 12190: @cindex code words, portable
12191: Another option for implementing normal and defining words efficiently
12192: is to add the desired functionality to the source of Gforth. For normal
12193: words you just have to edit @file{primitives} (@pxref{Automatic
12194: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12195: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12196: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12197:
1.78 anton 12198: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12199: @subsection Common Assembler
1.44 crook 12200:
1.78 anton 12201: The assemblers in Gforth generally use a postfix syntax, i.e., the
12202: instruction name follows the operands.
1.21 crook 12203:
1.78 anton 12204: The operands are passed in the usual order (the same that is used in the
12205: manual of the architecture). Since they all are Forth words, they have
12206: to be separated by spaces; you can also use Forth words to compute the
12207: operands.
1.44 crook 12208:
1.78 anton 12209: The instruction names usually end with a @code{,}. This makes it easier
12210: to visually separate instructions if you put several of them on one
12211: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12212:
1.78 anton 12213: Registers are usually specified by number; e.g., (decimal) @code{11}
12214: specifies registers R11 and F11 on the Alpha architecture (which one,
12215: depends on the instruction). The usual names are also available, e.g.,
12216: @code{s2} for R11 on Alpha.
1.21 crook 12217:
1.78 anton 12218: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12219: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12220: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12221: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12222: conditions are specified in a way specific to each assembler.
1.1 anton 12223:
1.78 anton 12224: Note that the register assignments of the Gforth engine can change
12225: between Gforth versions, or even between different compilations of the
12226: same Gforth version (e.g., if you use a different GCC version). So if
12227: you want to refer to Gforth's registers (e.g., the stack pointer or
12228: TOS), I recommend defining your own words for refering to these
12229: registers, and using them later on; then you can easily adapt to a
12230: changed register assignment. The stability of the register assignment
12231: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12232:
1.100 anton 12233: The most common use of these registers is to dispatch to the next word
12234: (the @code{next} routine). A portable way to do this is to jump to
12235: @code{' noop >code-address} (of course, this is less efficient than
12236: integrating the @code{next} code and scheduling it well).
1.1 anton 12237:
1.96 anton 12238: Another difference between Gforth version is that the top of stack is
12239: kept in memory in @code{gforth} and, on most platforms, in a register in
12240: @code{gforth-fast}.
12241:
1.78 anton 12242: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12243: @subsection Common Disassembler
1.127 anton 12244: @cindex disassembler, general
12245: @cindex gdb disassembler
1.1 anton 12246:
1.78 anton 12247: You can disassemble a @code{code} word with @code{see}
12248: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12249:
1.127 anton 12250: doc-discode
1.44 crook 12251:
1.127 anton 12252: There are two kinds of disassembler for Gforth: The Forth disassembler
12253: (available on some CPUs) and the gdb disassembler (available on
12254: platforms with @command{gdb} and @command{mktemp}). If both are
12255: available, the Forth disassembler is used by default. If you prefer
12256: the gdb disassembler, say
12257:
12258: @example
12259: ' disasm-gdb is discode
12260: @end example
12261:
12262: If neither is available, @code{discode} performs @code{dump}.
12263:
12264: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12265: assembler (i.e., same syntax, etc.). It also includes additional
12266: information in comments. In particular, the address of the instruction
12267: is given in a comment before the instruction.
1.1 anton 12268:
1.127 anton 12269: The gdb disassembler produces output in the same format as the gdb
12270: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12271: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12272: the 386 and AMD64 architectures).
12273:
1.78 anton 12274: @code{See} may display more or less than the actual code of the word,
12275: because the recognition of the end of the code is unreliable. You can
1.127 anton 12276: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12277: the code word is not immediately followed by a named word. If you have
1.116 anton 12278: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12279: to ensure that the end is recognized.
1.21 crook 12280:
1.78 anton 12281: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12282: @subsection 386 Assembler
1.44 crook 12283:
1.78 anton 12284: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12285: available under GPL, and originally part of bigFORTH.
1.21 crook 12286:
1.78 anton 12287: The 386 disassembler included in Gforth was written by Andrew McKewan
12288: and is in the public domain.
1.21 crook 12289:
1.91 anton 12290: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12291:
1.78 anton 12292: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12293:
1.78 anton 12294: The assembler includes all instruction of the Athlon, i.e. 486 core
12295: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12296: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12297: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12298:
1.78 anton 12299: There are several prefixes to switch between different operation sizes,
12300: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12301: double-word accesses. Addressing modes can be switched with @code{.wa}
12302: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12303: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12304:
1.78 anton 12305: For floating point operations, the prefixes are @code{.fs} (IEEE
12306: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12307: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12308:
1.78 anton 12309: The MMX opcodes don't have size prefixes, they are spelled out like in
12310: the Intel assembler. Instead of move from and to memory, there are
12311: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12312:
1.78 anton 12313: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12314: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12315: e.g., @code{3 #}. Here are some examples of addressing modes in various
12316: syntaxes:
1.21 crook 12317:
1.26 crook 12318: @example
1.91 anton 12319: Gforth Intel (NASM) AT&T (gas) Name
12320: .w ax ax %ax register (16 bit)
12321: ax eax %eax register (32 bit)
12322: 3 # offset 3 $3 immediate
12323: 1000 #) byte ptr 1000 1000 displacement
12324: bx ) [ebx] (%ebx) base
12325: 100 di d) 100[edi] 100(%edi) base+displacement
12326: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12327: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12328: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12329: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12330: @end example
12331:
12332: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12333: @code{DI)} to enforce 32-bit displacement fields (useful for
12334: later patching).
1.21 crook 12335:
1.78 anton 12336: Some example of instructions are:
1.1 anton 12337:
12338: @example
1.78 anton 12339: ax bx mov \ move ebx,eax
12340: 3 # ax mov \ mov eax,3
1.137 pazsan 12341: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12342: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12343: .w ax bx mov \ mov bx,ax
1.1 anton 12344: @end example
12345:
1.78 anton 12346: The following forms are supported for binary instructions:
1.1 anton 12347:
12348: @example
1.78 anton 12349: <reg> <reg> <inst>
12350: <n> # <reg> <inst>
12351: <mem> <reg> <inst>
12352: <reg> <mem> <inst>
1.136 pazsan 12353: <n> # <mem> <inst>
1.1 anton 12354: @end example
12355:
1.136 pazsan 12356: The shift/rotate syntax is:
1.1 anton 12357:
1.26 crook 12358: @example
1.78 anton 12359: <reg/mem> 1 # shl \ shortens to shift without immediate
12360: <reg/mem> 4 # shl
12361: <reg/mem> cl shl
1.26 crook 12362: @end example
1.1 anton 12363:
1.78 anton 12364: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12365: the byte version.
1.1 anton 12366:
1.78 anton 12367: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12368: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12369: pc < >= <= >}. (Note that most of these words shadow some Forth words
12370: when @code{assembler} is in front of @code{forth} in the search path,
12371: e.g., in @code{code} words). Currently the control structure words use
12372: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12373: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12374:
1.78 anton 12375: Here is an example of a @code{code} word (assumes that the stack pointer
12376: is in esi and the TOS is in ebx):
1.21 crook 12377:
1.26 crook 12378: @example
1.78 anton 12379: code my+ ( n1 n2 -- n )
12380: 4 si D) bx add
12381: 4 # si add
12382: Next
12383: end-code
1.26 crook 12384: @end example
1.21 crook 12385:
1.161 anton 12386:
1.78 anton 12387: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12388: @subsection Alpha Assembler
1.21 crook 12389:
1.78 anton 12390: The Alpha assembler and disassembler were originally written by Bernd
12391: Thallner.
1.26 crook 12392:
1.78 anton 12393: The register names @code{a0}--@code{a5} are not available to avoid
12394: shadowing hex numbers.
1.2 jwilke 12395:
1.78 anton 12396: Immediate forms of arithmetic instructions are distinguished by a
12397: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12398: does not count as arithmetic instruction).
1.2 jwilke 12399:
1.78 anton 12400: You have to specify all operands to an instruction, even those that
12401: other assemblers consider optional, e.g., the destination register for
12402: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12403:
1.78 anton 12404: You can specify conditions for @code{if,} by removing the first @code{b}
12405: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12406:
1.26 crook 12407: @example
1.78 anton 12408: 11 fgt if, \ if F11>0e
12409: ...
12410: endif,
1.26 crook 12411: @end example
1.2 jwilke 12412:
1.78 anton 12413: @code{fbgt,} gives @code{fgt}.
12414:
1.161 anton 12415: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12416: @subsection MIPS assembler
1.2 jwilke 12417:
1.78 anton 12418: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12419:
1.78 anton 12420: Currently the assembler and disassembler only cover the MIPS-I
12421: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12422:
1.78 anton 12423: The register names @code{$a0}--@code{$a3} are not available to avoid
12424: shadowing hex numbers.
1.2 jwilke 12425:
1.78 anton 12426: Because there is no way to distinguish registers from immediate values,
12427: you have to explicitly use the immediate forms of instructions, i.e.,
12428: @code{addiu,}, not just @code{addu,} (@command{as} does this
12429: implicitly).
1.2 jwilke 12430:
1.78 anton 12431: If the architecture manual specifies several formats for the instruction
12432: (e.g., for @code{jalr,}), you usually have to use the one with more
12433: arguments (i.e., two for @code{jalr,}). When in doubt, see
12434: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12435:
1.78 anton 12436: Branches and jumps in the MIPS architecture have a delay slot. You have
12437: to fill it yourself (the simplest way is to use @code{nop,}), the
12438: assembler does not do it for you (unlike @command{as}). Even
12439: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12440: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12441: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12442:
1.78 anton 12443: Note that you must not put branches, jumps, or @code{li,} into the delay
12444: slot: @code{li,} may expand to several instructions, and control flow
12445: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12446:
1.78 anton 12447: For branches the argument specifying the target is a relative address;
12448: You have to add the address of the delay slot to get the absolute
12449: address.
1.1 anton 12450:
1.78 anton 12451: The MIPS architecture also has load delay slots and restrictions on
12452: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12453: yourself to satisfy these restrictions, the assembler does not do it for
12454: you.
1.1 anton 12455:
1.78 anton 12456: You can specify the conditions for @code{if,} etc. by taking a
12457: conditional branch and leaving away the @code{b} at the start and the
12458: @code{,} at the end. E.g.,
1.1 anton 12459:
1.26 crook 12460: @example
1.78 anton 12461: 4 5 eq if,
12462: ... \ do something if $4 equals $5
12463: then,
1.26 crook 12464: @end example
1.1 anton 12465:
1.161 anton 12466:
12467: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
12468: @subsection PowerPC assembler
12469:
1.162 anton 12470: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12471: Revucky.
12472:
1.162 anton 12473: This assembler does not follow the convention of ending mnemonic names
12474: with a ``,'', so some mnemonic names shadow regular Forth words (in
12475: particular: @code{and or xor fabs}); so if you want to use the Forth
12476: words, you have to make them visible first, e.g., with @code{also
12477: forth}.
12478:
1.161 anton 12479: Registers are referred to by their number, e.g., @code{9} means the
12480: integer register 9 or the FP register 9 (depending on the
12481: instruction).
12482:
12483: Because there is no way to distinguish registers from immediate values,
12484: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12485: @code{addi,}, not just @code{add,}.
1.161 anton 12486:
1.162 anton 12487: The assembler and disassembler usually support the most general form
1.161 anton 12488: of an instruction, but usually not the shorter forms (especially for
12489: branches).
12490:
12491:
12492:
12493: @node Other assemblers, , PowerPC assembler, Assembler and Code Words
1.78 anton 12494: @subsection Other assemblers
12495:
12496: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12497: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12498: an assembler already. If you are writing them from scratch, please use
12499: a similar syntax style as the one we use (i.e., postfix, commas at the
12500: end of the instruction names, @pxref{Common Assembler}); make the output
12501: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12502: similar to the style we used.
12503:
12504: Hints on implementation: The most important part is to have a good test
12505: suite that contains all instructions. Once you have that, the rest is
12506: easy. For actual coding you can take a look at
12507: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12508: the assembler and disassembler, avoiding redundancy and some potential
12509: bugs. You can also look at that file (and @pxref{Advanced does> usage
12510: example}) to get ideas how to factor a disassembler.
12511:
12512: Start with the disassembler, because it's easier to reuse data from the
12513: disassembler for the assembler than the other way round.
1.1 anton 12514:
1.78 anton 12515: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12516: how simple it can be.
1.1 anton 12517:
1.161 anton 12518:
12519:
12520:
1.78 anton 12521: @c -------------------------------------------------------------
12522: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12523: @section Threading Words
12524: @cindex threading words
1.1 anton 12525:
1.78 anton 12526: @cindex code address
12527: These words provide access to code addresses and other threading stuff
12528: in Gforth (and, possibly, other interpretive Forths). It more or less
12529: abstracts away the differences between direct and indirect threading
12530: (and, for direct threading, the machine dependences). However, at
12531: present this wordset is still incomplete. It is also pretty low-level;
12532: some day it will hopefully be made unnecessary by an internals wordset
12533: that abstracts implementation details away completely.
1.1 anton 12534:
1.78 anton 12535: The terminology used here stems from indirect threaded Forth systems; in
12536: such a system, the XT of a word is represented by the CFA (code field
12537: address) of a word; the CFA points to a cell that contains the code
12538: address. The code address is the address of some machine code that
12539: performs the run-time action of invoking the word (e.g., the
12540: @code{dovar:} routine pushes the address of the body of the word (a
12541: variable) on the stack
12542: ).
1.1 anton 12543:
1.78 anton 12544: @cindex code address
12545: @cindex code field address
12546: In an indirect threaded Forth, you can get the code address of @i{name}
12547: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12548: >code-address}, independent of the threading method.
1.1 anton 12549:
1.78 anton 12550: doc-threading-method
12551: doc->code-address
12552: doc-code-address!
1.1 anton 12553:
1.78 anton 12554: @cindex @code{does>}-handler
12555: @cindex @code{does>}-code
12556: For a word defined with @code{DOES>}, the code address usually points to
12557: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12558: routine (in Gforth on some platforms, it can also point to the dodoes
12559: routine itself). What you are typically interested in, though, is
12560: whether a word is a @code{DOES>}-defined word, and what Forth code it
12561: executes; @code{>does-code} tells you that.
1.1 anton 12562:
1.78 anton 12563: doc->does-code
1.1 anton 12564:
1.78 anton 12565: To create a @code{DOES>}-defined word with the following basic words,
12566: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12567: @code{/does-handler} aus behind you have to place your executable Forth
12568: code. Finally you have to create a word and modify its behaviour with
12569: @code{does-handler!}.
1.1 anton 12570:
1.78 anton 12571: doc-does-code!
12572: doc-does-handler!
12573: doc-/does-handler
1.1 anton 12574:
1.78 anton 12575: The code addresses produced by various defining words are produced by
12576: the following words:
1.1 anton 12577:
1.78 anton 12578: doc-docol:
12579: doc-docon:
12580: doc-dovar:
12581: doc-douser:
12582: doc-dodefer:
12583: doc-dofield:
1.1 anton 12584:
1.99 anton 12585: @cindex definer
12586: The following two words generalize @code{>code-address},
12587: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12588:
12589: doc->definer
12590: doc-definer!
12591:
1.26 crook 12592: @c -------------------------------------------------------------
1.78 anton 12593: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12594: @section Passing Commands to the Operating System
12595: @cindex operating system - passing commands
12596: @cindex shell commands
12597:
12598: Gforth allows you to pass an arbitrary string to the host operating
12599: system shell (if such a thing exists) for execution.
12600:
12601: doc-sh
12602: doc-system
12603: doc-$?
1.23 crook 12604: doc-getenv
1.44 crook 12605:
1.26 crook 12606: @c -------------------------------------------------------------
1.47 crook 12607: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12608: @section Keeping track of Time
12609: @cindex time-related words
12610:
12611: doc-ms
12612: doc-time&date
1.79 anton 12613: doc-utime
12614: doc-cputime
1.47 crook 12615:
12616:
12617: @c -------------------------------------------------------------
12618: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12619: @section Miscellaneous Words
12620: @cindex miscellaneous words
12621:
1.29 crook 12622: @comment TODO find homes for these
12623:
1.26 crook 12624: These section lists the ANS Forth words that are not documented
1.21 crook 12625: elsewhere in this manual. Ultimately, they all need proper homes.
12626:
1.68 anton 12627: doc-quit
1.44 crook 12628:
1.26 crook 12629: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12630: (@pxref{ANS conformance}):
1.21 crook 12631:
12632: @code{EDITOR}
12633: @code{EMIT?}
12634: @code{FORGET}
12635:
1.24 anton 12636: @c ******************************************************************
12637: @node Error messages, Tools, Words, Top
12638: @chapter Error messages
12639: @cindex error messages
12640: @cindex backtrace
12641:
12642: A typical Gforth error message looks like this:
12643:
12644: @example
1.86 anton 12645: in file included from \evaluated string/:-1
1.24 anton 12646: in file included from ./yyy.fs:1
12647: ./xxx.fs:4: Invalid memory address
1.134 anton 12648: >>>bar<<<
1.79 anton 12649: Backtrace:
1.25 anton 12650: $400E664C @@
12651: $400E6664 foo
1.24 anton 12652: @end example
12653:
12654: The message identifying the error is @code{Invalid memory address}. The
12655: error happened when text-interpreting line 4 of the file
12656: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12657: word on the line where the error happened, is pointed out (with
1.134 anton 12658: @code{>>>} and @code{<<<}).
1.24 anton 12659:
12660: The file containing the error was included in line 1 of @file{./yyy.fs},
12661: and @file{yyy.fs} was included from a non-file (in this case, by giving
12662: @file{yyy.fs} as command-line parameter to Gforth).
12663:
12664: At the end of the error message you find a return stack dump that can be
12665: interpreted as a backtrace (possibly empty). On top you find the top of
12666: the return stack when the @code{throw} happened, and at the bottom you
12667: find the return stack entry just above the return stack of the topmost
12668: text interpreter.
12669:
12670: To the right of most return stack entries you see a guess for the word
12671: that pushed that return stack entry as its return address. This gives a
12672: backtrace. In our case we see that @code{bar} called @code{foo}, and
12673: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12674: address} exception).
12675:
12676: Note that the backtrace is not perfect: We don't know which return stack
12677: entries are return addresses (so we may get false positives); and in
12678: some cases (e.g., for @code{abort"}) we cannot determine from the return
12679: address the word that pushed the return address, so for some return
12680: addresses you see no names in the return stack dump.
1.25 anton 12681:
12682: @cindex @code{catch} and backtraces
12683: The return stack dump represents the return stack at the time when a
12684: specific @code{throw} was executed. In programs that make use of
12685: @code{catch}, it is not necessarily clear which @code{throw} should be
12686: used for the return stack dump (e.g., consider one @code{throw} that
12687: indicates an error, which is caught, and during recovery another error
1.160 anton 12688: happens; which @code{throw} should be used for the stack dump?).
12689: Gforth presents the return stack dump for the first @code{throw} after
12690: the last executed (not returned-to) @code{catch} or @code{nothrow};
12691: this works well in the usual case. To get the right backtrace, you
12692: usually want to insert @code{nothrow} or @code{['] false catch drop}
12693: after a @code{catch} if the error is not rethrown.
1.25 anton 12694:
12695: @cindex @code{gforth-fast} and backtraces
12696: @cindex @code{gforth-fast}, difference from @code{gforth}
12697: @cindex backtraces with @code{gforth-fast}
12698: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12699: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12700: from primitives (e.g., invalid memory address, stack empty etc.);
12701: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12702: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12703: exception caused by a primitive in @code{gforth-fast}, you will
12704: typically see no return stack dump at all; however, if the exception is
12705: caught by @code{catch} (e.g., for restoring some state), and then
12706: @code{throw}n again, the return stack dump will be for the first such
12707: @code{throw}.
1.2 jwilke 12708:
1.5 anton 12709: @c ******************************************************************
1.24 anton 12710: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12711: @chapter Tools
12712:
12713: @menu
12714: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12715: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12716: @end menu
12717:
12718: See also @ref{Emacs and Gforth}.
12719:
1.126 pazsan 12720: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12721: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12722: @cindex @file{ans-report.fs}
12723: @cindex report the words used in your program
12724: @cindex words used in your program
12725:
12726: If you want to label a Forth program as ANS Forth Program, you must
12727: document which wordsets the program uses; for extension wordsets, it is
12728: helpful to list the words the program requires from these wordsets
12729: (because Forth systems are allowed to provide only some words of them).
12730:
12731: The @file{ans-report.fs} tool makes it easy for you to determine which
12732: words from which wordset and which non-ANS words your application
12733: uses. You simply have to include @file{ans-report.fs} before loading the
12734: program you want to check. After loading your program, you can get the
12735: report with @code{print-ans-report}. A typical use is to run this as
12736: batch job like this:
12737: @example
12738: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12739: @end example
12740:
12741: The output looks like this (for @file{compat/control.fs}):
12742: @example
12743: The program uses the following words
12744: from CORE :
12745: : POSTPONE THEN ; immediate ?dup IF 0=
12746: from BLOCK-EXT :
12747: \
12748: from FILE :
12749: (
12750: @end example
12751:
12752: @subsection Caveats
12753:
12754: Note that @file{ans-report.fs} just checks which words are used, not whether
12755: they are used in an ANS Forth conforming way!
12756:
12757: Some words are defined in several wordsets in the
12758: standard. @file{ans-report.fs} reports them for only one of the
12759: wordsets, and not necessarily the one you expect. It depends on usage
12760: which wordset is the right one to specify. E.g., if you only use the
12761: compilation semantics of @code{S"}, it is a Core word; if you also use
12762: its interpretation semantics, it is a File word.
1.124 anton 12763:
12764:
1.127 anton 12765: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12766: @section Stack depth changes during interpretation
12767: @cindex @file{depth-changes.fs}
12768: @cindex depth changes during interpretation
12769: @cindex stack depth changes during interpretation
12770: @cindex items on the stack after interpretation
12771:
12772: Sometimes you notice that, after loading a file, there are items left
12773: on the stack. The tool @file{depth-changes.fs} helps you find out
12774: quickly where in the file these stack items are coming from.
12775:
12776: The simplest way of using @file{depth-changes.fs} is to include it
12777: before the file(s) you want to check, e.g.:
12778:
12779: @example
12780: gforth depth-changes.fs my-file.fs
12781: @end example
12782:
12783: This will compare the stack depths of the data and FP stack at every
12784: empty line (in interpretation state) against these depths at the last
12785: empty line (in interpretation state). If the depths are not equal,
12786: the position in the file and the stack contents are printed with
12787: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12788: change has occured in the paragraph of non-empty lines before the
12789: indicated line. It is a good idea to leave an empty line at the end
12790: of the file, so the last paragraph is checked, too.
12791:
12792: Checking only at empty lines usually works well, but sometimes you
12793: have big blocks of non-empty lines (e.g., when building a big table),
12794: and you want to know where in this block the stack depth changed. You
12795: can check all interpreted lines with
12796:
12797: @example
12798: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12799: @end example
12800:
12801: This checks the stack depth at every end-of-line. So the depth change
12802: occured in the line reported by the @code{~~} (not in the line
12803: before).
12804:
12805: Note that, while this offers better accuracy in indicating where the
12806: stack depth changes, it will often report many intentional stack depth
12807: changes (e.g., when an interpreted computation stretches across
12808: several lines). You can suppress the checking of some lines by
12809: putting backslashes at the end of these lines (not followed by white
12810: space), and using
12811:
12812: @example
12813: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12814: @end example
1.1 anton 12815:
12816: @c ******************************************************************
1.65 anton 12817: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12818: @chapter ANS conformance
12819: @cindex ANS conformance of Gforth
12820:
12821: To the best of our knowledge, Gforth is an
12822:
12823: ANS Forth System
12824: @itemize @bullet
12825: @item providing the Core Extensions word set
12826: @item providing the Block word set
12827: @item providing the Block Extensions word set
12828: @item providing the Double-Number word set
12829: @item providing the Double-Number Extensions word set
12830: @item providing the Exception word set
12831: @item providing the Exception Extensions word set
12832: @item providing the Facility word set
1.40 anton 12833: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12834: @item providing the File Access word set
12835: @item providing the File Access Extensions word set
12836: @item providing the Floating-Point word set
12837: @item providing the Floating-Point Extensions word set
12838: @item providing the Locals word set
12839: @item providing the Locals Extensions word set
12840: @item providing the Memory-Allocation word set
12841: @item providing the Memory-Allocation Extensions word set (that one's easy)
12842: @item providing the Programming-Tools word set
12843: @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
12844: @item providing the Search-Order word set
12845: @item providing the Search-Order Extensions word set
12846: @item providing the String word set
12847: @item providing the String Extensions word set (another easy one)
12848: @end itemize
12849:
1.118 anton 12850: Gforth has the following environmental restrictions:
12851:
12852: @cindex environmental restrictions
12853: @itemize @bullet
12854: @item
12855: While processing the OS command line, if an exception is not caught,
12856: Gforth exits with a non-zero exit code instyead of performing QUIT.
12857:
12858: @item
12859: When an @code{throw} is performed after a @code{query}, Gforth does not
12860: allways restore the input source specification in effect at the
12861: corresponding catch.
12862:
12863: @end itemize
12864:
12865:
1.1 anton 12866: @cindex system documentation
12867: In addition, ANS Forth systems are required to document certain
12868: implementation choices. This chapter tries to meet these
12869: requirements. In many cases it gives a way to ask the system for the
12870: information instead of providing the information directly, in
12871: particular, if the information depends on the processor, the operating
12872: system or the installation options chosen, or if they are likely to
12873: change during the maintenance of Gforth.
12874:
12875: @comment The framework for the rest has been taken from pfe.
12876:
12877: @menu
12878: * The Core Words::
12879: * The optional Block word set::
12880: * The optional Double Number word set::
12881: * The optional Exception word set::
12882: * The optional Facility word set::
12883: * The optional File-Access word set::
12884: * The optional Floating-Point word set::
12885: * The optional Locals word set::
12886: * The optional Memory-Allocation word set::
12887: * The optional Programming-Tools word set::
12888: * The optional Search-Order word set::
12889: @end menu
12890:
12891:
12892: @c =====================================================================
12893: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12894: @comment node-name, next, previous, up
12895: @section The Core Words
12896: @c =====================================================================
12897: @cindex core words, system documentation
12898: @cindex system documentation, core words
12899:
12900: @menu
12901: * core-idef:: Implementation Defined Options
12902: * core-ambcond:: Ambiguous Conditions
12903: * core-other:: Other System Documentation
12904: @end menu
12905:
12906: @c ---------------------------------------------------------------------
12907: @node core-idef, core-ambcond, The Core Words, The Core Words
12908: @subsection Implementation Defined Options
12909: @c ---------------------------------------------------------------------
12910: @cindex core words, implementation-defined options
12911: @cindex implementation-defined options, core words
12912:
12913:
12914: @table @i
12915: @item (Cell) aligned addresses:
12916: @cindex cell-aligned addresses
12917: @cindex aligned addresses
12918: processor-dependent. Gforth's alignment words perform natural alignment
12919: (e.g., an address aligned for a datum of size 8 is divisible by
12920: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12921:
12922: @item @code{EMIT} and non-graphic characters:
12923: @cindex @code{EMIT} and non-graphic characters
12924: @cindex non-graphic characters and @code{EMIT}
12925: The character is output using the C library function (actually, macro)
12926: @code{putc}.
12927:
12928: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12929: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12930: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12931: @cindex @code{ACCEPT}, editing
12932: @cindex @code{EXPECT}, editing
12933: This is modeled on the GNU readline library (@pxref{Readline
12934: Interaction, , Command Line Editing, readline, The GNU Readline
12935: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12936: producing a full word completion every time you type it (instead of
1.28 crook 12937: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12938:
12939: @item character set:
12940: @cindex character set
12941: The character set of your computer and display device. Gforth is
12942: 8-bit-clean (but some other component in your system may make trouble).
12943:
12944: @item Character-aligned address requirements:
12945: @cindex character-aligned address requirements
12946: installation-dependent. Currently a character is represented by a C
12947: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12948: (Comments on that requested).
12949:
12950: @item character-set extensions and matching of names:
12951: @cindex character-set extensions and matching of names
1.26 crook 12952: @cindex case-sensitivity for name lookup
12953: @cindex name lookup, case-sensitivity
12954: @cindex locale and case-sensitivity
1.21 crook 12955: Any character except the ASCII NUL character can be used in a
1.1 anton 12956: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12957: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12958: function is probably influenced by the locale. E.g., the @code{C} locale
12959: does not know about accents and umlauts, so they are matched
12960: case-sensitively in that locale. For portability reasons it is best to
12961: write programs such that they work in the @code{C} locale. Then one can
12962: use libraries written by a Polish programmer (who might use words
12963: containing ISO Latin-2 encoded characters) and by a French programmer
12964: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12965: funny results for some of the words (which ones, depends on the font you
12966: are using)). Also, the locale you prefer may not be available in other
12967: operating systems. Hopefully, Unicode will solve these problems one day.
12968:
12969: @item conditions under which control characters match a space delimiter:
12970: @cindex space delimiters
12971: @cindex control characters as delimiters
1.117 anton 12972: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12973: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12974: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12975: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12976: interpreter (aka text interpreter) by default, treats all white-space
12977: characters as delimiters.
12978:
1.26 crook 12979: @item format of the control-flow stack:
12980: @cindex control-flow stack, format
12981: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12982: stack item in cells is given by the constant @code{cs-item-size}. At the
12983: time of this writing, an item consists of a (pointer to a) locals list
12984: (third), an address in the code (second), and a tag for identifying the
12985: item (TOS). The following tags are used: @code{defstart},
12986: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12987: @code{scopestart}.
12988:
12989: @item conversion of digits > 35
12990: @cindex digits > 35
12991: The characters @code{[\]^_'} are the digits with the decimal value
12992: 36@minus{}41. There is no way to input many of the larger digits.
12993:
12994: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12995: @cindex @code{EXPECT}, display after end of input
12996: @cindex @code{ACCEPT}, display after end of input
12997: The cursor is moved to the end of the entered string. If the input is
12998: terminated using the @kbd{Return} key, a space is typed.
12999:
13000: @item exception abort sequence of @code{ABORT"}:
13001: @cindex exception abort sequence of @code{ABORT"}
13002: @cindex @code{ABORT"}, exception abort sequence
13003: The error string is stored into the variable @code{"error} and a
13004: @code{-2 throw} is performed.
13005:
13006: @item input line terminator:
13007: @cindex input line terminator
13008: @cindex line terminator on input
1.26 crook 13009: @cindex newline character on input
1.1 anton 13010: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13011: lines. One of these characters is typically produced when you type the
13012: @kbd{Enter} or @kbd{Return} key.
13013:
13014: @item maximum size of a counted string:
13015: @cindex maximum size of a counted string
13016: @cindex counted string, maximum size
13017: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13018: on all platforms, but this may change.
1.1 anton 13019:
13020: @item maximum size of a parsed string:
13021: @cindex maximum size of a parsed string
13022: @cindex parsed string, maximum size
13023: Given by the constant @code{/line}. Currently 255 characters.
13024:
13025: @item maximum size of a definition name, in characters:
13026: @cindex maximum size of a definition name, in characters
13027: @cindex name, maximum length
1.113 anton 13028: MAXU/8
1.1 anton 13029:
13030: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13031: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13032: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13033: MAXU/8
1.1 anton 13034:
13035: @item method of selecting the user input device:
13036: @cindex user input device, method of selecting
13037: The user input device is the standard input. There is currently no way to
13038: change it from within Gforth. However, the input can typically be
13039: redirected in the command line that starts Gforth.
13040:
13041: @item method of selecting the user output device:
13042: @cindex user output device, method of selecting
13043: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13044: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13045: output when the user output device is a terminal, otherwise the output
13046: is buffered.
1.1 anton 13047:
13048: @item methods of dictionary compilation:
13049: What are we expected to document here?
13050:
13051: @item number of bits in one address unit:
13052: @cindex number of bits in one address unit
13053: @cindex address unit, size in bits
13054: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13055: platforms.
1.1 anton 13056:
13057: @item number representation and arithmetic:
13058: @cindex number representation and arithmetic
1.79 anton 13059: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13060:
13061: @item ranges for integer types:
13062: @cindex ranges for integer types
13063: @cindex integer types, ranges
13064: Installation-dependent. Make environmental queries for @code{MAX-N},
13065: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13066: unsigned (and positive) types is 0. The lower bound for signed types on
13067: two's complement and one's complement machines machines can be computed
13068: by adding 1 to the upper bound.
13069:
13070: @item read-only data space regions:
13071: @cindex read-only data space regions
13072: @cindex data-space, read-only regions
13073: The whole Forth data space is writable.
13074:
13075: @item size of buffer at @code{WORD}:
13076: @cindex size of buffer at @code{WORD}
13077: @cindex @code{WORD} buffer size
13078: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13079: shared with the pictured numeric output string. If overwriting
13080: @code{PAD} is acceptable, it is as large as the remaining dictionary
13081: space, although only as much can be sensibly used as fits in a counted
13082: string.
13083:
13084: @item size of one cell in address units:
13085: @cindex cell size
13086: @code{1 cells .}.
13087:
13088: @item size of one character in address units:
13089: @cindex char size
1.79 anton 13090: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13091:
13092: @item size of the keyboard terminal buffer:
13093: @cindex size of the keyboard terminal buffer
13094: @cindex terminal buffer, size
13095: Varies. You can determine the size at a specific time using @code{lp@@
13096: tib - .}. It is shared with the locals stack and TIBs of files that
13097: include the current file. You can change the amount of space for TIBs
13098: and locals stack at Gforth startup with the command line option
13099: @code{-l}.
13100:
13101: @item size of the pictured numeric output buffer:
13102: @cindex size of the pictured numeric output buffer
13103: @cindex pictured numeric output buffer, size
13104: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13105: shared with @code{WORD}.
13106:
13107: @item size of the scratch area returned by @code{PAD}:
13108: @cindex size of the scratch area returned by @code{PAD}
13109: @cindex @code{PAD} size
13110: The remainder of dictionary space. @code{unused pad here - - .}.
13111:
13112: @item system case-sensitivity characteristics:
13113: @cindex case-sensitivity characteristics
1.26 crook 13114: Dictionary searches are case-insensitive (except in
1.1 anton 13115: @code{TABLE}s). However, as explained above under @i{character-set
13116: extensions}, the matching for non-ASCII characters is determined by the
13117: locale you are using. In the default @code{C} locale all non-ASCII
13118: characters are matched case-sensitively.
13119:
13120: @item system prompt:
13121: @cindex system prompt
13122: @cindex prompt
13123: @code{ ok} in interpret state, @code{ compiled} in compile state.
13124:
13125: @item division rounding:
13126: @cindex division rounding
1.166 anton 13127: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13128: division (with the default installation of Gforth). You can check
13129: this with @code{s" floored" environment? drop .}. If you write
13130: programs that need a specific division rounding, best use
13131: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13132:
13133: @item values of @code{STATE} when true:
13134: @cindex @code{STATE} values
13135: -1.
13136:
13137: @item values returned after arithmetic overflow:
13138: On two's complement machines, arithmetic is performed modulo
13139: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13140: arithmetic (with appropriate mapping for signed types). Division by
13141: zero typically results in a @code{-55 throw} (Floating-point
13142: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13143: division overflow can result in these throws, or in @code{-11 throw};
13144: in @code{gforth-fast} division overflow and divide by zero may also
13145: result in returning bogus results without producing an exception.
1.1 anton 13146:
13147: @item whether the current definition can be found after @t{DOES>}:
13148: @cindex @t{DOES>}, visibility of current definition
13149: No.
13150:
13151: @end table
13152:
13153: @c ---------------------------------------------------------------------
13154: @node core-ambcond, core-other, core-idef, The Core Words
13155: @subsection Ambiguous conditions
13156: @c ---------------------------------------------------------------------
13157: @cindex core words, ambiguous conditions
13158: @cindex ambiguous conditions, core words
13159:
13160: @table @i
13161:
13162: @item a name is neither a word nor a number:
13163: @cindex name not found
1.26 crook 13164: @cindex undefined word
1.80 anton 13165: @code{-13 throw} (Undefined word).
1.1 anton 13166:
13167: @item a definition name exceeds the maximum length allowed:
1.26 crook 13168: @cindex word name too long
1.1 anton 13169: @code{-19 throw} (Word name too long)
13170:
13171: @item addressing a region not inside the various data spaces of the forth system:
13172: @cindex Invalid memory address
1.32 anton 13173: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13174: typically readable. Accessing other addresses gives results dependent on
13175: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13176: address).
13177:
13178: @item argument type incompatible with parameter:
1.26 crook 13179: @cindex argument type mismatch
1.1 anton 13180: This is usually not caught. Some words perform checks, e.g., the control
13181: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13182: mismatch).
13183:
13184: @item attempting to obtain the execution token of a word with undefined execution semantics:
13185: @cindex Interpreting a compile-only word, for @code{'} etc.
13186: @cindex execution token of words with undefined execution semantics
13187: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13188: get an execution token for @code{compile-only-error} (which performs a
13189: @code{-14 throw} when executed).
13190:
13191: @item dividing by zero:
13192: @cindex dividing by zero
13193: @cindex floating point unidentified fault, integer division
1.80 anton 13194: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13195: zero); on other systems, this typically results in a @code{-55 throw}
13196: (Floating-point unidentified fault).
1.1 anton 13197:
13198: @item insufficient data stack or return stack space:
13199: @cindex insufficient data stack or return stack space
13200: @cindex stack overflow
1.26 crook 13201: @cindex address alignment exception, stack overflow
1.1 anton 13202: @cindex Invalid memory address, stack overflow
13203: Depending on the operating system, the installation, and the invocation
13204: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13205: it is not checked. If it is checked, you typically get a @code{-3 throw}
13206: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13207: throw} (Invalid memory address) (depending on the platform and how you
13208: achieved the overflow) as soon as the overflow happens. If it is not
13209: checked, overflows typically result in mysterious illegal memory
13210: accesses, producing @code{-9 throw} (Invalid memory address) or
13211: @code{-23 throw} (Address alignment exception); they might also destroy
13212: the internal data structure of @code{ALLOCATE} and friends, resulting in
13213: various errors in these words.
1.1 anton 13214:
13215: @item insufficient space for loop control parameters:
13216: @cindex insufficient space for loop control parameters
1.80 anton 13217: Like other return stack overflows.
1.1 anton 13218:
13219: @item insufficient space in the dictionary:
13220: @cindex insufficient space in the dictionary
13221: @cindex dictionary overflow
1.12 anton 13222: If you try to allot (either directly with @code{allot}, or indirectly
13223: with @code{,}, @code{create} etc.) more memory than available in the
13224: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13225: to access memory beyond the end of the dictionary, the results are
13226: similar to stack overflows.
1.1 anton 13227:
13228: @item interpreting a word with undefined interpretation semantics:
13229: @cindex interpreting a word with undefined interpretation semantics
13230: @cindex Interpreting a compile-only word
13231: For some words, we have defined interpretation semantics. For the
13232: others: @code{-14 throw} (Interpreting a compile-only word).
13233:
13234: @item modifying the contents of the input buffer or a string literal:
13235: @cindex modifying the contents of the input buffer or a string literal
13236: These are located in writable memory and can be modified.
13237:
13238: @item overflow of the pictured numeric output string:
13239: @cindex overflow of the pictured numeric output string
13240: @cindex pictured numeric output string, overflow
1.24 anton 13241: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13242:
13243: @item parsed string overflow:
13244: @cindex parsed string overflow
13245: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13246:
13247: @item producing a result out of range:
13248: @cindex result out of range
13249: On two's complement machines, arithmetic is performed modulo
13250: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13251: arithmetic (with appropriate mapping for signed types). Division by
13252: zero typically results in a @code{-10 throw} (divide by zero) or
13253: @code{-55 throw} (floating point unidentified fault). Overflow on
13254: division may result in these errors or in @code{-11 throw} (result out
13255: of range). @code{Gforth-fast} may silently produce bogus results on
13256: division overflow or division by zero. @code{Convert} and
1.24 anton 13257: @code{>number} currently overflow silently.
1.1 anton 13258:
13259: @item reading from an empty data or return stack:
13260: @cindex stack empty
13261: @cindex stack underflow
1.24 anton 13262: @cindex return stack underflow
1.1 anton 13263: The data stack is checked by the outer (aka text) interpreter after
13264: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13265: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13266: depending on operating system, installation, and invocation. If they are
13267: caught by a check, they typically result in @code{-4 throw} (Stack
13268: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13269: (Invalid memory address), depending on the platform and which stack
13270: underflows and by how much. Note that even if the system uses checking
13271: (through the MMU), your program may have to underflow by a significant
13272: number of stack items to trigger the reaction (the reason for this is
13273: that the MMU, and therefore the checking, works with a page-size
13274: granularity). If there is no checking, the symptoms resulting from an
13275: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13276: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13277: (Invalid memory address) and Illegal Instruction (typically @code{-260
13278: throw}).
1.1 anton 13279:
13280: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13281: @cindex unexpected end of the input buffer
13282: @cindex zero-length string as a name
13283: @cindex Attempt to use zero-length string as a name
13284: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13285: use zero-length string as a name). Words like @code{'} probably will not
13286: find what they search. Note that it is possible to create zero-length
13287: names with @code{nextname} (should it not?).
13288:
13289: @item @code{>IN} greater than input buffer:
13290: @cindex @code{>IN} greater than input buffer
13291: The next invocation of a parsing word returns a string with length 0.
13292:
13293: @item @code{RECURSE} appears after @code{DOES>}:
13294: @cindex @code{RECURSE} appears after @code{DOES>}
13295: Compiles a recursive call to the defining word, not to the defined word.
13296:
13297: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13298: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13299: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13300: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13301: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13302: the end of the file was reached), its source-id may be
13303: reused. Therefore, restoring an input source specification referencing a
13304: closed file may lead to unpredictable results instead of a @code{-12
13305: THROW}.
13306:
13307: In the future, Gforth may be able to restore input source specifications
13308: from other than the current input source.
13309:
13310: @item data space containing definitions gets de-allocated:
13311: @cindex data space containing definitions gets de-allocated
13312: Deallocation with @code{allot} is not checked. This typically results in
13313: memory access faults or execution of illegal instructions.
13314:
13315: @item data space read/write with incorrect alignment:
13316: @cindex data space read/write with incorrect alignment
13317: @cindex alignment faults
1.26 crook 13318: @cindex address alignment exception
1.1 anton 13319: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13320: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13321: alignment turned on, incorrect alignment results in a @code{-9 throw}
13322: (Invalid memory address). There are reportedly some processors with
1.12 anton 13323: alignment restrictions that do not report violations.
1.1 anton 13324:
13325: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13326: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13327: Like other alignment errors.
13328:
13329: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13330: Like other stack underflows.
13331:
13332: @item loop control parameters not available:
13333: @cindex loop control parameters not available
13334: Not checked. The counted loop words simply assume that the top of return
13335: stack items are loop control parameters and behave accordingly.
13336:
13337: @item most recent definition does not have a name (@code{IMMEDIATE}):
13338: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13339: @cindex last word was headerless
13340: @code{abort" last word was headerless"}.
13341:
13342: @item name not defined by @code{VALUE} used by @code{TO}:
13343: @cindex name not defined by @code{VALUE} used by @code{TO}
13344: @cindex @code{TO} on non-@code{VALUE}s
13345: @cindex Invalid name argument, @code{TO}
13346: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13347: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13348:
13349: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13350: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13351: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13352: @code{-13 throw} (Undefined word)
13353:
13354: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13355: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13356: Gforth behaves as if they were of the same type. I.e., you can predict
13357: the behaviour by interpreting all parameters as, e.g., signed.
13358:
13359: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13360: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13361: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13362: compilation semantics of @code{TO}.
13363:
13364: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13365: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13366: @cindex @code{WORD}, string overflow
13367: Not checked. The string will be ok, but the count will, of course,
13368: contain only the least significant bits of the length.
13369:
13370: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13371: @cindex @code{LSHIFT}, large shift counts
13372: @cindex @code{RSHIFT}, large shift counts
13373: Processor-dependent. Typical behaviours are returning 0 and using only
13374: the low bits of the shift count.
13375:
13376: @item word not defined via @code{CREATE}:
13377: @cindex @code{>BODY} of non-@code{CREATE}d words
13378: @code{>BODY} produces the PFA of the word no matter how it was defined.
13379:
13380: @cindex @code{DOES>} of non-@code{CREATE}d words
13381: @code{DOES>} changes the execution semantics of the last defined word no
13382: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13383: @code{CREATE , DOES>}.
13384:
13385: @item words improperly used outside @code{<#} and @code{#>}:
13386: Not checked. As usual, you can expect memory faults.
13387:
13388: @end table
13389:
13390:
13391: @c ---------------------------------------------------------------------
13392: @node core-other, , core-ambcond, The Core Words
13393: @subsection Other system documentation
13394: @c ---------------------------------------------------------------------
13395: @cindex other system documentation, core words
13396: @cindex core words, other system documentation
13397:
13398: @table @i
13399: @item nonstandard words using @code{PAD}:
13400: @cindex @code{PAD} use by nonstandard words
13401: None.
13402:
13403: @item operator's terminal facilities available:
13404: @cindex operator's terminal facilities available
1.80 anton 13405: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13406: and you can give commands to Gforth interactively. The actual facilities
13407: available depend on how you invoke Gforth.
13408:
13409: @item program data space available:
13410: @cindex program data space available
13411: @cindex data space available
13412: @code{UNUSED .} gives the remaining dictionary space. The total
13413: dictionary space can be specified with the @code{-m} switch
13414: (@pxref{Invoking Gforth}) when Gforth starts up.
13415:
13416: @item return stack space available:
13417: @cindex return stack space available
13418: You can compute the total return stack space in cells with
13419: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13420: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13421:
13422: @item stack space available:
13423: @cindex stack space available
13424: You can compute the total data stack space in cells with
13425: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13426: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13427:
13428: @item system dictionary space required, in address units:
13429: @cindex system dictionary space required, in address units
13430: Type @code{here forthstart - .} after startup. At the time of this
13431: writing, this gives 80080 (bytes) on a 32-bit system.
13432: @end table
13433:
13434:
13435: @c =====================================================================
13436: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13437: @section The optional Block word set
13438: @c =====================================================================
13439: @cindex system documentation, block words
13440: @cindex block words, system documentation
13441:
13442: @menu
13443: * block-idef:: Implementation Defined Options
13444: * block-ambcond:: Ambiguous Conditions
13445: * block-other:: Other System Documentation
13446: @end menu
13447:
13448:
13449: @c ---------------------------------------------------------------------
13450: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13451: @subsection Implementation Defined Options
13452: @c ---------------------------------------------------------------------
13453: @cindex implementation-defined options, block words
13454: @cindex block words, implementation-defined options
13455:
13456: @table @i
13457: @item the format for display by @code{LIST}:
13458: @cindex @code{LIST} display format
13459: First the screen number is displayed, then 16 lines of 64 characters,
13460: each line preceded by the line number.
13461:
13462: @item the length of a line affected by @code{\}:
13463: @cindex length of a line affected by @code{\}
13464: @cindex @code{\}, line length in blocks
13465: 64 characters.
13466: @end table
13467:
13468:
13469: @c ---------------------------------------------------------------------
13470: @node block-ambcond, block-other, block-idef, The optional Block word set
13471: @subsection Ambiguous conditions
13472: @c ---------------------------------------------------------------------
13473: @cindex block words, ambiguous conditions
13474: @cindex ambiguous conditions, block words
13475:
13476: @table @i
13477: @item correct block read was not possible:
13478: @cindex block read not possible
13479: Typically results in a @code{throw} of some OS-derived value (between
13480: -512 and -2048). If the blocks file was just not long enough, blanks are
13481: supplied for the missing portion.
13482:
13483: @item I/O exception in block transfer:
13484: @cindex I/O exception in block transfer
13485: @cindex block transfer, I/O exception
13486: Typically results in a @code{throw} of some OS-derived value (between
13487: -512 and -2048).
13488:
13489: @item invalid block number:
13490: @cindex invalid block number
13491: @cindex block number invalid
13492: @code{-35 throw} (Invalid block number)
13493:
13494: @item a program directly alters the contents of @code{BLK}:
13495: @cindex @code{BLK}, altering @code{BLK}
13496: The input stream is switched to that other block, at the same
13497: position. If the storing to @code{BLK} happens when interpreting
13498: non-block input, the system will get quite confused when the block ends.
13499:
13500: @item no current block buffer for @code{UPDATE}:
13501: @cindex @code{UPDATE}, no current block buffer
13502: @code{UPDATE} has no effect.
13503:
13504: @end table
13505:
13506: @c ---------------------------------------------------------------------
13507: @node block-other, , block-ambcond, The optional Block word set
13508: @subsection Other system documentation
13509: @c ---------------------------------------------------------------------
13510: @cindex other system documentation, block words
13511: @cindex block words, other system documentation
13512:
13513: @table @i
13514: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13515: No restrictions (yet).
13516:
13517: @item the number of blocks available for source and data:
13518: depends on your disk space.
13519:
13520: @end table
13521:
13522:
13523: @c =====================================================================
13524: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13525: @section The optional Double Number word set
13526: @c =====================================================================
13527: @cindex system documentation, double words
13528: @cindex double words, system documentation
13529:
13530: @menu
13531: * double-ambcond:: Ambiguous Conditions
13532: @end menu
13533:
13534:
13535: @c ---------------------------------------------------------------------
13536: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13537: @subsection Ambiguous conditions
13538: @c ---------------------------------------------------------------------
13539: @cindex double words, ambiguous conditions
13540: @cindex ambiguous conditions, double words
13541:
13542: @table @i
1.29 crook 13543: @item @i{d} outside of range of @i{n} in @code{D>S}:
13544: @cindex @code{D>S}, @i{d} out of range of @i{n}
13545: The least significant cell of @i{d} is produced.
1.1 anton 13546:
13547: @end table
13548:
13549:
13550: @c =====================================================================
13551: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13552: @section The optional Exception word set
13553: @c =====================================================================
13554: @cindex system documentation, exception words
13555: @cindex exception words, system documentation
13556:
13557: @menu
13558: * exception-idef:: Implementation Defined Options
13559: @end menu
13560:
13561:
13562: @c ---------------------------------------------------------------------
13563: @node exception-idef, , The optional Exception word set, The optional Exception word set
13564: @subsection Implementation Defined Options
13565: @c ---------------------------------------------------------------------
13566: @cindex implementation-defined options, exception words
13567: @cindex exception words, implementation-defined options
13568:
13569: @table @i
13570: @item @code{THROW}-codes used in the system:
13571: @cindex @code{THROW}-codes used in the system
13572: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13573: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13574: codes -512@minus{}-2047 are used for OS errors (for file and memory
13575: allocation operations). The mapping from OS error numbers to throw codes
13576: is -512@minus{}@code{errno}. One side effect of this mapping is that
13577: undefined OS errors produce a message with a strange number; e.g.,
13578: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13579: @end table
13580:
13581: @c =====================================================================
13582: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13583: @section The optional Facility word set
13584: @c =====================================================================
13585: @cindex system documentation, facility words
13586: @cindex facility words, system documentation
13587:
13588: @menu
13589: * facility-idef:: Implementation Defined Options
13590: * facility-ambcond:: Ambiguous Conditions
13591: @end menu
13592:
13593:
13594: @c ---------------------------------------------------------------------
13595: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13596: @subsection Implementation Defined Options
13597: @c ---------------------------------------------------------------------
13598: @cindex implementation-defined options, facility words
13599: @cindex facility words, implementation-defined options
13600:
13601: @table @i
13602: @item encoding of keyboard events (@code{EKEY}):
13603: @cindex keyboard events, encoding in @code{EKEY}
13604: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13605: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13606: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13607: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13608: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13609: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13610:
1.1 anton 13611:
13612: @item duration of a system clock tick:
13613: @cindex duration of a system clock tick
13614: @cindex clock tick duration
13615: System dependent. With respect to @code{MS}, the time is specified in
13616: microseconds. How well the OS and the hardware implement this, is
13617: another question.
13618:
13619: @item repeatability to be expected from the execution of @code{MS}:
13620: @cindex repeatability to be expected from the execution of @code{MS}
13621: @cindex @code{MS}, repeatability to be expected
13622: System dependent. On Unix, a lot depends on load. If the system is
13623: lightly loaded, and the delay is short enough that Gforth does not get
13624: swapped out, the performance should be acceptable. Under MS-DOS and
13625: other single-tasking systems, it should be good.
13626:
13627: @end table
13628:
13629:
13630: @c ---------------------------------------------------------------------
13631: @node facility-ambcond, , facility-idef, The optional Facility word set
13632: @subsection Ambiguous conditions
13633: @c ---------------------------------------------------------------------
13634: @cindex facility words, ambiguous conditions
13635: @cindex ambiguous conditions, facility words
13636:
13637: @table @i
13638: @item @code{AT-XY} can't be performed on user output device:
13639: @cindex @code{AT-XY} can't be performed on user output device
13640: Largely terminal dependent. No range checks are done on the arguments.
13641: No errors are reported. You may see some garbage appearing, you may see
13642: simply nothing happen.
13643:
13644: @end table
13645:
13646:
13647: @c =====================================================================
13648: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13649: @section The optional File-Access word set
13650: @c =====================================================================
13651: @cindex system documentation, file words
13652: @cindex file words, system documentation
13653:
13654: @menu
13655: * file-idef:: Implementation Defined Options
13656: * file-ambcond:: Ambiguous Conditions
13657: @end menu
13658:
13659: @c ---------------------------------------------------------------------
13660: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13661: @subsection Implementation Defined Options
13662: @c ---------------------------------------------------------------------
13663: @cindex implementation-defined options, file words
13664: @cindex file words, implementation-defined options
13665:
13666: @table @i
13667: @item file access methods used:
13668: @cindex file access methods used
13669: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13670: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13671: @code{wb}): The file is cleared, if it exists, and created, if it does
13672: not (with both @code{open-file} and @code{create-file}). Under Unix
13673: @code{create-file} creates a file with 666 permissions modified by your
13674: umask.
13675:
13676: @item file exceptions:
13677: @cindex file exceptions
13678: The file words do not raise exceptions (except, perhaps, memory access
13679: faults when you pass illegal addresses or file-ids).
13680:
13681: @item file line terminator:
13682: @cindex file line terminator
13683: System-dependent. Gforth uses C's newline character as line
13684: terminator. What the actual character code(s) of this are is
13685: system-dependent.
13686:
13687: @item file name format:
13688: @cindex file name format
13689: System dependent. Gforth just uses the file name format of your OS.
13690:
13691: @item information returned by @code{FILE-STATUS}:
13692: @cindex @code{FILE-STATUS}, returned information
13693: @code{FILE-STATUS} returns the most powerful file access mode allowed
13694: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13695: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13696: along with the returned mode.
13697:
13698: @item input file state after an exception when including source:
13699: @cindex exception when including source
13700: All files that are left via the exception are closed.
13701:
1.29 crook 13702: @item @i{ior} values and meaning:
13703: @cindex @i{ior} values and meaning
1.68 anton 13704: @cindex @i{wior} values and meaning
1.29 crook 13705: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13706: intended as throw codes. They typically are in the range
13707: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13708: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13709:
13710: @item maximum depth of file input nesting:
13711: @cindex maximum depth of file input nesting
13712: @cindex file input nesting, maximum depth
13713: limited by the amount of return stack, locals/TIB stack, and the number
13714: of open files available. This should not give you troubles.
13715:
13716: @item maximum size of input line:
13717: @cindex maximum size of input line
13718: @cindex input line size, maximum
13719: @code{/line}. Currently 255.
13720:
13721: @item methods of mapping block ranges to files:
13722: @cindex mapping block ranges to files
13723: @cindex files containing blocks
13724: @cindex blocks in files
13725: By default, blocks are accessed in the file @file{blocks.fb} in the
13726: current working directory. The file can be switched with @code{USE}.
13727:
13728: @item number of string buffers provided by @code{S"}:
13729: @cindex @code{S"}, number of string buffers
13730: 1
13731:
13732: @item size of string buffer used by @code{S"}:
13733: @cindex @code{S"}, size of string buffer
13734: @code{/line}. currently 255.
13735:
13736: @end table
13737:
13738: @c ---------------------------------------------------------------------
13739: @node file-ambcond, , file-idef, The optional File-Access word set
13740: @subsection Ambiguous conditions
13741: @c ---------------------------------------------------------------------
13742: @cindex file words, ambiguous conditions
13743: @cindex ambiguous conditions, file words
13744:
13745: @table @i
13746: @item attempting to position a file outside its boundaries:
13747: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13748: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13749: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13750:
13751: @item attempting to read from file positions not yet written:
13752: @cindex reading from file positions not yet written
13753: End-of-file, i.e., zero characters are read and no error is reported.
13754:
1.29 crook 13755: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13756: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13757: An appropriate exception may be thrown, but a memory fault or other
13758: problem is more probable.
13759:
1.29 crook 13760: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13761: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13762: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13763: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13764: thrown.
13765:
13766: @item named file cannot be opened (@code{INCLUDED}):
13767: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13768: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13769:
13770: @item requesting an unmapped block number:
13771: @cindex unmapped block numbers
13772: There are no unmapped legal block numbers. On some operating systems,
13773: writing a block with a large number may overflow the file system and
13774: have an error message as consequence.
13775:
13776: @item using @code{source-id} when @code{blk} is non-zero:
13777: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13778: @code{source-id} performs its function. Typically it will give the id of
13779: the source which loaded the block. (Better ideas?)
13780:
13781: @end table
13782:
13783:
13784: @c =====================================================================
13785: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13786: @section The optional Floating-Point word set
13787: @c =====================================================================
13788: @cindex system documentation, floating-point words
13789: @cindex floating-point words, system documentation
13790:
13791: @menu
13792: * floating-idef:: Implementation Defined Options
13793: * floating-ambcond:: Ambiguous Conditions
13794: @end menu
13795:
13796:
13797: @c ---------------------------------------------------------------------
13798: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13799: @subsection Implementation Defined Options
13800: @c ---------------------------------------------------------------------
13801: @cindex implementation-defined options, floating-point words
13802: @cindex floating-point words, implementation-defined options
13803:
13804: @table @i
13805: @item format and range of floating point numbers:
13806: @cindex format and range of floating point numbers
13807: @cindex floating point numbers, format and range
13808: System-dependent; the @code{double} type of C.
13809:
1.29 crook 13810: @item results of @code{REPRESENT} when @i{float} is out of range:
13811: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13812: System dependent; @code{REPRESENT} is implemented using the C library
13813: function @code{ecvt()} and inherits its behaviour in this respect.
13814:
13815: @item rounding or truncation of floating-point numbers:
13816: @cindex rounding of floating-point numbers
13817: @cindex truncation of floating-point numbers
13818: @cindex floating-point numbers, rounding or truncation
13819: System dependent; the rounding behaviour is inherited from the hosting C
13820: compiler. IEEE-FP-based (i.e., most) systems by default round to
13821: nearest, and break ties by rounding to even (i.e., such that the last
13822: bit of the mantissa is 0).
13823:
13824: @item size of floating-point stack:
13825: @cindex floating-point stack size
13826: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13827: the floating-point stack (in floats). You can specify this on startup
13828: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13829:
13830: @item width of floating-point stack:
13831: @cindex floating-point stack width
13832: @code{1 floats}.
13833:
13834: @end table
13835:
13836:
13837: @c ---------------------------------------------------------------------
13838: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13839: @subsection Ambiguous conditions
13840: @c ---------------------------------------------------------------------
13841: @cindex floating-point words, ambiguous conditions
13842: @cindex ambiguous conditions, floating-point words
13843:
13844: @table @i
13845: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13846: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13847: System-dependent. Typically results in a @code{-23 THROW} like other
13848: alignment violations.
13849:
13850: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13851: @cindex @code{f@@} used with an address that is not float aligned
13852: @cindex @code{f!} used with an address that is not float aligned
13853: System-dependent. Typically results in a @code{-23 THROW} like other
13854: alignment violations.
13855:
13856: @item floating-point result out of range:
13857: @cindex floating-point result out of range
1.80 anton 13858: System-dependent. Can result in a @code{-43 throw} (floating point
13859: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13860: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13861: unidentified fault), or can produce a special value representing, e.g.,
13862: Infinity.
13863:
13864: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13865: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13866: System-dependent. Typically results in an alignment fault like other
13867: alignment violations.
13868:
1.35 anton 13869: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13870: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13871: The floating-point number is converted into decimal nonetheless.
13872:
13873: @item Both arguments are equal to zero (@code{FATAN2}):
13874: @cindex @code{FATAN2}, both arguments are equal to zero
13875: System-dependent. @code{FATAN2} is implemented using the C library
13876: function @code{atan2()}.
13877:
1.29 crook 13878: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13879: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13880: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13881: because of small errors and the tan will be a very large (or very small)
13882: but finite number.
13883:
1.29 crook 13884: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13885: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13886: The result is rounded to the nearest float.
13887:
13888: @item dividing by zero:
13889: @cindex dividing by zero, floating-point
13890: @cindex floating-point dividing by zero
13891: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13892: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13893: (floating point divide by zero) or @code{-55 throw} (Floating-point
13894: unidentified fault).
1.1 anton 13895:
13896: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13897: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13898: System dependent. On IEEE-FP based systems the number is converted into
13899: an infinity.
13900:
1.29 crook 13901: @item @i{float}<1 (@code{FACOSH}):
13902: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13903: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13904: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13905:
1.29 crook 13906: @item @i{float}=<-1 (@code{FLNP1}):
13907: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13908: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13909: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13910: negative infinity for @i{float}=-1).
1.1 anton 13911:
1.29 crook 13912: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13913: @cindex @code{FLN}, @i{float}=<0
13914: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13915: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13916: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13917: negative infinity for @i{float}=0).
1.1 anton 13918:
1.29 crook 13919: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13920: @cindex @code{FASINH}, @i{float}<0
13921: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13922: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13923: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13924: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13925: C library?).
1.1 anton 13926:
1.29 crook 13927: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13928: @cindex @code{FACOS}, |@i{float}|>1
13929: @cindex @code{FASIN}, |@i{float}|>1
13930: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13931: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13932: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13933:
1.29 crook 13934: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13935: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13936: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13937: Platform-dependent; typically, some double number is produced and no
13938: error is reported.
1.1 anton 13939:
13940: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13941: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13942: @code{Precision} characters of the numeric output area are used. If
13943: @code{precision} is too high, these words will smash the data or code
13944: close to @code{here}.
1.1 anton 13945: @end table
13946:
13947: @c =====================================================================
13948: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13949: @section The optional Locals word set
13950: @c =====================================================================
13951: @cindex system documentation, locals words
13952: @cindex locals words, system documentation
13953:
13954: @menu
13955: * locals-idef:: Implementation Defined Options
13956: * locals-ambcond:: Ambiguous Conditions
13957: @end menu
13958:
13959:
13960: @c ---------------------------------------------------------------------
13961: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13962: @subsection Implementation Defined Options
13963: @c ---------------------------------------------------------------------
13964: @cindex implementation-defined options, locals words
13965: @cindex locals words, implementation-defined options
13966:
13967: @table @i
13968: @item maximum number of locals in a definition:
13969: @cindex maximum number of locals in a definition
13970: @cindex locals, maximum number in a definition
13971: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13972: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13973: characters. The number of locals in a definition is bounded by the size
13974: of locals-buffer, which contains the names of the locals.
13975:
13976: @end table
13977:
13978:
13979: @c ---------------------------------------------------------------------
13980: @node locals-ambcond, , locals-idef, The optional Locals word set
13981: @subsection Ambiguous conditions
13982: @c ---------------------------------------------------------------------
13983: @cindex locals words, ambiguous conditions
13984: @cindex ambiguous conditions, locals words
13985:
13986: @table @i
13987: @item executing a named local in interpretation state:
13988: @cindex local in interpretation state
13989: @cindex Interpreting a compile-only word, for a local
13990: Locals have no interpretation semantics. If you try to perform the
13991: interpretation semantics, you will get a @code{-14 throw} somewhere
13992: (Interpreting a compile-only word). If you perform the compilation
13993: semantics, the locals access will be compiled (irrespective of state).
13994:
1.29 crook 13995: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13996: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13997: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13998: @cindex Invalid name argument, @code{TO}
13999: @code{-32 throw} (Invalid name argument)
14000:
14001: @end table
14002:
14003:
14004: @c =====================================================================
14005: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14006: @section The optional Memory-Allocation word set
14007: @c =====================================================================
14008: @cindex system documentation, memory-allocation words
14009: @cindex memory-allocation words, system documentation
14010:
14011: @menu
14012: * memory-idef:: Implementation Defined Options
14013: @end menu
14014:
14015:
14016: @c ---------------------------------------------------------------------
14017: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14018: @subsection Implementation Defined Options
14019: @c ---------------------------------------------------------------------
14020: @cindex implementation-defined options, memory-allocation words
14021: @cindex memory-allocation words, implementation-defined options
14022:
14023: @table @i
1.29 crook 14024: @item values and meaning of @i{ior}:
14025: @cindex @i{ior} values and meaning
14026: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14027: intended as throw codes. They typically are in the range
14028: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14029: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14030:
14031: @end table
14032:
14033: @c =====================================================================
14034: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14035: @section The optional Programming-Tools word set
14036: @c =====================================================================
14037: @cindex system documentation, programming-tools words
14038: @cindex programming-tools words, system documentation
14039:
14040: @menu
14041: * programming-idef:: Implementation Defined Options
14042: * programming-ambcond:: Ambiguous Conditions
14043: @end menu
14044:
14045:
14046: @c ---------------------------------------------------------------------
14047: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14048: @subsection Implementation Defined Options
14049: @c ---------------------------------------------------------------------
14050: @cindex implementation-defined options, programming-tools words
14051: @cindex programming-tools words, implementation-defined options
14052:
14053: @table @i
14054: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14055: @cindex @code{;CODE} ending sequence
14056: @cindex @code{CODE} ending sequence
14057: @code{END-CODE}
14058:
14059: @item manner of processing input following @code{;CODE} and @code{CODE}:
14060: @cindex @code{;CODE}, processing input
14061: @cindex @code{CODE}, processing input
14062: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14063: the input is processed by the text interpreter, (starting) in interpret
14064: state.
14065:
14066: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14067: @cindex @code{ASSEMBLER}, search order capability
14068: The ANS Forth search order word set.
14069:
14070: @item source and format of display by @code{SEE}:
14071: @cindex @code{SEE}, source and format of output
1.80 anton 14072: The source for @code{see} is the executable code used by the inner
1.1 anton 14073: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14074: (and on some platforms, assembly code for primitives) as well as
14075: possible.
1.1 anton 14076:
14077: @end table
14078:
14079: @c ---------------------------------------------------------------------
14080: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14081: @subsection Ambiguous conditions
14082: @c ---------------------------------------------------------------------
14083: @cindex programming-tools words, ambiguous conditions
14084: @cindex ambiguous conditions, programming-tools words
14085:
14086: @table @i
14087:
1.21 crook 14088: @item deleting the compilation word list (@code{FORGET}):
14089: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14090: Not implemented (yet).
14091:
1.29 crook 14092: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14093: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14094: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14095: @cindex control-flow stack underflow
14096: This typically results in an @code{abort"} with a descriptive error
14097: message (may change into a @code{-22 throw} (Control structure mismatch)
14098: in the future). You may also get a memory access error. If you are
14099: unlucky, this ambiguous condition is not caught.
14100:
1.29 crook 14101: @item @i{name} can't be found (@code{FORGET}):
14102: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14103: Not implemented (yet).
14104:
1.29 crook 14105: @item @i{name} not defined via @code{CREATE}:
14106: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14107: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14108: the execution semantics of the last defined word no matter how it was
14109: defined.
14110:
14111: @item @code{POSTPONE} applied to @code{[IF]}:
14112: @cindex @code{POSTPONE} applied to @code{[IF]}
14113: @cindex @code{[IF]} and @code{POSTPONE}
14114: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14115: equivalent to @code{[IF]}.
14116:
14117: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14118: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14119: Continue in the same state of conditional compilation in the next outer
14120: input source. Currently there is no warning to the user about this.
14121:
14122: @item removing a needed definition (@code{FORGET}):
14123: @cindex @code{FORGET}, removing a needed definition
14124: Not implemented (yet).
14125:
14126: @end table
14127:
14128:
14129: @c =====================================================================
14130: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14131: @section The optional Search-Order word set
14132: @c =====================================================================
14133: @cindex system documentation, search-order words
14134: @cindex search-order words, system documentation
14135:
14136: @menu
14137: * search-idef:: Implementation Defined Options
14138: * search-ambcond:: Ambiguous Conditions
14139: @end menu
14140:
14141:
14142: @c ---------------------------------------------------------------------
14143: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14144: @subsection Implementation Defined Options
14145: @c ---------------------------------------------------------------------
14146: @cindex implementation-defined options, search-order words
14147: @cindex search-order words, implementation-defined options
14148:
14149: @table @i
14150: @item maximum number of word lists in search order:
14151: @cindex maximum number of word lists in search order
14152: @cindex search order, maximum depth
14153: @code{s" wordlists" environment? drop .}. Currently 16.
14154:
14155: @item minimum search order:
14156: @cindex minimum search order
14157: @cindex search order, minimum
14158: @code{root root}.
14159:
14160: @end table
14161:
14162: @c ---------------------------------------------------------------------
14163: @node search-ambcond, , search-idef, The optional Search-Order word set
14164: @subsection Ambiguous conditions
14165: @c ---------------------------------------------------------------------
14166: @cindex search-order words, ambiguous conditions
14167: @cindex ambiguous conditions, search-order words
14168:
14169: @table @i
1.21 crook 14170: @item changing the compilation word list (during compilation):
14171: @cindex changing the compilation word list (during compilation)
14172: @cindex compilation word list, change before definition ends
14173: The word is entered into the word list that was the compilation word list
1.1 anton 14174: at the start of the definition. Any changes to the name field (e.g.,
14175: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14176: are applied to the latest defined word (as reported by @code{latest} or
14177: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14178:
14179: @item search order empty (@code{previous}):
14180: @cindex @code{previous}, search order empty
1.26 crook 14181: @cindex vocstack empty, @code{previous}
1.1 anton 14182: @code{abort" Vocstack empty"}.
14183:
14184: @item too many word lists in search order (@code{also}):
14185: @cindex @code{also}, too many word lists in search order
1.26 crook 14186: @cindex vocstack full, @code{also}
1.1 anton 14187: @code{abort" Vocstack full"}.
14188:
14189: @end table
14190:
14191: @c ***************************************************************
1.65 anton 14192: @node Standard vs Extensions, Model, ANS conformance, Top
14193: @chapter Should I use Gforth extensions?
14194: @cindex Gforth extensions
14195:
14196: As you read through the rest of this manual, you will see documentation
14197: for @i{Standard} words, and documentation for some appealing Gforth
14198: @i{extensions}. You might ask yourself the question: @i{``Should I
14199: restrict myself to the standard, or should I use the extensions?''}
14200:
14201: The answer depends on the goals you have for the program you are working
14202: on:
14203:
14204: @itemize @bullet
14205:
14206: @item Is it just for yourself or do you want to share it with others?
14207:
14208: @item
14209: If you want to share it, do the others all use Gforth?
14210:
14211: @item
14212: If it is just for yourself, do you want to restrict yourself to Gforth?
14213:
14214: @end itemize
14215:
14216: If restricting the program to Gforth is ok, then there is no reason not
14217: to use extensions. It is still a good idea to keep to the standard
14218: where it is easy, in case you want to reuse these parts in another
14219: program that you want to be portable.
14220:
14221: If you want to be able to port the program to other Forth systems, there
14222: are the following points to consider:
14223:
14224: @itemize @bullet
14225:
14226: @item
14227: Most Forth systems that are being maintained support the ANS Forth
14228: standard. So if your program complies with the standard, it will be
14229: portable among many systems.
14230:
14231: @item
14232: A number of the Gforth extensions can be implemented in ANS Forth using
14233: public-domain files provided in the @file{compat/} directory. These are
14234: mentioned in the text in passing. There is no reason not to use these
14235: extensions, your program will still be ANS Forth compliant; just include
14236: the appropriate compat files with your program.
14237:
14238: @item
14239: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14240: analyse your program and determine what non-Standard words it relies
14241: upon. However, it does not check whether you use standard words in a
14242: non-standard way.
14243:
14244: @item
14245: Some techniques are not standardized by ANS Forth, and are hard or
14246: impossible to implement in a standard way, but can be implemented in
14247: most Forth systems easily, and usually in similar ways (e.g., accessing
14248: word headers). Forth has a rich historical precedent for programmers
14249: taking advantage of implementation-dependent features of their tools
14250: (for example, relying on a knowledge of the dictionary
14251: structure). Sometimes these techniques are necessary to extract every
14252: last bit of performance from the hardware, sometimes they are just a
14253: programming shorthand.
14254:
14255: @item
14256: Does using a Gforth extension save more work than the porting this part
14257: to other Forth systems (if any) will cost?
14258:
14259: @item
14260: Is the additional functionality worth the reduction in portability and
14261: the additional porting problems?
14262:
14263: @end itemize
14264:
14265: In order to perform these consideratios, you need to know what's
14266: standard and what's not. This manual generally states if something is
1.81 anton 14267: non-standard, but the authoritative source is the
14268: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14269: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14270: into the thought processes of the technical committee.
14271:
14272: Note also that portability between Forth systems is not the only
14273: portability issue; there is also the issue of portability between
14274: different platforms (processor/OS combinations).
14275:
14276: @c ***************************************************************
14277: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14278: @chapter Model
14279:
14280: This chapter has yet to be written. It will contain information, on
14281: which internal structures you can rely.
14282:
14283: @c ***************************************************************
14284: @node Integrating Gforth, Emacs and Gforth, Model, Top
14285: @chapter Integrating Gforth into C programs
14286:
14287: This is not yet implemented.
14288:
14289: Several people like to use Forth as scripting language for applications
14290: that are otherwise written in C, C++, or some other language.
14291:
14292: The Forth system ATLAST provides facilities for embedding it into
14293: applications; unfortunately it has several disadvantages: most
14294: importantly, it is not based on ANS Forth, and it is apparently dead
14295: (i.e., not developed further and not supported). The facilities
1.21 crook 14296: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14297: making the switch should not be hard.
14298:
14299: We also tried to design the interface such that it can easily be
14300: implemented by other Forth systems, so that we may one day arrive at a
14301: standardized interface. Such a standard interface would allow you to
14302: replace the Forth system without having to rewrite C code.
14303:
14304: You embed the Gforth interpreter by linking with the library
14305: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14306: global symbols in this library that belong to the interface, have the
14307: prefix @code{forth_}. (Global symbols that are used internally have the
14308: prefix @code{gforth_}).
14309:
14310: You can include the declarations of Forth types and the functions and
14311: variables of the interface with @code{#include <forth.h>}.
14312:
14313: Types.
14314:
14315: Variables.
14316:
14317: Data and FP Stack pointer. Area sizes.
14318:
14319: functions.
14320:
14321: forth_init(imagefile)
14322: forth_evaluate(string) exceptions?
14323: forth_goto(address) (or forth_execute(xt)?)
14324: forth_continue() (a corountining mechanism)
14325:
14326: Adding primitives.
14327:
14328: No checking.
14329:
14330: Signals?
14331:
14332: Accessing the Stacks
14333:
1.26 crook 14334: @c ******************************************************************
1.1 anton 14335: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14336: @chapter Emacs and Gforth
14337: @cindex Emacs and Gforth
14338:
14339: @cindex @file{gforth.el}
14340: @cindex @file{forth.el}
14341: @cindex Rydqvist, Goran
1.107 dvdkhlng 14342: @cindex Kuehling, David
1.1 anton 14343: @cindex comment editing commands
14344: @cindex @code{\}, editing with Emacs
14345: @cindex debug tracer editing commands
14346: @cindex @code{~~}, removal with Emacs
14347: @cindex Forth mode in Emacs
1.107 dvdkhlng 14348:
1.1 anton 14349: Gforth comes with @file{gforth.el}, an improved version of
14350: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14351: improvements are:
14352:
14353: @itemize @bullet
14354: @item
1.107 dvdkhlng 14355: A better handling of indentation.
14356: @item
14357: A custom hilighting engine for Forth-code.
1.26 crook 14358: @item
14359: Comment paragraph filling (@kbd{M-q})
14360: @item
14361: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14362: @item
14363: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14364: @item
14365: Support of the @code{info-lookup} feature for looking up the
14366: documentation of a word.
1.107 dvdkhlng 14367: @item
14368: Support for reading and writing blocks files.
1.26 crook 14369: @end itemize
14370:
1.107 dvdkhlng 14371: To get a basic description of these features, enter Forth mode and
14372: type @kbd{C-h m}.
1.1 anton 14373:
14374: @cindex source location of error or debugging output in Emacs
14375: @cindex error output, finding the source location in Emacs
14376: @cindex debugging output, finding the source location in Emacs
14377: In addition, Gforth supports Emacs quite well: The source code locations
14378: given in error messages, debugging output (from @code{~~}) and failed
14379: assertion messages are in the right format for Emacs' compilation mode
14380: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14381: Manual}) so the source location corresponding to an error or other
14382: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14383: @kbd{C-c C-c} for the error under the cursor).
14384:
1.107 dvdkhlng 14385: @cindex viewing the documentation of a word in Emacs
14386: @cindex context-sensitive help
14387: Moreover, for words documented in this manual, you can look up the
14388: glossary entry quickly by using @kbd{C-h TAB}
14389: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14390: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14391: later and does not work for words containing @code{:}.
14392:
14393: @menu
14394: * Installing gforth.el:: Making Emacs aware of Forth.
14395: * Emacs Tags:: Viewing the source of a word in Emacs.
14396: * Hilighting:: Making Forth code look prettier.
14397: * Auto-Indentation:: Customizing auto-indentation.
14398: * Blocks Files:: Reading and writing blocks files.
14399: @end menu
14400:
14401: @c ----------------------------------
1.109 anton 14402: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14403: @section Installing gforth.el
14404: @cindex @file{.emacs}
14405: @cindex @file{gforth.el}, installation
14406: To make the features from @file{gforth.el} available in Emacs, add
14407: the following lines to your @file{.emacs} file:
14408:
14409: @example
14410: (autoload 'forth-mode "gforth.el")
14411: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14412: auto-mode-alist))
14413: (autoload 'forth-block-mode "gforth.el")
14414: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14415: auto-mode-alist))
14416: (add-hook 'forth-mode-hook (function (lambda ()
14417: ;; customize variables here:
14418: (setq forth-indent-level 4)
14419: (setq forth-minor-indent-level 2)
14420: (setq forth-hilight-level 3)
14421: ;;; ...
14422: )))
14423: @end example
14424:
14425: @c ----------------------------------
14426: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14427: @section Emacs Tags
1.1 anton 14428: @cindex @file{TAGS} file
14429: @cindex @file{etags.fs}
14430: @cindex viewing the source of a word in Emacs
1.43 anton 14431: @cindex @code{require}, placement in files
14432: @cindex @code{include}, placement in files
1.107 dvdkhlng 14433: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14434: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14435: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14436: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14437: several tags files at the same time (e.g., one for the Gforth sources
14438: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14439: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14440: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14441: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14442: with @file{etags.fs}, you should avoid putting definitions both before
14443: and after @code{require} etc., otherwise you will see the same file
14444: visited several times by commands like @code{tags-search}.
1.1 anton 14445:
1.107 dvdkhlng 14446: @c ----------------------------------
14447: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14448: @section Hilighting
14449: @cindex hilighting Forth code in Emacs
14450: @cindex highlighting Forth code in Emacs
14451: @file{gforth.el} comes with a custom source hilighting engine. When
14452: you open a file in @code{forth-mode}, it will be completely parsed,
14453: assigning faces to keywords, comments, strings etc. While you edit
14454: the file, modified regions get parsed and updated on-the-fly.
14455:
14456: Use the variable `forth-hilight-level' to change the level of
14457: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14458: you set the hilighting level to 0, the parser will still work in the
14459: background, collecting information about whether regions of text are
14460: ``compiled'' or ``interpreted''. Those information are required for
14461: auto-indentation to work properly. Set `forth-disable-parser' to
14462: non-nil if your computer is too slow to handle parsing. This will
14463: have an impact on the smartness of the auto-indentation engine,
14464: though.
14465:
14466: Sometimes Forth sources define new features that should be hilighted,
14467: new control structures, defining-words etc. You can use the variable
14468: `forth-custom-words' to make @code{forth-mode} hilight additional
14469: words and constructs. See the docstring of `forth-words' for details
14470: (in Emacs, type @kbd{C-h v forth-words}).
14471:
14472: `forth-custom-words' is meant to be customized in your
14473: @file{.emacs} file. To customize hilighing in a file-specific manner,
14474: set `forth-local-words' in a local-variables section at the end of
14475: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14476:
14477: Example:
14478: @example
14479: 0 [IF]
14480: Local Variables:
14481: forth-local-words:
14482: ((("t:") definition-starter (font-lock-keyword-face . 1)
14483: "[ \t\n]" t name (font-lock-function-name-face . 3))
14484: ((";t") definition-ender (font-lock-keyword-face . 1)))
14485: End:
14486: [THEN]
14487: @end example
14488:
14489: @c ----------------------------------
14490: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14491: @section Auto-Indentation
14492: @cindex auto-indentation of Forth code in Emacs
14493: @cindex indentation of Forth code in Emacs
14494: @code{forth-mode} automatically tries to indent lines in a smart way,
14495: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14496:
14497: Simple customization can be achieved by setting
14498: `forth-indent-level' and `forth-minor-indent-level' in your
14499: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14500: per default by multiples of 4 columns. To use the more traditional
14501: 3-column indentation, add the following lines to your @file{.emacs}:
14502:
14503: @example
14504: (add-hook 'forth-mode-hook (function (lambda ()
14505: ;; customize variables here:
14506: (setq forth-indent-level 3)
14507: (setq forth-minor-indent-level 1)
14508: )))
14509: @end example
14510:
14511: If you want indentation to recognize non-default words, customize it
14512: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14513: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14514: v forth-indent-words}).
14515:
14516: To customize indentation in a file-specific manner, set
14517: `forth-local-indent-words' in a local-variables section at the end of
14518: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14519: Emacs Manual}).
14520:
14521: Example:
14522: @example
14523: 0 [IF]
14524: Local Variables:
14525: forth-local-indent-words:
14526: ((("t:") (0 . 2) (0 . 2))
14527: ((";t") (-2 . 0) (0 . -2)))
14528: End:
14529: [THEN]
14530: @end example
14531:
14532: @c ----------------------------------
1.109 anton 14533: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14534: @section Blocks Files
14535: @cindex blocks files, use with Emacs
14536: @code{forth-mode} Autodetects blocks files by checking whether the
14537: length of the first line exceeds 1023 characters. It then tries to
14538: convert the file into normal text format. When you save the file, it
14539: will be written to disk as normal stream-source file.
14540:
14541: If you want to write blocks files, use @code{forth-blocks-mode}. It
14542: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14543:
1.107 dvdkhlng 14544: @itemize @bullet
14545: @item
14546: Files are written to disk in blocks file format.
14547: @item
14548: Screen numbers are displayed in the mode line (enumerated beginning
14549: with the value of `forth-block-base')
14550: @item
14551: Warnings are displayed when lines exceed 64 characters.
14552: @item
14553: The beginning of the currently edited block is marked with an
14554: overlay-arrow.
14555: @end itemize
1.41 anton 14556:
1.107 dvdkhlng 14557: There are some restrictions you should be aware of. When you open a
14558: blocks file that contains tabulator or newline characters, these
14559: characters will be translated into spaces when the file is written
14560: back to disk. If tabs or newlines are encountered during blocks file
14561: reading, an error is output to the echo area. So have a look at the
14562: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14563:
1.107 dvdkhlng 14564: Please consult the docstring of @code{forth-blocks-mode} for more
14565: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14566:
1.26 crook 14567: @c ******************************************************************
1.1 anton 14568: @node Image Files, Engine, Emacs and Gforth, Top
14569: @chapter Image Files
1.26 crook 14570: @cindex image file
14571: @cindex @file{.fi} files
1.1 anton 14572: @cindex precompiled Forth code
14573: @cindex dictionary in persistent form
14574: @cindex persistent form of dictionary
14575:
14576: An image file is a file containing an image of the Forth dictionary,
14577: i.e., compiled Forth code and data residing in the dictionary. By
14578: convention, we use the extension @code{.fi} for image files.
14579:
14580: @menu
1.18 anton 14581: * Image Licensing Issues:: Distribution terms for images.
14582: * Image File Background:: Why have image files?
1.67 anton 14583: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14584: * Data-Relocatable Image Files:: are better.
1.67 anton 14585: * Fully Relocatable Image Files:: better yet.
1.18 anton 14586: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14587: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14588: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14589: @end menu
14590:
1.18 anton 14591: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14592: @section Image Licensing Issues
14593: @cindex license for images
14594: @cindex image license
14595:
14596: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14597: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14598: original image; i.e., according to copyright law it is a derived work of
14599: the original image.
14600:
14601: Since Gforth is distributed under the GNU GPL, the newly created image
14602: falls under the GNU GPL, too. In particular, this means that if you
14603: distribute the image, you have to make all of the sources for the image
1.113 anton 14604: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14605: GNU General Public License (Section 3)}.
14606:
14607: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14608: contains only code compiled from the sources you gave it; if none of
14609: these sources is under the GPL, the terms discussed above do not apply
14610: to the image. However, if your image needs an engine (a gforth binary)
14611: that is under the GPL, you should make sure that you distribute both in
14612: a way that is at most a @emph{mere aggregation}, if you don't want the
14613: terms of the GPL to apply to the image.
14614:
14615: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14616: @section Image File Background
14617: @cindex image file background
14618:
1.80 anton 14619: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14620: definitions written in Forth. Since the Forth compiler itself belongs to
14621: those definitions, it is not possible to start the system with the
1.80 anton 14622: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14623: code as an image file in nearly executable form. When Gforth starts up,
14624: a C routine loads the image file into memory, optionally relocates the
14625: addresses, then sets up the memory (stacks etc.) according to
14626: information in the image file, and (finally) starts executing Forth
14627: code.
1.1 anton 14628:
14629: The image file variants represent different compromises between the
14630: goals of making it easy to generate image files and making them
14631: portable.
14632:
14633: @cindex relocation at run-time
1.26 crook 14634: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14635: run-time. This avoids many of the complications discussed below (image
14636: files are data relocatable without further ado), but costs performance
14637: (one addition per memory access).
14638:
14639: @cindex relocation at load-time
1.26 crook 14640: By contrast, the Gforth loader performs relocation at image load time. The
14641: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14642: appropriate code-field addresses (or code addresses in the case of
14643: direct threading).
14644:
14645: There are three kinds of image files, with different degrees of
14646: relocatability: non-relocatable, data-relocatable, and fully relocatable
14647: image files.
14648:
14649: @cindex image file loader
14650: @cindex relocating loader
14651: @cindex loader for image files
14652: These image file variants have several restrictions in common; they are
14653: caused by the design of the image file loader:
14654:
14655: @itemize @bullet
14656: @item
14657: There is only one segment; in particular, this means, that an image file
14658: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14659: them). The contents of the stacks are not represented, either.
1.1 anton 14660:
14661: @item
14662: The only kinds of relocation supported are: adding the same offset to
14663: all cells that represent data addresses; and replacing special tokens
14664: with code addresses or with pieces of machine code.
14665:
14666: If any complex computations involving addresses are performed, the
14667: results cannot be represented in the image file. Several applications that
14668: use such computations come to mind:
14669: @itemize @minus
14670: @item
14671: Hashing addresses (or data structures which contain addresses) for table
14672: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14673: purpose, you will have no problem, because the hash tables are
14674: recomputed automatically when the system is started. If you use your own
14675: hash tables, you will have to do something similar.
14676:
14677: @item
14678: There's a cute implementation of doubly-linked lists that uses
14679: @code{XOR}ed addresses. You could represent such lists as singly-linked
14680: in the image file, and restore the doubly-linked representation on
14681: startup.@footnote{In my opinion, though, you should think thrice before
14682: using a doubly-linked list (whatever implementation).}
14683:
14684: @item
14685: The code addresses of run-time routines like @code{docol:} cannot be
14686: represented in the image file (because their tokens would be replaced by
14687: machine code in direct threaded implementations). As a workaround,
14688: compute these addresses at run-time with @code{>code-address} from the
14689: executions tokens of appropriate words (see the definitions of
1.80 anton 14690: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14691:
14692: @item
14693: On many architectures addresses are represented in machine code in some
14694: shifted or mangled form. You cannot put @code{CODE} words that contain
14695: absolute addresses in this form in a relocatable image file. Workarounds
14696: are representing the address in some relative form (e.g., relative to
14697: the CFA, which is present in some register), or loading the address from
14698: a place where it is stored in a non-mangled form.
14699: @end itemize
14700: @end itemize
14701:
14702: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14703: @section Non-Relocatable Image Files
14704: @cindex non-relocatable image files
1.26 crook 14705: @cindex image file, non-relocatable
1.1 anton 14706:
14707: These files are simple memory dumps of the dictionary. They are specific
14708: to the executable (i.e., @file{gforth} file) they were created
14709: with. What's worse, they are specific to the place on which the
14710: dictionary resided when the image was created. Now, there is no
14711: guarantee that the dictionary will reside at the same place the next
14712: time you start Gforth, so there's no guarantee that a non-relocatable
14713: image will work the next time (Gforth will complain instead of crashing,
14714: though).
14715:
14716: You can create a non-relocatable image file with
14717:
1.44 crook 14718:
1.1 anton 14719: doc-savesystem
14720:
1.44 crook 14721:
1.1 anton 14722: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14723: @section Data-Relocatable Image Files
14724: @cindex data-relocatable image files
1.26 crook 14725: @cindex image file, data-relocatable
1.1 anton 14726:
14727: These files contain relocatable data addresses, but fixed code addresses
14728: (instead of tokens). They are specific to the executable (i.e.,
14729: @file{gforth} file) they were created with. For direct threading on some
14730: architectures (e.g., the i386), data-relocatable images do not work. You
14731: get a data-relocatable image, if you use @file{gforthmi} with a
14732: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14733: Relocatable Image Files}).
14734:
14735: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14736: @section Fully Relocatable Image Files
14737: @cindex fully relocatable image files
1.26 crook 14738: @cindex image file, fully relocatable
1.1 anton 14739:
14740: @cindex @file{kern*.fi}, relocatability
14741: @cindex @file{gforth.fi}, relocatability
14742: These image files have relocatable data addresses, and tokens for code
14743: addresses. They can be used with different binaries (e.g., with and
14744: without debugging) on the same machine, and even across machines with
14745: the same data formats (byte order, cell size, floating point
14746: format). However, they are usually specific to the version of Gforth
14747: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14748: are fully relocatable.
14749:
14750: There are two ways to create a fully relocatable image file:
14751:
14752: @menu
1.29 crook 14753: * gforthmi:: The normal way
1.1 anton 14754: * cross.fs:: The hard way
14755: @end menu
14756:
14757: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14758: @subsection @file{gforthmi}
14759: @cindex @file{comp-i.fs}
14760: @cindex @file{gforthmi}
14761:
14762: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14763: image @i{file} that contains everything you would load by invoking
14764: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14765: @example
1.29 crook 14766: gforthmi @i{file} @i{options}
1.1 anton 14767: @end example
14768:
14769: E.g., if you want to create an image @file{asm.fi} that has the file
14770: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14771: like this:
14772:
14773: @example
14774: gforthmi asm.fi asm.fs
14775: @end example
14776:
1.27 crook 14777: @file{gforthmi} is implemented as a sh script and works like this: It
14778: produces two non-relocatable images for different addresses and then
14779: compares them. Its output reflects this: first you see the output (if
1.62 crook 14780: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14781: files, then you see the output of the comparing program: It displays the
14782: offset used for data addresses and the offset used for code addresses;
1.1 anton 14783: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14784: image files, it displays a line like this:
1.1 anton 14785:
14786: @example
14787: 78DC BFFFFA50 BFFFFA40
14788: @end example
14789:
14790: This means that at offset $78dc from @code{forthstart}, one input image
14791: contains $bffffa50, and the other contains $bffffa40. Since these cells
14792: cannot be represented correctly in the output image, you should examine
14793: these places in the dictionary and verify that these cells are dead
14794: (i.e., not read before they are written).
1.39 anton 14795:
14796: @cindex --application, @code{gforthmi} option
14797: If you insert the option @code{--application} in front of the image file
14798: name, you will get an image that uses the @code{--appl-image} option
14799: instead of the @code{--image-file} option (@pxref{Invoking
14800: Gforth}). When you execute such an image on Unix (by typing the image
14801: name as command), the Gforth engine will pass all options to the image
14802: instead of trying to interpret them as engine options.
1.1 anton 14803:
1.27 crook 14804: If you type @file{gforthmi} with no arguments, it prints some usage
14805: instructions.
14806:
1.1 anton 14807: @cindex @code{savesystem} during @file{gforthmi}
14808: @cindex @code{bye} during @file{gforthmi}
14809: @cindex doubly indirect threaded code
1.44 crook 14810: @cindex environment variables
14811: @cindex @code{GFORTHD} -- environment variable
14812: @cindex @code{GFORTH} -- environment variable
1.1 anton 14813: @cindex @code{gforth-ditc}
1.29 crook 14814: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14815: words @code{savesystem} and @code{bye} must be visible. A special doubly
14816: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14817: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14818: this executable through the environment variable @code{GFORTHD}
14819: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14820: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14821: data-relocatable image (because there is no code address offset). The
14822: normal @file{gforth} executable is used for creating the relocatable
14823: image; you can pass the exact filename of this executable through the
14824: environment variable @code{GFORTH}.
1.1 anton 14825:
14826: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14827: @subsection @file{cross.fs}
14828: @cindex @file{cross.fs}
14829: @cindex cross-compiler
14830: @cindex metacompiler
1.47 crook 14831: @cindex target compiler
1.1 anton 14832:
14833: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14834: programming language (@pxref{Cross Compiler}).
1.1 anton 14835:
1.47 crook 14836: @code{cross} allows you to create image files for machines with
1.1 anton 14837: different data sizes and data formats than the one used for generating
14838: the image file. You can also use it to create an application image that
14839: does not contain a Forth compiler. These features are bought with
14840: restrictions and inconveniences in programming. E.g., addresses have to
14841: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14842: order to make the code relocatable.
14843:
14844:
14845: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14846: @section Stack and Dictionary Sizes
14847: @cindex image file, stack and dictionary sizes
14848: @cindex dictionary size default
14849: @cindex stack size default
14850:
14851: If you invoke Gforth with a command line flag for the size
14852: (@pxref{Invoking Gforth}), the size you specify is stored in the
14853: dictionary. If you save the dictionary with @code{savesystem} or create
14854: an image with @file{gforthmi}, this size will become the default
14855: for the resulting image file. E.g., the following will create a
1.21 crook 14856: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14857:
14858: @example
14859: gforthmi gforth.fi -m 1M
14860: @end example
14861:
14862: In other words, if you want to set the default size for the dictionary
14863: and the stacks of an image, just invoke @file{gforthmi} with the
14864: appropriate options when creating the image.
14865:
14866: @cindex stack size, cache-friendly
14867: Note: For cache-friendly behaviour (i.e., good performance), you should
14868: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14869: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14870: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14871:
14872: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14873: @section Running Image Files
14874: @cindex running image files
14875: @cindex invoking image files
14876: @cindex image file invocation
14877:
14878: @cindex -i, invoke image file
14879: @cindex --image file, invoke image file
1.29 crook 14880: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14881: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14882: @example
1.29 crook 14883: gforth -i @i{image}
1.1 anton 14884: @end example
14885:
14886: @cindex executable image file
1.26 crook 14887: @cindex image file, executable
1.1 anton 14888: If your operating system supports starting scripts with a line of the
14889: form @code{#! ...}, you just have to type the image file name to start
14890: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14891: just a convention). I.e., to run Gforth with the image file @i{image},
14892: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14893: This works because every @code{.fi} file starts with a line of this
14894: format:
14895:
14896: @example
14897: #! /usr/local/bin/gforth-0.4.0 -i
14898: @end example
14899:
14900: The file and pathname for the Gforth engine specified on this line is
14901: the specific Gforth executable that it was built against; i.e. the value
14902: of the environment variable @code{GFORTH} at the time that
14903: @file{gforthmi} was executed.
1.1 anton 14904:
1.27 crook 14905: You can make use of the same shell capability to make a Forth source
14906: file into an executable. For example, if you place this text in a file:
1.26 crook 14907:
14908: @example
14909: #! /usr/local/bin/gforth
14910:
14911: ." Hello, world" CR
14912: bye
14913: @end example
14914:
14915: @noindent
1.27 crook 14916: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14917: directly from the command line. The sequence @code{#!} is used in two
14918: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14919: system@footnote{The Unix kernel actually recognises two types of files:
14920: executable files and files of data, where the data is processed by an
14921: interpreter that is specified on the ``interpreter line'' -- the first
14922: line of the file, starting with the sequence #!. There may be a small
14923: limit (e.g., 32) on the number of characters that may be specified on
14924: the interpreter line.} secondly it is treated as a comment character by
14925: Gforth. Because of the second usage, a space is required between
1.80 anton 14926: @code{#!} and the path to the executable (moreover, some Unixes
14927: require the sequence @code{#! /}).
1.27 crook 14928:
14929: The disadvantage of this latter technique, compared with using
1.80 anton 14930: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14931: compiled on-the-fly, each time the program is invoked.
1.26 crook 14932:
1.1 anton 14933: doc-#!
14934:
1.44 crook 14935:
1.1 anton 14936: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14937: @section Modifying the Startup Sequence
14938: @cindex startup sequence for image file
14939: @cindex image file initialization sequence
14940: @cindex initialization sequence of image file
14941:
1.120 anton 14942: You can add your own initialization to the startup sequence of an image
14943: through the deferred word @code{'cold}. @code{'cold} is invoked just
14944: before the image-specific command line processing (i.e., loading files
14945: and evaluating (@code{-e}) strings) starts.
1.1 anton 14946:
14947: A sequence for adding your initialization usually looks like this:
14948:
14949: @example
14950: :noname
14951: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14952: ... \ your stuff
14953: ; IS 'cold
14954: @end example
14955:
1.157 anton 14956: After @code{'cold}, Gforth processes the image options
14957: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
14958: another deferred word. This normally prints Gforth's startup message
14959: and does nothing else.
14960:
1.1 anton 14961: @cindex turnkey image files
1.26 crook 14962: @cindex image file, turnkey applications
1.157 anton 14963: So, if you want to make a turnkey image (i.e., an image for an
14964: application instead of an extended Forth system), you can do this in
14965: two ways:
14966:
14967: @itemize @bullet
14968:
14969: @item
14970: If you want to do your interpretation of the OS command-line
14971: arguments, hook into @code{'cold}. In that case you probably also
14972: want to build the image with @code{gforthmi --application}
14973: (@pxref{gforthmi}) to keep the engine from processing OS command line
14974: options. You can then do your own command-line processing with
14975: @code{next-arg}
14976:
14977: @item
14978: If you want to have the normal Gforth processing of OS command-line
14979: arguments, hook into @code{bootmessage}.
14980:
14981: @end itemize
14982:
14983: In either case, you probably do not want the word that you execute in
14984: these hooks to exit normally, but use @code{bye} or @code{throw}.
14985: Otherwise the Gforth startup process would continue and eventually
14986: present the Forth command line to the user.
1.26 crook 14987:
14988: doc-'cold
1.157 anton 14989: doc-bootmessage
1.44 crook 14990:
1.1 anton 14991: @c ******************************************************************
1.113 anton 14992: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14993: @chapter Engine
14994: @cindex engine
14995: @cindex virtual machine
14996:
1.26 crook 14997: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14998: may be helpful for finding your way in the Gforth sources.
14999:
1.109 anton 15000: The ideas in this section have also been published in the following
15001: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15002: Forth-Tagung '93; M. Anton Ertl,
15003: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15004: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15005: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15006: Threaded code variations and optimizations (extended version)}},
15007: Forth-Tagung '02.
1.1 anton 15008:
15009: @menu
15010: * Portability::
15011: * Threading::
15012: * Primitives::
15013: * Performance::
15014: @end menu
15015:
15016: @node Portability, Threading, Engine, Engine
15017: @section Portability
15018: @cindex engine portability
15019:
1.26 crook 15020: An important goal of the Gforth Project is availability across a wide
15021: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15022: achieved this goal by manually coding the engine in assembly language
15023: for several then-popular processors. This approach is very
15024: labor-intensive and the results are short-lived due to progress in
15025: computer architecture.
1.1 anton 15026:
15027: @cindex C, using C for the engine
15028: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15029: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15030: particularly popular for UNIX-based Forths due to the large variety of
15031: architectures of UNIX machines. Unfortunately an implementation in C
15032: does not mix well with the goals of efficiency and with using
15033: traditional techniques: Indirect or direct threading cannot be expressed
15034: in C, and switch threading, the fastest technique available in C, is
15035: significantly slower. Another problem with C is that it is very
15036: cumbersome to express double integer arithmetic.
15037:
15038: @cindex GNU C for the engine
15039: @cindex long long
15040: Fortunately, there is a portable language that does not have these
15041: limitations: GNU C, the version of C processed by the GNU C compiler
15042: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15043: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15044: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15045: threading possible, its @code{long long} type (@pxref{Long Long, ,
15046: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15047: double numbers on many systems. GNU C is freely available on all
1.1 anton 15048: important (and many unimportant) UNIX machines, VMS, 80386s running
15049: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15050: on all these machines.
15051:
15052: Writing in a portable language has the reputation of producing code that
15053: is slower than assembly. For our Forth engine we repeatedly looked at
15054: the code produced by the compiler and eliminated most compiler-induced
15055: inefficiencies by appropriate changes in the source code.
15056:
15057: @cindex explicit register declarations
15058: @cindex --enable-force-reg, configuration flag
15059: @cindex -DFORCE_REG
15060: However, register allocation cannot be portably influenced by the
15061: programmer, leading to some inefficiencies on register-starved
15062: machines. We use explicit register declarations (@pxref{Explicit Reg
15063: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15064: improve the speed on some machines. They are turned on by using the
15065: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15066: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15067: machine, but also on the compiler version: On some machines some
15068: compiler versions produce incorrect code when certain explicit register
15069: declarations are used. So by default @code{-DFORCE_REG} is not used.
15070:
15071: @node Threading, Primitives, Portability, Engine
15072: @section Threading
15073: @cindex inner interpreter implementation
15074: @cindex threaded code implementation
15075:
15076: @cindex labels as values
15077: GNU C's labels as values extension (available since @code{gcc-2.0},
15078: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15079: makes it possible to take the address of @i{label} by writing
15080: @code{&&@i{label}}. This address can then be used in a statement like
15081: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15082: @code{goto x}.
15083:
1.26 crook 15084: @cindex @code{NEXT}, indirect threaded
1.1 anton 15085: @cindex indirect threaded inner interpreter
15086: @cindex inner interpreter, indirect threaded
1.26 crook 15087: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15088: @example
15089: cfa = *ip++;
15090: ca = *cfa;
15091: goto *ca;
15092: @end example
15093: @cindex instruction pointer
15094: For those unfamiliar with the names: @code{ip} is the Forth instruction
15095: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15096: execution token and points to the code field of the next word to be
15097: executed; The @code{ca} (code address) fetched from there points to some
15098: executable code, e.g., a primitive or the colon definition handler
15099: @code{docol}.
15100:
1.26 crook 15101: @cindex @code{NEXT}, direct threaded
1.1 anton 15102: @cindex direct threaded inner interpreter
15103: @cindex inner interpreter, direct threaded
15104: Direct threading is even simpler:
15105: @example
15106: ca = *ip++;
15107: goto *ca;
15108: @end example
15109:
15110: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15111: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15112:
15113: @menu
15114: * Scheduling::
15115: * Direct or Indirect Threaded?::
1.109 anton 15116: * Dynamic Superinstructions::
1.1 anton 15117: * DOES>::
15118: @end menu
15119:
15120: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15121: @subsection Scheduling
15122: @cindex inner interpreter optimization
15123:
15124: There is a little complication: Pipelined and superscalar processors,
15125: i.e., RISC and some modern CISC machines can process independent
15126: instructions while waiting for the results of an instruction. The
15127: compiler usually reorders (schedules) the instructions in a way that
15128: achieves good usage of these delay slots. However, on our first tries
15129: the compiler did not do well on scheduling primitives. E.g., for
15130: @code{+} implemented as
15131: @example
15132: n=sp[0]+sp[1];
15133: sp++;
15134: sp[0]=n;
15135: NEXT;
15136: @end example
1.81 anton 15137: the @code{NEXT} comes strictly after the other code, i.e., there is
15138: nearly no scheduling. After a little thought the problem becomes clear:
15139: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15140: addresses (and the version of @code{gcc} we used would not know it even
15141: if it was possible), so it could not move the load of the cfa above the
15142: store to the TOS. Indeed the pointers could be the same, if code on or
15143: very near the top of stack were executed. In the interest of speed we
15144: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15145: in scheduling: @code{NEXT} is divided into several parts:
15146: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15147: like:
1.1 anton 15148: @example
1.81 anton 15149: NEXT_P0;
1.1 anton 15150: n=sp[0]+sp[1];
15151: sp++;
15152: NEXT_P1;
15153: sp[0]=n;
15154: NEXT_P2;
15155: @end example
15156:
1.81 anton 15157: There are various schemes that distribute the different operations of
15158: NEXT between these parts in several ways; in general, different schemes
15159: perform best on different processors. We use a scheme for most
15160: architectures that performs well for most processors of this
1.109 anton 15161: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15162: the scheme on installation time.
15163:
1.1 anton 15164:
1.109 anton 15165: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15166: @subsection Direct or Indirect Threaded?
15167: @cindex threading, direct or indirect?
15168:
1.109 anton 15169: Threaded forth code consists of references to primitives (simple machine
15170: code routines like @code{+}) and to non-primitives (e.g., colon
15171: definitions, variables, constants); for a specific class of
15172: non-primitives (e.g., variables) there is one code routine (e.g.,
15173: @code{dovar}), but each variable needs a separate reference to its data.
15174:
15175: Traditionally Forth has been implemented as indirect threaded code,
15176: because this allows to use only one cell to reference a non-primitive
15177: (basically you point to the data, and find the code address there).
15178:
15179: @cindex primitive-centric threaded code
15180: However, threaded code in Gforth (since 0.6.0) uses two cells for
15181: non-primitives, one for the code address, and one for the data address;
15182: the data pointer is an immediate argument for the virtual machine
15183: instruction represented by the code address. We call this
15184: @emph{primitive-centric} threaded code, because all code addresses point
15185: to simple primitives. E.g., for a variable, the code address is for
15186: @code{lit} (also used for integer literals like @code{99}).
15187:
15188: Primitive-centric threaded code allows us to use (faster) direct
15189: threading as dispatch method, completely portably (direct threaded code
15190: in Gforth before 0.6.0 required architecture-specific code). It also
15191: eliminates the performance problems related to I-cache consistency that
15192: 386 implementations have with direct threaded code, and allows
15193: additional optimizations.
15194:
15195: @cindex hybrid direct/indirect threaded code
15196: There is a catch, however: the @var{xt} parameter of @code{execute} can
15197: occupy only one cell, so how do we pass non-primitives with their code
15198: @emph{and} data addresses to them? Our answer is to use indirect
15199: threaded dispatch for @code{execute} and other words that use a
15200: single-cell xt. So, normal threaded code in colon definitions uses
15201: direct threading, and @code{execute} and similar words, which dispatch
15202: to xts on the data stack, use indirect threaded code. We call this
15203: @emph{hybrid direct/indirect} threaded code.
15204:
15205: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15206: @cindex gforth engine
15207: @cindex gforth-fast engine
15208: The engines @command{gforth} and @command{gforth-fast} use hybrid
15209: direct/indirect threaded code. This means that with these engines you
15210: cannot use @code{,} to compile an xt. Instead, you have to use
15211: @code{compile,}.
15212:
15213: @cindex gforth-itc engine
1.115 anton 15214: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15215: This engine uses plain old indirect threaded code. It still compiles in
15216: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15217: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15218: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15219: and execute @code{' , is compile,}. Your program can check if it is
15220: running on a hybrid direct/indirect threaded engine or a pure indirect
15221: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15222:
15223:
15224: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15225: @subsection Dynamic Superinstructions
15226: @cindex Dynamic superinstructions with replication
15227: @cindex Superinstructions
15228: @cindex Replication
15229:
15230: The engines @command{gforth} and @command{gforth-fast} use another
15231: optimization: Dynamic superinstructions with replication. As an
15232: example, consider the following colon definition:
15233:
15234: @example
15235: : squared ( n1 -- n2 )
15236: dup * ;
15237: @end example
15238:
15239: Gforth compiles this into the threaded code sequence
15240:
15241: @example
15242: dup
15243: *
15244: ;s
15245: @end example
15246:
15247: In normal direct threaded code there is a code address occupying one
15248: cell for each of these primitives. Each code address points to a
15249: machine code routine, and the interpreter jumps to this machine code in
15250: order to execute the primitive. The routines for these three
15251: primitives are (in @command{gforth-fast} on the 386):
15252:
15253: @example
15254: Code dup
15255: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15256: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15257: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15258: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15259: end-code
15260: Code *
15261: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15262: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15263: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15264: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15265: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15266: end-code
15267: Code ;s
15268: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15269: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15270: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15271: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15272: end-code
15273: @end example
15274:
15275: With dynamic superinstructions and replication the compiler does not
15276: just lay down the threaded code, but also copies the machine code
15277: fragments, usually without the jump at the end.
15278:
15279: @example
15280: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15281: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15282: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15283: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15284: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15285: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15286: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15287: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15288: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15289: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15290: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15291: @end example
15292:
15293: Only when a threaded-code control-flow change happens (e.g., in
15294: @code{;s}), the jump is appended. This optimization eliminates many of
15295: these jumps and makes the rest much more predictable. The speedup
15296: depends on the processor and the application; on the Athlon and Pentium
15297: III this optimization typically produces a speedup by a factor of 2.
15298:
15299: The code addresses in the direct-threaded code are set to point to the
15300: appropriate points in the copied machine code, in this example like
15301: this:
1.1 anton 15302:
1.109 anton 15303: @example
15304: primitive code address
15305: dup $4057D27D
15306: * $4057D286
15307: ;s $4057D292
15308: @end example
15309:
15310: Thus there can be threaded-code jumps to any place in this piece of
15311: code. This also simplifies decompilation quite a bit.
15312:
15313: @cindex --no-dynamic command-line option
15314: @cindex --no-super command-line option
15315: You can disable this optimization with @option{--no-dynamic}. You can
15316: use the copying without eliminating the jumps (i.e., dynamic
15317: replication, but without superinstructions) with @option{--no-super};
15318: this gives the branch prediction benefit alone; the effect on
1.110 anton 15319: performance depends on the CPU; on the Athlon and Pentium III the
15320: speedup is a little less than for dynamic superinstructions with
15321: replication.
15322:
15323: @cindex patching threaded code
15324: One use of these options is if you want to patch the threaded code.
15325: With superinstructions, many of the dispatch jumps are eliminated, so
15326: patching often has no effect. These options preserve all the dispatch
15327: jumps.
1.109 anton 15328:
15329: @cindex --dynamic command-line option
1.110 anton 15330: On some machines dynamic superinstructions are disabled by default,
15331: because it is unsafe on these machines. However, if you feel
15332: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15333:
15334: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15335: @subsection DOES>
15336: @cindex @code{DOES>} implementation
15337:
1.26 crook 15338: @cindex @code{dodoes} routine
15339: @cindex @code{DOES>}-code
1.1 anton 15340: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15341: the chunk of code executed by every word defined by a
1.109 anton 15342: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15343: this is only needed if the xt of the word is @code{execute}d. The main
15344: problem here is: How to find the Forth code to be executed, i.e. the
15345: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15346: solutions:
1.1 anton 15347:
1.21 crook 15348: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15349: @code{DOES>}-code address is stored in the cell after the code address
15350: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15351: illegal in the Forth-79 and all later standards, because in fig-Forth
15352: this address lies in the body (which is illegal in these
15353: standards). However, by making the code field larger for all words this
15354: solution becomes legal again. We use this approach. Leaving a cell
15355: unused in most words is a bit wasteful, but on the machines we are
15356: targeting this is hardly a problem.
15357:
1.1 anton 15358:
15359: @node Primitives, Performance, Threading, Engine
15360: @section Primitives
15361: @cindex primitives, implementation
15362: @cindex virtual machine instructions, implementation
15363:
15364: @menu
15365: * Automatic Generation::
15366: * TOS Optimization::
15367: * Produced code::
15368: @end menu
15369:
15370: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15371: @subsection Automatic Generation
15372: @cindex primitives, automatic generation
15373:
15374: @cindex @file{prims2x.fs}
1.109 anton 15375:
1.1 anton 15376: Since the primitives are implemented in a portable language, there is no
15377: longer any need to minimize the number of primitives. On the contrary,
15378: having many primitives has an advantage: speed. In order to reduce the
15379: number of errors in primitives and to make programming them easier, we
1.109 anton 15380: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15381: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15382: generates most (and sometimes all) of the C code for a primitive from
15383: the stack effect notation. The source for a primitive has the following
15384: form:
1.1 anton 15385:
15386: @cindex primitive source format
15387: @format
1.58 anton 15388: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15389: [@code{""}@i{glossary entry}@code{""}]
15390: @i{C code}
1.1 anton 15391: [@code{:}
1.29 crook 15392: @i{Forth code}]
1.1 anton 15393: @end format
15394:
15395: The items in brackets are optional. The category and glossary fields
15396: are there for generating the documentation, the Forth code is there
15397: for manual implementations on machines without GNU C. E.g., the source
15398: for the primitive @code{+} is:
15399: @example
1.58 anton 15400: + ( n1 n2 -- n ) core plus
1.1 anton 15401: n = n1+n2;
15402: @end example
15403:
15404: This looks like a specification, but in fact @code{n = n1+n2} is C
15405: code. Our primitive generation tool extracts a lot of information from
15406: the stack effect notations@footnote{We use a one-stack notation, even
15407: though we have separate data and floating-point stacks; The separate
15408: notation can be generated easily from the unified notation.}: The number
15409: of items popped from and pushed on the stack, their type, and by what
15410: name they are referred to in the C code. It then generates a C code
15411: prelude and postlude for each primitive. The final C code for @code{+}
15412: looks like this:
15413:
15414: @example
1.46 pazsan 15415: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15416: /* */ /* documentation */
1.81 anton 15417: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15418: @{
15419: DEF_CA /* definition of variable ca (indirect threading) */
15420: Cell n1; /* definitions of variables */
15421: Cell n2;
15422: Cell n;
1.81 anton 15423: NEXT_P0; /* NEXT part 0 */
1.1 anton 15424: n1 = (Cell) sp[1]; /* input */
15425: n2 = (Cell) TOS;
15426: sp += 1; /* stack adjustment */
15427: @{
15428: n = n1+n2; /* C code taken from the source */
15429: @}
15430: NEXT_P1; /* NEXT part 1 */
15431: TOS = (Cell)n; /* output */
15432: NEXT_P2; /* NEXT part 2 */
15433: @}
15434: @end example
15435:
15436: This looks long and inefficient, but the GNU C compiler optimizes quite
15437: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15438: HP RISC machines: Defining the @code{n}s does not produce any code, and
15439: using them as intermediate storage also adds no cost.
15440:
1.26 crook 15441: There are also other optimizations that are not illustrated by this
15442: example: assignments between simple variables are usually for free (copy
1.1 anton 15443: propagation). If one of the stack items is not used by the primitive
15444: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15445: (dead code elimination). On the other hand, there are some things that
15446: the compiler does not do, therefore they are performed by
15447: @file{prims2x.fs}: The compiler does not optimize code away that stores
15448: a stack item to the place where it just came from (e.g., @code{over}).
15449:
15450: While programming a primitive is usually easy, there are a few cases
15451: where the programmer has to take the actions of the generator into
15452: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15453: fall through to @code{NEXT}.
1.109 anton 15454:
15455: For more information
1.1 anton 15456:
15457: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15458: @subsection TOS Optimization
15459: @cindex TOS optimization for primitives
15460: @cindex primitives, keeping the TOS in a register
15461:
15462: An important optimization for stack machine emulators, e.g., Forth
15463: engines, is keeping one or more of the top stack items in
1.29 crook 15464: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15465: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15466: @itemize @bullet
15467: @item
1.29 crook 15468: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15469: due to fewer loads from and stores to the stack.
1.29 crook 15470: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15471: @i{y<n}, due to additional moves between registers.
1.1 anton 15472: @end itemize
15473:
15474: @cindex -DUSE_TOS
15475: @cindex -DUSE_NO_TOS
15476: In particular, keeping one item in a register is never a disadvantage,
15477: if there are enough registers. Keeping two items in registers is a
15478: disadvantage for frequent words like @code{?branch}, constants,
15479: variables, literals and @code{i}. Therefore our generator only produces
15480: code that keeps zero or one items in registers. The generated C code
15481: covers both cases; the selection between these alternatives is made at
15482: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15483: code for @code{+} is just a simple variable name in the one-item case,
15484: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15485: GNU C compiler tries to keep simple variables like @code{TOS} in
15486: registers, and it usually succeeds, if there are enough registers.
15487:
15488: @cindex -DUSE_FTOS
15489: @cindex -DUSE_NO_FTOS
15490: The primitive generator performs the TOS optimization for the
15491: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15492: operations the benefit of this optimization is even larger:
15493: floating-point operations take quite long on most processors, but can be
15494: performed in parallel with other operations as long as their results are
15495: not used. If the FP-TOS is kept in a register, this works. If
15496: it is kept on the stack, i.e., in memory, the store into memory has to
15497: wait for the result of the floating-point operation, lengthening the
15498: execution time of the primitive considerably.
15499:
15500: The TOS optimization makes the automatic generation of primitives a
15501: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15502: @code{TOS} is not sufficient. There are some special cases to
15503: consider:
15504: @itemize @bullet
15505: @item In the case of @code{dup ( w -- w w )} the generator must not
15506: eliminate the store to the original location of the item on the stack,
15507: if the TOS optimization is turned on.
15508: @item Primitives with stack effects of the form @code{--}
1.29 crook 15509: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15510: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15511: must load the TOS from the stack at the end. But for the null stack
15512: effect @code{--} no stores or loads should be generated.
15513: @end itemize
15514:
15515: @node Produced code, , TOS Optimization, Primitives
15516: @subsection Produced code
15517: @cindex primitives, assembly code listing
15518:
15519: @cindex @file{engine.s}
15520: To see what assembly code is produced for the primitives on your machine
15521: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15522: look at the resulting file @file{engine.s}. Alternatively, you can also
15523: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15524:
15525: @node Performance, , Primitives, Engine
15526: @section Performance
15527: @cindex performance of some Forth interpreters
15528: @cindex engine performance
15529: @cindex benchmarking Forth systems
15530: @cindex Gforth performance
15531:
15532: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15533: impossible to write a significantly faster threaded-code engine.
1.1 anton 15534:
15535: On register-starved machines like the 386 architecture processors
15536: improvements are possible, because @code{gcc} does not utilize the
15537: registers as well as a human, even with explicit register declarations;
15538: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15539: and hand-tuned it for the 486; this system is 1.19 times faster on the
15540: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15541: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15542: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15543: registers fit in real registers (and we can even afford to use the TOS
15544: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15545: earlier results. And dynamic superinstructions provide another speedup
15546: (but only around a factor 1.2 on the 486).
1.1 anton 15547:
15548: @cindex Win32Forth performance
15549: @cindex NT Forth performance
15550: @cindex eforth performance
15551: @cindex ThisForth performance
15552: @cindex PFE performance
15553: @cindex TILE performance
1.81 anton 15554: The potential advantage of assembly language implementations is not
1.112 anton 15555: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15556: (direct threaded, compiled with @code{gcc-2.95.1} and
15557: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15558: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15559: (with and without peephole (aka pinhole) optimization of the threaded
15560: code); all these systems were written in assembly language. We also
15561: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15562: with @code{gcc-2.6.3} with the default configuration for Linux:
15563: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15564: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15565: employs peephole optimization of the threaded code) and TILE (compiled
15566: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15567: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15568: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15569: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15570: then extended it to run the benchmarks, added the peephole optimizer,
15571: ran the benchmarks and reported the results.
1.40 anton 15572:
1.1 anton 15573: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15574: matrix multiplication come from the Stanford integer benchmarks and have
15575: been translated into Forth by Martin Fraeman; we used the versions
15576: included in the TILE Forth package, but with bigger data set sizes; and
15577: a recursive Fibonacci number computation for benchmarking calling
15578: performance. The following table shows the time taken for the benchmarks
15579: scaled by the time taken by Gforth (in other words, it shows the speedup
15580: factor that Gforth achieved over the other systems).
15581:
15582: @example
1.112 anton 15583: relative Win32- NT eforth This-
15584: time Gforth Forth Forth eforth +opt PFE Forth TILE
15585: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15586: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15587: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15588: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15589: @end example
15590:
1.26 crook 15591: You may be quite surprised by the good performance of Gforth when
15592: compared with systems written in assembly language. One important reason
15593: for the disappointing performance of these other systems is probably
15594: that they are not written optimally for the 486 (e.g., they use the
15595: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15596: but costly method for relocating the Forth image: like @code{cforth}, it
15597: computes the actual addresses at run time, resulting in two address
15598: computations per @code{NEXT} (@pxref{Image File Background}).
15599:
1.1 anton 15600: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15601: explained with the self-imposed restriction of the latter systems to
15602: standard C, which makes efficient threading impossible (however, the
1.4 anton 15603: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15604: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15605: Moreover, current C compilers have a hard time optimizing other aspects
15606: of the ThisForth and the TILE source.
15607:
1.26 crook 15608: The performance of Gforth on 386 architecture processors varies widely
15609: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15610: allocate any of the virtual machine registers into real machine
15611: registers by itself and would not work correctly with explicit register
1.112 anton 15612: declarations, giving a significantly slower engine (on a 486DX2/66
15613: running the Sieve) than the one measured above.
1.1 anton 15614:
1.26 crook 15615: Note that there have been several releases of Win32Forth since the
15616: release presented here, so the results presented above may have little
1.40 anton 15617: predictive value for the performance of Win32Forth today (results for
15618: the current release on an i486DX2/66 are welcome).
1.1 anton 15619:
15620: @cindex @file{Benchres}
1.66 anton 15621: In
15622: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15623: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15624: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15625: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15626: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15627: than the version used here. You can find a newer version of these
15628: measurements at
1.47 crook 15629: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15630: find numbers for Gforth on various machines in @file{Benchres}.
15631:
1.26 crook 15632: @c ******************************************************************
1.113 anton 15633: @c @node Binding to System Library, Cross Compiler, Engine, Top
15634: @c @chapter Binding to System Library
1.13 pazsan 15635:
1.113 anton 15636: @c ****************************************************************
15637: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15638: @chapter Cross Compiler
1.47 crook 15639: @cindex @file{cross.fs}
15640: @cindex cross-compiler
15641: @cindex metacompiler
15642: @cindex target compiler
1.13 pazsan 15643:
1.46 pazsan 15644: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15645: mostly written in Forth, including crucial parts like the outer
15646: interpreter and compiler, it needs compiled Forth code to get
15647: started. The cross compiler allows to create new images for other
15648: architectures, even running under another Forth system.
1.13 pazsan 15649:
15650: @menu
1.67 anton 15651: * Using the Cross Compiler::
15652: * How the Cross Compiler Works::
1.13 pazsan 15653: @end menu
15654:
1.21 crook 15655: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15656: @section Using the Cross Compiler
1.46 pazsan 15657:
15658: The cross compiler uses a language that resembles Forth, but isn't. The
15659: main difference is that you can execute Forth code after definition,
15660: while you usually can't execute the code compiled by cross, because the
15661: code you are compiling is typically for a different computer than the
15662: one you are compiling on.
15663:
1.81 anton 15664: @c anton: This chapter is somewhat different from waht I would expect: I
15665: @c would expect an explanation of the cross language and how to create an
15666: @c application image with it. The section explains some aspects of
15667: @c creating a Gforth kernel.
15668:
1.46 pazsan 15669: The Makefile is already set up to allow you to create kernels for new
15670: architectures with a simple make command. The generic kernels using the
15671: GCC compiled virtual machine are created in the normal build process
15672: with @code{make}. To create a embedded Gforth executable for e.g. the
15673: 8086 processor (running on a DOS machine), type
15674:
15675: @example
15676: make kernl-8086.fi
15677: @end example
15678:
15679: This will use the machine description from the @file{arch/8086}
15680: directory to create a new kernel. A machine file may look like that:
15681:
15682: @example
15683: \ Parameter for target systems 06oct92py
15684:
15685: 4 Constant cell \ cell size in bytes
15686: 2 Constant cell<< \ cell shift to bytes
15687: 5 Constant cell>bit \ cell shift to bits
15688: 8 Constant bits/char \ bits per character
15689: 8 Constant bits/byte \ bits per byte [default: 8]
15690: 8 Constant float \ bytes per float
15691: 8 Constant /maxalign \ maximum alignment in bytes
15692: false Constant bigendian \ byte order
15693: ( true=big, false=little )
15694:
15695: include machpc.fs \ feature list
15696: @end example
15697:
15698: This part is obligatory for the cross compiler itself, the feature list
15699: is used by the kernel to conditionally compile some features in and out,
15700: depending on whether the target supports these features.
15701:
15702: There are some optional features, if you define your own primitives,
15703: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15704: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15705: @code{prims-include} includes primitives, and @code{>boot} prepares for
15706: booting.
15707:
15708: @example
15709: : asm-include ." Include assembler" cr
15710: s" arch/8086/asm.fs" included ;
15711:
15712: : prims-include ." Include primitives" cr
15713: s" arch/8086/prim.fs" included ;
15714:
15715: : >boot ." Prepare booting" cr
15716: s" ' boot >body into-forth 1+ !" evaluate ;
15717: @end example
15718:
15719: These words are used as sort of macro during the cross compilation in
1.81 anton 15720: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15721: be possible --- but more complicated --- to write a new kernel project
15722: file, too.
15723:
15724: @file{kernel/main.fs} expects the machine description file name on the
15725: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15726: @code{mach-file} leaves a counted string on the stack, or
15727: @code{machine-file} leaves an address, count pair of the filename on the
15728: stack.
15729:
15730: The feature list is typically controlled using @code{SetValue}, generic
15731: files that are used by several projects can use @code{DefaultValue}
15732: instead. Both functions work like @code{Value}, when the value isn't
15733: defined, but @code{SetValue} works like @code{to} if the value is
15734: defined, and @code{DefaultValue} doesn't set anything, if the value is
15735: defined.
15736:
15737: @example
15738: \ generic mach file for pc gforth 03sep97jaw
15739:
15740: true DefaultValue NIL \ relocating
15741:
15742: >ENVIRON
15743:
15744: true DefaultValue file \ controls the presence of the
15745: \ file access wordset
15746: true DefaultValue OS \ flag to indicate a operating system
15747:
15748: true DefaultValue prims \ true: primitives are c-code
15749:
15750: true DefaultValue floating \ floating point wordset is present
15751:
15752: true DefaultValue glocals \ gforth locals are present
15753: \ will be loaded
15754: true DefaultValue dcomps \ double number comparisons
15755:
15756: true DefaultValue hash \ hashing primitives are loaded/present
15757:
15758: true DefaultValue xconds \ used together with glocals,
15759: \ special conditionals supporting gforths'
15760: \ local variables
15761: true DefaultValue header \ save a header information
15762:
15763: true DefaultValue backtrace \ enables backtrace code
15764:
15765: false DefaultValue ec
15766: false DefaultValue crlf
15767:
15768: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15769:
15770: &16 KB DefaultValue stack-size
15771: &15 KB &512 + DefaultValue fstack-size
15772: &15 KB DefaultValue rstack-size
15773: &14 KB &512 + DefaultValue lstack-size
15774: @end example
1.13 pazsan 15775:
1.48 anton 15776: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15777: @section How the Cross Compiler Works
1.13 pazsan 15778:
15779: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15780: @appendix Bugs
1.1 anton 15781: @cindex bug reporting
15782:
1.21 crook 15783: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15784:
1.103 anton 15785: If you find a bug, please submit a bug report through
15786: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15787:
15788: @itemize @bullet
15789: @item
1.81 anton 15790: A program (or a sequence of keyboard commands) that reproduces the bug.
15791: @item
15792: A description of what you think constitutes the buggy behaviour.
15793: @item
1.21 crook 15794: The Gforth version used (it is announced at the start of an
15795: interactive Gforth session).
15796: @item
15797: The machine and operating system (on Unix
15798: systems @code{uname -a} will report this information).
15799: @item
1.81 anton 15800: The installation options (you can find the configure options at the
15801: start of @file{config.status}) and configuration (@code{configure}
15802: output or @file{config.cache}).
1.21 crook 15803: @item
15804: A complete list of changes (if any) you (or your installer) have made to the
15805: Gforth sources.
15806: @end itemize
1.1 anton 15807:
15808: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15809: to Report Bugs, gcc.info, GNU C Manual}.
15810:
15811:
1.21 crook 15812: @node Origin, Forth-related information, Bugs, Top
15813: @appendix Authors and Ancestors of Gforth
1.1 anton 15814:
15815: @section Authors and Contributors
15816: @cindex authors of Gforth
15817: @cindex contributors to Gforth
15818:
15819: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15820: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15821: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 15822: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
15823: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
15824: and Stuart Ramsden inspired us with their continuous feedback. Lennart
15825: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
15826: working on automatic support for calling C libraries. Helpful comments
15827: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
15828: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
15829: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
15830: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
15831: comments from many others; thank you all, sorry for not listing you
15832: here (but digging through my mailbox to extract your names is on my
15833: to-do list).
1.1 anton 15834:
15835: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15836: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15837: was developed across the Internet, and its authors did not meet
1.20 pazsan 15838: physically for the first 4 years of development.
1.1 anton 15839:
15840: @section Pedigree
1.26 crook 15841: @cindex pedigree of Gforth
1.1 anton 15842:
1.81 anton 15843: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15844: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15845:
1.20 pazsan 15846: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15847: 32 bit native code version of VolksForth for the Atari ST, written
15848: mostly by Dietrich Weineck.
15849:
1.81 anton 15850: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15851: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 15852: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 15853:
1.147 anton 15854: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15855: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 15856:
15857: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15858: 1979. Robert Selzer and Bill Ragsdale developed the original
15859: implementation of fig-Forth for the 6502 based on microForth.
15860:
15861: The principal architect of microForth was Dean Sanderson. microForth was
15862: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15863: the 1802, and subsequently implemented on the 8080, the 6800 and the
15864: Z80.
15865:
15866: All earlier Forth systems were custom-made, usually by Charles Moore,
15867: who discovered (as he puts it) Forth during the late 60s. The first full
15868: Forth existed in 1971.
15869:
1.81 anton 15870: A part of the information in this section comes from
15871: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15872: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 15873: Charles H. Moore, presented at the HOPL-II conference and preprinted
15874: in SIGPLAN Notices 28(3), 1993. You can find more historical and
15875: genealogical information about Forth there. For a more general (and
15876: graphical) Forth family tree look see
15877: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15878: Forth Family Tree and Timeline}.
1.1 anton 15879:
1.81 anton 15880: @c ------------------------------------------------------------------
1.113 anton 15881: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15882: @appendix Other Forth-related information
15883: @cindex Forth-related information
15884:
1.81 anton 15885: @c anton: I threw most of this stuff out, because it can be found through
15886: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15887:
15888: @cindex comp.lang.forth
15889: @cindex frequently asked questions
1.81 anton 15890: There is an active news group (comp.lang.forth) discussing Forth
15891: (including Gforth) and Forth-related issues. Its
15892: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15893: (frequently asked questions and their answers) contains a lot of
15894: information on Forth. You should read it before posting to
15895: comp.lang.forth.
1.21 crook 15896:
1.81 anton 15897: The ANS Forth standard is most usable in its
15898: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15899:
1.113 anton 15900: @c ---------------------------------------------------
15901: @node Licenses, Word Index, Forth-related information, Top
15902: @appendix Licenses
15903:
15904: @menu
15905: * GNU Free Documentation License:: License for copying this manual.
15906: * Copying:: GPL (for copying this software).
15907: @end menu
15908:
15909: @include fdl.texi
15910:
15911: @include gpl.texi
15912:
15913:
15914:
1.81 anton 15915: @c ------------------------------------------------------------------
1.113 anton 15916: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15917: @unnumbered Word Index
15918:
1.26 crook 15919: This index is a list of Forth words that have ``glossary'' entries
15920: within this manual. Each word is listed with its stack effect and
15921: wordset.
1.1 anton 15922:
15923: @printindex fn
15924:
1.81 anton 15925: @c anton: the name index seems superfluous given the word and concept indices.
15926:
15927: @c @node Name Index, Concept Index, Word Index, Top
15928: @c @unnumbered Name Index
1.41 anton 15929:
1.81 anton 15930: @c This index is a list of Forth words that have ``glossary'' entries
15931: @c within this manual.
1.41 anton 15932:
1.81 anton 15933: @c @printindex ky
1.41 anton 15934:
1.113 anton 15935: @c -------------------------------------------------------
1.81 anton 15936: @node Concept Index, , Word Index, Top
1.1 anton 15937: @unnumbered Concept and Word Index
15938:
1.26 crook 15939: Not all entries listed in this index are present verbatim in the
15940: text. This index also duplicates, in abbreviated form, all of the words
15941: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15942:
15943: @printindex cp
15944:
15945: @bye
1.81 anton 15946:
15947:
1.1 anton 15948:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>