Annotation of gforth/doc/gforth.ds, revision 1.166
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.142 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005 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.44 crook 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::
320: * Search Paths::
321:
322: Search Paths
323:
1.75 anton 324: * Source Search Paths::
1.26 crook 325: * General Search Paths::
326:
327: Other I/O
328:
1.32 anton 329: * Simple numeric output:: Predefined formats
330: * Formatted numeric output:: Formatted (pictured) output
331: * String Formats:: How Forth stores strings in memory
1.67 anton 332: * Displaying characters and strings:: Other stuff
1.32 anton 333: * Input:: Input
1.112 anton 334: * Pipes:: How to create your own pipes
1.149 pazsan 335: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 336:
337: Locals
338:
339: * Gforth locals::
340: * ANS Forth locals::
341:
342: Gforth locals
343:
344: * Where are locals visible by name?::
345: * How long do locals live?::
1.78 anton 346: * Locals programming style::
347: * Locals implementation::
1.26 crook 348:
1.12 anton 349: Structures
350:
351: * Why explicit structure support?::
352: * Structure Usage::
353: * Structure Naming Convention::
354: * Structure Implementation::
355: * Structure Glossary::
356:
357: Object-oriented Forth
358:
1.48 anton 359: * Why object-oriented programming?::
360: * Object-Oriented Terminology::
361: * Objects::
362: * OOF::
363: * Mini-OOF::
1.23 crook 364: * Comparison with other object models::
1.12 anton 365:
1.24 anton 366: The @file{objects.fs} model
1.12 anton 367:
368: * Properties of the Objects model::
369: * Basic Objects Usage::
1.41 anton 370: * The Objects base class::
1.12 anton 371: * Creating objects::
372: * Object-Oriented Programming Style::
373: * Class Binding::
374: * Method conveniences::
375: * Classes and Scoping::
1.41 anton 376: * Dividing classes::
1.12 anton 377: * Object Interfaces::
378: * Objects Implementation::
379: * Objects Glossary::
380:
1.24 anton 381: The @file{oof.fs} model
1.12 anton 382:
1.67 anton 383: * Properties of the OOF model::
384: * Basic OOF Usage::
385: * The OOF base class::
386: * Class Declaration::
387: * Class Implementation::
1.12 anton 388:
1.24 anton 389: The @file{mini-oof.fs} model
1.23 crook 390:
1.48 anton 391: * Basic Mini-OOF Usage::
392: * Mini-OOF Example::
393: * Mini-OOF Implementation::
1.23 crook 394:
1.78 anton 395: Programming Tools
396:
1.150 anton 397: * Examining:: Data and Code.
398: * Forgetting words:: Usually before reloading.
1.78 anton 399: * Debugging:: Simple and quick.
400: * Assertions:: Making your programs self-checking.
401: * Singlestep Debugger:: Executing your program word by word.
402:
1.155 anton 403: C Interface
404:
405: * Calling C Functions::
406: * Declaring C Functions::
407: * Callbacks::
408: * Low-Level C Interface Words::
409:
1.78 anton 410: Assembler and Code Words
411:
412: * Code and ;code::
413: * Common Assembler:: Assembler Syntax
414: * Common Disassembler::
415: * 386 Assembler:: Deviations and special cases
416: * Alpha Assembler:: Deviations and special cases
417: * MIPS assembler:: Deviations and special cases
1.161 anton 418: * PowerPC assembler::
1.78 anton 419: * Other assemblers:: How to write them
420:
1.12 anton 421: Tools
422:
423: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 424: * Stack depth changes:: Where does this stack item come from?
1.12 anton 425:
426: ANS conformance
427:
428: * The Core Words::
429: * The optional Block word set::
430: * The optional Double Number word set::
431: * The optional Exception word set::
432: * The optional Facility word set::
433: * The optional File-Access word set::
434: * The optional Floating-Point word set::
435: * The optional Locals word set::
436: * The optional Memory-Allocation word set::
437: * The optional Programming-Tools word set::
438: * The optional Search-Order word set::
439:
440: The Core Words
441:
442: * core-idef:: Implementation Defined Options
443: * core-ambcond:: Ambiguous Conditions
444: * core-other:: Other System Documentation
445:
446: The optional Block word set
447:
448: * block-idef:: Implementation Defined Options
449: * block-ambcond:: Ambiguous Conditions
450: * block-other:: Other System Documentation
451:
452: The optional Double Number word set
453:
454: * double-ambcond:: Ambiguous Conditions
455:
456: The optional Exception word set
457:
458: * exception-idef:: Implementation Defined Options
459:
460: The optional Facility word set
461:
462: * facility-idef:: Implementation Defined Options
463: * facility-ambcond:: Ambiguous Conditions
464:
465: The optional File-Access word set
466:
467: * file-idef:: Implementation Defined Options
468: * file-ambcond:: Ambiguous Conditions
469:
470: The optional Floating-Point word set
471:
472: * floating-idef:: Implementation Defined Options
473: * floating-ambcond:: Ambiguous Conditions
474:
475: The optional Locals word set
476:
477: * locals-idef:: Implementation Defined Options
478: * locals-ambcond:: Ambiguous Conditions
479:
480: The optional Memory-Allocation word set
481:
482: * memory-idef:: Implementation Defined Options
483:
484: The optional Programming-Tools word set
485:
486: * programming-idef:: Implementation Defined Options
487: * programming-ambcond:: Ambiguous Conditions
488:
489: The optional Search-Order word set
490:
491: * search-idef:: Implementation Defined Options
492: * search-ambcond:: Ambiguous Conditions
493:
1.109 anton 494: Emacs and Gforth
495:
496: * Installing gforth.el:: Making Emacs aware of Forth.
497: * Emacs Tags:: Viewing the source of a word in Emacs.
498: * Hilighting:: Making Forth code look prettier.
499: * Auto-Indentation:: Customizing auto-indentation.
500: * Blocks Files:: Reading and writing blocks files.
501:
1.12 anton 502: Image Files
503:
1.24 anton 504: * Image Licensing Issues:: Distribution terms for images.
505: * Image File Background:: Why have image files?
1.67 anton 506: * Non-Relocatable Image Files:: don't always work.
1.24 anton 507: * Data-Relocatable Image Files:: are better.
1.67 anton 508: * Fully Relocatable Image Files:: better yet.
1.24 anton 509: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 510: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 511: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 512:
513: Fully Relocatable Image Files
514:
1.27 crook 515: * gforthmi:: The normal way
1.12 anton 516: * cross.fs:: The hard way
517:
518: Engine
519:
520: * Portability::
521: * Threading::
522: * Primitives::
523: * Performance::
524:
525: Threading
526:
527: * Scheduling::
528: * Direct or Indirect Threaded?::
1.109 anton 529: * Dynamic Superinstructions::
1.12 anton 530: * DOES>::
531:
532: Primitives
533:
534: * Automatic Generation::
535: * TOS Optimization::
536: * Produced code::
1.13 pazsan 537:
538: Cross Compiler
539:
1.67 anton 540: * Using the Cross Compiler::
541: * How the Cross Compiler Works::
1.13 pazsan 542:
1.113 anton 543: Licenses
544:
545: * GNU Free Documentation License:: License for copying this manual.
546: * Copying:: GPL (for copying this software).
547:
1.24 anton 548: @end detailmenu
1.1 anton 549: @end menu
550:
1.113 anton 551: @c ----------------------------------------------------------
1.1 anton 552: @iftex
553: @unnumbered Preface
554: @cindex Preface
1.21 crook 555: This manual documents Gforth. Some introductory material is provided for
556: readers who are unfamiliar with Forth or who are migrating to Gforth
557: from other Forth compilers. However, this manual is primarily a
558: reference manual.
1.1 anton 559: @end iftex
560:
1.28 crook 561: @comment TODO much more blurb here.
1.26 crook 562:
563: @c ******************************************************************
1.113 anton 564: @node Goals, Gforth Environment, Top, Top
1.26 crook 565: @comment node-name, next, previous, up
566: @chapter Goals of Gforth
567: @cindex goals of the Gforth project
568: The goal of the Gforth Project is to develop a standard model for
569: ANS Forth. This can be split into several subgoals:
570:
571: @itemize @bullet
572: @item
573: Gforth should conform to the ANS Forth Standard.
574: @item
575: It should be a model, i.e. it should define all the
576: implementation-dependent things.
577: @item
578: It should become standard, i.e. widely accepted and used. This goal
579: is the most difficult one.
580: @end itemize
581:
582: To achieve these goals Gforth should be
583: @itemize @bullet
584: @item
585: Similar to previous models (fig-Forth, F83)
586: @item
587: Powerful. It should provide for all the things that are considered
588: necessary today and even some that are not yet considered necessary.
589: @item
590: Efficient. It should not get the reputation of being exceptionally
591: slow.
592: @item
593: Free.
594: @item
595: Available on many machines/easy to port.
596: @end itemize
597:
598: Have we achieved these goals? Gforth conforms to the ANS Forth
599: standard. It may be considered a model, but we have not yet documented
600: which parts of the model are stable and which parts we are likely to
601: change. It certainly has not yet become a de facto standard, but it
602: appears to be quite popular. It has some similarities to and some
603: differences from previous models. It has some powerful features, but not
604: yet everything that we envisioned. We certainly have achieved our
1.65 anton 605: execution speed goals (@pxref{Performance})@footnote{However, in 1998
606: the bar was raised when the major commercial Forth vendors switched to
607: native code compilers.}. It is free and available on many machines.
1.29 crook 608:
1.26 crook 609: @c ******************************************************************
1.48 anton 610: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 611: @chapter Gforth Environment
612: @cindex Gforth environment
1.21 crook 613:
1.45 crook 614: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 615: material in this chapter.
1.21 crook 616:
617: @menu
1.29 crook 618: * Invoking Gforth:: Getting in
619: * Leaving Gforth:: Getting out
620: * Command-line editing::
1.48 anton 621: * Environment variables:: that affect how Gforth starts up
1.29 crook 622: * Gforth Files:: What gets installed and where
1.112 anton 623: * Gforth in pipes::
1.48 anton 624: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 625: @end menu
626:
1.49 anton 627: For related information about the creation of images see @ref{Image Files}.
1.29 crook 628:
1.21 crook 629: @comment ----------------------------------------------
1.48 anton 630: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 631: @section Invoking Gforth
632: @cindex invoking Gforth
633: @cindex running Gforth
634: @cindex command-line options
635: @cindex options on the command line
636: @cindex flags on the command line
1.21 crook 637:
1.30 anton 638: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 639: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 640: will usually just say @code{gforth} -- this automatically loads the
641: default image file @file{gforth.fi}. In many other cases the default
642: Gforth image will be invoked like this:
1.21 crook 643: @example
1.30 anton 644: gforth [file | -e forth-code] ...
1.21 crook 645: @end example
1.29 crook 646: @noindent
647: This interprets the contents of the files and the Forth code in the order they
648: are given.
1.21 crook 649:
1.109 anton 650: In addition to the @command{gforth} engine, there is also an engine
651: called @command{gforth-fast}, which is faster, but gives less
652: informative error messages (@pxref{Error messages}) and may catch some
1.166 ! anton 653: errors (in particular, stack underflows and integer division errors)
! 654: later or not at all. You should use it for debugged,
1.109 anton 655: performance-critical programs.
656:
657: Moreover, there is an engine called @command{gforth-itc}, which is
658: useful in some backwards-compatibility situations (@pxref{Direct or
659: Indirect Threaded?}).
1.30 anton 660:
1.29 crook 661: In general, the command line looks like this:
1.21 crook 662:
663: @example
1.30 anton 664: gforth[-fast] [engine options] [image options]
1.21 crook 665: @end example
666:
1.30 anton 667: The engine options must come before the rest of the command
1.29 crook 668: line. They are:
1.26 crook 669:
1.29 crook 670: @table @code
671: @cindex -i, command-line option
672: @cindex --image-file, command-line option
673: @item --image-file @i{file}
674: @itemx -i @i{file}
675: Loads the Forth image @i{file} instead of the default
676: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 677:
1.39 anton 678: @cindex --appl-image, command-line option
679: @item --appl-image @i{file}
680: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 681: to the image (instead of processing them as engine options). This is
682: useful for building executable application images on Unix, built with
1.39 anton 683: @code{gforthmi --application ...}.
684:
1.29 crook 685: @cindex --path, command-line option
686: @cindex -p, command-line option
687: @item --path @i{path}
688: @itemx -p @i{path}
689: Uses @i{path} for searching the image file and Forth source code files
690: instead of the default in the environment variable @code{GFORTHPATH} or
691: the path specified at installation time (e.g.,
692: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
693: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 694:
1.29 crook 695: @cindex --dictionary-size, command-line option
696: @cindex -m, command-line option
697: @cindex @i{size} parameters for command-line options
698: @cindex size of the dictionary and the stacks
699: @item --dictionary-size @i{size}
700: @itemx -m @i{size}
701: Allocate @i{size} space for the Forth dictionary space instead of
702: using the default specified in the image (typically 256K). The
703: @i{size} specification for this and subsequent options consists of
704: an integer and a unit (e.g.,
705: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
706: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
707: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
708: @code{e} is used.
1.21 crook 709:
1.29 crook 710: @cindex --data-stack-size, command-line option
711: @cindex -d, command-line option
712: @item --data-stack-size @i{size}
713: @itemx -d @i{size}
714: Allocate @i{size} space for the data stack instead of using the
715: default specified in the image (typically 16K).
1.21 crook 716:
1.29 crook 717: @cindex --return-stack-size, command-line option
718: @cindex -r, command-line option
719: @item --return-stack-size @i{size}
720: @itemx -r @i{size}
721: Allocate @i{size} space for the return stack instead of using the
722: default specified in the image (typically 15K).
1.21 crook 723:
1.29 crook 724: @cindex --fp-stack-size, command-line option
725: @cindex -f, command-line option
726: @item --fp-stack-size @i{size}
727: @itemx -f @i{size}
728: Allocate @i{size} space for the floating point stack instead of
729: using the default specified in the image (typically 15.5K). In this case
730: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 731:
1.48 anton 732: @cindex --locals-stack-size, command-line option
733: @cindex -l, command-line option
734: @item --locals-stack-size @i{size}
735: @itemx -l @i{size}
736: Allocate @i{size} space for the locals stack instead of using the
737: default specified in the image (typically 14.5K).
738:
739: @cindex -h, command-line option
740: @cindex --help, command-line option
741: @item --help
742: @itemx -h
743: Print a message about the command-line options
744:
745: @cindex -v, command-line option
746: @cindex --version, command-line option
747: @item --version
748: @itemx -v
749: Print version and exit
750:
751: @cindex --debug, command-line option
752: @item --debug
753: Print some information useful for debugging on startup.
754:
755: @cindex --offset-image, command-line option
756: @item --offset-image
757: Start the dictionary at a slightly different position than would be used
758: otherwise (useful for creating data-relocatable images,
759: @pxref{Data-Relocatable Image Files}).
760:
761: @cindex --no-offset-im, command-line option
762: @item --no-offset-im
763: Start the dictionary at the normal position.
764:
765: @cindex --clear-dictionary, command-line option
766: @item --clear-dictionary
767: Initialize all bytes in the dictionary to 0 before loading the image
768: (@pxref{Data-Relocatable Image Files}).
769:
770: @cindex --die-on-signal, command-line-option
771: @item --die-on-signal
772: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
773: or the segmentation violation SIGSEGV) by translating it into a Forth
774: @code{THROW}. With this option, Gforth exits if it receives such a
775: signal. This option is useful when the engine and/or the image might be
776: severely broken (such that it causes another signal before recovering
777: from the first); this option avoids endless loops in such cases.
1.109 anton 778:
1.119 anton 779: @cindex --no-dynamic, command-line option
780: @cindex --dynamic, command-line option
1.109 anton 781: @item --no-dynamic
782: @item --dynamic
783: Disable or enable dynamic superinstructions with replication
784: (@pxref{Dynamic Superinstructions}).
785:
1.119 anton 786: @cindex --no-super, command-line option
1.109 anton 787: @item --no-super
1.110 anton 788: Disable dynamic superinstructions, use just dynamic replication; this is
789: useful if you want to patch threaded code (@pxref{Dynamic
790: Superinstructions}).
1.119 anton 791:
792: @cindex --ss-number, command-line option
793: @item --ss-number=@var{N}
794: Use only the first @var{N} static superinstructions compiled into the
795: engine (default: use them all; note that only @code{gforth-fast} has
796: any). This option is useful for measuring the performance impact of
797: static superinstructions.
798:
799: @cindex --ss-min-..., command-line options
800: @item --ss-min-codesize
801: @item --ss-min-ls
802: @item --ss-min-lsu
803: @item --ss-min-nexts
804: Use specified metric for determining the cost of a primitive or static
805: superinstruction for static superinstruction selection. @code{Codesize}
806: is the native code size of the primive or static superinstruction,
807: @code{ls} is the number of loads and stores, @code{lsu} is the number of
808: loads, stores, and updates, and @code{nexts} is the number of dispatches
809: (not taking dynamic superinstructions into account), i.e. every
810: primitive or static superinstruction has cost 1. Default:
811: @code{codesize} if you use dynamic code generation, otherwise
812: @code{nexts}.
813:
814: @cindex --ss-greedy, command-line option
815: @item --ss-greedy
816: This option is useful for measuring the performance impact of static
817: superinstructions. By default, an optimal shortest-path algorithm is
818: used for selecting static superinstructions. With @option{--ss-greedy}
819: this algorithm is modified to assume that anything after the static
820: superinstruction currently under consideration is not combined into
821: static superinstructions. With @option{--ss-min-nexts} this produces
822: the same result as a greedy algorithm that always selects the longest
823: superinstruction available at the moment. E.g., if there are
824: superinstructions AB and BCD, then for the sequence A B C D the optimal
825: algorithm will select A BCD and the greedy algorithm will select AB C D.
826:
827: @cindex --print-metrics, command-line option
828: @item --print-metrics
829: Prints some metrics used during static superinstruction selection:
830: @code{code size} is the actual size of the dynamically generated code.
831: @code{Metric codesize} is the sum of the codesize metrics as seen by
832: static superinstruction selection; there is a difference from @code{code
833: size}, because not all primitives and static superinstructions are
834: compiled into dynamically generated code, and because of markers. The
835: other metrics correspond to the @option{ss-min-...} options. This
836: option is useful for evaluating the effects of the @option{--ss-...}
837: options.
1.109 anton 838:
1.48 anton 839: @end table
840:
841: @cindex loading files at startup
842: @cindex executing code on startup
843: @cindex batch processing with Gforth
844: As explained above, the image-specific command-line arguments for the
845: default image @file{gforth.fi} consist of a sequence of filenames and
846: @code{-e @var{forth-code}} options that are interpreted in the sequence
847: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 848: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
849: option takes only one argument; if you want to evaluate more Forth
850: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 851: after processing the command line (instead of entering interactive mode)
1.121 anton 852: append @code{-e bye} to the command line. You can also process the
853: command-line arguments with a Forth program (@pxref{OS command line
854: arguments}).
1.48 anton 855:
856: @cindex versions, invoking other versions of Gforth
857: If you have several versions of Gforth installed, @code{gforth} will
858: invoke the version that was installed last. @code{gforth-@i{version}}
859: invokes a specific version. If your environment contains the variable
860: @code{GFORTHPATH}, you may want to override it by using the
861: @code{--path} option.
862:
863: Not yet implemented:
864: On startup the system first executes the system initialization file
865: (unless the option @code{--no-init-file} is given; note that the system
866: resulting from using this option may not be ANS Forth conformant). Then
867: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 868: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 869: then in @file{~}, then in the normal path (see above).
870:
871:
872:
873: @comment ----------------------------------------------
874: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
875: @section Leaving Gforth
876: @cindex Gforth - leaving
877: @cindex leaving Gforth
878:
879: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
880: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
881: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 882: data are discarded. For ways of saving the state of the system before
883: leaving Gforth see @ref{Image Files}.
1.48 anton 884:
885: doc-bye
886:
887:
888: @comment ----------------------------------------------
1.65 anton 889: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 890: @section Command-line editing
891: @cindex command-line editing
892:
893: Gforth maintains a history file that records every line that you type to
894: the text interpreter. This file is preserved between sessions, and is
895: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
896: repeatedly you can recall successively older commands from this (or
897: previous) session(s). The full list of command-line editing facilities is:
898:
899: @itemize @bullet
900: @item
901: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
902: commands from the history buffer.
903: @item
904: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
905: from the history buffer.
906: @item
907: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
908: @item
909: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
910: @item
911: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
912: closing up the line.
913: @item
914: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
915: @item
916: @kbd{Ctrl-a} to move the cursor to the start of the line.
917: @item
918: @kbd{Ctrl-e} to move the cursor to the end of the line.
919: @item
920: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
921: line.
922: @item
923: @key{TAB} to step through all possible full-word completions of the word
924: currently being typed.
925: @item
1.65 anton 926: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
927: using @code{bye}).
928: @item
929: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
930: character under the cursor.
1.48 anton 931: @end itemize
932:
933: When editing, displayable characters are inserted to the left of the
934: cursor position; the line is always in ``insert'' (as opposed to
935: ``overstrike'') mode.
936:
937: @cindex history file
938: @cindex @file{.gforth-history}
939: On Unix systems, the history file is @file{~/.gforth-history} by
940: default@footnote{i.e. it is stored in the user's home directory.}. You
941: can find out the name and location of your history file using:
942:
943: @example
944: history-file type \ Unix-class systems
945:
946: history-file type \ Other systems
947: history-dir type
948: @end example
949:
950: If you enter long definitions by hand, you can use a text editor to
951: paste them out of the history file into a Forth source file for reuse at
952: a later time.
953:
954: Gforth never trims the size of the history file, so you should do this
955: periodically, if necessary.
956:
957: @comment this is all defined in history.fs
958: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
959: @comment chosen?
960:
961:
962: @comment ----------------------------------------------
1.65 anton 963: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 964: @section Environment variables
965: @cindex environment variables
966:
967: Gforth uses these environment variables:
968:
969: @itemize @bullet
970: @item
971: @cindex @code{GFORTHHIST} -- environment variable
972: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
973: open/create the history file, @file{.gforth-history}. Default:
974: @code{$HOME}.
975:
976: @item
977: @cindex @code{GFORTHPATH} -- environment variable
978: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
979: for Forth source-code files.
980:
981: @item
1.147 anton 982: @cindex @code{LANG} -- environment variable
983: @code{LANG} -- see @code{LC_CTYPE}
984:
985: @item
986: @cindex @code{LC_ALL} -- environment variable
987: @code{LC_ALL} -- see @code{LC_CTYPE}
988:
989: @item
990: @cindex @code{LC_CTYPE} -- environment variable
991: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
992: startup, Gforth uses the UTF-8 encoding for strings internally and
993: expects its input and produces its output in UTF-8 encoding, otherwise
994: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
995: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
996: that is unset, in @code{LANG}.
997:
998: @item
1.129 anton 999: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1000:
1001: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1002: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1003: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1004: and the command are directly concatenated, so if a space between them is
1005: necessary, append it to the prefix.
1006:
1007: @item
1.48 anton 1008: @cindex @code{GFORTH} -- environment variable
1.49 anton 1009: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1010:
1011: @item
1012: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1013: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1014:
1015: @item
1016: @cindex @code{TMP}, @code{TEMP} - environment variable
1017: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1018: location for the history file.
1019: @end itemize
1020:
1021: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1022: @comment mentioning these.
1023:
1024: All the Gforth environment variables default to sensible values if they
1025: are not set.
1026:
1027:
1028: @comment ----------------------------------------------
1.112 anton 1029: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1030: @section Gforth files
1031: @cindex Gforth files
1032:
1033: When you install Gforth on a Unix system, it installs files in these
1034: locations by default:
1035:
1036: @itemize @bullet
1037: @item
1038: @file{/usr/local/bin/gforth}
1039: @item
1040: @file{/usr/local/bin/gforthmi}
1041: @item
1042: @file{/usr/local/man/man1/gforth.1} - man page.
1043: @item
1044: @file{/usr/local/info} - the Info version of this manual.
1045: @item
1046: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1047: @item
1048: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1049: @item
1050: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1051: @item
1052: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1053: @end itemize
1054:
1055: You can select different places for installation by using
1056: @code{configure} options (listed with @code{configure --help}).
1057:
1058: @comment ----------------------------------------------
1.112 anton 1059: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1060: @section Gforth in pipes
1061: @cindex pipes, Gforth as part of
1062:
1063: Gforth can be used in pipes created elsewhere (described here). It can
1064: also create pipes on its own (@pxref{Pipes}).
1065:
1066: @cindex input from pipes
1067: If you pipe into Gforth, your program should read with @code{read-file}
1068: or @code{read-line} from @code{stdin} (@pxref{General files}).
1069: @code{Key} does not recognize the end of input. Words like
1070: @code{accept} echo the input and are therefore usually not useful for
1071: reading from a pipe. You have to invoke the Forth program with an OS
1072: command-line option, as you have no chance to use the Forth command line
1073: (the text interpreter would try to interpret the pipe input).
1074:
1075: @cindex output in pipes
1076: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1077:
1078: @cindex silent exiting from Gforth
1079: When you write to a pipe that has been closed at the other end, Gforth
1080: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1081: into the exception @code{broken-pipe-error}. If your application does
1082: not catch that exception, the system catches it and exits, usually
1083: silently (unless you were working on the Forth command line; then it
1084: prints an error message and exits). This is usually the desired
1085: behaviour.
1086:
1087: If you do not like this behaviour, you have to catch the exception
1088: yourself, and react to it.
1089:
1090: Here's an example of an invocation of Gforth that is usable in a pipe:
1091:
1092: @example
1093: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1094: type repeat ; foo bye"
1095: @end example
1096:
1097: This example just copies the input verbatim to the output. A very
1098: simple pipe containing this example looks like this:
1099:
1100: @example
1101: cat startup.fs |
1102: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1103: type repeat ; foo bye"|
1104: head
1105: @end example
1106:
1107: @cindex stderr and pipes
1108: Pipes involving Gforth's @code{stderr} output do not work.
1109:
1110: @comment ----------------------------------------------
1111: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1112: @section Startup speed
1113: @cindex Startup speed
1114: @cindex speed, startup
1115:
1116: If Gforth is used for CGI scripts or in shell scripts, its startup
1117: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1118: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1119: system time.
1120:
1121: If startup speed is a problem, you may consider the following ways to
1122: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1123: (for example, by using Fast-CGI).
1.48 anton 1124:
1.112 anton 1125: An easy step that influences Gforth startup speed is the use of the
1126: @option{--no-dynamic} option; this decreases image loading speed, but
1127: increases compile-time and run-time.
1128:
1129: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1130: building it with @code{XLDFLAGS=-static}. This requires more memory for
1131: the code and will therefore slow down the first invocation, but
1132: subsequent invocations avoid the dynamic linking overhead. Another
1133: disadvantage is that Gforth won't profit from library upgrades. As a
1134: result, @code{gforth-static -e bye} takes about 17.1ms user and
1135: 8.2ms system time.
1136:
1137: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1138: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1139: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1140: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1141: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1142: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1143: address for the dictionary, for whatever reason; so you better provide a
1144: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1145: bye} takes about 15.3ms user and 7.5ms system time.
1146:
1147: The final step is to disable dictionary hashing in Gforth. Gforth
1148: builds the hash table on startup, which takes much of the startup
1149: overhead. You can do this by commenting out the @code{include hash.fs}
1150: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1151: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1152: The disadvantages are that functionality like @code{table} and
1153: @code{ekey} is missing and that text interpretation (e.g., compiling)
1154: now takes much longer. So, you should only use this method if there is
1155: no significant text interpretation to perform (the script should be
1.62 crook 1156: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1157: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1158:
1159: @c ******************************************************************
1160: @node Tutorial, Introduction, Gforth Environment, Top
1161: @chapter Forth Tutorial
1162: @cindex Tutorial
1163: @cindex Forth Tutorial
1164:
1.67 anton 1165: @c Topics from nac's Introduction that could be mentioned:
1166: @c press <ret> after each line
1167: @c Prompt
1168: @c numbers vs. words in dictionary on text interpretation
1169: @c what happens on redefinition
1170: @c parsing words (in particular, defining words)
1171:
1.83 anton 1172: The difference of this chapter from the Introduction
1173: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1174: be used while sitting in front of a computer, and covers much more
1175: material, but does not explain how the Forth system works.
1176:
1.62 crook 1177: This tutorial can be used with any ANS-compliant Forth; any
1178: Gforth-specific features are marked as such and you can skip them if you
1179: work with another Forth. This tutorial does not explain all features of
1180: Forth, just enough to get you started and give you some ideas about the
1181: facilities available in Forth. Read the rest of the manual and the
1182: standard when you are through this.
1.48 anton 1183:
1184: The intended way to use this tutorial is that you work through it while
1185: sitting in front of the console, take a look at the examples and predict
1186: what they will do, then try them out; if the outcome is not as expected,
1187: find out why (e.g., by trying out variations of the example), so you
1188: understand what's going on. There are also some assignments that you
1189: should solve.
1190:
1191: This tutorial assumes that you have programmed before and know what,
1192: e.g., a loop is.
1193:
1194: @c !! explain compat library
1195:
1196: @menu
1197: * Starting Gforth Tutorial::
1198: * Syntax Tutorial::
1199: * Crash Course Tutorial::
1200: * Stack Tutorial::
1201: * Arithmetics Tutorial::
1202: * Stack Manipulation Tutorial::
1203: * Using files for Forth code Tutorial::
1204: * Comments Tutorial::
1205: * Colon Definitions Tutorial::
1206: * Decompilation Tutorial::
1207: * Stack-Effect Comments Tutorial::
1208: * Types Tutorial::
1209: * Factoring Tutorial::
1210: * Designing the stack effect Tutorial::
1211: * Local Variables Tutorial::
1212: * Conditional execution Tutorial::
1213: * Flags and Comparisons Tutorial::
1214: * General Loops Tutorial::
1215: * Counted loops Tutorial::
1216: * Recursion Tutorial::
1217: * Leaving definitions or loops Tutorial::
1218: * Return Stack Tutorial::
1219: * Memory Tutorial::
1220: * Characters and Strings Tutorial::
1221: * Alignment Tutorial::
1.87 anton 1222: * Files Tutorial::
1.48 anton 1223: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1224: * Execution Tokens Tutorial::
1225: * Exceptions Tutorial::
1226: * Defining Words Tutorial::
1227: * Arrays and Records Tutorial::
1228: * POSTPONE Tutorial::
1229: * Literal Tutorial::
1230: * Advanced macros Tutorial::
1231: * Compilation Tokens Tutorial::
1232: * Wordlists and Search Order Tutorial::
1233: @end menu
1234:
1235: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1236: @section Starting Gforth
1.66 anton 1237: @cindex starting Gforth tutorial
1.48 anton 1238: You can start Gforth by typing its name:
1239:
1240: @example
1241: gforth
1242: @end example
1243:
1244: That puts you into interactive mode; you can leave Gforth by typing
1245: @code{bye}. While in Gforth, you can edit the command line and access
1246: the command line history with cursor keys, similar to bash.
1247:
1248:
1249: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1250: @section Syntax
1.66 anton 1251: @cindex syntax tutorial
1.48 anton 1252:
1253: A @dfn{word} is a sequence of arbitrary characters (expcept white
1254: space). Words are separated by white space. E.g., each of the
1255: following lines contains exactly one word:
1256:
1257: @example
1258: word
1259: !@@#$%^&*()
1260: 1234567890
1261: 5!a
1262: @end example
1263:
1264: A frequent beginner's error is to leave away necessary white space,
1265: resulting in an error like @samp{Undefined word}; so if you see such an
1266: error, check if you have put spaces wherever necessary.
1267:
1268: @example
1269: ." hello, world" \ correct
1270: ."hello, world" \ gives an "Undefined word" error
1271: @end example
1272:
1.65 anton 1273: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1274: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1275: your system is case-sensitive, you may have to type all the examples
1276: given here in upper case.
1277:
1278:
1279: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1280: @section Crash Course
1281:
1282: Type
1283:
1284: @example
1285: 0 0 !
1286: here execute
1287: ' catch >body 20 erase abort
1288: ' (quit) >body 20 erase
1289: @end example
1290:
1291: The last two examples are guaranteed to destroy parts of Gforth (and
1292: most other systems), so you better leave Gforth afterwards (if it has
1293: not finished by itself). On some systems you may have to kill gforth
1294: from outside (e.g., in Unix with @code{kill}).
1295:
1296: Now that you know how to produce crashes (and that there's not much to
1297: them), let's learn how to produce meaningful programs.
1298:
1299:
1300: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1301: @section Stack
1.66 anton 1302: @cindex stack tutorial
1.48 anton 1303:
1304: The most obvious feature of Forth is the stack. When you type in a
1305: number, it is pushed on the stack. You can display the content of the
1306: stack with @code{.s}.
1307:
1308: @example
1309: 1 2 .s
1310: 3 .s
1311: @end example
1312:
1313: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1314: appear in @code{.s} output as they appeared in the input.
1315:
1316: You can print the top of stack element with @code{.}.
1317:
1318: @example
1319: 1 2 3 . . .
1320: @end example
1321:
1322: In general, words consume their stack arguments (@code{.s} is an
1323: exception).
1324:
1.141 anton 1325: @quotation Assignment
1.48 anton 1326: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1327: @end quotation
1.48 anton 1328:
1329:
1330: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1331: @section Arithmetics
1.66 anton 1332: @cindex arithmetics tutorial
1.48 anton 1333:
1334: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1335: operate on the top two stack items:
1336:
1337: @example
1.67 anton 1338: 2 2 .s
1339: + .s
1340: .
1.48 anton 1341: 2 1 - .
1342: 7 3 mod .
1343: @end example
1344:
1345: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1346: as in the corresponding infix expression (this is generally the case in
1347: Forth).
1348:
1349: Parentheses are superfluous (and not available), because the order of
1350: the words unambiguously determines the order of evaluation and the
1351: operands:
1352:
1353: @example
1354: 3 4 + 5 * .
1355: 3 4 5 * + .
1356: @end example
1357:
1.141 anton 1358: @quotation Assignment
1.48 anton 1359: What are the infix expressions corresponding to the Forth code above?
1360: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1361: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1362: @end quotation
1.48 anton 1363:
1364: To change the sign, use @code{negate}:
1365:
1366: @example
1367: 2 negate .
1368: @end example
1369:
1.141 anton 1370: @quotation Assignment
1.48 anton 1371: Convert -(-3)*4-5 to Forth.
1.141 anton 1372: @end quotation
1.48 anton 1373:
1374: @code{/mod} performs both @code{/} and @code{mod}.
1375:
1376: @example
1377: 7 3 /mod . .
1378: @end example
1379:
1.66 anton 1380: Reference: @ref{Arithmetic}.
1381:
1382:
1.48 anton 1383: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1384: @section Stack Manipulation
1.66 anton 1385: @cindex stack manipulation tutorial
1.48 anton 1386:
1387: Stack manipulation words rearrange the data on the stack.
1388:
1389: @example
1390: 1 .s drop .s
1391: 1 .s dup .s drop drop .s
1392: 1 2 .s over .s drop drop drop
1393: 1 2 .s swap .s drop drop
1394: 1 2 3 .s rot .s drop drop drop
1395: @end example
1396:
1397: These are the most important stack manipulation words. There are also
1398: variants that manipulate twice as many stack items:
1399:
1400: @example
1401: 1 2 3 4 .s 2swap .s 2drop 2drop
1402: @end example
1403:
1404: Two more stack manipulation words are:
1405:
1406: @example
1407: 1 2 .s nip .s drop
1408: 1 2 .s tuck .s 2drop drop
1409: @end example
1410:
1.141 anton 1411: @quotation Assignment
1.48 anton 1412: Replace @code{nip} and @code{tuck} with combinations of other stack
1413: manipulation words.
1414:
1415: @example
1416: Given: How do you get:
1417: 1 2 3 3 2 1
1418: 1 2 3 1 2 3 2
1419: 1 2 3 1 2 3 3
1420: 1 2 3 1 3 3
1421: 1 2 3 2 1 3
1422: 1 2 3 4 4 3 2 1
1423: 1 2 3 1 2 3 1 2 3
1424: 1 2 3 4 1 2 3 4 1 2
1425: 1 2 3
1426: 1 2 3 1 2 3 4
1427: 1 2 3 1 3
1428: @end example
1.141 anton 1429: @end quotation
1.48 anton 1430:
1431: @example
1432: 5 dup * .
1433: @end example
1434:
1.141 anton 1435: @quotation Assignment
1.48 anton 1436: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1437: Write a piece of Forth code that expects two numbers on the stack
1438: (@var{a} and @var{b}, with @var{b} on top) and computes
1439: @code{(a-b)(a+1)}.
1.141 anton 1440: @end quotation
1.48 anton 1441:
1.66 anton 1442: Reference: @ref{Stack Manipulation}.
1443:
1444:
1.48 anton 1445: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1446: @section Using files for Forth code
1.66 anton 1447: @cindex loading Forth code, tutorial
1448: @cindex files containing Forth code, tutorial
1.48 anton 1449:
1450: While working at the Forth command line is convenient for one-line
1451: examples and short one-off code, you probably want to store your source
1452: code in files for convenient editing and persistence. You can use your
1453: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1454: Gforth}) to create @var{file.fs} and use
1.48 anton 1455:
1456: @example
1.102 anton 1457: s" @var{file.fs}" included
1.48 anton 1458: @end example
1459:
1460: to load it into your Forth system. The file name extension I use for
1461: Forth files is @samp{.fs}.
1462:
1463: You can easily start Gforth with some files loaded like this:
1464:
1465: @example
1.102 anton 1466: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1467: @end example
1468:
1469: If an error occurs during loading these files, Gforth terminates,
1470: whereas an error during @code{INCLUDED} within Gforth usually gives you
1471: a Gforth command line. Starting the Forth system every time gives you a
1472: clean start every time, without interference from the results of earlier
1473: tries.
1474:
1475: I often put all the tests in a file, then load the code and run the
1476: tests with
1477:
1478: @example
1.102 anton 1479: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1480: @end example
1481:
1482: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1483: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1484: restart this command without ado.
1485:
1486: The advantage of this approach is that the tests can be repeated easily
1487: every time the program ist changed, making it easy to catch bugs
1488: introduced by the change.
1489:
1.66 anton 1490: Reference: @ref{Forth source files}.
1491:
1.48 anton 1492:
1493: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1494: @section Comments
1.66 anton 1495: @cindex comments tutorial
1.48 anton 1496:
1497: @example
1498: \ That's a comment; it ends at the end of the line
1499: ( Another comment; it ends here: ) .s
1500: @end example
1501:
1502: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1503: separated with white space from the following text.
1504:
1505: @example
1506: \This gives an "Undefined word" error
1507: @end example
1508:
1509: The first @code{)} ends a comment started with @code{(}, so you cannot
1510: nest @code{(}-comments; and you cannot comment out text containing a
1511: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1512: avoid @code{)} in word names.}.
1513:
1514: I use @code{\}-comments for descriptive text and for commenting out code
1515: of one or more line; I use @code{(}-comments for describing the stack
1516: effect, the stack contents, or for commenting out sub-line pieces of
1517: code.
1518:
1519: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1520: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1521: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1522: with @kbd{M-q}.
1523:
1.66 anton 1524: Reference: @ref{Comments}.
1525:
1.48 anton 1526:
1527: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1528: @section Colon Definitions
1.66 anton 1529: @cindex colon definitions, tutorial
1530: @cindex definitions, tutorial
1531: @cindex procedures, tutorial
1532: @cindex functions, tutorial
1.48 anton 1533:
1534: are similar to procedures and functions in other programming languages.
1535:
1536: @example
1537: : squared ( n -- n^2 )
1538: dup * ;
1539: 5 squared .
1540: 7 squared .
1541: @end example
1542:
1543: @code{:} starts the colon definition; its name is @code{squared}. The
1544: following comment describes its stack effect. The words @code{dup *}
1545: are not executed, but compiled into the definition. @code{;} ends the
1546: colon definition.
1547:
1548: The newly-defined word can be used like any other word, including using
1549: it in other definitions:
1550:
1551: @example
1552: : cubed ( n -- n^3 )
1553: dup squared * ;
1554: -5 cubed .
1555: : fourth-power ( n -- n^4 )
1556: squared squared ;
1557: 3 fourth-power .
1558: @end example
1559:
1.141 anton 1560: @quotation Assignment
1.48 anton 1561: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1562: @code{/mod} in terms of other Forth words, and check if they work (hint:
1563: test your tests on the originals first). Don't let the
1564: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1565: @end quotation
1.48 anton 1566:
1.66 anton 1567: Reference: @ref{Colon Definitions}.
1568:
1.48 anton 1569:
1570: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1571: @section Decompilation
1.66 anton 1572: @cindex decompilation tutorial
1573: @cindex see tutorial
1.48 anton 1574:
1575: You can decompile colon definitions with @code{see}:
1576:
1577: @example
1578: see squared
1579: see cubed
1580: @end example
1581:
1582: In Gforth @code{see} shows you a reconstruction of the source code from
1583: the executable code. Informations that were present in the source, but
1584: not in the executable code, are lost (e.g., comments).
1585:
1.65 anton 1586: You can also decompile the predefined words:
1587:
1588: @example
1589: see .
1590: see +
1591: @end example
1592:
1593:
1.48 anton 1594: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1595: @section Stack-Effect Comments
1.66 anton 1596: @cindex stack-effect comments, tutorial
1597: @cindex --, tutorial
1.48 anton 1598: By convention the comment after the name of a definition describes the
1599: stack effect: The part in from of the @samp{--} describes the state of
1600: the stack before the execution of the definition, i.e., the parameters
1601: that are passed into the colon definition; the part behind the @samp{--}
1602: is the state of the stack after the execution of the definition, i.e.,
1603: the results of the definition. The stack comment only shows the top
1604: stack items that the definition accesses and/or changes.
1605:
1606: You should put a correct stack effect on every definition, even if it is
1607: just @code{( -- )}. You should also add some descriptive comment to
1608: more complicated words (I usually do this in the lines following
1609: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1610: you have to work through every definition before you can understand
1.48 anton 1611: any).
1612:
1.141 anton 1613: @quotation Assignment
1.48 anton 1614: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1615: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1616: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1617: are done, you can compare your stack effects to those in this manual
1.48 anton 1618: (@pxref{Word Index}).
1.141 anton 1619: @end quotation
1.48 anton 1620:
1621: Sometimes programmers put comments at various places in colon
1622: definitions that describe the contents of the stack at that place (stack
1623: comments); i.e., they are like the first part of a stack-effect
1624: comment. E.g.,
1625:
1626: @example
1627: : cubed ( n -- n^3 )
1628: dup squared ( n n^2 ) * ;
1629: @end example
1630:
1631: In this case the stack comment is pretty superfluous, because the word
1632: is simple enough. If you think it would be a good idea to add such a
1633: comment to increase readability, you should also consider factoring the
1634: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1635: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1636: however, if you decide not to refactor it, then having such a comment is
1637: better than not having it.
1638:
1639: The names of the stack items in stack-effect and stack comments in the
1640: standard, in this manual, and in many programs specify the type through
1641: a type prefix, similar to Fortran and Hungarian notation. The most
1642: frequent prefixes are:
1643:
1644: @table @code
1645: @item n
1646: signed integer
1647: @item u
1648: unsigned integer
1649: @item c
1650: character
1651: @item f
1652: Boolean flags, i.e. @code{false} or @code{true}.
1653: @item a-addr,a-
1654: Cell-aligned address
1655: @item c-addr,c-
1656: Char-aligned address (note that a Char may have two bytes in Windows NT)
1657: @item xt
1658: Execution token, same size as Cell
1659: @item w,x
1660: Cell, can contain an integer or an address. It usually takes 32, 64 or
1661: 16 bits (depending on your platform and Forth system). A cell is more
1662: commonly known as machine word, but the term @emph{word} already means
1663: something different in Forth.
1664: @item d
1665: signed double-cell integer
1666: @item ud
1667: unsigned double-cell integer
1668: @item r
1669: Float (on the FP stack)
1670: @end table
1671:
1672: You can find a more complete list in @ref{Notation}.
1673:
1.141 anton 1674: @quotation Assignment
1.48 anton 1675: Write stack-effect comments for all definitions you have written up to
1676: now.
1.141 anton 1677: @end quotation
1.48 anton 1678:
1679:
1680: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1681: @section Types
1.66 anton 1682: @cindex types tutorial
1.48 anton 1683:
1684: In Forth the names of the operations are not overloaded; so similar
1685: operations on different types need different names; e.g., @code{+} adds
1686: integers, and you have to use @code{f+} to add floating-point numbers.
1687: The following prefixes are often used for related operations on
1688: different types:
1689:
1690: @table @code
1691: @item (none)
1692: signed integer
1693: @item u
1694: unsigned integer
1695: @item c
1696: character
1697: @item d
1698: signed double-cell integer
1699: @item ud, du
1700: unsigned double-cell integer
1701: @item 2
1702: two cells (not-necessarily double-cell numbers)
1703: @item m, um
1704: mixed single-cell and double-cell operations
1705: @item f
1706: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1707: and @samp{r} represents FP numbers).
1.48 anton 1708: @end table
1709:
1710: If there are no differences between the signed and the unsigned variant
1711: (e.g., for @code{+}), there is only the prefix-less variant.
1712:
1713: Forth does not perform type checking, neither at compile time, nor at
1714: run time. If you use the wrong oeration, the data are interpreted
1715: incorrectly:
1716:
1717: @example
1718: -1 u.
1719: @end example
1720:
1721: If you have only experience with type-checked languages until now, and
1722: have heard how important type-checking is, don't panic! In my
1723: experience (and that of other Forthers), type errors in Forth code are
1724: usually easy to find (once you get used to it), the increased vigilance
1725: of the programmer tends to catch some harder errors in addition to most
1726: type errors, and you never have to work around the type system, so in
1727: most situations the lack of type-checking seems to be a win (projects to
1728: add type checking to Forth have not caught on).
1729:
1730:
1731: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1732: @section Factoring
1.66 anton 1733: @cindex factoring tutorial
1.48 anton 1734:
1735: If you try to write longer definitions, you will soon find it hard to
1736: keep track of the stack contents. Therefore, good Forth programmers
1737: tend to write only short definitions (e.g., three lines). The art of
1738: finding meaningful short definitions is known as factoring (as in
1739: factoring polynomials).
1740:
1741: Well-factored programs offer additional advantages: smaller, more
1742: general words, are easier to test and debug and can be reused more and
1743: better than larger, specialized words.
1744:
1745: So, if you run into difficulties with stack management, when writing
1746: code, try to define meaningful factors for the word, and define the word
1747: in terms of those. Even if a factor contains only two words, it is
1748: often helpful.
1749:
1.65 anton 1750: Good factoring is not easy, and it takes some practice to get the knack
1751: for it; but even experienced Forth programmers often don't find the
1752: right solution right away, but only when rewriting the program. So, if
1753: you don't come up with a good solution immediately, keep trying, don't
1754: despair.
1.48 anton 1755:
1756: @c example !!
1757:
1758:
1759: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1760: @section Designing the stack effect
1.66 anton 1761: @cindex Stack effect design, tutorial
1762: @cindex design of stack effects, tutorial
1.48 anton 1763:
1764: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1765: function; and since there is only one result, you don't have to deal with
1.48 anton 1766: the order of results, either.
1767:
1.117 anton 1768: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1769: parameter and result order of a definition is important and should be
1770: designed well. The general guideline is to design the stack effect such
1771: that the word is simple to use in most cases, even if that complicates
1772: the implementation of the word. Some concrete rules are:
1773:
1774: @itemize @bullet
1775:
1776: @item
1777: Words consume all of their parameters (e.g., @code{.}).
1778:
1779: @item
1780: If there is a convention on the order of parameters (e.g., from
1781: mathematics or another programming language), stick with it (e.g.,
1782: @code{-}).
1783:
1784: @item
1785: If one parameter usually requires only a short computation (e.g., it is
1786: a constant), pass it on the top of the stack. Conversely, parameters
1787: that usually require a long sequence of code to compute should be passed
1788: as the bottom (i.e., first) parameter. This makes the code easier to
1789: read, because reader does not need to keep track of the bottom item
1790: through a long sequence of code (or, alternatively, through stack
1.49 anton 1791: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1792: address on top of the stack because it is usually simpler to compute
1793: than the stored value (often the address is just a variable).
1794:
1795: @item
1796: Similarly, results that are usually consumed quickly should be returned
1797: on the top of stack, whereas a result that is often used in long
1798: computations should be passed as bottom result. E.g., the file words
1799: like @code{open-file} return the error code on the top of stack, because
1800: it is usually consumed quickly by @code{throw}; moreover, the error code
1801: has to be checked before doing anything with the other results.
1802:
1803: @end itemize
1804:
1805: These rules are just general guidelines, don't lose sight of the overall
1806: goal to make the words easy to use. E.g., if the convention rule
1807: conflicts with the computation-length rule, you might decide in favour
1808: of the convention if the word will be used rarely, and in favour of the
1809: computation-length rule if the word will be used frequently (because
1810: with frequent use the cost of breaking the computation-length rule would
1811: be quite high, and frequent use makes it easier to remember an
1812: unconventional order).
1813:
1814: @c example !! structure package
1815:
1.65 anton 1816:
1.48 anton 1817: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1818: @section Local Variables
1.66 anton 1819: @cindex local variables, tutorial
1.48 anton 1820:
1821: You can define local variables (@emph{locals}) in a colon definition:
1822:
1823: @example
1824: : swap @{ a b -- b a @}
1825: b a ;
1826: 1 2 swap .s 2drop
1827: @end example
1828:
1829: (If your Forth system does not support this syntax, include
1830: @file{compat/anslocals.fs} first).
1831:
1832: In this example @code{@{ a b -- b a @}} is the locals definition; it
1833: takes two cells from the stack, puts the top of stack in @code{b} and
1834: the next stack element in @code{a}. @code{--} starts a comment ending
1835: with @code{@}}. After the locals definition, using the name of the
1836: local will push its value on the stack. You can leave the comment
1837: part (@code{-- b a}) away:
1838:
1839: @example
1840: : swap ( x1 x2 -- x2 x1 )
1841: @{ a b @} b a ;
1842: @end example
1843:
1844: In Gforth you can have several locals definitions, anywhere in a colon
1845: definition; in contrast, in a standard program you can have only one
1846: locals definition per colon definition, and that locals definition must
1.163 anton 1847: be outside any control structure.
1.48 anton 1848:
1849: With locals you can write slightly longer definitions without running
1850: into stack trouble. However, I recommend trying to write colon
1851: definitions without locals for exercise purposes to help you gain the
1852: essential factoring skills.
1853:
1.141 anton 1854: @quotation Assignment
1.48 anton 1855: Rewrite your definitions until now with locals
1.141 anton 1856: @end quotation
1.48 anton 1857:
1.66 anton 1858: Reference: @ref{Locals}.
1859:
1.48 anton 1860:
1861: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1862: @section Conditional execution
1.66 anton 1863: @cindex conditionals, tutorial
1864: @cindex if, tutorial
1.48 anton 1865:
1866: In Forth you can use control structures only inside colon definitions.
1867: An @code{if}-structure looks like this:
1868:
1869: @example
1870: : abs ( n1 -- +n2 )
1871: dup 0 < if
1872: negate
1873: endif ;
1874: 5 abs .
1875: -5 abs .
1876: @end example
1877:
1878: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1879: the following code is performed, otherwise execution continues after the
1.51 pazsan 1880: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1881: elements and prioduces a flag:
1882:
1883: @example
1884: 1 2 < .
1885: 2 1 < .
1886: 1 1 < .
1887: @end example
1888:
1889: Actually the standard name for @code{endif} is @code{then}. This
1890: tutorial presents the examples using @code{endif}, because this is often
1891: less confusing for people familiar with other programming languages
1892: where @code{then} has a different meaning. If your system does not have
1893: @code{endif}, define it with
1894:
1895: @example
1896: : endif postpone then ; immediate
1897: @end example
1898:
1899: You can optionally use an @code{else}-part:
1900:
1901: @example
1902: : min ( n1 n2 -- n )
1903: 2dup < if
1904: drop
1905: else
1906: nip
1907: endif ;
1908: 2 3 min .
1909: 3 2 min .
1910: @end example
1911:
1.141 anton 1912: @quotation Assignment
1.48 anton 1913: Write @code{min} without @code{else}-part (hint: what's the definition
1914: of @code{nip}?).
1.141 anton 1915: @end quotation
1.48 anton 1916:
1.66 anton 1917: Reference: @ref{Selection}.
1918:
1.48 anton 1919:
1920: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1921: @section Flags and Comparisons
1.66 anton 1922: @cindex flags tutorial
1923: @cindex comparison tutorial
1.48 anton 1924:
1925: In a false-flag all bits are clear (0 when interpreted as integer). In
1926: a canonical true-flag all bits are set (-1 as a twos-complement signed
1927: integer); in many contexts (e.g., @code{if}) any non-zero value is
1928: treated as true flag.
1929:
1930: @example
1931: false .
1932: true .
1933: true hex u. decimal
1934: @end example
1935:
1936: Comparison words produce canonical flags:
1937:
1938: @example
1939: 1 1 = .
1940: 1 0= .
1941: 0 1 < .
1942: 0 0 < .
1943: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1944: -1 1 < .
1945: @end example
1946:
1.66 anton 1947: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1948: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1949: these combinations are standard (for details see the standard,
1950: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1951:
1952: You can use @code{and or xor invert} can be used as operations on
1953: canonical flags. Actually they are bitwise operations:
1954:
1955: @example
1956: 1 2 and .
1957: 1 2 or .
1958: 1 3 xor .
1959: 1 invert .
1960: @end example
1961:
1962: You can convert a zero/non-zero flag into a canonical flag with
1963: @code{0<>} (and complement it on the way with @code{0=}).
1964:
1965: @example
1966: 1 0= .
1967: 1 0<> .
1968: @end example
1969:
1.65 anton 1970: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1971: operation of the Boolean operations to avoid @code{if}s:
1972:
1973: @example
1974: : foo ( n1 -- n2 )
1975: 0= if
1976: 14
1977: else
1978: 0
1979: endif ;
1980: 0 foo .
1981: 1 foo .
1982:
1983: : foo ( n1 -- n2 )
1984: 0= 14 and ;
1985: 0 foo .
1986: 1 foo .
1987: @end example
1988:
1.141 anton 1989: @quotation Assignment
1.48 anton 1990: Write @code{min} without @code{if}.
1.141 anton 1991: @end quotation
1.48 anton 1992:
1.66 anton 1993: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1994: @ref{Bitwise operations}.
1995:
1.48 anton 1996:
1997: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1998: @section General Loops
1.66 anton 1999: @cindex loops, indefinite, tutorial
1.48 anton 2000:
2001: The endless loop is the most simple one:
2002:
2003: @example
2004: : endless ( -- )
2005: 0 begin
2006: dup . 1+
2007: again ;
2008: endless
2009: @end example
2010:
2011: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2012: does nothing at run-time, @code{again} jumps back to @code{begin}.
2013:
2014: A loop with one exit at any place looks like this:
2015:
2016: @example
2017: : log2 ( +n1 -- n2 )
2018: \ logarithmus dualis of n1>0, rounded down to the next integer
2019: assert( dup 0> )
2020: 2/ 0 begin
2021: over 0> while
2022: 1+ swap 2/ swap
2023: repeat
2024: nip ;
2025: 7 log2 .
2026: 8 log2 .
2027: @end example
2028:
2029: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2030: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2031: continues behind the @code{while}. @code{Repeat} jumps back to
2032: @code{begin}, just like @code{again}.
2033:
2034: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2035: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2036: one bit (arithmetic shift right):
2037:
2038: @example
2039: -5 2 / .
2040: -5 2/ .
2041: @end example
2042:
2043: @code{assert(} is no standard word, but you can get it on systems other
2044: then Gforth by including @file{compat/assert.fs}. You can see what it
2045: does by trying
2046:
2047: @example
2048: 0 log2 .
2049: @end example
2050:
2051: Here's a loop with an exit at the end:
2052:
2053: @example
2054: : log2 ( +n1 -- n2 )
2055: \ logarithmus dualis of n1>0, rounded down to the next integer
2056: assert( dup 0 > )
2057: -1 begin
2058: 1+ swap 2/ swap
2059: over 0 <=
2060: until
2061: nip ;
2062: @end example
2063:
2064: @code{Until} consumes a flag; if it is non-zero, execution continues at
2065: the @code{begin}, otherwise after the @code{until}.
2066:
1.141 anton 2067: @quotation Assignment
1.48 anton 2068: Write a definition for computing the greatest common divisor.
1.141 anton 2069: @end quotation
1.48 anton 2070:
1.66 anton 2071: Reference: @ref{Simple Loops}.
2072:
1.48 anton 2073:
2074: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2075: @section Counted loops
1.66 anton 2076: @cindex loops, counted, tutorial
1.48 anton 2077:
2078: @example
2079: : ^ ( n1 u -- n )
2080: \ n = the uth power of u1
2081: 1 swap 0 u+do
2082: over *
2083: loop
2084: nip ;
2085: 3 2 ^ .
2086: 4 3 ^ .
2087: @end example
2088:
2089: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2090: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2091: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2092: times (or not at all, if @code{u3-u4<0}).
2093:
2094: You can see the stack effect design rules at work in the stack effect of
2095: the loop start words: Since the start value of the loop is more
2096: frequently constant than the end value, the start value is passed on
2097: the top-of-stack.
2098:
2099: You can access the counter of a counted loop with @code{i}:
2100:
2101: @example
2102: : fac ( u -- u! )
2103: 1 swap 1+ 1 u+do
2104: i *
2105: loop ;
2106: 5 fac .
2107: 7 fac .
2108: @end example
2109:
2110: There is also @code{+do}, which expects signed numbers (important for
2111: deciding whether to enter the loop).
2112:
1.141 anton 2113: @quotation Assignment
1.48 anton 2114: Write a definition for computing the nth Fibonacci number.
1.141 anton 2115: @end quotation
1.48 anton 2116:
1.65 anton 2117: You can also use increments other than 1:
2118:
2119: @example
2120: : up2 ( n1 n2 -- )
2121: +do
2122: i .
2123: 2 +loop ;
2124: 10 0 up2
2125:
2126: : down2 ( n1 n2 -- )
2127: -do
2128: i .
2129: 2 -loop ;
2130: 0 10 down2
2131: @end example
1.48 anton 2132:
1.66 anton 2133: Reference: @ref{Counted Loops}.
2134:
1.48 anton 2135:
2136: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2137: @section Recursion
1.66 anton 2138: @cindex recursion tutorial
1.48 anton 2139:
2140: Usually the name of a definition is not visible in the definition; but
2141: earlier definitions are usually visible:
2142:
2143: @example
1.166 ! anton 2144: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2145: : / ( n1 n2 -- n )
2146: dup 0= if
2147: -10 throw \ report division by zero
2148: endif
2149: / \ old version
2150: ;
2151: 1 0 /
2152: @end example
2153:
2154: For recursive definitions you can use @code{recursive} (non-standard) or
2155: @code{recurse}:
2156:
2157: @example
2158: : fac1 ( n -- n! ) recursive
2159: dup 0> if
2160: dup 1- fac1 *
2161: else
2162: drop 1
2163: endif ;
2164: 7 fac1 .
2165:
2166: : fac2 ( n -- n! )
2167: dup 0> if
2168: dup 1- recurse *
2169: else
2170: drop 1
2171: endif ;
2172: 8 fac2 .
2173: @end example
2174:
1.141 anton 2175: @quotation Assignment
1.48 anton 2176: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2177: @end quotation
1.48 anton 2178:
1.66 anton 2179: Reference (including indirect recursion): @xref{Calls and returns}.
2180:
1.48 anton 2181:
2182: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2183: @section Leaving definitions or loops
1.66 anton 2184: @cindex leaving definitions, tutorial
2185: @cindex leaving loops, tutorial
1.48 anton 2186:
2187: @code{EXIT} exits the current definition right away. For every counted
2188: loop that is left in this way, an @code{UNLOOP} has to be performed
2189: before the @code{EXIT}:
2190:
2191: @c !! real examples
2192: @example
2193: : ...
2194: ... u+do
2195: ... if
2196: ... unloop exit
2197: endif
2198: ...
2199: loop
2200: ... ;
2201: @end example
2202:
2203: @code{LEAVE} leaves the innermost counted loop right away:
2204:
2205: @example
2206: : ...
2207: ... u+do
2208: ... if
2209: ... leave
2210: endif
2211: ...
2212: loop
2213: ... ;
2214: @end example
2215:
1.65 anton 2216: @c !! example
1.48 anton 2217:
1.66 anton 2218: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2219:
2220:
1.48 anton 2221: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2222: @section Return Stack
1.66 anton 2223: @cindex return stack tutorial
1.48 anton 2224:
2225: In addition to the data stack Forth also has a second stack, the return
2226: stack; most Forth systems store the return addresses of procedure calls
2227: there (thus its name). Programmers can also use this stack:
2228:
2229: @example
2230: : foo ( n1 n2 -- )
2231: .s
2232: >r .s
1.50 anton 2233: r@@ .
1.48 anton 2234: >r .s
1.50 anton 2235: r@@ .
1.48 anton 2236: r> .
1.50 anton 2237: r@@ .
1.48 anton 2238: r> . ;
2239: 1 2 foo
2240: @end example
2241:
2242: @code{>r} takes an element from the data stack and pushes it onto the
2243: return stack; conversely, @code{r>} moves an elementm from the return to
2244: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2245: on the data stack.
1.48 anton 2246:
2247: Forth programmers usually use the return stack for storing data
2248: temporarily, if using the data stack alone would be too complex, and
2249: factoring and locals are not an option:
2250:
2251: @example
2252: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2253: rot >r rot r> ;
2254: @end example
2255:
2256: The return address of the definition and the loop control parameters of
2257: counted loops usually reside on the return stack, so you have to take
2258: all items, that you have pushed on the return stack in a colon
2259: definition or counted loop, from the return stack before the definition
2260: or loop ends. You cannot access items that you pushed on the return
2261: stack outside some definition or loop within the definition of loop.
2262:
2263: If you miscount the return stack items, this usually ends in a crash:
2264:
2265: @example
2266: : crash ( n -- )
2267: >r ;
2268: 5 crash
2269: @end example
2270:
2271: You cannot mix using locals and using the return stack (according to the
2272: standard; Gforth has no problem). However, they solve the same
2273: problems, so this shouldn't be an issue.
2274:
1.141 anton 2275: @quotation Assignment
1.48 anton 2276: Can you rewrite any of the definitions you wrote until now in a better
2277: way using the return stack?
1.141 anton 2278: @end quotation
1.48 anton 2279:
1.66 anton 2280: Reference: @ref{Return stack}.
2281:
1.48 anton 2282:
2283: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2284: @section Memory
1.66 anton 2285: @cindex memory access/allocation tutorial
1.48 anton 2286:
2287: You can create a global variable @code{v} with
2288:
2289: @example
2290: variable v ( -- addr )
2291: @end example
2292:
2293: @code{v} pushes the address of a cell in memory on the stack. This cell
2294: was reserved by @code{variable}. You can use @code{!} (store) to store
2295: values into this cell and @code{@@} (fetch) to load the value from the
2296: stack into memory:
2297:
2298: @example
2299: v .
2300: 5 v ! .s
1.50 anton 2301: v @@ .
1.48 anton 2302: @end example
2303:
1.65 anton 2304: You can see a raw dump of memory with @code{dump}:
2305:
2306: @example
2307: v 1 cells .s dump
2308: @end example
2309:
2310: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2311: generally, address units (aus)) that @code{n1 cells} occupy. You can
2312: also reserve more memory:
1.48 anton 2313:
2314: @example
2315: create v2 20 cells allot
1.65 anton 2316: v2 20 cells dump
1.48 anton 2317: @end example
2318:
1.65 anton 2319: creates a word @code{v2} and reserves 20 uninitialized cells; the
2320: address pushed by @code{v2} points to the start of these 20 cells. You
2321: can use address arithmetic to access these cells:
1.48 anton 2322:
2323: @example
2324: 3 v2 5 cells + !
1.65 anton 2325: v2 20 cells dump
1.48 anton 2326: @end example
2327:
2328: You can reserve and initialize memory with @code{,}:
2329:
2330: @example
2331: create v3
2332: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2333: v3 @@ .
2334: v3 cell+ @@ .
2335: v3 2 cells + @@ .
1.65 anton 2336: v3 5 cells dump
1.48 anton 2337: @end example
2338:
1.141 anton 2339: @quotation Assignment
1.48 anton 2340: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2341: @code{u} cells, with the first of these cells at @code{addr}, the next
2342: one at @code{addr cell+} etc.
1.141 anton 2343: @end quotation
1.48 anton 2344:
2345: You can also reserve memory without creating a new word:
2346:
2347: @example
1.60 anton 2348: here 10 cells allot .
2349: here .
1.48 anton 2350: @end example
2351:
2352: @code{Here} pushes the start address of the memory area. You should
2353: store it somewhere, or you will have a hard time finding the memory area
2354: again.
2355:
2356: @code{Allot} manages dictionary memory. The dictionary memory contains
2357: the system's data structures for words etc. on Gforth and most other
2358: Forth systems. It is managed like a stack: You can free the memory that
2359: you have just @code{allot}ed with
2360:
2361: @example
2362: -10 cells allot
1.60 anton 2363: here .
1.48 anton 2364: @end example
2365:
2366: Note that you cannot do this if you have created a new word in the
2367: meantime (because then your @code{allot}ed memory is no longer on the
2368: top of the dictionary ``stack'').
2369:
2370: Alternatively, you can use @code{allocate} and @code{free} which allow
2371: freeing memory in any order:
2372:
2373: @example
2374: 10 cells allocate throw .s
2375: 20 cells allocate throw .s
2376: swap
2377: free throw
2378: free throw
2379: @end example
2380:
2381: The @code{throw}s deal with errors (e.g., out of memory).
2382:
1.65 anton 2383: And there is also a
2384: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2385: garbage collector}, which eliminates the need to @code{free} memory
2386: explicitly.
1.48 anton 2387:
1.66 anton 2388: Reference: @ref{Memory}.
2389:
1.48 anton 2390:
2391: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2392: @section Characters and Strings
1.66 anton 2393: @cindex strings tutorial
2394: @cindex characters tutorial
1.48 anton 2395:
2396: On the stack characters take up a cell, like numbers. In memory they
2397: have their own size (one 8-bit byte on most systems), and therefore
2398: require their own words for memory access:
2399:
2400: @example
2401: create v4
2402: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2403: v4 4 chars + c@@ .
1.65 anton 2404: v4 5 chars dump
1.48 anton 2405: @end example
2406:
2407: The preferred representation of strings on the stack is @code{addr
2408: u-count}, where @code{addr} is the address of the first character and
2409: @code{u-count} is the number of characters in the string.
2410:
2411: @example
2412: v4 5 type
2413: @end example
2414:
2415: You get a string constant with
2416:
2417: @example
2418: s" hello, world" .s
2419: type
2420: @end example
2421:
2422: Make sure you have a space between @code{s"} and the string; @code{s"}
2423: is a normal Forth word and must be delimited with white space (try what
2424: happens when you remove the space).
2425:
2426: However, this interpretive use of @code{s"} is quite restricted: the
2427: string exists only until the next call of @code{s"} (some Forth systems
2428: keep more than one of these strings, but usually they still have a
1.62 crook 2429: limited lifetime).
1.48 anton 2430:
2431: @example
2432: s" hello," s" world" .s
2433: type
2434: type
2435: @end example
2436:
1.62 crook 2437: You can also use @code{s"} in a definition, and the resulting
2438: strings then live forever (well, for as long as the definition):
1.48 anton 2439:
2440: @example
2441: : foo s" hello," s" world" ;
2442: foo .s
2443: type
2444: type
2445: @end example
2446:
1.141 anton 2447: @quotation Assignment
1.48 anton 2448: @code{Emit ( c -- )} types @code{c} as character (not a number).
2449: Implement @code{type ( addr u -- )}.
1.141 anton 2450: @end quotation
1.48 anton 2451:
1.66 anton 2452: Reference: @ref{Memory Blocks}.
2453:
2454:
1.84 pazsan 2455: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2456: @section Alignment
1.66 anton 2457: @cindex alignment tutorial
2458: @cindex memory alignment tutorial
1.48 anton 2459:
2460: On many processors cells have to be aligned in memory, if you want to
2461: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2462: not require alignment, access to aligned cells is faster).
1.48 anton 2463:
2464: @code{Create} aligns @code{here} (i.e., the place where the next
2465: allocation will occur, and that the @code{create}d word points to).
2466: Likewise, the memory produced by @code{allocate} starts at an aligned
2467: address. Adding a number of @code{cells} to an aligned address produces
2468: another aligned address.
2469:
2470: However, address arithmetic involving @code{char+} and @code{chars} can
2471: create an address that is not cell-aligned. @code{Aligned ( addr --
2472: a-addr )} produces the next aligned address:
2473:
2474: @example
1.50 anton 2475: v3 char+ aligned .s @@ .
2476: v3 char+ .s @@ .
1.48 anton 2477: @end example
2478:
2479: Similarly, @code{align} advances @code{here} to the next aligned
2480: address:
2481:
2482: @example
2483: create v5 97 c,
2484: here .
2485: align here .
2486: 1000 ,
2487: @end example
2488:
2489: Note that you should use aligned addresses even if your processor does
2490: not require them, if you want your program to be portable.
2491:
1.66 anton 2492: Reference: @ref{Address arithmetic}.
2493:
1.48 anton 2494:
1.84 pazsan 2495: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2496: @section Files
2497: @cindex files tutorial
2498:
2499: This section gives a short introduction into how to use files inside
2500: Forth. It's broken up into five easy steps:
2501:
2502: @enumerate 1
2503: @item Opened an ASCII text file for input
2504: @item Opened a file for output
2505: @item Read input file until string matched (or some other condition matched)
2506: @item Wrote some lines from input ( modified or not) to output
2507: @item Closed the files.
2508: @end enumerate
2509:
1.153 anton 2510: Reference: @ref{General files}.
2511:
1.84 pazsan 2512: @subsection Open file for input
2513:
2514: @example
2515: s" foo.in" r/o open-file throw Value fd-in
2516: @end example
2517:
2518: @subsection Create file for output
2519:
2520: @example
2521: s" foo.out" w/o create-file throw Value fd-out
2522: @end example
2523:
2524: The available file modes are r/o for read-only access, r/w for
2525: read-write access, and w/o for write-only access. You could open both
2526: files with r/w, too, if you like. All file words return error codes; for
2527: most applications, it's best to pass there error codes with @code{throw}
2528: to the outer error handler.
2529:
2530: If you want words for opening and assigning, define them as follows:
2531:
2532: @example
2533: 0 Value fd-in
2534: 0 Value fd-out
2535: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2536: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2537: @end example
2538:
2539: Usage example:
2540:
2541: @example
2542: s" foo.in" open-input
2543: s" foo.out" open-output
2544: @end example
2545:
2546: @subsection Scan file for a particular line
2547:
2548: @example
2549: 256 Constant max-line
2550: Create line-buffer max-line 2 + allot
2551:
2552: : scan-file ( addr u -- )
2553: begin
2554: line-buffer max-line fd-in read-line throw
2555: while
2556: >r 2dup line-buffer r> compare 0=
2557: until
2558: else
2559: drop
2560: then
2561: 2drop ;
2562: @end example
2563:
2564: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2565: the buffer at addr, and returns the number of bytes read, a flag that is
2566: false when the end of file is reached, and an error code.
1.84 pazsan 2567:
2568: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2569: returns zero if both strings are equal. It returns a positive number if
2570: the first string is lexically greater, a negative if the second string
2571: is lexically greater.
2572:
2573: We haven't seen this loop here; it has two exits. Since the @code{while}
2574: exits with the number of bytes read on the stack, we have to clean up
2575: that separately; that's after the @code{else}.
2576:
2577: Usage example:
2578:
2579: @example
2580: s" The text I search is here" scan-file
2581: @end example
2582:
2583: @subsection Copy input to output
2584:
2585: @example
2586: : copy-file ( -- )
2587: begin
2588: line-buffer max-line fd-in read-line throw
2589: while
2590: line-buffer swap fd-out write-file throw
2591: repeat ;
2592: @end example
2593:
2594: @subsection Close files
2595:
2596: @example
2597: fd-in close-file throw
2598: fd-out close-file throw
2599: @end example
2600:
2601: Likewise, you can put that into definitions, too:
2602:
2603: @example
2604: : close-input ( -- ) fd-in close-file throw ;
2605: : close-output ( -- ) fd-out close-file throw ;
2606: @end example
2607:
1.141 anton 2608: @quotation Assignment
1.84 pazsan 2609: How could you modify @code{copy-file} so that it copies until a second line is
2610: matched? Can you write a program that extracts a section of a text file,
2611: given the line that starts and the line that terminates that section?
1.141 anton 2612: @end quotation
1.84 pazsan 2613:
2614: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2615: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2616: @cindex semantics tutorial
2617: @cindex interpretation semantics tutorial
2618: @cindex compilation semantics tutorial
2619: @cindex immediate, tutorial
1.48 anton 2620:
2621: When a word is compiled, it behaves differently from being interpreted.
2622: E.g., consider @code{+}:
2623:
2624: @example
2625: 1 2 + .
2626: : foo + ;
2627: @end example
2628:
2629: These two behaviours are known as compilation and interpretation
2630: semantics. For normal words (e.g., @code{+}), the compilation semantics
2631: is to append the interpretation semantics to the currently defined word
2632: (@code{foo} in the example above). I.e., when @code{foo} is executed
2633: later, the interpretation semantics of @code{+} (i.e., adding two
2634: numbers) will be performed.
2635:
2636: However, there are words with non-default compilation semantics, e.g.,
2637: the control-flow words like @code{if}. You can use @code{immediate} to
2638: change the compilation semantics of the last defined word to be equal to
2639: the interpretation semantics:
2640:
2641: @example
2642: : [FOO] ( -- )
2643: 5 . ; immediate
2644:
2645: [FOO]
2646: : bar ( -- )
2647: [FOO] ;
2648: bar
2649: see bar
2650: @end example
2651:
2652: Two conventions to mark words with non-default compilation semnatics are
2653: names with brackets (more frequently used) and to write them all in
2654: upper case (less frequently used).
2655:
2656: In Gforth (and many other systems) you can also remove the
2657: interpretation semantics with @code{compile-only} (the compilation
2658: semantics is derived from the original interpretation semantics):
2659:
2660: @example
2661: : flip ( -- )
2662: 6 . ; compile-only \ but not immediate
2663: flip
2664:
2665: : flop ( -- )
2666: flip ;
2667: flop
2668: @end example
2669:
2670: In this example the interpretation semantics of @code{flop} is equal to
2671: the original interpretation semantics of @code{flip}.
2672:
2673: The text interpreter has two states: in interpret state, it performs the
2674: interpretation semantics of words it encounters; in compile state, it
2675: performs the compilation semantics of these words.
2676:
2677: Among other things, @code{:} switches into compile state, and @code{;}
2678: switches back to interpret state. They contain the factors @code{]}
2679: (switch to compile state) and @code{[} (switch to interpret state), that
2680: do nothing but switch the state.
2681:
2682: @example
2683: : xxx ( -- )
2684: [ 5 . ]
2685: ;
2686:
2687: xxx
2688: see xxx
2689: @end example
2690:
2691: These brackets are also the source of the naming convention mentioned
2692: above.
2693:
1.66 anton 2694: Reference: @ref{Interpretation and Compilation Semantics}.
2695:
1.48 anton 2696:
2697: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2698: @section Execution Tokens
1.66 anton 2699: @cindex execution tokens tutorial
2700: @cindex XT tutorial
1.48 anton 2701:
2702: @code{' word} gives you the execution token (XT) of a word. The XT is a
2703: cell representing the interpretation semantics of a word. You can
2704: execute this semantics with @code{execute}:
2705:
2706: @example
2707: ' + .s
2708: 1 2 rot execute .
2709: @end example
2710:
2711: The XT is similar to a function pointer in C. However, parameter
2712: passing through the stack makes it a little more flexible:
2713:
2714: @example
2715: : map-array ( ... addr u xt -- ... )
1.50 anton 2716: \ executes xt ( ... x -- ... ) for every element of the array starting
2717: \ at addr and containing u elements
1.48 anton 2718: @{ xt @}
2719: cells over + swap ?do
1.50 anton 2720: i @@ xt execute
1.48 anton 2721: 1 cells +loop ;
2722:
2723: create a 3 , 4 , 2 , -1 , 4 ,
2724: a 5 ' . map-array .s
2725: 0 a 5 ' + map-array .
2726: s" max-n" environment? drop .s
2727: a 5 ' min map-array .
2728: @end example
2729:
2730: You can use map-array with the XTs of words that consume one element
2731: more than they produce. In theory you can also use it with other XTs,
2732: but the stack effect then depends on the size of the array, which is
2733: hard to understand.
2734:
1.51 pazsan 2735: Since XTs are cell-sized, you can store them in memory and manipulate
2736: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2737: word with @code{compile,}:
2738:
2739: @example
2740: : foo1 ( n1 n2 -- n )
2741: [ ' + compile, ] ;
2742: see foo
2743: @end example
2744:
2745: This is non-standard, because @code{compile,} has no compilation
2746: semantics in the standard, but it works in good Forth systems. For the
2747: broken ones, use
2748:
2749: @example
2750: : [compile,] compile, ; immediate
2751:
2752: : foo1 ( n1 n2 -- n )
2753: [ ' + ] [compile,] ;
2754: see foo
2755: @end example
2756:
2757: @code{'} is a word with default compilation semantics; it parses the
2758: next word when its interpretation semantics are executed, not during
2759: compilation:
2760:
2761: @example
2762: : foo ( -- xt )
2763: ' ;
2764: see foo
2765: : bar ( ... "word" -- ... )
2766: ' execute ;
2767: see bar
1.60 anton 2768: 1 2 bar + .
1.48 anton 2769: @end example
2770:
2771: You often want to parse a word during compilation and compile its XT so
2772: it will be pushed on the stack at run-time. @code{[']} does this:
2773:
2774: @example
2775: : xt-+ ( -- xt )
2776: ['] + ;
2777: see xt-+
2778: 1 2 xt-+ execute .
2779: @end example
2780:
2781: Many programmers tend to see @code{'} and the word it parses as one
2782: unit, and expect it to behave like @code{[']} when compiled, and are
2783: confused by the actual behaviour. If you are, just remember that the
2784: Forth system just takes @code{'} as one unit and has no idea that it is
2785: a parsing word (attempts to convenience programmers in this issue have
2786: usually resulted in even worse pitfalls, see
1.66 anton 2787: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2788: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2789:
2790: Note that the state of the interpreter does not come into play when
1.51 pazsan 2791: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2792: compile state, it still gives you the interpretation semantics. And
2793: whatever that state is, @code{execute} performs the semantics
1.66 anton 2794: represented by the XT (i.e., for XTs produced with @code{'} the
2795: interpretation semantics).
2796:
2797: Reference: @ref{Tokens for Words}.
1.48 anton 2798:
2799:
2800: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2801: @section Exceptions
1.66 anton 2802: @cindex exceptions tutorial
1.48 anton 2803:
2804: @code{throw ( n -- )} causes an exception unless n is zero.
2805:
2806: @example
2807: 100 throw .s
2808: 0 throw .s
2809: @end example
2810:
2811: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2812: it catches exceptions and pushes the number of the exception on the
2813: stack (or 0, if the xt executed without exception). If there was an
2814: exception, the stacks have the same depth as when entering @code{catch}:
2815:
2816: @example
2817: .s
2818: 3 0 ' / catch .s
2819: 3 2 ' / catch .s
2820: @end example
2821:
1.141 anton 2822: @quotation Assignment
1.48 anton 2823: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2824: @end quotation
1.48 anton 2825:
2826: @code{Throw} always jumps to the dynamically next enclosing
2827: @code{catch}, even if it has to leave several call levels to achieve
2828: this:
2829:
2830: @example
2831: : foo 100 throw ;
2832: : foo1 foo ." after foo" ;
1.51 pazsan 2833: : bar ['] foo1 catch ;
1.60 anton 2834: bar .
1.48 anton 2835: @end example
2836:
2837: It is often important to restore a value upon leaving a definition, even
2838: if the definition is left through an exception. You can ensure this
2839: like this:
2840:
2841: @example
2842: : ...
2843: save-x
1.51 pazsan 2844: ['] word-changing-x catch ( ... n )
1.48 anton 2845: restore-x
2846: ( ... n ) throw ;
2847: @end example
2848:
1.55 anton 2849: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2850: @code{try ... recover ... endtry}. If the code between @code{try} and
2851: @code{recover} has an exception, the stack depths are restored, the
2852: exception number is pushed on the stack, and the code between
2853: @code{recover} and @code{endtry} is performed. E.g., the definition for
2854: @code{catch} is
2855:
2856: @example
2857: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2858: try
2859: execute 0
2860: recover
2861: nip
2862: endtry ;
2863: @end example
2864:
2865: The equivalent to the restoration code above is
2866:
2867: @example
2868: : ...
2869: save-x
2870: try
1.92 anton 2871: word-changing-x 0
2872: recover endtry
1.48 anton 2873: restore-x
2874: throw ;
2875: @end example
2876:
1.92 anton 2877: This works if @code{word-changing-x} does not change the stack depth,
2878: otherwise you should add some code between @code{recover} and
2879: @code{endtry} to balance the stack.
1.48 anton 2880:
1.66 anton 2881: Reference: @ref{Exception Handling}.
2882:
1.48 anton 2883:
2884: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2885: @section Defining Words
1.66 anton 2886: @cindex defining words tutorial
2887: @cindex does> tutorial
2888: @cindex create...does> tutorial
2889:
2890: @c before semantics?
1.48 anton 2891:
2892: @code{:}, @code{create}, and @code{variable} are definition words: They
2893: define other words. @code{Constant} is another definition word:
2894:
2895: @example
2896: 5 constant foo
2897: foo .
2898: @end example
2899:
2900: You can also use the prefixes @code{2} (double-cell) and @code{f}
2901: (floating point) with @code{variable} and @code{constant}.
2902:
2903: You can also define your own defining words. E.g.:
2904:
2905: @example
2906: : variable ( "name" -- )
2907: create 0 , ;
2908: @end example
2909:
2910: You can also define defining words that create words that do something
2911: other than just producing their address:
2912:
2913: @example
2914: : constant ( n "name" -- )
2915: create ,
2916: does> ( -- n )
1.50 anton 2917: ( addr ) @@ ;
1.48 anton 2918:
2919: 5 constant foo
2920: foo .
2921: @end example
2922:
2923: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2924: @code{does>} replaces @code{;}, but it also does something else: It
2925: changes the last defined word such that it pushes the address of the
2926: body of the word and then performs the code after the @code{does>}
2927: whenever it is called.
2928:
2929: In the example above, @code{constant} uses @code{,} to store 5 into the
2930: body of @code{foo}. When @code{foo} executes, it pushes the address of
2931: the body onto the stack, then (in the code after the @code{does>})
2932: fetches the 5 from there.
2933:
2934: The stack comment near the @code{does>} reflects the stack effect of the
2935: defined word, not the stack effect of the code after the @code{does>}
2936: (the difference is that the code expects the address of the body that
2937: the stack comment does not show).
2938:
2939: You can use these definition words to do factoring in cases that involve
2940: (other) definition words. E.g., a field offset is always added to an
2941: address. Instead of defining
2942:
2943: @example
2944: 2 cells constant offset-field1
2945: @end example
2946:
2947: and using this like
2948:
2949: @example
2950: ( addr ) offset-field1 +
2951: @end example
2952:
2953: you can define a definition word
2954:
2955: @example
2956: : simple-field ( n "name" -- )
2957: create ,
2958: does> ( n1 -- n1+n )
1.50 anton 2959: ( addr ) @@ + ;
1.48 anton 2960: @end example
1.21 crook 2961:
1.48 anton 2962: Definition and use of field offsets now look like this:
1.21 crook 2963:
1.48 anton 2964: @example
2965: 2 cells simple-field field1
1.60 anton 2966: create mystruct 4 cells allot
2967: mystruct .s field1 .s drop
1.48 anton 2968: @end example
1.21 crook 2969:
1.48 anton 2970: If you want to do something with the word without performing the code
2971: after the @code{does>}, you can access the body of a @code{create}d word
2972: with @code{>body ( xt -- addr )}:
1.21 crook 2973:
1.48 anton 2974: @example
2975: : value ( n "name" -- )
2976: create ,
2977: does> ( -- n1 )
1.50 anton 2978: @@ ;
1.48 anton 2979: : to ( n "name" -- )
2980: ' >body ! ;
1.21 crook 2981:
1.48 anton 2982: 5 value foo
2983: foo .
2984: 7 to foo
2985: foo .
2986: @end example
1.21 crook 2987:
1.141 anton 2988: @quotation Assignment
1.48 anton 2989: Define @code{defer ( "name" -- )}, which creates a word that stores an
2990: XT (at the start the XT of @code{abort}), and upon execution
2991: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2992: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2993: recursion is one application of @code{defer}.
1.141 anton 2994: @end quotation
1.29 crook 2995:
1.66 anton 2996: Reference: @ref{User-defined Defining Words}.
2997:
2998:
1.48 anton 2999: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3000: @section Arrays and Records
1.66 anton 3001: @cindex arrays tutorial
3002: @cindex records tutorial
3003: @cindex structs tutorial
1.29 crook 3004:
1.48 anton 3005: Forth has no standard words for defining data structures such as arrays
3006: and records (structs in C terminology), but you can build them yourself
3007: based on address arithmetic. You can also define words for defining
3008: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3009:
1.48 anton 3010: One of the first projects a Forth newcomer sets out upon when learning
3011: about defining words is an array defining word (possibly for
3012: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3013: learn something from it. However, don't be disappointed when you later
3014: learn that you have little use for these words (inappropriate use would
3015: be even worse). I have not yet found a set of useful array words yet;
3016: the needs are just too diverse, and named, global arrays (the result of
3017: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3018: consider how to pass them as parameters). Another such project is a set
3019: of words to help dealing with strings.
1.29 crook 3020:
1.48 anton 3021: On the other hand, there is a useful set of record words, and it has
3022: been defined in @file{compat/struct.fs}; these words are predefined in
3023: Gforth. They are explained in depth elsewhere in this manual (see
3024: @pxref{Structures}). The @code{simple-field} example above is
3025: simplified variant of fields in this package.
1.21 crook 3026:
3027:
1.48 anton 3028: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3029: @section @code{POSTPONE}
1.66 anton 3030: @cindex postpone tutorial
1.21 crook 3031:
1.48 anton 3032: You can compile the compilation semantics (instead of compiling the
3033: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3034:
1.48 anton 3035: @example
3036: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3037: POSTPONE + ; immediate
1.48 anton 3038: : foo ( n1 n2 -- n )
3039: MY-+ ;
3040: 1 2 foo .
3041: see foo
3042: @end example
1.21 crook 3043:
1.48 anton 3044: During the definition of @code{foo} the text interpreter performs the
3045: compilation semantics of @code{MY-+}, which performs the compilation
3046: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3047:
3048: This example also displays separate stack comments for the compilation
3049: semantics and for the stack effect of the compiled code. For words with
3050: default compilation semantics these stack effects are usually not
3051: displayed; the stack effect of the compilation semantics is always
3052: @code{( -- )} for these words, the stack effect for the compiled code is
3053: the stack effect of the interpretation semantics.
3054:
3055: Note that the state of the interpreter does not come into play when
3056: performing the compilation semantics in this way. You can also perform
3057: it interpretively, e.g.:
3058:
3059: @example
3060: : foo2 ( n1 n2 -- n )
3061: [ MY-+ ] ;
3062: 1 2 foo .
3063: see foo
3064: @end example
1.21 crook 3065:
1.48 anton 3066: However, there are some broken Forth systems where this does not always
1.62 crook 3067: work, and therefore this practice was been declared non-standard in
1.48 anton 3068: 1999.
3069: @c !! repair.fs
3070:
3071: Here is another example for using @code{POSTPONE}:
1.44 crook 3072:
1.48 anton 3073: @example
3074: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3075: POSTPONE negate POSTPONE + ; immediate compile-only
3076: : bar ( n1 n2 -- n )
3077: MY-- ;
3078: 2 1 bar .
3079: see bar
3080: @end example
1.21 crook 3081:
1.48 anton 3082: You can define @code{ENDIF} in this way:
1.21 crook 3083:
1.48 anton 3084: @example
3085: : ENDIF ( Compilation: orig -- )
3086: POSTPONE then ; immediate
3087: @end example
1.21 crook 3088:
1.141 anton 3089: @quotation Assignment
1.48 anton 3090: Write @code{MY-2DUP} that has compilation semantics equivalent to
3091: @code{2dup}, but compiles @code{over over}.
1.141 anton 3092: @end quotation
1.29 crook 3093:
1.66 anton 3094: @c !! @xref{Macros} for reference
3095:
3096:
1.48 anton 3097: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3098: @section @code{Literal}
1.66 anton 3099: @cindex literal tutorial
1.29 crook 3100:
1.48 anton 3101: You cannot @code{POSTPONE} numbers:
1.21 crook 3102:
1.48 anton 3103: @example
3104: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3105: @end example
3106:
1.48 anton 3107: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3108:
1.48 anton 3109: @example
3110: : [FOO] ( compilation: --; run-time: -- n )
3111: 500 POSTPONE literal ; immediate
1.29 crook 3112:
1.60 anton 3113: : flip [FOO] ;
1.48 anton 3114: flip .
3115: see flip
3116: @end example
1.29 crook 3117:
1.48 anton 3118: @code{LITERAL} consumes a number at compile-time (when it's compilation
3119: semantics are executed) and pushes it at run-time (when the code it
3120: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3121: number computed at compile time into the current word:
1.29 crook 3122:
1.48 anton 3123: @example
3124: : bar ( -- n )
3125: [ 2 2 + ] literal ;
3126: see bar
3127: @end example
1.29 crook 3128:
1.141 anton 3129: @quotation Assignment
1.48 anton 3130: Write @code{]L} which allows writing the example above as @code{: bar (
3131: -- n ) [ 2 2 + ]L ;}
1.141 anton 3132: @end quotation
1.48 anton 3133:
1.66 anton 3134: @c !! @xref{Macros} for reference
3135:
1.48 anton 3136:
3137: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3138: @section Advanced macros
1.66 anton 3139: @cindex macros, advanced tutorial
3140: @cindex run-time code generation, tutorial
1.48 anton 3141:
1.66 anton 3142: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3143: Execution Tokens}. It frequently performs @code{execute}, a relatively
3144: expensive operation in some Forth implementations. You can use
1.48 anton 3145: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3146: and produce a word that contains the word to be performed directly:
3147:
3148: @c use ]] ... [[
3149: @example
3150: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3151: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3152: \ array beginning at addr and containing u elements
3153: @{ xt @}
3154: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3155: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3156: 1 cells POSTPONE literal POSTPONE +loop ;
3157:
3158: : sum-array ( addr u -- n )
3159: 0 rot rot [ ' + compile-map-array ] ;
3160: see sum-array
3161: a 5 sum-array .
3162: @end example
3163:
3164: You can use the full power of Forth for generating the code; here's an
3165: example where the code is generated in a loop:
3166:
3167: @example
3168: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3169: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3170: POSTPONE tuck POSTPONE @@
1.48 anton 3171: POSTPONE literal POSTPONE * POSTPONE +
3172: POSTPONE swap POSTPONE cell+ ;
3173:
3174: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3175: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3176: 0 postpone literal postpone swap
3177: [ ' compile-vmul-step compile-map-array ]
3178: postpone drop ;
3179: see compile-vmul
3180:
3181: : a-vmul ( addr -- n )
1.51 pazsan 3182: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3183: [ a 5 compile-vmul ] ;
3184: see a-vmul
3185: a a-vmul .
3186: @end example
3187:
3188: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3189: also use @code{map-array} instead (try it now!).
1.48 anton 3190:
3191: You can use this technique for efficient multiplication of large
3192: matrices. In matrix multiplication, you multiply every line of one
3193: matrix with every column of the other matrix. You can generate the code
3194: for one line once, and use it for every column. The only downside of
3195: this technique is that it is cumbersome to recover the memory consumed
3196: by the generated code when you are done (and in more complicated cases
3197: it is not possible portably).
3198:
1.66 anton 3199: @c !! @xref{Macros} for reference
3200:
3201:
1.48 anton 3202: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3203: @section Compilation Tokens
1.66 anton 3204: @cindex compilation tokens, tutorial
3205: @cindex CT, tutorial
1.48 anton 3206:
3207: This section is Gforth-specific. You can skip it.
3208:
3209: @code{' word compile,} compiles the interpretation semantics. For words
3210: with default compilation semantics this is the same as performing the
3211: compilation semantics. To represent the compilation semantics of other
3212: words (e.g., words like @code{if} that have no interpretation
3213: semantics), Gforth has the concept of a compilation token (CT,
3214: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3215: You can perform the compilation semantics represented by a CT with
3216: @code{execute}:
1.29 crook 3217:
1.48 anton 3218: @example
3219: : foo2 ( n1 n2 -- n )
3220: [ comp' + execute ] ;
3221: see foo
3222: @end example
1.29 crook 3223:
1.48 anton 3224: You can compile the compilation semantics represented by a CT with
3225: @code{postpone,}:
1.30 anton 3226:
1.48 anton 3227: @example
3228: : foo3 ( -- )
3229: [ comp' + postpone, ] ;
3230: see foo3
3231: @end example
1.30 anton 3232:
1.51 pazsan 3233: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3234: @code{comp'} is particularly useful for words that have no
3235: interpretation semantics:
1.29 crook 3236:
1.30 anton 3237: @example
1.48 anton 3238: ' if
1.60 anton 3239: comp' if .s 2drop
1.30 anton 3240: @end example
3241:
1.66 anton 3242: Reference: @ref{Tokens for Words}.
3243:
1.29 crook 3244:
1.48 anton 3245: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3246: @section Wordlists and Search Order
1.66 anton 3247: @cindex wordlists tutorial
3248: @cindex search order, tutorial
1.48 anton 3249:
3250: The dictionary is not just a memory area that allows you to allocate
3251: memory with @code{allot}, it also contains the Forth words, arranged in
3252: several wordlists. When searching for a word in a wordlist,
3253: conceptually you start searching at the youngest and proceed towards
3254: older words (in reality most systems nowadays use hash-tables); i.e., if
3255: you define a word with the same name as an older word, the new word
3256: shadows the older word.
3257:
3258: Which wordlists are searched in which order is determined by the search
3259: order. You can display the search order with @code{order}. It displays
3260: first the search order, starting with the wordlist searched first, then
3261: it displays the wordlist that will contain newly defined words.
1.21 crook 3262:
1.48 anton 3263: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3264:
1.48 anton 3265: @example
3266: wordlist constant mywords
3267: @end example
1.21 crook 3268:
1.48 anton 3269: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3270: defined words (the @emph{current} wordlist):
1.21 crook 3271:
1.48 anton 3272: @example
3273: mywords set-current
3274: order
3275: @end example
1.26 crook 3276:
1.48 anton 3277: Gforth does not display a name for the wordlist in @code{mywords}
3278: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3279:
1.48 anton 3280: You can get the current wordlist with @code{get-current ( -- wid)}. If
3281: you want to put something into a specific wordlist without overall
3282: effect on the current wordlist, this typically looks like this:
1.21 crook 3283:
1.48 anton 3284: @example
3285: get-current mywords set-current ( wid )
3286: create someword
3287: ( wid ) set-current
3288: @end example
1.21 crook 3289:
1.48 anton 3290: You can write the search order with @code{set-order ( wid1 .. widn n --
3291: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3292: searched wordlist is topmost.
1.21 crook 3293:
1.48 anton 3294: @example
3295: get-order mywords swap 1+ set-order
3296: order
3297: @end example
1.21 crook 3298:
1.48 anton 3299: Yes, the order of wordlists in the output of @code{order} is reversed
3300: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3301:
1.141 anton 3302: @quotation Assignment
1.48 anton 3303: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3304: wordlist to the search order. Define @code{previous ( -- )}, which
3305: removes the first searched wordlist from the search order. Experiment
3306: with boundary conditions (you will see some crashes or situations that
3307: are hard or impossible to leave).
1.141 anton 3308: @end quotation
1.21 crook 3309:
1.48 anton 3310: The search order is a powerful foundation for providing features similar
3311: to Modula-2 modules and C++ namespaces. However, trying to modularize
3312: programs in this way has disadvantages for debugging and reuse/factoring
3313: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3314: though). These disadvantages are not so clear in other
1.82 anton 3315: languages/programming environments, because these languages are not so
1.48 anton 3316: strong in debugging and reuse.
1.21 crook 3317:
1.66 anton 3318: @c !! example
3319:
3320: Reference: @ref{Word Lists}.
1.21 crook 3321:
1.29 crook 3322: @c ******************************************************************
1.48 anton 3323: @node Introduction, Words, Tutorial, Top
1.29 crook 3324: @comment node-name, next, previous, up
3325: @chapter An Introduction to ANS Forth
3326: @cindex Forth - an introduction
1.21 crook 3327:
1.83 anton 3328: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3329: that it is slower-paced in its examples, but uses them to dive deep into
3330: explaining Forth internals (not covered by the Tutorial). Apart from
3331: that, this chapter covers far less material. It is suitable for reading
3332: without using a computer.
3333:
1.29 crook 3334: The primary purpose of this manual is to document Gforth. However, since
3335: Forth is not a widely-known language and there is a lack of up-to-date
3336: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3337: material. For other sources of Forth-related
3338: information, see @ref{Forth-related information}.
1.21 crook 3339:
1.29 crook 3340: The examples in this section should work on any ANS Forth; the
3341: output shown was produced using Gforth. Each example attempts to
3342: reproduce the exact output that Gforth produces. If you try out the
3343: examples (and you should), what you should type is shown @kbd{like this}
3344: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3345: that, where the example shows @key{RET} it means that you should
1.29 crook 3346: press the ``carriage return'' key. Unfortunately, some output formats for
3347: this manual cannot show the difference between @kbd{this} and
3348: @code{this} which will make trying out the examples harder (but not
3349: impossible).
1.21 crook 3350:
1.29 crook 3351: Forth is an unusual language. It provides an interactive development
3352: environment which includes both an interpreter and compiler. Forth
3353: programming style encourages you to break a problem down into many
3354: @cindex factoring
3355: small fragments (@dfn{factoring}), and then to develop and test each
3356: fragment interactively. Forth advocates assert that breaking the
3357: edit-compile-test cycle used by conventional programming languages can
3358: lead to great productivity improvements.
1.21 crook 3359:
1.29 crook 3360: @menu
1.67 anton 3361: * Introducing the Text Interpreter::
3362: * Stacks and Postfix notation::
3363: * Your first definition::
3364: * How does that work?::
3365: * Forth is written in Forth::
3366: * Review - elements of a Forth system::
3367: * Where to go next::
3368: * Exercises::
1.29 crook 3369: @end menu
1.21 crook 3370:
1.29 crook 3371: @comment ----------------------------------------------
3372: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3373: @section Introducing the Text Interpreter
3374: @cindex text interpreter
3375: @cindex outer interpreter
1.21 crook 3376:
1.30 anton 3377: @c IMO this is too detailed and the pace is too slow for
3378: @c an introduction. If you know German, take a look at
3379: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3380: @c to see how I do it - anton
3381:
1.44 crook 3382: @c nac-> Where I have accepted your comments 100% and modified the text
3383: @c accordingly, I have deleted your comments. Elsewhere I have added a
3384: @c response like this to attempt to rationalise what I have done. Of
3385: @c course, this is a very clumsy mechanism for something that would be
3386: @c done far more efficiently over a beer. Please delete any dialogue
3387: @c you consider closed.
3388:
1.29 crook 3389: When you invoke the Forth image, you will see a startup banner printed
3390: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3391: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3392: its command line interpreter, which is called the @dfn{Text Interpreter}
3393: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3394: about the text interpreter as you read through this chapter, for more
3395: detail @pxref{The Text Interpreter}).
1.21 crook 3396:
1.29 crook 3397: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3398: input. Type a number and press the @key{RET} key:
1.21 crook 3399:
1.26 crook 3400: @example
1.30 anton 3401: @kbd{45@key{RET}} ok
1.26 crook 3402: @end example
1.21 crook 3403:
1.29 crook 3404: Rather than give you a prompt to invite you to input something, the text
3405: interpreter prints a status message @i{after} it has processed a line
3406: of input. The status message in this case (``@code{ ok}'' followed by
3407: carriage-return) indicates that the text interpreter was able to process
3408: all of your input successfully. Now type something illegal:
3409:
3410: @example
1.30 anton 3411: @kbd{qwer341@key{RET}}
1.134 anton 3412: *the terminal*:2: Undefined word
3413: >>>qwer341<<<
3414: Backtrace:
3415: $2A95B42A20 throw
3416: $2A95B57FB8 no.extensions
1.29 crook 3417: @end example
1.23 crook 3418:
1.134 anton 3419: The exact text, other than the ``Undefined word'' may differ slightly
3420: on your system, but the effect is the same; when the text interpreter
1.29 crook 3421: detects an error, it discards any remaining text on a line, resets
1.134 anton 3422: certain internal state and prints an error message. For a detailed
3423: description of error messages see @ref{Error messages}.
1.23 crook 3424:
1.29 crook 3425: The text interpreter waits for you to press carriage-return, and then
3426: processes your input line. Starting at the beginning of the line, it
3427: breaks the line into groups of characters separated by spaces. For each
3428: group of characters in turn, it makes two attempts to do something:
1.23 crook 3429:
1.29 crook 3430: @itemize @bullet
3431: @item
1.44 crook 3432: @cindex name dictionary
1.29 crook 3433: It tries to treat it as a command. It does this by searching a @dfn{name
3434: dictionary}. If the group of characters matches an entry in the name
3435: dictionary, the name dictionary provides the text interpreter with
3436: information that allows the text interpreter perform some actions. In
3437: Forth jargon, we say that the group
3438: @cindex word
3439: @cindex definition
3440: @cindex execution token
3441: @cindex xt
3442: of characters names a @dfn{word}, that the dictionary search returns an
3443: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3444: word, and that the text interpreter executes the xt. Often, the terms
3445: @dfn{word} and @dfn{definition} are used interchangeably.
3446: @item
3447: If the text interpreter fails to find a match in the name dictionary, it
3448: tries to treat the group of characters as a number in the current number
3449: base (when you start up Forth, the current number base is base 10). If
3450: the group of characters legitimately represents a number, the text
3451: interpreter pushes the number onto a stack (we'll learn more about that
3452: in the next section).
3453: @end itemize
1.23 crook 3454:
1.29 crook 3455: If the text interpreter is unable to do either of these things with any
3456: group of characters, it discards the group of characters and the rest of
3457: the line, then prints an error message. If the text interpreter reaches
3458: the end of the line without error, it prints the status message ``@code{ ok}''
3459: followed by carriage-return.
1.21 crook 3460:
1.29 crook 3461: This is the simplest command we can give to the text interpreter:
1.23 crook 3462:
3463: @example
1.30 anton 3464: @key{RET} ok
1.23 crook 3465: @end example
1.21 crook 3466:
1.29 crook 3467: The text interpreter did everything we asked it to do (nothing) without
3468: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3469: command:
1.21 crook 3470:
1.23 crook 3471: @example
1.30 anton 3472: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3473: *the terminal*:3: Undefined word
3474: 12 dup >>>fred<<< dup
3475: Backtrace:
3476: $2A95B42A20 throw
3477: $2A95B57FB8 no.extensions
1.23 crook 3478: @end example
1.21 crook 3479:
1.29 crook 3480: When you press the carriage-return key, the text interpreter starts to
3481: work its way along the line:
1.21 crook 3482:
1.29 crook 3483: @itemize @bullet
3484: @item
3485: When it gets to the space after the @code{2}, it takes the group of
3486: characters @code{12} and looks them up in the name
3487: dictionary@footnote{We can't tell if it found them or not, but assume
3488: for now that it did not}. There is no match for this group of characters
3489: in the name dictionary, so it tries to treat them as a number. It is
3490: able to do this successfully, so it puts the number, 12, ``on the stack''
3491: (whatever that means).
3492: @item
3493: The text interpreter resumes scanning the line and gets the next group
3494: of characters, @code{dup}. It looks it up in the name dictionary and
3495: (you'll have to take my word for this) finds it, and executes the word
3496: @code{dup} (whatever that means).
3497: @item
3498: Once again, the text interpreter resumes scanning the line and gets the
3499: group of characters @code{fred}. It looks them up in the name
3500: dictionary, but can't find them. It tries to treat them as a number, but
3501: they don't represent any legal number.
3502: @end itemize
1.21 crook 3503:
1.29 crook 3504: At this point, the text interpreter gives up and prints an error
3505: message. The error message shows exactly how far the text interpreter
3506: got in processing the line. In particular, it shows that the text
3507: interpreter made no attempt to do anything with the final character
3508: group, @code{dup}, even though we have good reason to believe that the
3509: text interpreter would have no problem looking that word up and
3510: executing it a second time.
1.21 crook 3511:
3512:
1.29 crook 3513: @comment ----------------------------------------------
3514: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3515: @section Stacks, postfix notation and parameter passing
3516: @cindex text interpreter
3517: @cindex outer interpreter
1.21 crook 3518:
1.29 crook 3519: In procedural programming languages (like C and Pascal), the
3520: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3521: functions or procedures are called with @dfn{explicit parameters}. For
3522: example, in C we might write:
1.21 crook 3523:
1.23 crook 3524: @example
1.29 crook 3525: total = total + new_volume(length,height,depth);
1.23 crook 3526: @end example
1.21 crook 3527:
1.23 crook 3528: @noindent
1.29 crook 3529: where new_volume is a function-call to another piece of code, and total,
3530: length, height and depth are all variables. length, height and depth are
3531: parameters to the function-call.
1.21 crook 3532:
1.29 crook 3533: In Forth, the equivalent of the function or procedure is the
3534: @dfn{definition} and parameters are implicitly passed between
3535: definitions using a shared stack that is visible to the
3536: programmer. Although Forth does support variables, the existence of the
3537: stack means that they are used far less often than in most other
3538: programming languages. When the text interpreter encounters a number, it
3539: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3540: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3541: used for any operation is implied unambiguously by the operation being
3542: performed. The stack used for all integer operations is called the @dfn{data
3543: stack} and, since this is the stack used most commonly, references to
3544: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3545:
1.29 crook 3546: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3547:
1.23 crook 3548: @example
1.30 anton 3549: @kbd{1 2 3@key{RET}} ok
1.23 crook 3550: @end example
1.21 crook 3551:
1.29 crook 3552: Then this instructs the text interpreter to placed three numbers on the
3553: (data) stack. An analogy for the behaviour of the stack is to take a
3554: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3555: the table. The 3 was the last card onto the pile (``last-in'') and if
3556: you take a card off the pile then, unless you're prepared to fiddle a
3557: bit, the card that you take off will be the 3 (``first-out''). The
3558: number that will be first-out of the stack is called the @dfn{top of
3559: stack}, which
3560: @cindex TOS definition
3561: is often abbreviated to @dfn{TOS}.
1.21 crook 3562:
1.29 crook 3563: To understand how parameters are passed in Forth, consider the
3564: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3565: be surprised to learn that this definition performs addition. More
3566: precisely, it adds two number together and produces a result. Where does
3567: it get the two numbers from? It takes the top two numbers off the
3568: stack. Where does it place the result? On the stack. You can act-out the
3569: behaviour of @code{+} with your playing cards like this:
1.21 crook 3570:
3571: @itemize @bullet
3572: @item
1.29 crook 3573: Pick up two cards from the stack on the table
1.21 crook 3574: @item
1.29 crook 3575: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3576: numbers''
1.21 crook 3577: @item
1.29 crook 3578: Decide that the answer is 5
1.21 crook 3579: @item
1.29 crook 3580: Shuffle the two cards back into the pack and find a 5
1.21 crook 3581: @item
1.29 crook 3582: Put a 5 on the remaining ace that's on the table.
1.21 crook 3583: @end itemize
3584:
1.29 crook 3585: If you don't have a pack of cards handy but you do have Forth running,
3586: you can use the definition @code{.s} to show the current state of the stack,
3587: without affecting the stack. Type:
1.21 crook 3588:
3589: @example
1.124 anton 3590: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3591: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3592: @end example
3593:
1.124 anton 3594: The text interpreter looks up the word @code{clearstacks} and executes
3595: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3596: left on it by earlier examples. The text interpreter pushes each of the
3597: three numbers in turn onto the stack. Finally, the text interpreter
3598: looks up the word @code{.s} and executes it. The effect of executing
3599: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3600: followed by a list of all the items on the stack; the item on the far
3601: right-hand side is the TOS.
1.21 crook 3602:
1.29 crook 3603: You can now type:
1.21 crook 3604:
1.29 crook 3605: @example
1.30 anton 3606: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3607: @end example
1.21 crook 3608:
1.29 crook 3609: @noindent
3610: which is correct; there are now 2 items on the stack and the result of
3611: the addition is 5.
1.23 crook 3612:
1.29 crook 3613: If you're playing with cards, try doing a second addition: pick up the
3614: two cards, work out that their sum is 6, shuffle them into the pack,
3615: look for a 6 and place that on the table. You now have just one item on
3616: the stack. What happens if you try to do a third addition? Pick up the
3617: first card, pick up the second card -- ah! There is no second card. This
3618: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3619: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3620: Underflow or an Invalid Memory Address error).
1.23 crook 3621:
1.29 crook 3622: The opposite situation to a stack underflow is a @dfn{stack overflow},
3623: which simply accepts that there is a finite amount of storage space
3624: reserved for the stack. To stretch the playing card analogy, if you had
3625: enough packs of cards and you piled the cards up on the table, you would
3626: eventually be unable to add another card; you'd hit the ceiling. Gforth
3627: allows you to set the maximum size of the stacks. In general, the only
3628: time that you will get a stack overflow is because a definition has a
3629: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3630:
1.29 crook 3631: There's one final use for the playing card analogy. If you model your
3632: stack using a pack of playing cards, the maximum number of items on
3633: your stack will be 52 (I assume you didn't use the Joker). The maximum
3634: @i{value} of any item on the stack is 13 (the King). In fact, the only
3635: possible numbers are positive integer numbers 1 through 13; you can't
3636: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3637: think about some of the cards, you can accommodate different
3638: numbers. For example, you could think of the Jack as representing 0,
3639: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3640: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3641: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3642:
1.29 crook 3643: In that analogy, the limit was the amount of information that a single
3644: stack entry could hold, and Forth has a similar limit. In Forth, the
3645: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3646: implementation dependent and affects the maximum value that a stack
3647: entry can hold. A Standard Forth provides a cell size of at least
3648: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3649:
1.29 crook 3650: Forth does not do any type checking for you, so you are free to
3651: manipulate and combine stack items in any way you wish. A convenient way
3652: of treating stack items is as 2's complement signed integers, and that
3653: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3654:
1.29 crook 3655: @example
1.30 anton 3656: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3657: @end example
1.21 crook 3658:
1.29 crook 3659: If you use numbers and definitions like @code{+} in order to turn Forth
3660: into a great big pocket calculator, you will realise that it's rather
3661: different from a normal calculator. Rather than typing 2 + 3 = you had
3662: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3663: result). The terminology used to describe this difference is to say that
3664: your calculator uses @dfn{Infix Notation} (parameters and operators are
3665: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3666: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3667:
1.29 crook 3668: Whilst postfix notation might look confusing to begin with, it has
3669: several important advantages:
1.21 crook 3670:
1.23 crook 3671: @itemize @bullet
3672: @item
1.29 crook 3673: it is unambiguous
1.23 crook 3674: @item
1.29 crook 3675: it is more concise
1.23 crook 3676: @item
1.29 crook 3677: it fits naturally with a stack-based system
1.23 crook 3678: @end itemize
1.21 crook 3679:
1.29 crook 3680: To examine these claims in more detail, consider these sums:
1.21 crook 3681:
1.29 crook 3682: @example
3683: 6 + 5 * 4 =
3684: 4 * 5 + 6 =
3685: @end example
1.21 crook 3686:
1.29 crook 3687: If you're just learning maths or your maths is very rusty, you will
3688: probably come up with the answer 44 for the first and 26 for the
3689: second. If you are a bit of a whizz at maths you will remember the
3690: @i{convention} that multiplication takes precendence over addition, and
3691: you'd come up with the answer 26 both times. To explain the answer 26
3692: to someone who got the answer 44, you'd probably rewrite the first sum
3693: like this:
1.21 crook 3694:
1.29 crook 3695: @example
3696: 6 + (5 * 4) =
3697: @end example
1.21 crook 3698:
1.29 crook 3699: If what you really wanted was to perform the addition before the
3700: multiplication, you would have to use parentheses to force it.
1.21 crook 3701:
1.29 crook 3702: If you did the first two sums on a pocket calculator you would probably
3703: get the right answers, unless you were very cautious and entered them using
3704: these keystroke sequences:
1.21 crook 3705:
1.29 crook 3706: 6 + 5 = * 4 =
3707: 4 * 5 = + 6 =
1.21 crook 3708:
1.29 crook 3709: Postfix notation is unambiguous because the order that the operators
3710: are applied is always explicit; that also means that parentheses are
3711: never required. The operators are @i{active} (the act of quoting the
3712: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3713:
1.29 crook 3714: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3715: equivalent ways:
1.26 crook 3716:
3717: @example
1.29 crook 3718: 6 5 4 * + or:
3719: 5 4 * 6 +
1.26 crook 3720: @end example
1.23 crook 3721:
1.29 crook 3722: An important thing that you should notice about this notation is that
3723: the @i{order} of the numbers does not change; if you want to subtract
3724: 2 from 10 you type @code{10 2 -}.
1.1 anton 3725:
1.29 crook 3726: The reason that Forth uses postfix notation is very simple to explain: it
3727: makes the implementation extremely simple, and it follows naturally from
3728: using the stack as a mechanism for passing parameters. Another way of
3729: thinking about this is to realise that all Forth definitions are
3730: @i{active}; they execute as they are encountered by the text
3731: interpreter. The result of this is that the syntax of Forth is trivially
3732: simple.
1.1 anton 3733:
3734:
3735:
1.29 crook 3736: @comment ----------------------------------------------
3737: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3738: @section Your first Forth definition
3739: @cindex first definition
1.1 anton 3740:
1.29 crook 3741: Until now, the examples we've seen have been trivial; we've just been
3742: using Forth as a bigger-than-pocket calculator. Also, each calculation
3743: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3744: again@footnote{That's not quite true. If you press the up-arrow key on
3745: your keyboard you should be able to scroll back to any earlier command,
3746: edit it and re-enter it.} In this section we'll see how to add new
3747: words to Forth's vocabulary.
1.1 anton 3748:
1.29 crook 3749: The easiest way to create a new word is to use a @dfn{colon
3750: definition}. We'll define a few and try them out before worrying too
3751: much about how they work. Try typing in these examples; be careful to
3752: copy the spaces accurately:
1.1 anton 3753:
1.29 crook 3754: @example
3755: : add-two 2 + . ;
3756: : greet ." Hello and welcome" ;
3757: : demo 5 add-two ;
3758: @end example
1.1 anton 3759:
1.29 crook 3760: @noindent
3761: Now try them out:
1.1 anton 3762:
1.29 crook 3763: @example
1.30 anton 3764: @kbd{greet@key{RET}} Hello and welcome ok
3765: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3766: @kbd{4 add-two@key{RET}} 6 ok
3767: @kbd{demo@key{RET}} 7 ok
3768: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3769: @end example
1.1 anton 3770:
1.29 crook 3771: The first new thing that we've introduced here is the pair of words
3772: @code{:} and @code{;}. These are used to start and terminate a new
3773: definition, respectively. The first word after the @code{:} is the name
3774: for the new definition.
1.1 anton 3775:
1.29 crook 3776: As you can see from the examples, a definition is built up of words that
3777: have already been defined; Forth makes no distinction between
3778: definitions that existed when you started the system up, and those that
3779: you define yourself.
1.1 anton 3780:
1.29 crook 3781: The examples also introduce the words @code{.} (dot), @code{."}
3782: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3783: the stack and displays it. It's like @code{.s} except that it only
3784: displays the top item of the stack and it is destructive; after it has
3785: executed, the number is no longer on the stack. There is always one
3786: space printed after the number, and no spaces before it. Dot-quote
3787: defines a string (a sequence of characters) that will be printed when
3788: the word is executed. The string can contain any printable characters
3789: except @code{"}. A @code{"} has a special function; it is not a Forth
3790: word but it acts as a delimiter (the way that delimiters work is
3791: described in the next section). Finally, @code{dup} duplicates the value
3792: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3793:
1.29 crook 3794: We already know that the text interpreter searches through the
3795: dictionary to locate names. If you've followed the examples earlier, you
3796: will already have a definition called @code{add-two}. Lets try modifying
3797: it by typing in a new definition:
1.1 anton 3798:
1.29 crook 3799: @example
1.30 anton 3800: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3801: @end example
1.5 anton 3802:
1.29 crook 3803: Forth recognised that we were defining a word that already exists, and
3804: printed a message to warn us of that fact. Let's try out the new
3805: definition:
1.5 anton 3806:
1.29 crook 3807: @example
1.30 anton 3808: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3809: @end example
1.1 anton 3810:
1.29 crook 3811: @noindent
3812: All that we've actually done here, though, is to create a new
3813: definition, with a particular name. The fact that there was already a
3814: definition with the same name did not make any difference to the way
3815: that the new definition was created (except that Forth printed a warning
3816: message). The old definition of add-two still exists (try @code{demo}
3817: again to see that this is true). Any new definition will use the new
3818: definition of @code{add-two}, but old definitions continue to use the
3819: version that already existed at the time that they were @code{compiled}.
1.1 anton 3820:
1.29 crook 3821: Before you go on to the next section, try defining and redefining some
3822: words of your own.
1.1 anton 3823:
1.29 crook 3824: @comment ----------------------------------------------
3825: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3826: @section How does that work?
3827: @cindex parsing words
1.1 anton 3828:
1.30 anton 3829: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3830:
3831: @c Is it a good idea to talk about the interpretation semantics of a
3832: @c number? We don't have an xt to go along with it. - anton
3833:
3834: @c Now that I have eliminated execution semantics, I wonder if it would not
3835: @c be better to keep them (or add run-time semantics), to make it easier to
3836: @c explain what compilation semantics usually does. - anton
3837:
1.44 crook 3838: @c nac-> I removed the term ``default compilation sematics'' from the
3839: @c introductory chapter. Removing ``execution semantics'' was making
3840: @c everything simpler to explain, then I think the use of this term made
3841: @c everything more complex again. I replaced it with ``default
3842: @c semantics'' (which is used elsewhere in the manual) by which I mean
3843: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3844: @c flag set''.
3845:
3846: @c anton: I have eliminated default semantics (except in one place where it
3847: @c means "default interpretation and compilation semantics"), because it
3848: @c makes no sense in the presence of combined words. I reverted to
3849: @c "execution semantics" where necessary.
3850:
3851: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3852: @c section (and, unusually for me, I think I even made it shorter!). See
3853: @c what you think -- I know I have not addressed your primary concern
3854: @c that it is too heavy-going for an introduction. From what I understood
3855: @c of your course notes it looks as though they might be a good framework.
3856: @c Things that I've tried to capture here are some things that came as a
3857: @c great revelation here when I first understood them. Also, I like the
3858: @c fact that a very simple code example shows up almost all of the issues
3859: @c that you need to understand to see how Forth works. That's unique and
3860: @c worthwhile to emphasise.
3861:
1.83 anton 3862: @c anton: I think it's a good idea to present the details, especially those
3863: @c that you found to be a revelation, and probably the tutorial tries to be
3864: @c too superficial and does not get some of the things across that make
3865: @c Forth special. I do believe that most of the time these things should
3866: @c be discussed at the end of a section or in separate sections instead of
3867: @c in the middle of a section (e.g., the stuff you added in "User-defined
3868: @c defining words" leads in a completely different direction from the rest
3869: @c of the section).
3870:
1.29 crook 3871: Now we're going to take another look at the definition of @code{add-two}
3872: from the previous section. From our knowledge of the way that the text
3873: interpreter works, we would have expected this result when we tried to
3874: define @code{add-two}:
1.21 crook 3875:
1.29 crook 3876: @example
1.44 crook 3877: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3878: *the terminal*:4: Undefined word
3879: : >>>add-two<<< 2 + . ;
1.29 crook 3880: @end example
1.28 crook 3881:
1.29 crook 3882: The reason that this didn't happen is bound up in the way that @code{:}
3883: works. The word @code{:} does two special things. The first special
3884: thing that it does prevents the text interpreter from ever seeing the
3885: characters @code{add-two}. The text interpreter uses a variable called
3886: @cindex modifying >IN
1.44 crook 3887: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3888: input line. When it encounters the word @code{:} it behaves in exactly
3889: the same way as it does for any other word; it looks it up in the name
3890: dictionary, finds its xt and executes it. When @code{:} executes, it
3891: looks at the input buffer, finds the word @code{add-two} and advances the
3892: value of @code{>IN} to point past it. It then does some other stuff
3893: associated with creating the new definition (including creating an entry
3894: for @code{add-two} in the name dictionary). When the execution of @code{:}
3895: completes, control returns to the text interpreter, which is oblivious
3896: to the fact that it has been tricked into ignoring part of the input
3897: line.
1.21 crook 3898:
1.29 crook 3899: @cindex parsing words
3900: Words like @code{:} -- words that advance the value of @code{>IN} and so
3901: prevent the text interpreter from acting on the whole of the input line
3902: -- are called @dfn{parsing words}.
1.21 crook 3903:
1.29 crook 3904: @cindex @code{state} - effect on the text interpreter
3905: @cindex text interpreter - effect of state
3906: The second special thing that @code{:} does is change the value of a
3907: variable called @code{state}, which affects the way that the text
3908: interpreter behaves. When Gforth starts up, @code{state} has the value
3909: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3910: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3911: the text interpreter is said to be @dfn{compiling}.
3912:
3913: In this example, the text interpreter is compiling when it processes the
3914: string ``@code{2 + . ;}''. It still breaks the string down into
3915: character sequences in the same way. However, instead of pushing the
3916: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3917: into the definition of @code{add-two} that will make the number @code{2} get
3918: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3919: the behaviours of @code{+} and @code{.} are also compiled into the
3920: definition.
3921:
3922: One category of words don't get compiled. These so-called @dfn{immediate
3923: words} get executed (performed @i{now}) regardless of whether the text
3924: interpreter is interpreting or compiling. The word @code{;} is an
3925: immediate word. Rather than being compiled into the definition, it
3926: executes. Its effect is to terminate the current definition, which
3927: includes changing the value of @code{state} back to 0.
3928:
3929: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3930: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3931: definition.
1.28 crook 3932:
1.30 anton 3933: In Forth, every word or number can be described in terms of two
1.29 crook 3934: properties:
1.28 crook 3935:
3936: @itemize @bullet
3937: @item
1.29 crook 3938: @cindex interpretation semantics
1.44 crook 3939: Its @dfn{interpretation semantics} describe how it will behave when the
3940: text interpreter encounters it in @dfn{interpret} state. The
3941: interpretation semantics of a word are represented by an @dfn{execution
3942: token}.
1.28 crook 3943: @item
1.29 crook 3944: @cindex compilation semantics
1.44 crook 3945: Its @dfn{compilation semantics} describe how it will behave when the
3946: text interpreter encounters it in @dfn{compile} state. The compilation
3947: semantics of a word are represented in an implementation-dependent way;
3948: Gforth uses a @dfn{compilation token}.
1.29 crook 3949: @end itemize
3950:
3951: @noindent
3952: Numbers are always treated in a fixed way:
3953:
3954: @itemize @bullet
1.28 crook 3955: @item
1.44 crook 3956: When the number is @dfn{interpreted}, its behaviour is to push the
3957: number onto the stack.
1.28 crook 3958: @item
1.30 anton 3959: When the number is @dfn{compiled}, a piece of code is appended to the
3960: current definition that pushes the number when it runs. (In other words,
3961: the compilation semantics of a number are to postpone its interpretation
3962: semantics until the run-time of the definition that it is being compiled
3963: into.)
1.29 crook 3964: @end itemize
3965:
1.44 crook 3966: Words don't behave in such a regular way, but most have @i{default
3967: semantics} which means that they behave like this:
1.29 crook 3968:
3969: @itemize @bullet
1.28 crook 3970: @item
1.30 anton 3971: The @dfn{interpretation semantics} of the word are to do something useful.
3972: @item
1.29 crook 3973: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3974: @dfn{interpretation semantics} to the current definition (so that its
3975: run-time behaviour is to do something useful).
1.28 crook 3976: @end itemize
3977:
1.30 anton 3978: @cindex immediate words
1.44 crook 3979: The actual behaviour of any particular word can be controlled by using
3980: the words @code{immediate} and @code{compile-only} when the word is
3981: defined. These words set flags in the name dictionary entry of the most
3982: recently defined word, and these flags are retrieved by the text
3983: interpreter when it finds the word in the name dictionary.
3984:
3985: A word that is marked as @dfn{immediate} has compilation semantics that
3986: are identical to its interpretation semantics. In other words, it
3987: behaves like this:
1.29 crook 3988:
3989: @itemize @bullet
3990: @item
1.30 anton 3991: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3992: @item
1.30 anton 3993: The @dfn{compilation semantics} of the word are to do something useful
3994: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3995: @end itemize
1.28 crook 3996:
1.44 crook 3997: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3998: performing the interpretation semantics of the word directly; an attempt
3999: to do so will generate an error. It is never necessary to use
4000: @code{compile-only} (and it is not even part of ANS Forth, though it is
4001: provided by many implementations) but it is good etiquette to apply it
4002: to a word that will not behave correctly (and might have unexpected
4003: side-effects) in interpret state. For example, it is only legal to use
4004: the conditional word @code{IF} within a definition. If you forget this
4005: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4006: @code{compile-only} allows the text interpreter to generate a helpful
4007: error message rather than subjecting you to the consequences of your
4008: folly.
4009:
1.29 crook 4010: This example shows the difference between an immediate and a
4011: non-immediate word:
1.28 crook 4012:
1.29 crook 4013: @example
4014: : show-state state @@ . ;
4015: : show-state-now show-state ; immediate
4016: : word1 show-state ;
4017: : word2 show-state-now ;
1.28 crook 4018: @end example
1.23 crook 4019:
1.29 crook 4020: The word @code{immediate} after the definition of @code{show-state-now}
4021: makes that word an immediate word. These definitions introduce a new
4022: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4023: variable, and leaves it on the stack. Therefore, the behaviour of
4024: @code{show-state} is to print a number that represents the current value
4025: of @code{state}.
1.28 crook 4026:
1.29 crook 4027: When you execute @code{word1}, it prints the number 0, indicating that
4028: the system is interpreting. When the text interpreter compiled the
4029: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4030: compilation semantics are to append its interpretation semantics to the
1.29 crook 4031: current definition. When you execute @code{word1}, it performs the
1.30 anton 4032: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4033: (and therefore @code{show-state}) are executed, the system is
4034: interpreting.
1.28 crook 4035:
1.30 anton 4036: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4037: you should have seen the number -1 printed, followed by ``@code{
4038: ok}''. When the text interpreter compiled the definition of
4039: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4040: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4041: semantics. It is executed straight away (even before the text
4042: interpreter has moved on to process another group of characters; the
4043: @code{;} in this example). The effect of executing it are to display the
4044: value of @code{state} @i{at the time that the definition of}
4045: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4046: system is compiling at this time. If you execute @code{word2} it does
4047: nothing at all.
1.28 crook 4048:
1.29 crook 4049: @cindex @code{."}, how it works
4050: Before leaving the subject of immediate words, consider the behaviour of
4051: @code{."} in the definition of @code{greet}, in the previous
4052: section. This word is both a parsing word and an immediate word. Notice
4053: that there is a space between @code{."} and the start of the text
4054: @code{Hello and welcome}, but that there is no space between the last
4055: letter of @code{welcome} and the @code{"} character. The reason for this
4056: is that @code{."} is a Forth word; it must have a space after it so that
4057: the text interpreter can identify it. The @code{"} is not a Forth word;
4058: it is a @dfn{delimiter}. The examples earlier show that, when the string
4059: is displayed, there is neither a space before the @code{H} nor after the
4060: @code{e}. Since @code{."} is an immediate word, it executes at the time
4061: that @code{greet} is defined. When it executes, its behaviour is to
4062: search forward in the input line looking for the delimiter. When it
4063: finds the delimiter, it updates @code{>IN} to point past the
4064: delimiter. It also compiles some magic code into the definition of
4065: @code{greet}; the xt of a run-time routine that prints a text string. It
4066: compiles the string @code{Hello and welcome} into memory so that it is
4067: available to be printed later. When the text interpreter gains control,
4068: the next word it finds in the input stream is @code{;} and so it
4069: terminates the definition of @code{greet}.
1.28 crook 4070:
4071:
4072: @comment ----------------------------------------------
1.29 crook 4073: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4074: @section Forth is written in Forth
4075: @cindex structure of Forth programs
4076:
4077: When you start up a Forth compiler, a large number of definitions
4078: already exist. In Forth, you develop a new application using bottom-up
4079: programming techniques to create new definitions that are defined in
4080: terms of existing definitions. As you create each definition you can
4081: test and debug it interactively.
4082:
4083: If you have tried out the examples in this section, you will probably
4084: have typed them in by hand; when you leave Gforth, your definitions will
4085: be lost. You can avoid this by using a text editor to enter Forth source
4086: code into a file, and then loading code from the file using
1.49 anton 4087: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4088: processed by the text interpreter, just as though you had typed it in by
4089: hand@footnote{Actually, there are some subtle differences -- see
4090: @ref{The Text Interpreter}.}.
4091:
4092: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4093: files for program entry (@pxref{Blocks}).
1.28 crook 4094:
1.29 crook 4095: In common with many, if not most, Forth compilers, most of Gforth is
4096: actually written in Forth. All of the @file{.fs} files in the
4097: installation directory@footnote{For example,
1.30 anton 4098: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4099: study to see examples of Forth programming.
1.28 crook 4100:
1.29 crook 4101: Gforth maintains a history file that records every line that you type to
4102: the text interpreter. This file is preserved between sessions, and is
4103: used to provide a command-line recall facility. If you enter long
4104: definitions by hand, you can use a text editor to paste them out of the
4105: history file into a Forth source file for reuse at a later time
1.49 anton 4106: (for more information @pxref{Command-line editing}).
1.28 crook 4107:
4108:
4109: @comment ----------------------------------------------
1.29 crook 4110: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4111: @section Review - elements of a Forth system
4112: @cindex elements of a Forth system
1.28 crook 4113:
1.29 crook 4114: To summarise this chapter:
1.28 crook 4115:
4116: @itemize @bullet
4117: @item
1.29 crook 4118: Forth programs use @dfn{factoring} to break a problem down into small
4119: fragments called @dfn{words} or @dfn{definitions}.
4120: @item
4121: Forth program development is an interactive process.
4122: @item
4123: The main command loop that accepts input, and controls both
4124: interpretation and compilation, is called the @dfn{text interpreter}
4125: (also known as the @dfn{outer interpreter}).
4126: @item
4127: Forth has a very simple syntax, consisting of words and numbers
4128: separated by spaces or carriage-return characters. Any additional syntax
4129: is imposed by @dfn{parsing words}.
4130: @item
4131: Forth uses a stack to pass parameters between words. As a result, it
4132: uses postfix notation.
4133: @item
4134: To use a word that has previously been defined, the text interpreter
4135: searches for the word in the @dfn{name dictionary}.
4136: @item
1.30 anton 4137: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4138: @item
1.29 crook 4139: The text interpreter uses the value of @code{state} to select between
4140: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4141: semantics} of a word that it encounters.
1.28 crook 4142: @item
1.30 anton 4143: The relationship between the @dfn{interpretation semantics} and
4144: @dfn{compilation semantics} for a word
1.29 crook 4145: depend upon the way in which the word was defined (for example, whether
4146: it is an @dfn{immediate} word).
1.28 crook 4147: @item
1.29 crook 4148: Forth definitions can be implemented in Forth (called @dfn{high-level
4149: definitions}) or in some other way (usually a lower-level language and
4150: as a result often called @dfn{low-level definitions}, @dfn{code
4151: definitions} or @dfn{primitives}).
1.28 crook 4152: @item
1.29 crook 4153: Many Forth systems are implemented mainly in Forth.
1.28 crook 4154: @end itemize
4155:
4156:
1.29 crook 4157: @comment ----------------------------------------------
1.48 anton 4158: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4159: @section Where To Go Next
4160: @cindex where to go next
1.28 crook 4161:
1.29 crook 4162: Amazing as it may seem, if you have read (and understood) this far, you
4163: know almost all the fundamentals about the inner workings of a Forth
4164: system. You certainly know enough to be able to read and understand the
4165: rest of this manual and the ANS Forth document, to learn more about the
4166: facilities that Forth in general and Gforth in particular provide. Even
4167: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4168: However, that's not a good idea just yet... better to try writing some
1.29 crook 4169: programs in Gforth.
1.28 crook 4170:
1.29 crook 4171: Forth has such a rich vocabulary that it can be hard to know where to
4172: start in learning it. This section suggests a few sets of words that are
4173: enough to write small but useful programs. Use the word index in this
4174: document to learn more about each word, then try it out and try to write
4175: small definitions using it. Start by experimenting with these words:
1.28 crook 4176:
4177: @itemize @bullet
4178: @item
1.29 crook 4179: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4180: @item
4181: Comparison: @code{MIN MAX =}
4182: @item
4183: Logic: @code{AND OR XOR NOT}
4184: @item
4185: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4186: @item
1.29 crook 4187: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4188: @item
1.29 crook 4189: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4190: @item
1.29 crook 4191: Defining words: @code{: ; CREATE}
1.28 crook 4192: @item
1.29 crook 4193: Memory allocation words: @code{ALLOT ,}
1.28 crook 4194: @item
1.29 crook 4195: Tools: @code{SEE WORDS .S MARKER}
4196: @end itemize
4197:
4198: When you have mastered those, go on to:
4199:
4200: @itemize @bullet
1.28 crook 4201: @item
1.29 crook 4202: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4203: @item
1.29 crook 4204: Memory access: @code{@@ !}
1.28 crook 4205: @end itemize
1.23 crook 4206:
1.29 crook 4207: When you have mastered these, there's nothing for it but to read through
4208: the whole of this manual and find out what you've missed.
4209:
4210: @comment ----------------------------------------------
1.48 anton 4211: @node Exercises, , Where to go next, Introduction
1.29 crook 4212: @section Exercises
4213: @cindex exercises
4214:
4215: TODO: provide a set of programming excercises linked into the stuff done
4216: already and into other sections of the manual. Provide solutions to all
4217: the exercises in a .fs file in the distribution.
4218:
4219: @c Get some inspiration from Starting Forth and Kelly&Spies.
4220:
4221: @c excercises:
4222: @c 1. take inches and convert to feet and inches.
4223: @c 2. take temperature and convert from fahrenheight to celcius;
4224: @c may need to care about symmetric vs floored??
4225: @c 3. take input line and do character substitution
4226: @c to encipher or decipher
4227: @c 4. as above but work on a file for in and out
4228: @c 5. take input line and convert to pig-latin
4229: @c
4230: @c thing of sets of things to exercise then come up with
4231: @c problems that need those things.
4232:
4233:
1.26 crook 4234: @c ******************************************************************
1.29 crook 4235: @node Words, Error messages, Introduction, Top
1.1 anton 4236: @chapter Forth Words
1.26 crook 4237: @cindex words
1.1 anton 4238:
4239: @menu
4240: * Notation::
1.65 anton 4241: * Case insensitivity::
4242: * Comments::
4243: * Boolean Flags::
1.1 anton 4244: * Arithmetic::
4245: * Stack Manipulation::
1.5 anton 4246: * Memory::
1.1 anton 4247: * Control Structures::
4248: * Defining Words::
1.65 anton 4249: * Interpretation and Compilation Semantics::
1.47 crook 4250: * Tokens for Words::
1.81 anton 4251: * Compiling words::
1.65 anton 4252: * The Text Interpreter::
1.111 anton 4253: * The Input Stream::
1.65 anton 4254: * Word Lists::
4255: * Environmental Queries::
1.12 anton 4256: * Files::
4257: * Blocks::
4258: * Other I/O::
1.121 anton 4259: * OS command line arguments::
1.78 anton 4260: * Locals::
4261: * Structures::
4262: * Object-oriented Forth::
1.12 anton 4263: * Programming Tools::
1.150 anton 4264: * C Interface::
1.12 anton 4265: * Assembler and Code Words::
4266: * Threading Words::
1.65 anton 4267: * Passing Commands to the OS::
4268: * Keeping track of Time::
4269: * Miscellaneous Words::
1.1 anton 4270: @end menu
4271:
1.65 anton 4272: @node Notation, Case insensitivity, Words, Words
1.1 anton 4273: @section Notation
4274: @cindex notation of glossary entries
4275: @cindex format of glossary entries
4276: @cindex glossary notation format
4277: @cindex word glossary entry format
4278:
4279: The Forth words are described in this section in the glossary notation
1.67 anton 4280: that has become a de-facto standard for Forth texts:
1.1 anton 4281:
4282: @format
1.29 crook 4283: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4284: @end format
1.29 crook 4285: @i{Description}
1.1 anton 4286:
4287: @table @var
4288: @item word
1.28 crook 4289: The name of the word.
1.1 anton 4290:
4291: @item Stack effect
4292: @cindex stack effect
1.29 crook 4293: The stack effect is written in the notation @code{@i{before} --
4294: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4295: stack entries before and after the execution of the word. The rest of
4296: the stack is not touched by the word. The top of stack is rightmost,
4297: i.e., a stack sequence is written as it is typed in. Note that Gforth
4298: uses a separate floating point stack, but a unified stack
1.29 crook 4299: notation. Also, return stack effects are not shown in @i{stack
4300: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4301: the type and/or the function of the item. See below for a discussion of
4302: the types.
4303:
4304: All words have two stack effects: A compile-time stack effect and a
4305: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4306: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4307: this standard behaviour, or the word does other unusual things at
4308: compile time, both stack effects are shown; otherwise only the run-time
4309: stack effect is shown.
4310:
4311: @cindex pronounciation of words
4312: @item pronunciation
4313: How the word is pronounced.
4314:
4315: @cindex wordset
1.67 anton 4316: @cindex environment wordset
1.1 anton 4317: @item wordset
1.21 crook 4318: The ANS Forth standard is divided into several word sets. A standard
4319: system need not support all of them. Therefore, in theory, the fewer
4320: word sets your program uses the more portable it will be. However, we
4321: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4322: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4323: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4324: describes words that will work in future releases of Gforth;
4325: @code{gforth-internal} words are more volatile. Environmental query
4326: strings are also displayed like words; you can recognize them by the
1.21 crook 4327: @code{environment} in the word set field.
1.1 anton 4328:
4329: @item Description
4330: A description of the behaviour of the word.
4331: @end table
4332:
4333: @cindex types of stack items
4334: @cindex stack item types
4335: The type of a stack item is specified by the character(s) the name
4336: starts with:
4337:
4338: @table @code
4339: @item f
4340: @cindex @code{f}, stack item type
4341: Boolean flags, i.e. @code{false} or @code{true}.
4342: @item c
4343: @cindex @code{c}, stack item type
4344: Char
4345: @item w
4346: @cindex @code{w}, stack item type
4347: Cell, can contain an integer or an address
4348: @item n
4349: @cindex @code{n}, stack item type
4350: signed integer
4351: @item u
4352: @cindex @code{u}, stack item type
4353: unsigned integer
4354: @item d
4355: @cindex @code{d}, stack item type
4356: double sized signed integer
4357: @item ud
4358: @cindex @code{ud}, stack item type
4359: double sized unsigned integer
4360: @item r
4361: @cindex @code{r}, stack item type
4362: Float (on the FP stack)
1.21 crook 4363: @item a-
1.1 anton 4364: @cindex @code{a_}, stack item type
4365: Cell-aligned address
1.21 crook 4366: @item c-
1.1 anton 4367: @cindex @code{c_}, stack item type
4368: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4369: @item f-
1.1 anton 4370: @cindex @code{f_}, stack item type
4371: Float-aligned address
1.21 crook 4372: @item df-
1.1 anton 4373: @cindex @code{df_}, stack item type
4374: Address aligned for IEEE double precision float
1.21 crook 4375: @item sf-
1.1 anton 4376: @cindex @code{sf_}, stack item type
4377: Address aligned for IEEE single precision float
4378: @item xt
4379: @cindex @code{xt}, stack item type
4380: Execution token, same size as Cell
4381: @item wid
4382: @cindex @code{wid}, stack item type
1.21 crook 4383: Word list ID, same size as Cell
1.68 anton 4384: @item ior, wior
4385: @cindex ior type description
4386: @cindex wior type description
4387: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4388: @item f83name
4389: @cindex @code{f83name}, stack item type
4390: Pointer to a name structure
4391: @item "
4392: @cindex @code{"}, stack item type
1.12 anton 4393: string in the input stream (not on the stack). The terminating character
4394: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4395: quotes.
4396: @end table
4397:
1.65 anton 4398: @comment ----------------------------------------------
4399: @node Case insensitivity, Comments, Notation, Words
4400: @section Case insensitivity
4401: @cindex case sensitivity
4402: @cindex upper and lower case
4403:
4404: Gforth is case-insensitive; you can enter definitions and invoke
4405: Standard words using upper, lower or mixed case (however,
4406: @pxref{core-idef, Implementation-defined options, Implementation-defined
4407: options}).
4408:
4409: ANS Forth only @i{requires} implementations to recognise Standard words
4410: when they are typed entirely in upper case. Therefore, a Standard
4411: program must use upper case for all Standard words. You can use whatever
4412: case you like for words that you define, but in a Standard program you
4413: have to use the words in the same case that you defined them.
4414:
4415: Gforth supports case sensitivity through @code{table}s (case-sensitive
4416: wordlists, @pxref{Word Lists}).
4417:
4418: Two people have asked how to convert Gforth to be case-sensitive; while
4419: we think this is a bad idea, you can change all wordlists into tables
4420: like this:
4421:
4422: @example
4423: ' table-find forth-wordlist wordlist-map @ !
4424: @end example
4425:
4426: Note that you now have to type the predefined words in the same case
4427: that we defined them, which are varying. You may want to convert them
4428: to your favourite case before doing this operation (I won't explain how,
4429: because if you are even contemplating doing this, you'd better have
4430: enough knowledge of Forth systems to know this already).
4431:
4432: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4433: @section Comments
1.26 crook 4434: @cindex comments
1.21 crook 4435:
1.29 crook 4436: Forth supports two styles of comment; the traditional @i{in-line} comment,
4437: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4438:
1.44 crook 4439:
1.23 crook 4440: doc-(
1.21 crook 4441: doc-\
1.23 crook 4442: doc-\G
1.21 crook 4443:
1.44 crook 4444:
1.21 crook 4445: @node Boolean Flags, Arithmetic, Comments, Words
4446: @section Boolean Flags
1.26 crook 4447: @cindex Boolean flags
1.21 crook 4448:
4449: A Boolean flag is cell-sized. A cell with all bits clear represents the
4450: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4451: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4452: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4453: @c on and off to Memory?
4454: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4455:
1.21 crook 4456: doc-true
4457: doc-false
1.29 crook 4458: doc-on
4459: doc-off
1.21 crook 4460:
1.44 crook 4461:
1.21 crook 4462: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4463: @section Arithmetic
4464: @cindex arithmetic words
4465:
4466: @cindex division with potentially negative operands
4467: Forth arithmetic is not checked, i.e., you will not hear about integer
4468: overflow on addition or multiplication, you may hear about division by
4469: zero if you are lucky. The operator is written after the operands, but
4470: the operands are still in the original order. I.e., the infix @code{2-1}
4471: corresponds to @code{2 1 -}. Forth offers a variety of division
4472: operators. If you perform division with potentially negative operands,
4473: you do not want to use @code{/} or @code{/mod} with its undefined
4474: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4475: former, @pxref{Mixed precision}).
1.26 crook 4476: @comment TODO discuss the different division forms and the std approach
1.1 anton 4477:
4478: @menu
4479: * Single precision::
1.67 anton 4480: * Double precision:: Double-cell integer arithmetic
1.1 anton 4481: * Bitwise operations::
1.67 anton 4482: * Numeric comparison::
1.29 crook 4483: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4484: * Floating Point::
4485: @end menu
4486:
1.67 anton 4487: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4488: @subsection Single precision
4489: @cindex single precision arithmetic words
4490:
1.67 anton 4491: @c !! cell undefined
4492:
4493: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4494: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4495: treat them. For the rules used by the text interpreter for recognising
4496: single-precision integers see @ref{Number Conversion}.
1.21 crook 4497:
1.67 anton 4498: These words are all defined for signed operands, but some of them also
4499: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4500: @code{*}.
1.44 crook 4501:
1.1 anton 4502: doc-+
1.21 crook 4503: doc-1+
1.128 anton 4504: doc-under+
1.1 anton 4505: doc--
1.21 crook 4506: doc-1-
1.1 anton 4507: doc-*
4508: doc-/
4509: doc-mod
4510: doc-/mod
4511: doc-negate
4512: doc-abs
4513: doc-min
4514: doc-max
1.27 crook 4515: doc-floored
1.1 anton 4516:
1.44 crook 4517:
1.67 anton 4518: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4519: @subsection Double precision
4520: @cindex double precision arithmetic words
4521:
1.49 anton 4522: For the rules used by the text interpreter for
4523: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4524:
4525: A double precision number is represented by a cell pair, with the most
1.67 anton 4526: significant cell at the TOS. It is trivial to convert an unsigned single
4527: to a double: simply push a @code{0} onto the TOS. Since numbers are
4528: represented by Gforth using 2's complement arithmetic, converting a
4529: signed single to a (signed) double requires sign-extension across the
4530: most significant cell. This can be achieved using @code{s>d}. The moral
4531: of the story is that you cannot convert a number without knowing whether
4532: it represents an unsigned or a signed number.
1.21 crook 4533:
1.67 anton 4534: These words are all defined for signed operands, but some of them also
4535: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4536:
1.21 crook 4537: doc-s>d
1.67 anton 4538: doc-d>s
1.21 crook 4539: doc-d+
4540: doc-d-
4541: doc-dnegate
4542: doc-dabs
4543: doc-dmin
4544: doc-dmax
4545:
1.44 crook 4546:
1.67 anton 4547: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4548: @subsection Bitwise operations
4549: @cindex bitwise operation words
4550:
4551:
4552: doc-and
4553: doc-or
4554: doc-xor
4555: doc-invert
4556: doc-lshift
4557: doc-rshift
4558: doc-2*
4559: doc-d2*
4560: doc-2/
4561: doc-d2/
4562:
4563:
4564: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4565: @subsection Numeric comparison
4566: @cindex numeric comparison words
4567:
1.67 anton 4568: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4569: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4570:
1.28 crook 4571: doc-<
4572: doc-<=
4573: doc-<>
4574: doc-=
4575: doc->
4576: doc->=
4577:
1.21 crook 4578: doc-0<
1.23 crook 4579: doc-0<=
1.21 crook 4580: doc-0<>
4581: doc-0=
1.23 crook 4582: doc-0>
4583: doc-0>=
1.28 crook 4584:
4585: doc-u<
4586: doc-u<=
1.44 crook 4587: @c u<> and u= exist but are the same as <> and =
1.31 anton 4588: @c doc-u<>
4589: @c doc-u=
1.28 crook 4590: doc-u>
4591: doc-u>=
4592:
4593: doc-within
4594:
4595: doc-d<
4596: doc-d<=
4597: doc-d<>
4598: doc-d=
4599: doc-d>
4600: doc-d>=
1.23 crook 4601:
1.21 crook 4602: doc-d0<
1.23 crook 4603: doc-d0<=
4604: doc-d0<>
1.21 crook 4605: doc-d0=
1.23 crook 4606: doc-d0>
4607: doc-d0>=
4608:
1.21 crook 4609: doc-du<
1.28 crook 4610: doc-du<=
1.44 crook 4611: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4612: @c doc-du<>
4613: @c doc-du=
1.28 crook 4614: doc-du>
4615: doc-du>=
1.1 anton 4616:
1.44 crook 4617:
1.21 crook 4618: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4619: @subsection Mixed precision
4620: @cindex mixed precision arithmetic words
4621:
1.44 crook 4622:
1.1 anton 4623: doc-m+
4624: doc-*/
4625: doc-*/mod
4626: doc-m*
4627: doc-um*
4628: doc-m*/
4629: doc-um/mod
4630: doc-fm/mod
4631: doc-sm/rem
4632:
1.44 crook 4633:
1.21 crook 4634: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4635: @subsection Floating Point
4636: @cindex floating point arithmetic words
4637:
1.49 anton 4638: For the rules used by the text interpreter for
4639: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4640:
1.67 anton 4641: Gforth has a separate floating point stack, but the documentation uses
4642: the unified notation.@footnote{It's easy to generate the separate
4643: notation from that by just separating the floating-point numbers out:
4644: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4645: r3 )}.}
1.1 anton 4646:
4647: @cindex floating-point arithmetic, pitfalls
4648: Floating point numbers have a number of unpleasant surprises for the
4649: unwary (e.g., floating point addition is not associative) and even a few
4650: for the wary. You should not use them unless you know what you are doing
4651: or you don't care that the results you get are totally bogus. If you
4652: want to learn about the problems of floating point numbers (and how to
1.66 anton 4653: avoid them), you might start with @cite{David Goldberg,
4654: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4655: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4656: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4657:
1.44 crook 4658:
1.21 crook 4659: doc-d>f
4660: doc-f>d
1.1 anton 4661: doc-f+
4662: doc-f-
4663: doc-f*
4664: doc-f/
4665: doc-fnegate
4666: doc-fabs
4667: doc-fmax
4668: doc-fmin
4669: doc-floor
4670: doc-fround
4671: doc-f**
4672: doc-fsqrt
4673: doc-fexp
4674: doc-fexpm1
4675: doc-fln
4676: doc-flnp1
4677: doc-flog
4678: doc-falog
1.32 anton 4679: doc-f2*
4680: doc-f2/
4681: doc-1/f
4682: doc-precision
4683: doc-set-precision
4684:
4685: @cindex angles in trigonometric operations
4686: @cindex trigonometric operations
4687: Angles in floating point operations are given in radians (a full circle
4688: has 2 pi radians).
4689:
1.1 anton 4690: doc-fsin
4691: doc-fcos
4692: doc-fsincos
4693: doc-ftan
4694: doc-fasin
4695: doc-facos
4696: doc-fatan
4697: doc-fatan2
4698: doc-fsinh
4699: doc-fcosh
4700: doc-ftanh
4701: doc-fasinh
4702: doc-facosh
4703: doc-fatanh
1.21 crook 4704: doc-pi
1.28 crook 4705:
1.32 anton 4706: @cindex equality of floats
4707: @cindex floating-point comparisons
1.31 anton 4708: One particular problem with floating-point arithmetic is that comparison
4709: for equality often fails when you would expect it to succeed. For this
4710: reason approximate equality is often preferred (but you still have to
1.67 anton 4711: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4712: differently from what you might expect. The comparison words are:
1.31 anton 4713:
4714: doc-f~rel
4715: doc-f~abs
1.68 anton 4716: doc-f~
1.31 anton 4717: doc-f=
4718: doc-f<>
4719:
4720: doc-f<
4721: doc-f<=
4722: doc-f>
4723: doc-f>=
4724:
1.21 crook 4725: doc-f0<
1.28 crook 4726: doc-f0<=
4727: doc-f0<>
1.21 crook 4728: doc-f0=
1.28 crook 4729: doc-f0>
4730: doc-f0>=
4731:
1.1 anton 4732:
4733: @node Stack Manipulation, Memory, Arithmetic, Words
4734: @section Stack Manipulation
4735: @cindex stack manipulation words
4736:
4737: @cindex floating-point stack in the standard
1.21 crook 4738: Gforth maintains a number of separate stacks:
4739:
1.29 crook 4740: @cindex data stack
4741: @cindex parameter stack
1.21 crook 4742: @itemize @bullet
4743: @item
1.29 crook 4744: A data stack (also known as the @dfn{parameter stack}) -- for
4745: characters, cells, addresses, and double cells.
1.21 crook 4746:
1.29 crook 4747: @cindex floating-point stack
1.21 crook 4748: @item
1.44 crook 4749: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4750:
1.29 crook 4751: @cindex return stack
1.21 crook 4752: @item
1.44 crook 4753: A return stack -- for holding the return addresses of colon
1.32 anton 4754: definitions and other (non-FP) data.
1.21 crook 4755:
1.29 crook 4756: @cindex locals stack
1.21 crook 4757: @item
1.44 crook 4758: A locals stack -- for holding local variables.
1.21 crook 4759: @end itemize
4760:
1.1 anton 4761: @menu
4762: * Data stack::
4763: * Floating point stack::
4764: * Return stack::
4765: * Locals stack::
4766: * Stack pointer manipulation::
4767: @end menu
4768:
4769: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4770: @subsection Data stack
4771: @cindex data stack manipulation words
4772: @cindex stack manipulations words, data stack
4773:
1.44 crook 4774:
1.1 anton 4775: doc-drop
4776: doc-nip
4777: doc-dup
4778: doc-over
4779: doc-tuck
4780: doc-swap
1.21 crook 4781: doc-pick
1.1 anton 4782: doc-rot
4783: doc--rot
4784: doc-?dup
4785: doc-roll
4786: doc-2drop
4787: doc-2nip
4788: doc-2dup
4789: doc-2over
4790: doc-2tuck
4791: doc-2swap
4792: doc-2rot
4793:
1.44 crook 4794:
1.1 anton 4795: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4796: @subsection Floating point stack
4797: @cindex floating-point stack manipulation words
4798: @cindex stack manipulation words, floating-point stack
4799:
1.32 anton 4800: Whilst every sane Forth has a separate floating-point stack, it is not
4801: strictly required; an ANS Forth system could theoretically keep
4802: floating-point numbers on the data stack. As an additional difficulty,
4803: you don't know how many cells a floating-point number takes. It is
4804: reportedly possible to write words in a way that they work also for a
4805: unified stack model, but we do not recommend trying it. Instead, just
4806: say that your program has an environmental dependency on a separate
4807: floating-point stack.
4808:
4809: doc-floating-stack
4810:
1.1 anton 4811: doc-fdrop
4812: doc-fnip
4813: doc-fdup
4814: doc-fover
4815: doc-ftuck
4816: doc-fswap
1.21 crook 4817: doc-fpick
1.1 anton 4818: doc-frot
4819:
1.44 crook 4820:
1.1 anton 4821: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4822: @subsection Return stack
4823: @cindex return stack manipulation words
4824: @cindex stack manipulation words, return stack
4825:
1.32 anton 4826: @cindex return stack and locals
4827: @cindex locals and return stack
4828: A Forth system is allowed to keep local variables on the
4829: return stack. This is reasonable, as local variables usually eliminate
4830: the need to use the return stack explicitly. So, if you want to produce
4831: a standard compliant program and you are using local variables in a
4832: word, forget about return stack manipulations in that word (refer to the
4833: standard document for the exact rules).
4834:
1.1 anton 4835: doc->r
4836: doc-r>
4837: doc-r@
4838: doc-rdrop
4839: doc-2>r
4840: doc-2r>
4841: doc-2r@
4842: doc-2rdrop
4843:
1.44 crook 4844:
1.1 anton 4845: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4846: @subsection Locals stack
4847:
1.78 anton 4848: Gforth uses an extra locals stack. It is described, along with the
4849: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4850:
1.1 anton 4851: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4852: @subsection Stack pointer manipulation
4853: @cindex stack pointer manipulation words
4854:
1.44 crook 4855: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4856: doc-sp0
1.1 anton 4857: doc-sp@
4858: doc-sp!
1.21 crook 4859: doc-fp0
1.1 anton 4860: doc-fp@
4861: doc-fp!
1.21 crook 4862: doc-rp0
1.1 anton 4863: doc-rp@
4864: doc-rp!
1.21 crook 4865: doc-lp0
1.1 anton 4866: doc-lp@
4867: doc-lp!
4868:
1.44 crook 4869:
1.1 anton 4870: @node Memory, Control Structures, Stack Manipulation, Words
4871: @section Memory
1.26 crook 4872: @cindex memory words
1.1 anton 4873:
1.32 anton 4874: @menu
4875: * Memory model::
4876: * Dictionary allocation::
4877: * Heap Allocation::
4878: * Memory Access::
4879: * Address arithmetic::
4880: * Memory Blocks::
4881: @end menu
4882:
1.67 anton 4883: In addition to the standard Forth memory allocation words, there is also
4884: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4885: garbage collector}.
4886:
1.32 anton 4887: @node Memory model, Dictionary allocation, Memory, Memory
4888: @subsection ANS Forth and Gforth memory models
4889:
4890: @c The ANS Forth description is a mess (e.g., is the heap part of
4891: @c the dictionary?), so let's not stick to closely with it.
4892:
1.67 anton 4893: ANS Forth considers a Forth system as consisting of several address
4894: spaces, of which only @dfn{data space} is managed and accessible with
4895: the memory words. Memory not necessarily in data space includes the
4896: stacks, the code (called code space) and the headers (called name
4897: space). In Gforth everything is in data space, but the code for the
4898: primitives is usually read-only.
1.32 anton 4899:
4900: Data space is divided into a number of areas: The (data space portion of
4901: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4902: refer to the search data structure embodied in word lists and headers,
4903: because it is used for looking up names, just as you would in a
4904: conventional dictionary.}, the heap, and a number of system-allocated
4905: buffers.
4906:
1.68 anton 4907: @cindex address arithmetic restrictions, ANS vs. Gforth
4908: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4909: In ANS Forth data space is also divided into contiguous regions. You
4910: can only use address arithmetic within a contiguous region, not between
4911: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4912: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4913: allocation}).
4914:
4915: Gforth provides one big address space, and address arithmetic can be
4916: performed between any addresses. However, in the dictionary headers or
4917: code are interleaved with data, so almost the only contiguous data space
4918: regions there are those described by ANS Forth as contiguous; but you
4919: can be sure that the dictionary is allocated towards increasing
4920: addresses even between contiguous regions. The memory order of
4921: allocations in the heap is platform-dependent (and possibly different
4922: from one run to the next).
4923:
1.27 crook 4924:
1.32 anton 4925: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4926: @subsection Dictionary allocation
1.27 crook 4927: @cindex reserving data space
4928: @cindex data space - reserving some
4929:
1.32 anton 4930: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4931: you want to deallocate X, you also deallocate everything
4932: allocated after X.
4933:
1.68 anton 4934: @cindex contiguous regions in dictionary allocation
1.32 anton 4935: The allocations using the words below are contiguous and grow the region
4936: towards increasing addresses. Other words that allocate dictionary
4937: memory of any kind (i.e., defining words including @code{:noname}) end
4938: the contiguous region and start a new one.
4939:
4940: In ANS Forth only @code{create}d words are guaranteed to produce an
4941: address that is the start of the following contiguous region. In
4942: particular, the cell allocated by @code{variable} is not guaranteed to
4943: be contiguous with following @code{allot}ed memory.
4944:
4945: You can deallocate memory by using @code{allot} with a negative argument
4946: (with some restrictions, see @code{allot}). For larger deallocations use
4947: @code{marker}.
1.27 crook 4948:
1.29 crook 4949:
1.27 crook 4950: doc-here
4951: doc-unused
4952: doc-allot
4953: doc-c,
1.29 crook 4954: doc-f,
1.27 crook 4955: doc-,
4956: doc-2,
4957:
1.32 anton 4958: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4959: course you should allocate memory in an aligned way, too. I.e., before
4960: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4961: The words below align @code{here} if it is not already. Basically it is
4962: only already aligned for a type, if the last allocation was a multiple
4963: of the size of this type and if @code{here} was aligned for this type
4964: before.
4965:
4966: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4967: ANS Forth (@code{maxalign}ed in Gforth).
4968:
4969: doc-align
4970: doc-falign
4971: doc-sfalign
4972: doc-dfalign
4973: doc-maxalign
4974: doc-cfalign
4975:
4976:
4977: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4978: @subsection Heap allocation
4979: @cindex heap allocation
4980: @cindex dynamic allocation of memory
4981: @cindex memory-allocation word set
4982:
1.68 anton 4983: @cindex contiguous regions and heap allocation
1.32 anton 4984: Heap allocation supports deallocation of allocated memory in any
4985: order. Dictionary allocation is not affected by it (i.e., it does not
4986: end a contiguous region). In Gforth, these words are implemented using
4987: the standard C library calls malloc(), free() and resize().
4988:
1.68 anton 4989: The memory region produced by one invocation of @code{allocate} or
4990: @code{resize} is internally contiguous. There is no contiguity between
4991: such a region and any other region (including others allocated from the
4992: heap).
4993:
1.32 anton 4994: doc-allocate
4995: doc-free
4996: doc-resize
4997:
1.27 crook 4998:
1.32 anton 4999: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5000: @subsection Memory Access
5001: @cindex memory access words
5002:
5003: doc-@
5004: doc-!
5005: doc-+!
5006: doc-c@
5007: doc-c!
5008: doc-2@
5009: doc-2!
5010: doc-f@
5011: doc-f!
5012: doc-sf@
5013: doc-sf!
5014: doc-df@
5015: doc-df!
1.144 anton 5016: doc-sw@
5017: doc-uw@
5018: doc-w!
5019: doc-sl@
5020: doc-ul@
5021: doc-l!
1.68 anton 5022:
1.32 anton 5023: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5024: @subsection Address arithmetic
1.1 anton 5025: @cindex address arithmetic words
5026:
1.67 anton 5027: Address arithmetic is the foundation on which you can build data
5028: structures like arrays, records (@pxref{Structures}) and objects
5029: (@pxref{Object-oriented Forth}).
1.32 anton 5030:
1.68 anton 5031: @cindex address unit
5032: @cindex au (address unit)
1.1 anton 5033: ANS Forth does not specify the sizes of the data types. Instead, it
5034: offers a number of words for computing sizes and doing address
1.29 crook 5035: arithmetic. Address arithmetic is performed in terms of address units
5036: (aus); on most systems the address unit is one byte. Note that a
5037: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5038: platforms where it is a noop, it compiles to nothing).
1.1 anton 5039:
1.67 anton 5040: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5041: you have the address of a cell, perform @code{1 cells +}, and you will
5042: have the address of the next cell.
5043:
1.68 anton 5044: @cindex contiguous regions and address arithmetic
1.67 anton 5045: In ANS Forth you can perform address arithmetic only within a contiguous
5046: region, i.e., if you have an address into one region, you can only add
5047: and subtract such that the result is still within the region; you can
5048: only subtract or compare addresses from within the same contiguous
5049: region. Reasons: several contiguous regions can be arranged in memory
5050: in any way; on segmented systems addresses may have unusual
5051: representations, such that address arithmetic only works within a
5052: region. Gforth provides a few more guarantees (linear address space,
5053: dictionary grows upwards), but in general I have found it easy to stay
5054: within contiguous regions (exception: computing and comparing to the
5055: address just beyond the end of an array).
5056:
1.1 anton 5057: @cindex alignment of addresses for types
5058: ANS Forth also defines words for aligning addresses for specific
5059: types. Many computers require that accesses to specific data types
5060: must only occur at specific addresses; e.g., that cells may only be
5061: accessed at addresses divisible by 4. Even if a machine allows unaligned
5062: accesses, it can usually perform aligned accesses faster.
5063:
5064: For the performance-conscious: alignment operations are usually only
5065: necessary during the definition of a data structure, not during the
5066: (more frequent) accesses to it.
5067:
5068: ANS Forth defines no words for character-aligning addresses. This is not
5069: an oversight, but reflects the fact that addresses that are not
5070: char-aligned have no use in the standard and therefore will not be
5071: created.
5072:
5073: @cindex @code{CREATE} and alignment
1.29 crook 5074: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5075: are cell-aligned; in addition, Gforth guarantees that these addresses
5076: are aligned for all purposes.
5077:
1.26 crook 5078: Note that the ANS Forth word @code{char} has nothing to do with address
5079: arithmetic.
1.1 anton 5080:
1.44 crook 5081:
1.1 anton 5082: doc-chars
5083: doc-char+
5084: doc-cells
5085: doc-cell+
5086: doc-cell
5087: doc-aligned
5088: doc-floats
5089: doc-float+
5090: doc-float
5091: doc-faligned
5092: doc-sfloats
5093: doc-sfloat+
5094: doc-sfaligned
5095: doc-dfloats
5096: doc-dfloat+
5097: doc-dfaligned
5098: doc-maxaligned
5099: doc-cfaligned
5100: doc-address-unit-bits
1.145 anton 5101: doc-/w
5102: doc-/l
1.44 crook 5103:
1.32 anton 5104: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5105: @subsection Memory Blocks
5106: @cindex memory block words
1.27 crook 5107: @cindex character strings - moving and copying
5108:
1.49 anton 5109: Memory blocks often represent character strings; For ways of storing
5110: character strings in memory see @ref{String Formats}. For other
5111: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5112:
1.67 anton 5113: A few of these words work on address unit blocks. In that case, you
5114: usually have to insert @code{CHARS} before the word when working on
5115: character strings. Most words work on character blocks, and expect a
5116: char-aligned address.
5117:
5118: When copying characters between overlapping memory regions, use
5119: @code{chars move} or choose carefully between @code{cmove} and
5120: @code{cmove>}.
1.44 crook 5121:
1.1 anton 5122: doc-move
5123: doc-erase
5124: doc-cmove
5125: doc-cmove>
5126: doc-fill
5127: doc-blank
1.21 crook 5128: doc-compare
1.111 anton 5129: doc-str=
5130: doc-str<
5131: doc-string-prefix?
1.21 crook 5132: doc-search
1.27 crook 5133: doc--trailing
5134: doc-/string
1.82 anton 5135: doc-bounds
1.141 anton 5136: doc-pad
1.111 anton 5137:
1.27 crook 5138: @comment TODO examples
5139:
1.1 anton 5140:
1.26 crook 5141: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5142: @section Control Structures
5143: @cindex control structures
5144:
1.33 anton 5145: Control structures in Forth cannot be used interpretively, only in a
5146: colon definition@footnote{To be precise, they have no interpretation
5147: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5148: not like this limitation, but have not seen a satisfying way around it
5149: yet, although many schemes have been proposed.
1.1 anton 5150:
5151: @menu
1.33 anton 5152: * Selection:: IF ... ELSE ... ENDIF
5153: * Simple Loops:: BEGIN ...
1.29 crook 5154: * Counted Loops:: DO
1.67 anton 5155: * Arbitrary control structures::
5156: * Calls and returns::
1.1 anton 5157: * Exception Handling::
5158: @end menu
5159:
5160: @node Selection, Simple Loops, Control Structures, Control Structures
5161: @subsection Selection
5162: @cindex selection control structures
5163: @cindex control structures for selection
5164:
5165: @cindex @code{IF} control structure
5166: @example
1.29 crook 5167: @i{flag}
1.1 anton 5168: IF
1.29 crook 5169: @i{code}
1.1 anton 5170: ENDIF
5171: @end example
1.21 crook 5172: @noindent
1.33 anton 5173:
1.44 crook 5174: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5175: with any bit set represents truth) @i{code} is executed.
1.33 anton 5176:
1.1 anton 5177: @example
1.29 crook 5178: @i{flag}
1.1 anton 5179: IF
1.29 crook 5180: @i{code1}
1.1 anton 5181: ELSE
1.29 crook 5182: @i{code2}
1.1 anton 5183: ENDIF
5184: @end example
5185:
1.44 crook 5186: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5187: executed.
1.33 anton 5188:
1.1 anton 5189: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5190: standard, and @code{ENDIF} is not, although it is quite popular. We
5191: recommend using @code{ENDIF}, because it is less confusing for people
5192: who also know other languages (and is not prone to reinforcing negative
5193: prejudices against Forth in these people). Adding @code{ENDIF} to a
5194: system that only supplies @code{THEN} is simple:
5195: @example
1.82 anton 5196: : ENDIF POSTPONE then ; immediate
1.1 anton 5197: @end example
5198:
5199: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5200: (adv.)} has the following meanings:
5201: @quotation
5202: ... 2b: following next after in order ... 3d: as a necessary consequence
5203: (if you were there, then you saw them).
5204: @end quotation
5205: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5206: and many other programming languages has the meaning 3d.]
5207:
1.21 crook 5208: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5209: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5210: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5211: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5212: @file{compat/control.fs}.
5213:
5214: @cindex @code{CASE} control structure
5215: @example
1.29 crook 5216: @i{n}
1.1 anton 5217: CASE
1.29 crook 5218: @i{n1} OF @i{code1} ENDOF
5219: @i{n2} OF @i{code2} ENDOF
1.1 anton 5220: @dots{}
1.68 anton 5221: ( n ) @i{default-code} ( n )
1.131 anton 5222: ENDCASE ( )
1.1 anton 5223: @end example
5224:
1.131 anton 5225: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5226: no @i{ni} matches, the optional @i{default-code} is executed. The
5227: optional default case can be added by simply writing the code after
5228: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5229: but must not consume it. The value @i{n} is consumed by this
5230: construction (either by a OF that matches, or by the ENDCASE, if no OF
5231: matches).
1.1 anton 5232:
1.69 anton 5233: @progstyle
1.131 anton 5234: To keep the code understandable, you should ensure that you change the
5235: stack in the same way (wrt. number and types of stack items consumed
5236: and pushed) on all paths through a selection construct.
1.69 anton 5237:
1.1 anton 5238: @node Simple Loops, Counted Loops, Selection, Control Structures
5239: @subsection Simple Loops
5240: @cindex simple loops
5241: @cindex loops without count
5242:
5243: @cindex @code{WHILE} loop
5244: @example
5245: BEGIN
1.29 crook 5246: @i{code1}
5247: @i{flag}
1.1 anton 5248: WHILE
1.29 crook 5249: @i{code2}
1.1 anton 5250: REPEAT
5251: @end example
5252:
1.29 crook 5253: @i{code1} is executed and @i{flag} is computed. If it is true,
5254: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5255: false, execution continues after the @code{REPEAT}.
5256:
5257: @cindex @code{UNTIL} loop
5258: @example
5259: BEGIN
1.29 crook 5260: @i{code}
5261: @i{flag}
1.1 anton 5262: UNTIL
5263: @end example
5264:
1.29 crook 5265: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5266:
1.69 anton 5267: @progstyle
5268: To keep the code understandable, a complete iteration of the loop should
5269: not change the number and types of the items on the stacks.
5270:
1.1 anton 5271: @cindex endless loop
5272: @cindex loops, endless
5273: @example
5274: BEGIN
1.29 crook 5275: @i{code}
1.1 anton 5276: AGAIN
5277: @end example
5278:
5279: This is an endless loop.
5280:
5281: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5282: @subsection Counted Loops
5283: @cindex counted loops
5284: @cindex loops, counted
5285: @cindex @code{DO} loops
5286:
5287: The basic counted loop is:
5288: @example
1.29 crook 5289: @i{limit} @i{start}
1.1 anton 5290: ?DO
1.29 crook 5291: @i{body}
1.1 anton 5292: LOOP
5293: @end example
5294:
1.29 crook 5295: This performs one iteration for every integer, starting from @i{start}
5296: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5297: accessed with @code{i}. For example, the loop:
1.1 anton 5298: @example
5299: 10 0 ?DO
5300: i .
5301: LOOP
5302: @end example
1.21 crook 5303: @noindent
5304: prints @code{0 1 2 3 4 5 6 7 8 9}
5305:
1.1 anton 5306: The index of the innermost loop can be accessed with @code{i}, the index
5307: of the next loop with @code{j}, and the index of the third loop with
5308: @code{k}.
5309:
1.44 crook 5310:
1.1 anton 5311: doc-i
5312: doc-j
5313: doc-k
5314:
1.44 crook 5315:
1.1 anton 5316: The loop control data are kept on the return stack, so there are some
1.21 crook 5317: restrictions on mixing return stack accesses and counted loop words. In
5318: particuler, if you put values on the return stack outside the loop, you
5319: cannot read them inside the loop@footnote{well, not in a way that is
5320: portable.}. If you put values on the return stack within a loop, you
5321: have to remove them before the end of the loop and before accessing the
5322: index of the loop.
1.1 anton 5323:
5324: There are several variations on the counted loop:
5325:
1.21 crook 5326: @itemize @bullet
5327: @item
5328: @code{LEAVE} leaves the innermost counted loop immediately; execution
5329: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5330:
5331: @example
5332: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5333: @end example
5334: prints @code{0 1 2 3}
5335:
1.1 anton 5336:
1.21 crook 5337: @item
5338: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5339: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5340: return stack so @code{EXIT} can get to its return address. For example:
5341:
5342: @example
5343: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5344: @end example
5345: prints @code{0 1 2 3}
5346:
5347:
5348: @item
1.29 crook 5349: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5350: (and @code{LOOP} iterates until they become equal by wrap-around
5351: arithmetic). This behaviour is usually not what you want. Therefore,
5352: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5353: @code{?DO}), which do not enter the loop if @i{start} is greater than
5354: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5355: unsigned loop parameters.
5356:
1.21 crook 5357: @item
5358: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5359: the loop, independent of the loop parameters. Do not use @code{DO}, even
5360: if you know that the loop is entered in any case. Such knowledge tends
5361: to become invalid during maintenance of a program, and then the
5362: @code{DO} will make trouble.
5363:
5364: @item
1.29 crook 5365: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5366: index by @i{n} instead of by 1. The loop is terminated when the border
5367: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5368:
1.21 crook 5369: @example
5370: 4 0 +DO i . 2 +LOOP
5371: @end example
5372: @noindent
5373: prints @code{0 2}
5374:
5375: @example
5376: 4 1 +DO i . 2 +LOOP
5377: @end example
5378: @noindent
5379: prints @code{1 3}
1.1 anton 5380:
1.68 anton 5381: @item
1.1 anton 5382: @cindex negative increment for counted loops
5383: @cindex counted loops with negative increment
1.29 crook 5384: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5385:
1.21 crook 5386: @example
5387: -1 0 ?DO i . -1 +LOOP
5388: @end example
5389: @noindent
5390: prints @code{0 -1}
1.1 anton 5391:
1.21 crook 5392: @example
5393: 0 0 ?DO i . -1 +LOOP
5394: @end example
5395: prints nothing.
1.1 anton 5396:
1.29 crook 5397: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5398: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5399: index by @i{u} each iteration. The loop is terminated when the border
5400: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5401: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5402:
1.21 crook 5403: @example
5404: -2 0 -DO i . 1 -LOOP
5405: @end example
5406: @noindent
5407: prints @code{0 -1}
1.1 anton 5408:
1.21 crook 5409: @example
5410: -1 0 -DO i . 1 -LOOP
5411: @end example
5412: @noindent
5413: prints @code{0}
5414:
5415: @example
5416: 0 0 -DO i . 1 -LOOP
5417: @end example
5418: @noindent
5419: prints nothing.
1.1 anton 5420:
1.21 crook 5421: @end itemize
1.1 anton 5422:
5423: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5424: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5425: for these words that uses only standard words is provided in
5426: @file{compat/loops.fs}.
1.1 anton 5427:
5428:
5429: @cindex @code{FOR} loops
1.26 crook 5430: Another counted loop is:
1.1 anton 5431: @example
1.29 crook 5432: @i{n}
1.1 anton 5433: FOR
1.29 crook 5434: @i{body}
1.1 anton 5435: NEXT
5436: @end example
5437: This is the preferred loop of native code compiler writers who are too
1.26 crook 5438: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5439: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5440: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5441: Forth systems may behave differently, even if they support @code{FOR}
5442: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5443:
5444: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5445: @subsection Arbitrary control structures
5446: @cindex control structures, user-defined
5447:
5448: @cindex control-flow stack
5449: ANS Forth permits and supports using control structures in a non-nested
5450: way. Information about incomplete control structures is stored on the
5451: control-flow stack. This stack may be implemented on the Forth data
5452: stack, and this is what we have done in Gforth.
5453:
5454: @cindex @code{orig}, control-flow stack item
5455: @cindex @code{dest}, control-flow stack item
5456: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5457: entry represents a backward branch target. A few words are the basis for
5458: building any control structure possible (except control structures that
5459: need storage, like calls, coroutines, and backtracking).
5460:
1.44 crook 5461:
1.1 anton 5462: doc-if
5463: doc-ahead
5464: doc-then
5465: doc-begin
5466: doc-until
5467: doc-again
5468: doc-cs-pick
5469: doc-cs-roll
5470:
1.44 crook 5471:
1.21 crook 5472: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5473: manipulate the control-flow stack in a portable way. Without them, you
5474: would need to know how many stack items are occupied by a control-flow
5475: entry (many systems use one cell. In Gforth they currently take three,
5476: but this may change in the future).
5477:
1.1 anton 5478: Some standard control structure words are built from these words:
5479:
1.44 crook 5480:
1.1 anton 5481: doc-else
5482: doc-while
5483: doc-repeat
5484:
1.44 crook 5485:
5486: @noindent
1.1 anton 5487: Gforth adds some more control-structure words:
5488:
1.44 crook 5489:
1.1 anton 5490: doc-endif
5491: doc-?dup-if
5492: doc-?dup-0=-if
5493:
1.44 crook 5494:
5495: @noindent
1.1 anton 5496: Counted loop words constitute a separate group of words:
5497:
1.44 crook 5498:
1.1 anton 5499: doc-?do
5500: doc-+do
5501: doc-u+do
5502: doc--do
5503: doc-u-do
5504: doc-do
5505: doc-for
5506: doc-loop
5507: doc-+loop
5508: doc--loop
5509: doc-next
5510: doc-leave
5511: doc-?leave
5512: doc-unloop
5513: doc-done
5514:
1.44 crook 5515:
1.21 crook 5516: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5517: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5518: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5519: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5520: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5521: resolved (by using one of the loop-ending words or @code{DONE}).
5522:
1.44 crook 5523: @noindent
1.26 crook 5524: Another group of control structure words are:
1.1 anton 5525:
1.44 crook 5526:
1.1 anton 5527: doc-case
5528: doc-endcase
5529: doc-of
5530: doc-endof
5531:
1.44 crook 5532:
1.21 crook 5533: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5534: @code{CS-ROLL}.
1.1 anton 5535:
5536: @subsubsection Programming Style
1.47 crook 5537: @cindex control structures programming style
5538: @cindex programming style, arbitrary control structures
1.1 anton 5539:
5540: In order to ensure readability we recommend that you do not create
5541: arbitrary control structures directly, but define new control structure
5542: words for the control structure you want and use these words in your
1.26 crook 5543: program. For example, instead of writing:
1.1 anton 5544:
5545: @example
1.26 crook 5546: BEGIN
1.1 anton 5547: ...
1.26 crook 5548: IF [ 1 CS-ROLL ]
1.1 anton 5549: ...
1.26 crook 5550: AGAIN THEN
1.1 anton 5551: @end example
5552:
1.21 crook 5553: @noindent
1.1 anton 5554: we recommend defining control structure words, e.g.,
5555:
5556: @example
1.26 crook 5557: : WHILE ( DEST -- ORIG DEST )
5558: POSTPONE IF
5559: 1 CS-ROLL ; immediate
5560:
5561: : REPEAT ( orig dest -- )
5562: POSTPONE AGAIN
5563: POSTPONE THEN ; immediate
1.1 anton 5564: @end example
5565:
1.21 crook 5566: @noindent
1.1 anton 5567: and then using these to create the control structure:
5568:
5569: @example
1.26 crook 5570: BEGIN
1.1 anton 5571: ...
1.26 crook 5572: WHILE
1.1 anton 5573: ...
1.26 crook 5574: REPEAT
1.1 anton 5575: @end example
5576:
5577: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5578: @code{WHILE} are predefined, so in this example it would not be
5579: necessary to define them.
5580:
5581: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5582: @subsection Calls and returns
5583: @cindex calling a definition
5584: @cindex returning from a definition
5585:
1.3 anton 5586: @cindex recursive definitions
5587: A definition can be called simply be writing the name of the definition
1.26 crook 5588: to be called. Normally a definition is invisible during its own
1.3 anton 5589: definition. If you want to write a directly recursive definition, you
1.26 crook 5590: can use @code{recursive} to make the current definition visible, or
5591: @code{recurse} to call the current definition directly.
1.3 anton 5592:
1.44 crook 5593:
1.3 anton 5594: doc-recursive
5595: doc-recurse
5596:
1.44 crook 5597:
1.21 crook 5598: @comment TODO add example of the two recursion methods
1.12 anton 5599: @quotation
5600: @progstyle
5601: I prefer using @code{recursive} to @code{recurse}, because calling the
5602: definition by name is more descriptive (if the name is well-chosen) than
5603: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5604: implementation, it is much better to read (and think) ``now sort the
5605: partitions'' than to read ``now do a recursive call''.
5606: @end quotation
1.3 anton 5607:
1.29 crook 5608: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5609:
5610: @example
1.28 crook 5611: Defer foo
1.3 anton 5612:
5613: : bar ( ... -- ... )
5614: ... foo ... ;
5615:
5616: :noname ( ... -- ... )
5617: ... bar ... ;
5618: IS foo
5619: @end example
5620:
1.44 crook 5621: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5622:
1.26 crook 5623: The current definition returns control to the calling definition when
1.33 anton 5624: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5625:
5626: doc-exit
5627: doc-;s
5628:
1.44 crook 5629:
1.1 anton 5630: @node Exception Handling, , Calls and returns, Control Structures
5631: @subsection Exception Handling
1.26 crook 5632: @cindex exceptions
1.1 anton 5633:
1.68 anton 5634: @c quit is a very bad idea for error handling,
5635: @c because it does not translate into a THROW
5636: @c it also does not belong into this chapter
5637:
5638: If a word detects an error condition that it cannot handle, it can
5639: @code{throw} an exception. In the simplest case, this will terminate
5640: your program, and report an appropriate error.
1.21 crook 5641:
1.68 anton 5642: doc-throw
1.1 anton 5643:
1.69 anton 5644: @code{Throw} consumes a cell-sized error number on the stack. There are
5645: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5646: Gforth (and most other systems) you can use the iors produced by various
5647: words as error numbers (e.g., a typical use of @code{allocate} is
5648: @code{allocate throw}). Gforth also provides the word @code{exception}
5649: to define your own error numbers (with decent error reporting); an ANS
5650: Forth version of this word (but without the error messages) is available
5651: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5652: numbers (anything outside the range -4095..0), but won't get nice error
5653: messages, only numbers. For example, try:
5654:
5655: @example
1.69 anton 5656: -10 throw \ ANS defined
5657: -267 throw \ system defined
5658: s" my error" exception throw \ user defined
5659: 7 throw \ arbitrary number
1.68 anton 5660: @end example
5661:
5662: doc---exception-exception
1.1 anton 5663:
1.69 anton 5664: A common idiom to @code{THROW} a specific error if a flag is true is
5665: this:
5666:
5667: @example
5668: @code{( flag ) 0<> @i{errno} and throw}
5669: @end example
5670:
5671: Your program can provide exception handlers to catch exceptions. An
5672: exception handler can be used to correct the problem, or to clean up
5673: some data structures and just throw the exception to the next exception
5674: handler. Note that @code{throw} jumps to the dynamically innermost
5675: exception handler. The system's exception handler is outermost, and just
5676: prints an error and restarts command-line interpretation (or, in batch
5677: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5678:
1.68 anton 5679: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5680:
1.68 anton 5681: doc-catch
1.160 anton 5682: doc-nothrow
1.68 anton 5683:
5684: The most common use of exception handlers is to clean up the state when
5685: an error happens. E.g.,
1.1 anton 5686:
1.26 crook 5687: @example
1.68 anton 5688: base @ >r hex \ actually the hex should be inside foo, or we h
5689: ['] foo catch ( nerror|0 )
5690: r> base !
1.69 anton 5691: ( nerror|0 ) throw \ pass it on
1.26 crook 5692: @end example
1.1 anton 5693:
1.69 anton 5694: A use of @code{catch} for handling the error @code{myerror} might look
5695: like this:
1.44 crook 5696:
1.68 anton 5697: @example
1.69 anton 5698: ['] foo catch
5699: CASE
1.160 anton 5700: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5701: dup throw \ default: pass other errors on, do nothing on non-errors
5702: ENDCASE
1.68 anton 5703: @end example
1.44 crook 5704:
1.68 anton 5705: Having to wrap the code into a separate word is often cumbersome,
5706: therefore Gforth provides an alternative syntax:
1.1 anton 5707:
5708: @example
1.69 anton 5709: TRY
1.68 anton 5710: @i{code1}
1.160 anton 5711: RECOVER
1.68 anton 5712: @i{code2} \ optional
1.69 anton 5713: ENDTRY
1.1 anton 5714: @end example
5715:
1.68 anton 5716: This performs @i{Code1}. If @i{code1} completes normally, execution
5717: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5718: reset to the state during @code{try}, the throw value is pushed on the
5719: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5720: through the @code{endtry} into the following code.
1.26 crook 5721:
1.68 anton 5722: doc-try
5723: doc-recover
5724: doc-endtry
1.26 crook 5725:
1.69 anton 5726: The cleanup example from above in this syntax:
1.26 crook 5727:
1.68 anton 5728: @example
1.69 anton 5729: base @ >r TRY
1.68 anton 5730: hex foo \ now the hex is placed correctly
1.69 anton 5731: 0 \ value for throw
1.92 anton 5732: RECOVER ENDTRY
1.68 anton 5733: r> base ! throw
1.1 anton 5734: @end example
5735:
1.69 anton 5736: And here's the error handling example:
1.1 anton 5737:
1.68 anton 5738: @example
1.69 anton 5739: TRY
1.68 anton 5740: foo
1.69 anton 5741: RECOVER
5742: CASE
1.160 anton 5743: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5744: throw \ pass other errors on
5745: ENDCASE
5746: ENDTRY
1.68 anton 5747: @end example
1.1 anton 5748:
1.69 anton 5749: @progstyle
5750: As usual, you should ensure that the stack depth is statically known at
5751: the end: either after the @code{throw} for passing on errors, or after
5752: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5753: selection construct for handling the error).
5754:
1.68 anton 5755: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5756: and you can provide an error message. @code{Abort} just produces an
5757: ``Aborted'' error.
1.1 anton 5758:
1.68 anton 5759: The problem with these words is that exception handlers cannot
5760: differentiate between different @code{abort"}s; they just look like
5761: @code{-2 throw} to them (the error message cannot be accessed by
5762: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5763: exception handlers.
1.44 crook 5764:
1.68 anton 5765: doc-abort"
1.26 crook 5766: doc-abort
1.29 crook 5767:
5768:
1.44 crook 5769:
1.29 crook 5770: @c -------------------------------------------------------------
1.47 crook 5771: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5772: @section Defining Words
5773: @cindex defining words
5774:
1.47 crook 5775: Defining words are used to extend Forth by creating new entries in the dictionary.
5776:
1.29 crook 5777: @menu
1.67 anton 5778: * CREATE::
1.44 crook 5779: * Variables:: Variables and user variables
1.67 anton 5780: * Constants::
1.44 crook 5781: * Values:: Initialised variables
1.67 anton 5782: * Colon Definitions::
1.44 crook 5783: * Anonymous Definitions:: Definitions without names
1.69 anton 5784: * Supplying names:: Passing definition names as strings
1.67 anton 5785: * User-defined Defining Words::
1.44 crook 5786: * Deferred words:: Allow forward references
1.67 anton 5787: * Aliases::
1.29 crook 5788: @end menu
5789:
1.44 crook 5790: @node CREATE, Variables, Defining Words, Defining Words
5791: @subsection @code{CREATE}
1.29 crook 5792: @cindex simple defining words
5793: @cindex defining words, simple
5794:
5795: Defining words are used to create new entries in the dictionary. The
5796: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5797: this:
5798:
5799: @example
5800: CREATE new-word1
5801: @end example
5802:
1.69 anton 5803: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5804: input stream (@code{new-word1} in our example). It generates a
5805: dictionary entry for @code{new-word1}. When @code{new-word1} is
5806: executed, all that it does is leave an address on the stack. The address
5807: represents the value of the data space pointer (@code{HERE}) at the time
5808: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5809: associating a name with the address of a region of memory.
1.29 crook 5810:
1.34 anton 5811: doc-create
5812:
1.69 anton 5813: Note that in ANS Forth guarantees only for @code{create} that its body
5814: is in dictionary data space (i.e., where @code{here}, @code{allot}
5815: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5816: @code{create}d words can be modified with @code{does>}
5817: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5818: can only be applied to @code{create}d words.
5819:
1.29 crook 5820: By extending this example to reserve some memory in data space, we end
1.69 anton 5821: up with something like a @i{variable}. Here are two different ways to do
5822: it:
1.29 crook 5823:
5824: @example
5825: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5826: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5827: @end example
5828:
5829: The variable can be examined and modified using @code{@@} (``fetch'') and
5830: @code{!} (``store'') like this:
5831:
5832: @example
5833: new-word2 @@ . \ get address, fetch from it and display
5834: 1234 new-word2 ! \ new value, get address, store to it
5835: @end example
5836:
1.44 crook 5837: @cindex arrays
5838: A similar mechanism can be used to create arrays. For example, an
5839: 80-character text input buffer:
1.29 crook 5840:
5841: @example
1.44 crook 5842: CREATE text-buf 80 chars allot
5843:
5844: text-buf 0 chars c@@ \ the 1st character (offset 0)
5845: text-buf 3 chars c@@ \ the 4th character (offset 3)
5846: @end example
1.29 crook 5847:
1.44 crook 5848: You can build arbitrarily complex data structures by allocating
1.49 anton 5849: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5850: learn about some Gforth tools that make it easier,
1.49 anton 5851: @xref{Structures}.
1.44 crook 5852:
5853:
5854: @node Variables, Constants, CREATE, Defining Words
5855: @subsection Variables
5856: @cindex variables
5857:
5858: The previous section showed how a sequence of commands could be used to
5859: generate a variable. As a final refinement, the whole code sequence can
5860: be wrapped up in a defining word (pre-empting the subject of the next
5861: section), making it easier to create new variables:
5862:
5863: @example
5864: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5865: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5866:
5867: myvariableX foo \ variable foo starts off with an unknown value
5868: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5869:
5870: 45 3 * foo ! \ set foo to 135
5871: 1234 joe ! \ set joe to 1234
5872: 3 joe +! \ increment joe by 3.. to 1237
5873: @end example
5874:
5875: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5876: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5877: guarantee that a @code{Variable} is initialised when it is created
5878: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5879: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5880: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5881: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5882: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5883: store a boolean, you can use @code{on} and @code{off} to toggle its
5884: state.
1.29 crook 5885:
1.34 anton 5886: doc-variable
5887: doc-2variable
5888: doc-fvariable
5889:
1.29 crook 5890: @cindex user variables
5891: @cindex user space
5892: The defining word @code{User} behaves in the same way as @code{Variable}.
5893: The difference is that it reserves space in @i{user (data) space} rather
5894: than normal data space. In a Forth system that has a multi-tasker, each
5895: task has its own set of user variables.
5896:
1.34 anton 5897: doc-user
1.67 anton 5898: @c doc-udp
5899: @c doc-uallot
1.34 anton 5900:
1.29 crook 5901: @comment TODO is that stuff about user variables strictly correct? Is it
5902: @comment just terminal tasks that have user variables?
5903: @comment should document tasker.fs (with some examples) elsewhere
5904: @comment in this manual, then expand on user space and user variables.
5905:
1.44 crook 5906: @node Constants, Values, Variables, Defining Words
5907: @subsection Constants
5908: @cindex constants
5909:
5910: @code{Constant} allows you to declare a fixed value and refer to it by
5911: name. For example:
1.29 crook 5912:
5913: @example
5914: 12 Constant INCHES-PER-FOOT
5915: 3E+08 fconstant SPEED-O-LIGHT
5916: @end example
5917:
5918: A @code{Variable} can be both read and written, so its run-time
5919: behaviour is to supply an address through which its current value can be
5920: manipulated. In contrast, the value of a @code{Constant} cannot be
5921: changed once it has been declared@footnote{Well, often it can be -- but
5922: not in a Standard, portable way. It's safer to use a @code{Value} (read
5923: on).} so it's not necessary to supply the address -- it is more
5924: efficient to return the value of the constant directly. That's exactly
5925: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5926: the top of the stack (You can find one
5927: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5928:
1.69 anton 5929: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5930: double and floating-point constants, respectively.
5931:
1.34 anton 5932: doc-constant
5933: doc-2constant
5934: doc-fconstant
5935:
5936: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5937: @c nac-> How could that not be true in an ANS Forth? You can't define a
5938: @c constant, use it and then delete the definition of the constant..
1.69 anton 5939:
5940: @c anton->An ANS Forth system can compile a constant to a literal; On
5941: @c decompilation you would see only the number, just as if it had been used
5942: @c in the first place. The word will stay, of course, but it will only be
5943: @c used by the text interpreter (no run-time duties, except when it is
5944: @c POSTPONEd or somesuch).
5945:
5946: @c nac:
1.44 crook 5947: @c I agree that it's rather deep, but IMO it is an important difference
5948: @c relative to other programming languages.. often it's annoying: it
5949: @c certainly changes my programming style relative to C.
5950:
1.69 anton 5951: @c anton: In what way?
5952:
1.29 crook 5953: Constants in Forth behave differently from their equivalents in other
5954: programming languages. In other languages, a constant (such as an EQU in
5955: assembler or a #define in C) only exists at compile-time; in the
5956: executable program the constant has been translated into an absolute
5957: number and, unless you are using a symbolic debugger, it's impossible to
5958: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5959: an entry in the header space and remains there after the code that uses
5960: it has been defined. In fact, it must remain in the dictionary since it
5961: has run-time duties to perform. For example:
1.29 crook 5962:
5963: @example
5964: 12 Constant INCHES-PER-FOOT
5965: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5966: @end example
5967:
5968: @cindex in-lining of constants
5969: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5970: associated with the constant @code{INCHES-PER-FOOT}. If you use
5971: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5972: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5973: attempt to optimise constants by in-lining them where they are used. You
5974: can force Gforth to in-line a constant like this:
5975:
5976: @example
5977: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5978: @end example
5979:
5980: If you use @code{see} to decompile @i{this} version of
5981: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5982: longer present. To understand how this works, read
5983: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5984:
5985: In-lining constants in this way might improve execution time
5986: fractionally, and can ensure that a constant is now only referenced at
5987: compile-time. However, the definition of the constant still remains in
5988: the dictionary. Some Forth compilers provide a mechanism for controlling
5989: a second dictionary for holding transient words such that this second
5990: dictionary can be deleted later in order to recover memory
5991: space. However, there is no standard way of doing this.
5992:
5993:
1.44 crook 5994: @node Values, Colon Definitions, Constants, Defining Words
5995: @subsection Values
5996: @cindex values
1.34 anton 5997:
1.69 anton 5998: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5999: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6000: (not in ANS Forth) you can access (and change) a @code{value} also with
6001: @code{>body}.
6002:
6003: Here are some
6004: examples:
1.29 crook 6005:
6006: @example
1.69 anton 6007: 12 Value APPLES \ Define APPLES with an initial value of 12
6008: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6009: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6010: APPLES \ puts 35 on the top of the stack.
1.29 crook 6011: @end example
6012:
1.44 crook 6013: doc-value
6014: doc-to
1.29 crook 6015:
1.35 anton 6016:
1.69 anton 6017:
1.44 crook 6018: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6019: @subsection Colon Definitions
6020: @cindex colon definitions
1.35 anton 6021:
6022: @example
1.44 crook 6023: : name ( ... -- ... )
6024: word1 word2 word3 ;
1.29 crook 6025: @end example
6026:
1.44 crook 6027: @noindent
6028: Creates a word called @code{name} that, upon execution, executes
6029: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6030:
1.49 anton 6031: The explanation above is somewhat superficial. For simple examples of
6032: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6033: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6034: Compilation Semantics}.
1.29 crook 6035:
1.44 crook 6036: doc-:
6037: doc-;
1.1 anton 6038:
1.34 anton 6039:
1.69 anton 6040: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6041: @subsection Anonymous Definitions
6042: @cindex colon definitions
6043: @cindex defining words without name
1.34 anton 6044:
1.44 crook 6045: Sometimes you want to define an @dfn{anonymous word}; a word without a
6046: name. You can do this with:
1.1 anton 6047:
1.44 crook 6048: doc-:noname
1.1 anton 6049:
1.44 crook 6050: This leaves the execution token for the word on the stack after the
6051: closing @code{;}. Here's an example in which a deferred word is
6052: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6053:
1.29 crook 6054: @example
1.44 crook 6055: Defer deferred
6056: :noname ( ... -- ... )
6057: ... ;
6058: IS deferred
1.29 crook 6059: @end example
1.26 crook 6060:
1.44 crook 6061: @noindent
6062: Gforth provides an alternative way of doing this, using two separate
6063: words:
1.27 crook 6064:
1.44 crook 6065: doc-noname
6066: @cindex execution token of last defined word
1.116 anton 6067: doc-latestxt
1.1 anton 6068:
1.44 crook 6069: @noindent
6070: The previous example can be rewritten using @code{noname} and
1.116 anton 6071: @code{latestxt}:
1.1 anton 6072:
1.26 crook 6073: @example
1.44 crook 6074: Defer deferred
6075: noname : ( ... -- ... )
6076: ... ;
1.116 anton 6077: latestxt IS deferred
1.26 crook 6078: @end example
1.1 anton 6079:
1.29 crook 6080: @noindent
1.44 crook 6081: @code{noname} works with any defining word, not just @code{:}.
6082:
1.116 anton 6083: @code{latestxt} also works when the last word was not defined as
1.71 anton 6084: @code{noname}. It does not work for combined words, though. It also has
6085: the useful property that is is valid as soon as the header for a
6086: definition has been built. Thus:
1.44 crook 6087:
6088: @example
1.116 anton 6089: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6090: @end example
1.1 anton 6091:
1.44 crook 6092: @noindent
6093: prints 3 numbers; the last two are the same.
1.26 crook 6094:
1.69 anton 6095: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6096: @subsection Supplying the name of a defined word
6097: @cindex names for defined words
6098: @cindex defining words, name given in a string
6099:
6100: By default, a defining word takes the name for the defined word from the
6101: input stream. Sometimes you want to supply the name from a string. You
6102: can do this with:
6103:
6104: doc-nextname
6105:
6106: For example:
6107:
6108: @example
6109: s" foo" nextname create
6110: @end example
6111:
6112: @noindent
6113: is equivalent to:
6114:
6115: @example
6116: create foo
6117: @end example
6118:
6119: @noindent
6120: @code{nextname} works with any defining word.
6121:
1.1 anton 6122:
1.69 anton 6123: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6124: @subsection User-defined Defining Words
6125: @cindex user-defined defining words
6126: @cindex defining words, user-defined
1.1 anton 6127:
1.29 crook 6128: You can create a new defining word by wrapping defining-time code around
6129: an existing defining word and putting the sequence in a colon
1.69 anton 6130: definition.
6131:
6132: @c anton: This example is very complex and leads in a quite different
6133: @c direction from the CREATE-DOES> stuff that follows. It should probably
6134: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6135: @c subsection of Defining Words)
6136:
6137: For example, suppose that you have a word @code{stats} that
1.29 crook 6138: gathers statistics about colon definitions given the @i{xt} of the
6139: definition, and you want every colon definition in your application to
6140: make a call to @code{stats}. You can define and use a new version of
6141: @code{:} like this:
6142:
6143: @example
6144: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6145: ... ; \ other code
6146:
1.116 anton 6147: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6148:
6149: my: foo + - ;
6150: @end example
6151:
6152: When @code{foo} is defined using @code{my:} these steps occur:
6153:
6154: @itemize @bullet
6155: @item
6156: @code{my:} is executed.
6157: @item
6158: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6159: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6160: the input stream for a name, builds a dictionary header for the name
6161: @code{foo} and switches @code{state} from interpret to compile.
6162: @item
1.116 anton 6163: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6164: being defined -- @code{foo} -- onto the stack.
6165: @item
6166: The code that was produced by @code{postpone literal} is executed; this
6167: causes the value on the stack to be compiled as a literal in the code
6168: area of @code{foo}.
6169: @item
6170: The code @code{['] stats} compiles a literal into the definition of
6171: @code{my:}. When @code{compile,} is executed, that literal -- the
6172: execution token for @code{stats} -- is layed down in the code area of
6173: @code{foo} , following the literal@footnote{Strictly speaking, the
6174: mechanism that @code{compile,} uses to convert an @i{xt} into something
6175: in the code area is implementation-dependent. A threaded implementation
6176: might spit out the execution token directly whilst another
6177: implementation might spit out a native code sequence.}.
6178: @item
6179: At this point, the execution of @code{my:} is complete, and control
6180: returns to the text interpreter. The text interpreter is in compile
6181: state, so subsequent text @code{+ -} is compiled into the definition of
6182: @code{foo} and the @code{;} terminates the definition as always.
6183: @end itemize
6184:
6185: You can use @code{see} to decompile a word that was defined using
6186: @code{my:} and see how it is different from a normal @code{:}
6187: definition. For example:
6188:
6189: @example
6190: : bar + - ; \ like foo but using : rather than my:
6191: see bar
6192: : bar
6193: + - ;
6194: see foo
6195: : foo
6196: 107645672 stats + - ;
6197:
1.140 anton 6198: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6199: @end example
6200:
6201: You can use techniques like this to make new defining words in terms of
6202: @i{any} existing defining word.
1.1 anton 6203:
6204:
1.29 crook 6205: @cindex defining defining words
1.26 crook 6206: @cindex @code{CREATE} ... @code{DOES>}
6207: If you want the words defined with your defining words to behave
6208: differently from words defined with standard defining words, you can
6209: write your defining word like this:
1.1 anton 6210:
6211: @example
1.26 crook 6212: : def-word ( "name" -- )
1.29 crook 6213: CREATE @i{code1}
1.26 crook 6214: DOES> ( ... -- ... )
1.29 crook 6215: @i{code2} ;
1.26 crook 6216:
6217: def-word name
1.1 anton 6218: @end example
6219:
1.29 crook 6220: @cindex child words
6221: This fragment defines a @dfn{defining word} @code{def-word} and then
6222: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6223: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6224: is not executed at this time. The word @code{name} is sometimes called a
6225: @dfn{child} of @code{def-word}.
6226:
6227: When you execute @code{name}, the address of the body of @code{name} is
6228: put on the data stack and @i{code2} is executed (the address of the body
6229: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6230: @code{CREATE}, i.e., the address a @code{create}d word returns by
6231: default).
6232:
6233: @c anton:
6234: @c www.dictionary.com says:
6235: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6236: @c several generations of absence, usually caused by the chance
6237: @c recombination of genes. 2.An individual or a part that exhibits
6238: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6239: @c of previous behavior after a period of absence.
6240: @c
6241: @c Doesn't seem to fit.
1.29 crook 6242:
1.69 anton 6243: @c @cindex atavism in child words
1.33 anton 6244: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6245: similarly; they all have a common run-time behaviour determined by
6246: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6247: body of the child word. The structure of the data is common to all
6248: children of @code{def-word}, but the data values are specific -- and
6249: private -- to each child word. When a child word is executed, the
6250: address of its private data area is passed as a parameter on TOS to be
6251: used and manipulated@footnote{It is legitimate both to read and write to
6252: this data area.} by @i{code2}.
1.29 crook 6253:
6254: The two fragments of code that make up the defining words act (are
6255: executed) at two completely separate times:
1.1 anton 6256:
1.29 crook 6257: @itemize @bullet
6258: @item
6259: At @i{define time}, the defining word executes @i{code1} to generate a
6260: child word
6261: @item
6262: At @i{child execution time}, when a child word is invoked, @i{code2}
6263: is executed, using parameters (data) that are private and specific to
6264: the child word.
6265: @end itemize
6266:
1.44 crook 6267: Another way of understanding the behaviour of @code{def-word} and
6268: @code{name} is to say that, if you make the following definitions:
1.33 anton 6269: @example
6270: : def-word1 ( "name" -- )
6271: CREATE @i{code1} ;
6272:
6273: : action1 ( ... -- ... )
6274: @i{code2} ;
6275:
6276: def-word1 name1
6277: @end example
6278:
1.44 crook 6279: @noindent
6280: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6281:
1.29 crook 6282: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6283:
1.1 anton 6284: @example
1.29 crook 6285: : CONSTANT ( w "name" -- )
6286: CREATE ,
1.26 crook 6287: DOES> ( -- w )
6288: @@ ;
1.1 anton 6289: @end example
6290:
1.29 crook 6291: @comment There is a beautiful description of how this works and what
6292: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6293: @comment commentary on the Counting Fruits problem.
6294:
6295: When you create a constant with @code{5 CONSTANT five}, a set of
6296: define-time actions take place; first a new word @code{five} is created,
6297: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6298: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6299: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6300: no code of its own; it simply contains a data field and a pointer to the
6301: code that follows @code{DOES>} in its defining word. That makes words
6302: created in this way very compact.
6303:
6304: The final example in this section is intended to remind you that space
6305: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6306: both read and written by a Standard program@footnote{Exercise: use this
6307: example as a starting point for your own implementation of @code{Value}
6308: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6309: @code{[']}.}:
6310:
6311: @example
6312: : foo ( "name" -- )
6313: CREATE -1 ,
6314: DOES> ( -- )
1.33 anton 6315: @@ . ;
1.29 crook 6316:
6317: foo first-word
6318: foo second-word
6319:
6320: 123 ' first-word >BODY !
6321: @end example
6322:
6323: If @code{first-word} had been a @code{CREATE}d word, we could simply
6324: have executed it to get the address of its data field. However, since it
6325: was defined to have @code{DOES>} actions, its execution semantics are to
6326: perform those @code{DOES>} actions. To get the address of its data field
6327: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6328: translate the xt into the address of the data field. When you execute
6329: @code{first-word}, it will display @code{123}. When you execute
6330: @code{second-word} it will display @code{-1}.
1.26 crook 6331:
6332: @cindex stack effect of @code{DOES>}-parts
6333: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6334: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6335: the stack effect of the defined words, not the stack effect of the
6336: following code (the following code expects the address of the body on
6337: the top of stack, which is not reflected in the stack comment). This is
6338: the convention that I use and recommend (it clashes a bit with using
6339: locals declarations for stack effect specification, though).
1.1 anton 6340:
1.53 anton 6341: @menu
6342: * CREATE..DOES> applications::
6343: * CREATE..DOES> details::
1.63 anton 6344: * Advanced does> usage example::
1.155 anton 6345: * Const-does>::
1.53 anton 6346: @end menu
6347:
6348: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6349: @subsubsection Applications of @code{CREATE..DOES>}
6350: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6351:
1.26 crook 6352: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6353:
1.26 crook 6354: @cindex factoring similar colon definitions
6355: When you see a sequence of code occurring several times, and you can
6356: identify a meaning, you will factor it out as a colon definition. When
6357: you see similar colon definitions, you can factor them using
6358: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6359: that look very similar:
1.1 anton 6360: @example
1.26 crook 6361: : ori, ( reg-target reg-source n -- )
6362: 0 asm-reg-reg-imm ;
6363: : andi, ( reg-target reg-source n -- )
6364: 1 asm-reg-reg-imm ;
1.1 anton 6365: @end example
6366:
1.26 crook 6367: @noindent
6368: This could be factored with:
6369: @example
6370: : reg-reg-imm ( op-code -- )
6371: CREATE ,
6372: DOES> ( reg-target reg-source n -- )
6373: @@ asm-reg-reg-imm ;
6374:
6375: 0 reg-reg-imm ori,
6376: 1 reg-reg-imm andi,
6377: @end example
1.1 anton 6378:
1.26 crook 6379: @cindex currying
6380: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6381: supply a part of the parameters for a word (known as @dfn{currying} in
6382: the functional language community). E.g., @code{+} needs two
6383: parameters. Creating versions of @code{+} with one parameter fixed can
6384: be done like this:
1.82 anton 6385:
1.1 anton 6386: @example
1.82 anton 6387: : curry+ ( n1 "name" -- )
1.26 crook 6388: CREATE ,
6389: DOES> ( n2 -- n1+n2 )
6390: @@ + ;
6391:
6392: 3 curry+ 3+
6393: -2 curry+ 2-
1.1 anton 6394: @end example
6395:
1.91 anton 6396:
1.63 anton 6397: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6398: @subsubsection The gory details of @code{CREATE..DOES>}
6399: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6400:
1.26 crook 6401: doc-does>
1.1 anton 6402:
1.26 crook 6403: @cindex @code{DOES>} in a separate definition
6404: This means that you need not use @code{CREATE} and @code{DOES>} in the
6405: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6406: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6407: @example
6408: : does1
6409: DOES> ( ... -- ... )
1.44 crook 6410: ... ;
6411:
6412: : does2
6413: DOES> ( ... -- ... )
6414: ... ;
6415:
6416: : def-word ( ... -- ... )
6417: create ...
6418: IF
6419: does1
6420: ELSE
6421: does2
6422: ENDIF ;
6423: @end example
6424:
6425: In this example, the selection of whether to use @code{does1} or
1.69 anton 6426: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6427: @code{CREATE}d.
6428:
6429: @cindex @code{DOES>} in interpretation state
6430: In a standard program you can apply a @code{DOES>}-part only if the last
6431: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6432: will override the behaviour of the last word defined in any case. In a
6433: standard program, you can use @code{DOES>} only in a colon
6434: definition. In Gforth, you can also use it in interpretation state, in a
6435: kind of one-shot mode; for example:
6436: @example
6437: CREATE name ( ... -- ... )
6438: @i{initialization}
6439: DOES>
6440: @i{code} ;
6441: @end example
6442:
6443: @noindent
6444: is equivalent to the standard:
6445: @example
6446: :noname
6447: DOES>
6448: @i{code} ;
6449: CREATE name EXECUTE ( ... -- ... )
6450: @i{initialization}
6451: @end example
6452:
1.53 anton 6453: doc->body
6454:
1.152 pazsan 6455: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6456: @subsubsection Advanced does> usage example
6457:
6458: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6459: for disassembling instructions, that follow a very repetetive scheme:
6460:
6461: @example
6462: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6463: @var{entry-num} cells @var{table} + !
6464: @end example
6465:
6466: Of course, this inspires the idea to factor out the commonalities to
6467: allow a definition like
6468:
6469: @example
6470: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6471: @end example
6472:
6473: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6474: correlated. Moreover, before I wrote the disassembler, there already
6475: existed code that defines instructions like this:
1.63 anton 6476:
6477: @example
6478: @var{entry-num} @var{inst-format} @var{inst-name}
6479: @end example
6480:
6481: This code comes from the assembler and resides in
6482: @file{arch/mips/insts.fs}.
6483:
6484: So I had to define the @var{inst-format} words that performed the scheme
6485: above when executed. At first I chose to use run-time code-generation:
6486:
6487: @example
6488: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6489: :noname Postpone @var{disasm-operands}
6490: name Postpone sliteral Postpone type Postpone ;
6491: swap cells @var{table} + ! ;
6492: @end example
6493:
6494: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6495:
1.63 anton 6496: An alternative would have been to write this using
6497: @code{create}/@code{does>}:
6498:
6499: @example
6500: : @var{inst-format} ( entry-num "name" -- )
6501: here name string, ( entry-num c-addr ) \ parse and save "name"
6502: noname create , ( entry-num )
1.116 anton 6503: latestxt swap cells @var{table} + !
1.63 anton 6504: does> ( addr w -- )
6505: \ disassemble instruction w at addr
6506: @@ >r
6507: @var{disasm-operands}
6508: r> count type ;
6509: @end example
6510:
6511: Somehow the first solution is simpler, mainly because it's simpler to
6512: shift a string from definition-time to use-time with @code{sliteral}
6513: than with @code{string,} and friends.
6514:
6515: I wrote a lot of words following this scheme and soon thought about
6516: factoring out the commonalities among them. Note that this uses a
6517: two-level defining word, i.e., a word that defines ordinary defining
6518: words.
6519:
6520: This time a solution involving @code{postpone} and friends seemed more
6521: difficult (try it as an exercise), so I decided to use a
6522: @code{create}/@code{does>} word; since I was already at it, I also used
6523: @code{create}/@code{does>} for the lower level (try using
6524: @code{postpone} etc. as an exercise), resulting in the following
6525: definition:
6526:
6527: @example
6528: : define-format ( disasm-xt table-xt -- )
6529: \ define an instruction format that uses disasm-xt for
6530: \ disassembling and enters the defined instructions into table
6531: \ table-xt
6532: create 2,
6533: does> ( u "inst" -- )
6534: \ defines an anonymous word for disassembling instruction inst,
6535: \ and enters it as u-th entry into table-xt
6536: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6537: noname create 2, \ define anonymous word
1.116 anton 6538: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6539: does> ( addr w -- )
6540: \ disassemble instruction w at addr
6541: 2@@ >r ( addr w disasm-xt R: c-addr )
6542: execute ( R: c-addr ) \ disassemble operands
6543: r> count type ; \ print name
6544: @end example
6545:
6546: Note that the tables here (in contrast to above) do the @code{cells +}
6547: by themselves (that's why you have to pass an xt). This word is used in
6548: the following way:
6549:
6550: @example
6551: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6552: @end example
6553:
1.71 anton 6554: As shown above, the defined instruction format is then used like this:
6555:
6556: @example
6557: @var{entry-num} @var{inst-format} @var{inst-name}
6558: @end example
6559:
1.63 anton 6560: In terms of currying, this kind of two-level defining word provides the
6561: parameters in three stages: first @var{disasm-operands} and @var{table},
6562: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6563: the instruction to be disassembled.
6564:
6565: Of course this did not quite fit all the instruction format names used
6566: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6567: the parameters into the right form.
6568:
6569: If you have trouble following this section, don't worry. First, this is
6570: involved and takes time (and probably some playing around) to
6571: understand; second, this is the first two-level
6572: @code{create}/@code{does>} word I have written in seventeen years of
6573: Forth; and if I did not have @file{insts.fs} to start with, I may well
6574: have elected to use just a one-level defining word (with some repeating
6575: of parameters when using the defining word). So it is not necessary to
6576: understand this, but it may improve your understanding of Forth.
1.44 crook 6577:
6578:
1.152 pazsan 6579: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6580: @subsubsection @code{Const-does>}
6581:
6582: A frequent use of @code{create}...@code{does>} is for transferring some
6583: values from definition-time to run-time. Gforth supports this use with
6584:
6585: doc-const-does>
6586:
6587: A typical use of this word is:
6588:
6589: @example
6590: : curry+ ( n1 "name" -- )
6591: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6592: + ;
6593:
6594: 3 curry+ 3+
6595: @end example
6596:
6597: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6598: definition to run-time.
6599:
6600: The advantages of using @code{const-does>} are:
6601:
6602: @itemize
6603:
6604: @item
6605: You don't have to deal with storing and retrieving the values, i.e.,
6606: your program becomes more writable and readable.
6607:
6608: @item
6609: When using @code{does>}, you have to introduce a @code{@@} that cannot
6610: be optimized away (because you could change the data using
6611: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6612:
6613: @end itemize
6614:
6615: An ANS Forth implementation of @code{const-does>} is available in
6616: @file{compat/const-does.fs}.
6617:
6618:
1.44 crook 6619: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6620: @subsection Deferred words
6621: @cindex deferred words
6622:
6623: The defining word @code{Defer} allows you to define a word by name
6624: without defining its behaviour; the definition of its behaviour is
6625: deferred. Here are two situation where this can be useful:
6626:
6627: @itemize @bullet
6628: @item
6629: Where you want to allow the behaviour of a word to be altered later, and
6630: for all precompiled references to the word to change when its behaviour
6631: is changed.
6632: @item
6633: For mutual recursion; @xref{Calls and returns}.
6634: @end itemize
6635:
6636: In the following example, @code{foo} always invokes the version of
6637: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6638: always invokes the version that prints ``@code{Hello}''. There is no way
6639: of getting @code{foo} to use the later version without re-ordering the
6640: source code and recompiling it.
6641:
6642: @example
6643: : greet ." Good morning" ;
6644: : foo ... greet ... ;
6645: : greet ." Hello" ;
6646: : bar ... greet ... ;
6647: @end example
6648:
6649: This problem can be solved by defining @code{greet} as a @code{Defer}red
6650: word. The behaviour of a @code{Defer}red word can be defined and
6651: redefined at any time by using @code{IS} to associate the xt of a
6652: previously-defined word with it. The previous example becomes:
6653:
6654: @example
1.69 anton 6655: Defer greet ( -- )
1.44 crook 6656: : foo ... greet ... ;
6657: : bar ... greet ... ;
1.69 anton 6658: : greet1 ( -- ) ." Good morning" ;
6659: : greet2 ( -- ) ." Hello" ;
1.132 anton 6660: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6661: @end example
6662:
1.69 anton 6663: @progstyle
6664: You should write a stack comment for every deferred word, and put only
6665: XTs into deferred words that conform to this stack effect. Otherwise
6666: it's too difficult to use the deferred word.
6667:
1.44 crook 6668: A deferred word can be used to improve the statistics-gathering example
6669: from @ref{User-defined Defining Words}; rather than edit the
6670: application's source code to change every @code{:} to a @code{my:}, do
6671: this:
6672:
6673: @example
6674: : real: : ; \ retain access to the original
6675: defer : \ redefine as a deferred word
1.132 anton 6676: ' my: IS : \ use special version of :
1.44 crook 6677: \
6678: \ load application here
6679: \
1.132 anton 6680: ' real: IS : \ go back to the original
1.44 crook 6681: @end example
6682:
6683:
1.132 anton 6684: One thing to note is that @code{IS} has special compilation semantics,
6685: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6686:
6687: @example
6688: : set-greet ( xt -- )
1.132 anton 6689: IS greet ;
1.44 crook 6690:
6691: ' greet1 set-greet
6692: @end example
6693:
1.132 anton 6694: In situations where @code{IS} does not fit, use @code{defer!} instead.
6695:
1.69 anton 6696: A deferred word can only inherit execution semantics from the xt
6697: (because that is all that an xt can represent -- for more discussion of
6698: this @pxref{Tokens for Words}); by default it will have default
6699: interpretation and compilation semantics deriving from this execution
6700: semantics. However, you can change the interpretation and compilation
6701: semantics of the deferred word in the usual ways:
1.44 crook 6702:
6703: @example
1.132 anton 6704: : bar .... ; immediate
1.44 crook 6705: Defer fred immediate
6706: Defer jim
6707:
1.132 anton 6708: ' bar IS jim \ jim has default semantics
6709: ' bar IS fred \ fred is immediate
1.44 crook 6710: @end example
6711:
6712: doc-defer
1.132 anton 6713: doc-defer!
1.44 crook 6714: doc-is
1.132 anton 6715: doc-defer@
6716: doc-action-of
1.44 crook 6717: @comment TODO document these: what's defers [is]
6718: doc-defers
6719:
6720: @c Use @code{words-deferred} to see a list of deferred words.
6721:
1.132 anton 6722: Definitions of these words (except @code{defers}) in ANS Forth are
6723: provided in @file{compat/defer.fs}.
1.44 crook 6724:
6725:
1.69 anton 6726: @node Aliases, , Deferred words, Defining Words
1.44 crook 6727: @subsection Aliases
6728: @cindex aliases
1.1 anton 6729:
1.44 crook 6730: The defining word @code{Alias} allows you to define a word by name that
6731: has the same behaviour as some other word. Here are two situation where
6732: this can be useful:
1.1 anton 6733:
1.44 crook 6734: @itemize @bullet
6735: @item
6736: When you want access to a word's definition from a different word list
6737: (for an example of this, see the definition of the @code{Root} word list
6738: in the Gforth source).
6739: @item
6740: When you want to create a synonym; a definition that can be known by
6741: either of two names (for example, @code{THEN} and @code{ENDIF} are
6742: aliases).
6743: @end itemize
1.1 anton 6744:
1.69 anton 6745: Like deferred words, an alias has default compilation and interpretation
6746: semantics at the beginning (not the modifications of the other word),
6747: but you can change them in the usual ways (@code{immediate},
6748: @code{compile-only}). For example:
1.1 anton 6749:
6750: @example
1.44 crook 6751: : foo ... ; immediate
6752:
6753: ' foo Alias bar \ bar is not an immediate word
6754: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6755: @end example
6756:
1.44 crook 6757: Words that are aliases have the same xt, different headers in the
6758: dictionary, and consequently different name tokens (@pxref{Tokens for
6759: Words}) and possibly different immediate flags. An alias can only have
6760: default or immediate compilation semantics; you can define aliases for
6761: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6762:
1.44 crook 6763: doc-alias
1.1 anton 6764:
6765:
1.47 crook 6766: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6767: @section Interpretation and Compilation Semantics
1.26 crook 6768: @cindex semantics, interpretation and compilation
1.1 anton 6769:
1.71 anton 6770: @c !! state and ' are used without explanation
6771: @c example for immediate/compile-only? or is the tutorial enough
6772:
1.26 crook 6773: @cindex interpretation semantics
1.71 anton 6774: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6775: interpreter does when it encounters the word in interpret state. It also
6776: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6777: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6778: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6779: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6780:
1.26 crook 6781: @cindex compilation semantics
1.71 anton 6782: The @dfn{compilation semantics} of a (named) word are what the text
6783: interpreter does when it encounters the word in compile state. It also
6784: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6785: compiles@footnote{In standard terminology, ``appends to the current
6786: definition''.} the compilation semantics of @i{word}.
1.1 anton 6787:
1.26 crook 6788: @cindex execution semantics
6789: The standard also talks about @dfn{execution semantics}. They are used
6790: only for defining the interpretation and compilation semantics of many
6791: words. By default, the interpretation semantics of a word are to
6792: @code{execute} its execution semantics, and the compilation semantics of
6793: a word are to @code{compile,} its execution semantics.@footnote{In
6794: standard terminology: The default interpretation semantics are its
6795: execution semantics; the default compilation semantics are to append its
6796: execution semantics to the execution semantics of the current
6797: definition.}
6798:
1.71 anton 6799: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6800: the text interpreter, ticked, or @code{postpone}d, so they have no
6801: interpretation or compilation semantics. Their behaviour is represented
6802: by their XT (@pxref{Tokens for Words}), and we call it execution
6803: semantics, too.
6804:
1.26 crook 6805: @comment TODO expand, make it co-operate with new sections on text interpreter.
6806:
6807: @cindex immediate words
6808: @cindex compile-only words
6809: You can change the semantics of the most-recently defined word:
6810:
1.44 crook 6811:
1.26 crook 6812: doc-immediate
6813: doc-compile-only
6814: doc-restrict
6815:
1.82 anton 6816: By convention, words with non-default compilation semantics (e.g.,
6817: immediate words) often have names surrounded with brackets (e.g.,
6818: @code{[']}, @pxref{Execution token}).
1.44 crook 6819:
1.26 crook 6820: Note that ticking (@code{'}) a compile-only word gives an error
6821: (``Interpreting a compile-only word'').
1.1 anton 6822:
1.47 crook 6823: @menu
1.67 anton 6824: * Combined words::
1.47 crook 6825: @end menu
1.44 crook 6826:
1.71 anton 6827:
1.48 anton 6828: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6829: @subsection Combined Words
6830: @cindex combined words
6831:
6832: Gforth allows you to define @dfn{combined words} -- words that have an
6833: arbitrary combination of interpretation and compilation semantics.
6834:
1.26 crook 6835: doc-interpret/compile:
1.1 anton 6836:
1.26 crook 6837: This feature was introduced for implementing @code{TO} and @code{S"}. I
6838: recommend that you do not define such words, as cute as they may be:
6839: they make it hard to get at both parts of the word in some contexts.
6840: E.g., assume you want to get an execution token for the compilation
6841: part. Instead, define two words, one that embodies the interpretation
6842: part, and one that embodies the compilation part. Once you have done
6843: that, you can define a combined word with @code{interpret/compile:} for
6844: the convenience of your users.
1.1 anton 6845:
1.26 crook 6846: You might try to use this feature to provide an optimizing
6847: implementation of the default compilation semantics of a word. For
6848: example, by defining:
1.1 anton 6849: @example
1.26 crook 6850: :noname
6851: foo bar ;
6852: :noname
6853: POSTPONE foo POSTPONE bar ;
1.29 crook 6854: interpret/compile: opti-foobar
1.1 anton 6855: @end example
1.26 crook 6856:
1.23 crook 6857: @noindent
1.26 crook 6858: as an optimizing version of:
6859:
1.1 anton 6860: @example
1.26 crook 6861: : foobar
6862: foo bar ;
1.1 anton 6863: @end example
6864:
1.26 crook 6865: Unfortunately, this does not work correctly with @code{[compile]},
6866: because @code{[compile]} assumes that the compilation semantics of all
6867: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6868: opti-foobar} would compile compilation semantics, whereas
6869: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6870:
1.26 crook 6871: @cindex state-smart words (are a bad idea)
1.82 anton 6872: @anchor{state-smartness}
1.29 crook 6873: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6874: by @code{interpret/compile:} (words are state-smart if they check
6875: @code{STATE} during execution). E.g., they would try to code
6876: @code{foobar} like this:
1.1 anton 6877:
1.26 crook 6878: @example
6879: : foobar
6880: STATE @@
6881: IF ( compilation state )
6882: POSTPONE foo POSTPONE bar
6883: ELSE
6884: foo bar
6885: ENDIF ; immediate
6886: @end example
1.1 anton 6887:
1.26 crook 6888: Although this works if @code{foobar} is only processed by the text
6889: interpreter, it does not work in other contexts (like @code{'} or
6890: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6891: for a state-smart word, not for the interpretation semantics of the
6892: original @code{foobar}; when you execute this execution token (directly
6893: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6894: state, the result will not be what you expected (i.e., it will not
6895: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6896: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6897: M. Anton Ertl,
6898: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6899: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6900:
1.26 crook 6901: @cindex defining words with arbitrary semantics combinations
6902: It is also possible to write defining words that define words with
6903: arbitrary combinations of interpretation and compilation semantics. In
6904: general, they look like this:
1.1 anton 6905:
1.26 crook 6906: @example
6907: : def-word
6908: create-interpret/compile
1.29 crook 6909: @i{code1}
1.26 crook 6910: interpretation>
1.29 crook 6911: @i{code2}
1.26 crook 6912: <interpretation
6913: compilation>
1.29 crook 6914: @i{code3}
1.26 crook 6915: <compilation ;
6916: @end example
1.1 anton 6917:
1.29 crook 6918: For a @i{word} defined with @code{def-word}, the interpretation
6919: semantics are to push the address of the body of @i{word} and perform
6920: @i{code2}, and the compilation semantics are to push the address of
6921: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6922: can also be defined like this (except that the defined constants don't
6923: behave correctly when @code{[compile]}d):
1.1 anton 6924:
1.26 crook 6925: @example
6926: : constant ( n "name" -- )
6927: create-interpret/compile
6928: ,
6929: interpretation> ( -- n )
6930: @@
6931: <interpretation
6932: compilation> ( compilation. -- ; run-time. -- n )
6933: @@ postpone literal
6934: <compilation ;
6935: @end example
1.1 anton 6936:
1.44 crook 6937:
1.26 crook 6938: doc-create-interpret/compile
6939: doc-interpretation>
6940: doc-<interpretation
6941: doc-compilation>
6942: doc-<compilation
1.1 anton 6943:
1.44 crook 6944:
1.29 crook 6945: Words defined with @code{interpret/compile:} and
1.26 crook 6946: @code{create-interpret/compile} have an extended header structure that
6947: differs from other words; however, unless you try to access them with
6948: plain address arithmetic, you should not notice this. Words for
6949: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6950: @code{'} @i{word} @code{>body} also gives you the body of a word created
6951: with @code{create-interpret/compile}.
1.1 anton 6952:
1.44 crook 6953:
1.47 crook 6954: @c -------------------------------------------------------------
1.81 anton 6955: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6956: @section Tokens for Words
6957: @cindex tokens for words
6958:
6959: This section describes the creation and use of tokens that represent
6960: words.
6961:
1.71 anton 6962: @menu
6963: * Execution token:: represents execution/interpretation semantics
6964: * Compilation token:: represents compilation semantics
6965: * Name token:: represents named words
6966: @end menu
1.47 crook 6967:
1.71 anton 6968: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6969: @subsection Execution token
1.47 crook 6970:
6971: @cindex xt
6972: @cindex execution token
1.71 anton 6973: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6974: You can use @code{execute} to invoke this behaviour.
1.47 crook 6975:
1.71 anton 6976: @cindex tick (')
6977: You can use @code{'} to get an execution token that represents the
6978: interpretation semantics of a named word:
1.47 crook 6979:
6980: @example
1.97 anton 6981: 5 ' . ( n xt )
6982: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6983: @end example
1.47 crook 6984:
1.71 anton 6985: doc-'
6986:
6987: @code{'} parses at run-time; there is also a word @code{[']} that parses
6988: when it is compiled, and compiles the resulting XT:
6989:
6990: @example
6991: : foo ['] . execute ;
6992: 5 foo
6993: : bar ' execute ; \ by contrast,
6994: 5 bar . \ ' parses "." when bar executes
6995: @end example
6996:
6997: doc-[']
6998:
6999: If you want the execution token of @i{word}, write @code{['] @i{word}}
7000: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7001: @code{'} and @code{[']} behave somewhat unusually by complaining about
7002: compile-only words (because these words have no interpretation
7003: semantics). You might get what you want by using @code{COMP' @i{word}
7004: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7005: token}).
7006:
1.116 anton 7007: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7008: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7009: for the only behaviour the word has (the execution semantics). For
1.116 anton 7010: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7011: would produce if the word was defined anonymously.
7012:
7013: @example
7014: :noname ." hello" ;
7015: execute
1.47 crook 7016: @end example
7017:
1.71 anton 7018: An XT occupies one cell and can be manipulated like any other cell.
7019:
1.47 crook 7020: @cindex code field address
7021: @cindex CFA
1.71 anton 7022: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7023: operations that produce or consume it). For old hands: In Gforth, the
7024: XT is implemented as a code field address (CFA).
7025:
7026: doc-execute
7027: doc-perform
7028:
7029: @node Compilation token, Name token, Execution token, Tokens for Words
7030: @subsection Compilation token
1.47 crook 7031:
7032: @cindex compilation token
1.71 anton 7033: @cindex CT (compilation token)
7034: Gforth represents the compilation semantics of a named word by a
1.47 crook 7035: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7036: @i{xt} is an execution token. The compilation semantics represented by
7037: the compilation token can be performed with @code{execute}, which
7038: consumes the whole compilation token, with an additional stack effect
7039: determined by the represented compilation semantics.
7040:
7041: At present, the @i{w} part of a compilation token is an execution token,
7042: and the @i{xt} part represents either @code{execute} or
7043: @code{compile,}@footnote{Depending upon the compilation semantics of the
7044: word. If the word has default compilation semantics, the @i{xt} will
7045: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7046: @i{xt} will represent @code{execute}.}. However, don't rely on that
7047: knowledge, unless necessary; future versions of Gforth may introduce
7048: unusual compilation tokens (e.g., a compilation token that represents
7049: the compilation semantics of a literal).
7050:
1.71 anton 7051: You can perform the compilation semantics represented by the compilation
7052: token with @code{execute}. You can compile the compilation semantics
7053: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7054: equivalent to @code{postpone @i{word}}.
7055:
7056: doc-[comp']
7057: doc-comp'
7058: doc-postpone,
7059:
7060: @node Name token, , Compilation token, Tokens for Words
7061: @subsection Name token
1.47 crook 7062:
7063: @cindex name token
1.116 anton 7064: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7065: token is an abstract data type that occurs as argument or result of the
7066: words below.
7067:
7068: @c !! put this elswhere?
1.47 crook 7069: @cindex name field address
7070: @cindex NFA
1.116 anton 7071: The closest thing to the nt in older Forth systems is the name field
7072: address (NFA), but there are significant differences: in older Forth
7073: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7074: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7075: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7076: is a link field in the structure identified by the name token, but
7077: searching usually uses a hash table external to these structures; the
7078: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7079: implemented as the address of that count field.
1.47 crook 7080:
7081: doc-find-name
1.116 anton 7082: doc-latest
7083: doc->name
1.47 crook 7084: doc-name>int
7085: doc-name?int
7086: doc-name>comp
7087: doc-name>string
1.109 anton 7088: doc-id.
7089: doc-.name
7090: doc-.id
1.47 crook 7091:
1.81 anton 7092: @c ----------------------------------------------------------
7093: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7094: @section Compiling words
7095: @cindex compiling words
7096: @cindex macros
7097:
7098: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7099: between compilation and run-time. E.g., you can run arbitrary code
7100: between defining words (or for computing data used by defining words
7101: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7102: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7103: running arbitrary code while compiling a colon definition (exception:
7104: you must not allot dictionary space).
7105:
7106: @menu
7107: * Literals:: Compiling data values
7108: * Macros:: Compiling words
7109: @end menu
7110:
7111: @node Literals, Macros, Compiling words, Compiling words
7112: @subsection Literals
7113: @cindex Literals
7114:
7115: The simplest and most frequent example is to compute a literal during
7116: compilation. E.g., the following definition prints an array of strings,
7117: one string per line:
7118:
7119: @example
7120: : .strings ( addr u -- ) \ gforth
7121: 2* cells bounds U+DO
7122: cr i 2@@ type
7123: 2 cells +LOOP ;
7124: @end example
1.81 anton 7125:
1.82 anton 7126: With a simple-minded compiler like Gforth's, this computes @code{2
7127: cells} on every loop iteration. You can compute this value once and for
7128: all at compile time and compile it into the definition like this:
7129:
7130: @example
7131: : .strings ( addr u -- ) \ gforth
7132: 2* cells bounds U+DO
7133: cr i 2@@ type
7134: [ 2 cells ] literal +LOOP ;
7135: @end example
7136:
7137: @code{[} switches the text interpreter to interpret state (you will get
7138: an @code{ok} prompt if you type this example interactively and insert a
7139: newline between @code{[} and @code{]}), so it performs the
7140: interpretation semantics of @code{2 cells}; this computes a number.
7141: @code{]} switches the text interpreter back into compile state. It then
7142: performs @code{Literal}'s compilation semantics, which are to compile
7143: this number into the current word. You can decompile the word with
7144: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7145:
1.82 anton 7146: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7147: *} in this way.
1.81 anton 7148:
1.82 anton 7149: doc-[
7150: doc-]
1.81 anton 7151: doc-literal
7152: doc-]L
1.82 anton 7153:
7154: There are also words for compiling other data types than single cells as
7155: literals:
7156:
1.81 anton 7157: doc-2literal
7158: doc-fliteral
1.82 anton 7159: doc-sliteral
7160:
7161: @cindex colon-sys, passing data across @code{:}
7162: @cindex @code{:}, passing data across
7163: You might be tempted to pass data from outside a colon definition to the
7164: inside on the data stack. This does not work, because @code{:} puhes a
7165: colon-sys, making stuff below unaccessible. E.g., this does not work:
7166:
7167: @example
7168: 5 : foo literal ; \ error: "unstructured"
7169: @end example
7170:
7171: Instead, you have to pass the value in some other way, e.g., through a
7172: variable:
7173:
7174: @example
7175: variable temp
7176: 5 temp !
7177: : foo [ temp @@ ] literal ;
7178: @end example
7179:
7180:
7181: @node Macros, , Literals, Compiling words
7182: @subsection Macros
7183: @cindex Macros
7184: @cindex compiling compilation semantics
7185:
7186: @code{Literal} and friends compile data values into the current
7187: definition. You can also write words that compile other words into the
7188: current definition. E.g.,
7189:
7190: @example
7191: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7192: POSTPONE + ;
7193:
7194: : foo ( n1 n2 -- n )
7195: [ compile-+ ] ;
7196: 1 2 foo .
7197: @end example
7198:
7199: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7200: What happens in this example? @code{Postpone} compiles the compilation
7201: semantics of @code{+} into @code{compile-+}; later the text interpreter
7202: executes @code{compile-+} and thus the compilation semantics of +, which
7203: compile (the execution semantics of) @code{+} into
7204: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7205: should only be executed in compile state, so this example is not
7206: guaranteed to work on all standard systems, but on any decent system it
7207: will work.}
7208:
7209: doc-postpone
7210: doc-[compile]
7211:
7212: Compiling words like @code{compile-+} are usually immediate (or similar)
7213: so you do not have to switch to interpret state to execute them;
7214: mopifying the last example accordingly produces:
7215:
7216: @example
7217: : [compile-+] ( compilation: --; interpretation: -- )
7218: \ compiled code: ( n1 n2 -- n )
7219: POSTPONE + ; immediate
7220:
7221: : foo ( n1 n2 -- n )
7222: [compile-+] ;
7223: 1 2 foo .
7224: @end example
7225:
7226: Immediate compiling words are similar to macros in other languages (in
7227: particular, Lisp). The important differences to macros in, e.g., C are:
7228:
7229: @itemize @bullet
7230:
7231: @item
7232: You use the same language for defining and processing macros, not a
7233: separate preprocessing language and processor.
7234:
7235: @item
7236: Consequently, the full power of Forth is available in macro definitions.
7237: E.g., you can perform arbitrarily complex computations, or generate
7238: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7239: Tutorial}). This power is very useful when writing a parser generators
7240: or other code-generating software.
7241:
7242: @item
7243: Macros defined using @code{postpone} etc. deal with the language at a
7244: higher level than strings; name binding happens at macro definition
7245: time, so you can avoid the pitfalls of name collisions that can happen
7246: in C macros. Of course, Forth is a liberal language and also allows to
7247: shoot yourself in the foot with text-interpreted macros like
7248:
7249: @example
7250: : [compile-+] s" +" evaluate ; immediate
7251: @end example
7252:
7253: Apart from binding the name at macro use time, using @code{evaluate}
7254: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7255: @end itemize
7256:
7257: You may want the macro to compile a number into a word. The word to do
7258: it is @code{literal}, but you have to @code{postpone} it, so its
7259: compilation semantics take effect when the macro is executed, not when
7260: it is compiled:
7261:
7262: @example
7263: : [compile-5] ( -- ) \ compiled code: ( -- n )
7264: 5 POSTPONE literal ; immediate
7265:
7266: : foo [compile-5] ;
7267: foo .
7268: @end example
7269:
7270: You may want to pass parameters to a macro, that the macro should
7271: compile into the current definition. If the parameter is a number, then
7272: you can use @code{postpone literal} (similar for other values).
7273:
7274: If you want to pass a word that is to be compiled, the usual way is to
7275: pass an execution token and @code{compile,} it:
7276:
7277: @example
7278: : twice1 ( xt -- ) \ compiled code: ... -- ...
7279: dup compile, compile, ;
7280:
7281: : 2+ ( n1 -- n2 )
7282: [ ' 1+ twice1 ] ;
7283: @end example
7284:
7285: doc-compile,
7286:
7287: An alternative available in Gforth, that allows you to pass compile-only
7288: words as parameters is to use the compilation token (@pxref{Compilation
7289: token}). The same example in this technique:
7290:
7291: @example
7292: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7293: 2dup 2>r execute 2r> execute ;
7294:
7295: : 2+ ( n1 -- n2 )
7296: [ comp' 1+ twice ] ;
7297: @end example
7298:
7299: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7300: works even if the executed compilation semantics has an effect on the
7301: data stack.
7302:
7303: You can also define complete definitions with these words; this provides
7304: an alternative to using @code{does>} (@pxref{User-defined Defining
7305: Words}). E.g., instead of
7306:
7307: @example
7308: : curry+ ( n1 "name" -- )
7309: CREATE ,
7310: DOES> ( n2 -- n1+n2 )
7311: @@ + ;
7312: @end example
7313:
7314: you could define
7315:
7316: @example
7317: : curry+ ( n1 "name" -- )
7318: \ name execution: ( n2 -- n1+n2 )
7319: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7320:
1.82 anton 7321: -3 curry+ 3-
7322: see 3-
7323: @end example
1.81 anton 7324:
1.82 anton 7325: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7326: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7327:
1.82 anton 7328: This way of writing defining words is sometimes more, sometimes less
7329: convenient than using @code{does>} (@pxref{Advanced does> usage
7330: example}). One advantage of this method is that it can be optimized
7331: better, because the compiler knows that the value compiled with
7332: @code{literal} is fixed, whereas the data associated with a
7333: @code{create}d word can be changed.
1.47 crook 7334:
1.26 crook 7335: @c ----------------------------------------------------------
1.111 anton 7336: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7337: @section The Text Interpreter
7338: @cindex interpreter - outer
7339: @cindex text interpreter
7340: @cindex outer interpreter
1.1 anton 7341:
1.34 anton 7342: @c Should we really describe all these ugly details? IMO the text
7343: @c interpreter should be much cleaner, but that may not be possible within
7344: @c ANS Forth. - anton
1.44 crook 7345: @c nac-> I wanted to explain how it works to show how you can exploit
7346: @c it in your own programs. When I was writing a cross-compiler, figuring out
7347: @c some of these gory details was very helpful to me. None of the textbooks
7348: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7349: @c seems to positively avoid going into too much detail for some of
7350: @c the internals.
1.34 anton 7351:
1.71 anton 7352: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7353: @c it is; for the ugly details, I would prefer another place. I wonder
7354: @c whether we should have a chapter before "Words" that describes some
7355: @c basic concepts referred to in words, and a chapter after "Words" that
7356: @c describes implementation details.
7357:
1.29 crook 7358: The text interpreter@footnote{This is an expanded version of the
7359: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7360: that processes input from the current input device. It is also called
7361: the outer interpreter, in contrast to the inner interpreter
7362: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7363: implementations.
1.27 crook 7364:
1.29 crook 7365: @cindex interpret state
7366: @cindex compile state
7367: The text interpreter operates in one of two states: @dfn{interpret
7368: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7369: aptly-named variable @code{state}.
1.29 crook 7370:
7371: This section starts by describing how the text interpreter behaves when
7372: it is in interpret state, processing input from the user input device --
7373: the keyboard. This is the mode that a Forth system is in after it starts
7374: up.
7375:
7376: @cindex input buffer
7377: @cindex terminal input buffer
7378: The text interpreter works from an area of memory called the @dfn{input
7379: buffer}@footnote{When the text interpreter is processing input from the
7380: keyboard, this area of memory is called the @dfn{terminal input buffer}
7381: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7382: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7383: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7384: leading spaces (called @dfn{delimiters}) then parses a string (a
7385: sequence of non-space characters) until it reaches either a space
7386: character or the end of the buffer. Having parsed a string, it makes two
7387: attempts to process it:
1.27 crook 7388:
1.29 crook 7389: @cindex dictionary
1.27 crook 7390: @itemize @bullet
7391: @item
1.29 crook 7392: It looks for the string in a @dfn{dictionary} of definitions. If the
7393: string is found, the string names a @dfn{definition} (also known as a
7394: @dfn{word}) and the dictionary search returns information that allows
7395: the text interpreter to perform the word's @dfn{interpretation
7396: semantics}. In most cases, this simply means that the word will be
7397: executed.
1.27 crook 7398: @item
7399: If the string is not found in the dictionary, the text interpreter
1.29 crook 7400: attempts to treat it as a number, using the rules described in
7401: @ref{Number Conversion}. If the string represents a legal number in the
7402: current radix, the number is pushed onto a parameter stack (the data
7403: stack for integers, the floating-point stack for floating-point
7404: numbers).
7405: @end itemize
7406:
7407: If both attempts fail, or if the word is found in the dictionary but has
7408: no interpretation semantics@footnote{This happens if the word was
7409: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7410: remainder of the input buffer, issues an error message and waits for
7411: more input. If one of the attempts succeeds, the text interpreter
7412: repeats the parsing process until the whole of the input buffer has been
7413: processed, at which point it prints the status message ``@code{ ok}''
7414: and waits for more input.
7415:
1.71 anton 7416: @c anton: this should be in the input stream subsection (or below it)
7417:
1.29 crook 7418: @cindex parse area
7419: The text interpreter keeps track of its position in the input buffer by
7420: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7421: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7422: of the input buffer. The region from offset @code{>IN @@} to the end of
7423: the input buffer is called the @dfn{parse area}@footnote{In other words,
7424: the text interpreter processes the contents of the input buffer by
7425: parsing strings from the parse area until the parse area is empty.}.
7426: This example shows how @code{>IN} changes as the text interpreter parses
7427: the input buffer:
7428:
7429: @example
7430: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7431: CR ." ->" TYPE ." <-" ; IMMEDIATE
7432:
7433: 1 2 3 remaining + remaining .
7434:
7435: : foo 1 2 3 remaining SWAP remaining ;
7436: @end example
7437:
7438: @noindent
7439: The result is:
7440:
7441: @example
7442: ->+ remaining .<-
7443: ->.<-5 ok
7444:
7445: ->SWAP remaining ;-<
7446: ->;<- ok
7447: @end example
7448:
7449: @cindex parsing words
7450: The value of @code{>IN} can also be modified by a word in the input
7451: buffer that is executed by the text interpreter. This means that a word
7452: can ``trick'' the text interpreter into either skipping a section of the
7453: input buffer@footnote{This is how parsing words work.} or into parsing a
7454: section twice. For example:
1.27 crook 7455:
1.29 crook 7456: @example
1.71 anton 7457: : lat ." <<foo>>" ;
7458: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7459: @end example
7460:
7461: @noindent
7462: When @code{flat} is executed, this output is produced@footnote{Exercise
7463: for the reader: what would happen if the @code{3} were replaced with
7464: @code{4}?}:
7465:
7466: @example
1.71 anton 7467: <<bar>><<foo>>
1.29 crook 7468: @end example
7469:
1.71 anton 7470: This technique can be used to work around some of the interoperability
7471: problems of parsing words. Of course, it's better to avoid parsing
7472: words where possible.
7473:
1.29 crook 7474: @noindent
7475: Two important notes about the behaviour of the text interpreter:
1.27 crook 7476:
7477: @itemize @bullet
7478: @item
7479: It processes each input string to completion before parsing additional
1.29 crook 7480: characters from the input buffer.
7481: @item
7482: It treats the input buffer as a read-only region (and so must your code).
7483: @end itemize
7484:
7485: @noindent
7486: When the text interpreter is in compile state, its behaviour changes in
7487: these ways:
7488:
7489: @itemize @bullet
7490: @item
7491: If a parsed string is found in the dictionary, the text interpreter will
7492: perform the word's @dfn{compilation semantics}. In most cases, this
7493: simply means that the execution semantics of the word will be appended
7494: to the current definition.
1.27 crook 7495: @item
1.29 crook 7496: When a number is encountered, it is compiled into the current definition
7497: (as a literal) rather than being pushed onto a parameter stack.
7498: @item
7499: If an error occurs, @code{state} is modified to put the text interpreter
7500: back into interpret state.
7501: @item
7502: Each time a line is entered from the keyboard, Gforth prints
7503: ``@code{ compiled}'' rather than `` @code{ok}''.
7504: @end itemize
7505:
7506: @cindex text interpreter - input sources
7507: When the text interpreter is using an input device other than the
7508: keyboard, its behaviour changes in these ways:
7509:
7510: @itemize @bullet
7511: @item
7512: When the parse area is empty, the text interpreter attempts to refill
7513: the input buffer from the input source. When the input source is
1.71 anton 7514: exhausted, the input source is set back to the previous input source.
1.29 crook 7515: @item
7516: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7517: time the parse area is emptied.
7518: @item
7519: If an error occurs, the input source is set back to the user input
7520: device.
1.27 crook 7521: @end itemize
1.21 crook 7522:
1.49 anton 7523: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7524:
1.26 crook 7525: doc->in
1.27 crook 7526: doc-source
7527:
1.26 crook 7528: doc-tib
7529: doc-#tib
1.1 anton 7530:
1.44 crook 7531:
1.26 crook 7532: @menu
1.67 anton 7533: * Input Sources::
7534: * Number Conversion::
7535: * Interpret/Compile states::
7536: * Interpreter Directives::
1.26 crook 7537: @end menu
1.1 anton 7538:
1.29 crook 7539: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7540: @subsection Input Sources
7541: @cindex input sources
7542: @cindex text interpreter - input sources
7543:
1.44 crook 7544: By default, the text interpreter processes input from the user input
1.29 crook 7545: device (the keyboard) when Forth starts up. The text interpreter can
7546: process input from any of these sources:
7547:
7548: @itemize @bullet
7549: @item
7550: The user input device -- the keyboard.
7551: @item
7552: A file, using the words described in @ref{Forth source files}.
7553: @item
7554: A block, using the words described in @ref{Blocks}.
7555: @item
7556: A text string, using @code{evaluate}.
7557: @end itemize
7558:
7559: A program can identify the current input device from the values of
7560: @code{source-id} and @code{blk}.
7561:
1.44 crook 7562:
1.29 crook 7563: doc-source-id
7564: doc-blk
7565:
7566: doc-save-input
7567: doc-restore-input
7568:
7569: doc-evaluate
1.111 anton 7570: doc-query
1.1 anton 7571:
1.29 crook 7572:
1.44 crook 7573:
1.29 crook 7574: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7575: @subsection Number Conversion
7576: @cindex number conversion
7577: @cindex double-cell numbers, input format
7578: @cindex input format for double-cell numbers
7579: @cindex single-cell numbers, input format
7580: @cindex input format for single-cell numbers
7581: @cindex floating-point numbers, input format
7582: @cindex input format for floating-point numbers
1.1 anton 7583:
1.29 crook 7584: This section describes the rules that the text interpreter uses when it
7585: tries to convert a string into a number.
1.1 anton 7586:
1.26 crook 7587: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7588: number base@footnote{For example, 0-9 when the number base is decimal or
7589: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7590:
1.26 crook 7591: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7592:
1.29 crook 7593: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7594: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7595:
1.26 crook 7596: Let * represent any number of instances of the previous character
7597: (including none).
1.1 anton 7598:
1.26 crook 7599: Let any other character represent itself.
1.1 anton 7600:
1.29 crook 7601: @noindent
1.26 crook 7602: Now, the conversion rules are:
1.21 crook 7603:
1.26 crook 7604: @itemize @bullet
7605: @item
7606: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7607: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7608: @item
7609: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7610: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7611: arithmetic. Examples are -45 -5681 -0
7612: @item
7613: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7614: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7615: (all three of these represent the same number).
1.26 crook 7616: @item
7617: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7618: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7619: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7620: -34.65 (all three of these represent the same number).
1.26 crook 7621: @item
1.29 crook 7622: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7623: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7624: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7625: number) +12.E-4
1.26 crook 7626: @end itemize
1.1 anton 7627:
1.26 crook 7628: By default, the number base used for integer number conversion is given
1.35 anton 7629: by the contents of the variable @code{base}. Note that a lot of
7630: confusion can result from unexpected values of @code{base}. If you
7631: change @code{base} anywhere, make sure to save the old value and restore
7632: it afterwards. In general I recommend keeping @code{base} decimal, and
7633: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7634:
1.29 crook 7635: doc-dpl
1.26 crook 7636: doc-base
7637: doc-hex
7638: doc-decimal
1.1 anton 7639:
1.26 crook 7640: @cindex '-prefix for character strings
7641: @cindex &-prefix for decimal numbers
1.133 anton 7642: @cindex #-prefix for decimal numbers
1.26 crook 7643: @cindex %-prefix for binary numbers
7644: @cindex $-prefix for hexadecimal numbers
1.133 anton 7645: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7646: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7647: prefix@footnote{Some Forth implementations provide a similar scheme by
7648: implementing @code{$} etc. as parsing words that process the subsequent
7649: number in the input stream and push it onto the stack. For example, see
7650: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7651: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7652: is required between the prefix and the number.} before the first digit
1.133 anton 7653: of an (integer) number. The following prefixes are supported:
1.1 anton 7654:
1.26 crook 7655: @itemize @bullet
7656: @item
1.35 anton 7657: @code{&} -- decimal
1.26 crook 7658: @item
1.133 anton 7659: @code{#} -- decimal
7660: @item
1.35 anton 7661: @code{%} -- binary
1.26 crook 7662: @item
1.35 anton 7663: @code{$} -- hexadecimal
1.26 crook 7664: @item
1.133 anton 7665: @code{0x} -- hexadecimal, if base<33.
7666: @item
7667: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7668: optional @code{'} may be present after the character.
1.26 crook 7669: @end itemize
1.1 anton 7670:
1.26 crook 7671: Here are some examples, with the equivalent decimal number shown after
7672: in braces:
1.1 anton 7673:
1.26 crook 7674: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7675: 'A (65),
7676: -'a' (-97),
1.26 crook 7677: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7678:
1.26 crook 7679: @cindex number conversion - traps for the unwary
1.29 crook 7680: @noindent
1.26 crook 7681: Number conversion has a number of traps for the unwary:
1.1 anton 7682:
1.26 crook 7683: @itemize @bullet
7684: @item
7685: You cannot determine the current number base using the code sequence
1.35 anton 7686: @code{base @@ .} -- the number base is always 10 in the current number
7687: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7688: @item
7689: If the number base is set to a value greater than 14 (for example,
7690: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7691: it to be intepreted as either a single-precision integer or a
7692: floating-point number (Gforth treats it as an integer). The ambiguity
7693: can be resolved by explicitly stating the sign of the mantissa and/or
7694: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7695: ambiguity arises; either representation will be treated as a
7696: floating-point number.
7697: @item
1.29 crook 7698: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7699: It is used to specify file types.
7700: @item
1.72 anton 7701: ANS Forth requires the @code{.} of a double-precision number to be the
7702: final character in the string. Gforth allows the @code{.} to be
7703: anywhere after the first digit.
1.26 crook 7704: @item
7705: The number conversion process does not check for overflow.
7706: @item
1.72 anton 7707: In an ANS Forth program @code{base} is required to be decimal when
7708: converting floating-point numbers. In Gforth, number conversion to
7709: floating-point numbers always uses base &10, irrespective of the value
7710: of @code{base}.
1.26 crook 7711: @end itemize
1.1 anton 7712:
1.49 anton 7713: You can read numbers into your programs with the words described in
7714: @ref{Input}.
1.1 anton 7715:
1.82 anton 7716: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7717: @subsection Interpret/Compile states
7718: @cindex Interpret/Compile states
1.1 anton 7719:
1.29 crook 7720: A standard program is not permitted to change @code{state}
7721: explicitly. However, it can change @code{state} implicitly, using the
7722: words @code{[} and @code{]}. When @code{[} is executed it switches
7723: @code{state} to interpret state, and therefore the text interpreter
7724: starts interpreting. When @code{]} is executed it switches @code{state}
7725: to compile state and therefore the text interpreter starts
1.44 crook 7726: compiling. The most common usage for these words is for switching into
7727: interpret state and back from within a colon definition; this technique
1.49 anton 7728: can be used to compile a literal (for an example, @pxref{Literals}) or
7729: for conditional compilation (for an example, @pxref{Interpreter
7730: Directives}).
1.44 crook 7731:
1.35 anton 7732:
7733: @c This is a bad example: It's non-standard, and it's not necessary.
7734: @c However, I can't think of a good example for switching into compile
7735: @c state when there is no current word (@code{state}-smart words are not a
7736: @c good reason). So maybe we should use an example for switching into
7737: @c interpret @code{state} in a colon def. - anton
1.44 crook 7738: @c nac-> I agree. I started out by putting in the example, then realised
7739: @c that it was non-ANS, so wrote more words around it. I hope this
7740: @c re-written version is acceptable to you. I do want to keep the example
7741: @c as it is helpful for showing what is and what is not portable, particularly
7742: @c where it outlaws a style in common use.
7743:
1.72 anton 7744: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7745: @c that, we can also show what's not. In any case, I have written a
7746: @c section Compiling Words which also deals with [ ].
1.35 anton 7747:
1.95 anton 7748: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7749:
1.95 anton 7750: @c @code{[} and @code{]} also give you the ability to switch into compile
7751: @c state and back, but we cannot think of any useful Standard application
7752: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7753:
7754: @c @example
7755: @c : AA ." this is A" ;
7756: @c : BB ." this is B" ;
7757: @c : CC ." this is C" ;
7758:
7759: @c create table ] aa bb cc [
7760:
7761: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7762: @c cells table + @@ execute ;
7763: @c @end example
7764:
7765: @c This example builds a jump table; @code{0 go} will display ``@code{this
7766: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7767: @c defining @code{table} like this:
7768:
7769: @c @example
7770: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7771: @c @end example
7772:
7773: @c The problem with this code is that the definition of @code{table} is not
7774: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7775: @c @i{may} work on systems where code space and data space co-incide, the
7776: @c Standard only allows data space to be assigned for a @code{CREATE}d
7777: @c word. In addition, the Standard only allows @code{@@} to access data
7778: @c space, whilst this example is using it to access code space. The only
7779: @c portable, Standard way to build this table is to build it in data space,
7780: @c like this:
7781:
7782: @c @example
7783: @c create table ' aa , ' bb , ' cc ,
7784: @c @end example
1.29 crook 7785:
1.95 anton 7786: @c doc-state
1.44 crook 7787:
1.29 crook 7788:
1.82 anton 7789: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7790: @subsection Interpreter Directives
7791: @cindex interpreter directives
1.72 anton 7792: @cindex conditional compilation
1.1 anton 7793:
1.29 crook 7794: These words are usually used in interpret state; typically to control
7795: which parts of a source file are processed by the text
1.26 crook 7796: interpreter. There are only a few ANS Forth Standard words, but Gforth
7797: supplements these with a rich set of immediate control structure words
7798: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7799: used in compile state (@pxref{Control Structures}). Typical usages:
7800:
7801: @example
1.72 anton 7802: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7803: .
7804: .
1.72 anton 7805: HAVE-ASSEMBLER [IF]
1.29 crook 7806: : ASSEMBLER-FEATURE
7807: ...
7808: ;
7809: [ENDIF]
7810: .
7811: .
7812: : SEE
7813: ... \ general-purpose SEE code
1.72 anton 7814: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7815: ... \ assembler-specific SEE code
7816: [ [ENDIF] ]
7817: ;
7818: @end example
1.1 anton 7819:
1.44 crook 7820:
1.26 crook 7821: doc-[IF]
7822: doc-[ELSE]
7823: doc-[THEN]
7824: doc-[ENDIF]
1.1 anton 7825:
1.26 crook 7826: doc-[IFDEF]
7827: doc-[IFUNDEF]
1.1 anton 7828:
1.26 crook 7829: doc-[?DO]
7830: doc-[DO]
7831: doc-[FOR]
7832: doc-[LOOP]
7833: doc-[+LOOP]
7834: doc-[NEXT]
1.1 anton 7835:
1.26 crook 7836: doc-[BEGIN]
7837: doc-[UNTIL]
7838: doc-[AGAIN]
7839: doc-[WHILE]
7840: doc-[REPEAT]
1.1 anton 7841:
1.27 crook 7842:
1.26 crook 7843: @c -------------------------------------------------------------
1.111 anton 7844: @node The Input Stream, Word Lists, The Text Interpreter, Words
7845: @section The Input Stream
7846: @cindex input stream
7847:
7848: @c !! integrate this better with the "Text Interpreter" section
7849: The text interpreter reads from the input stream, which can come from
7850: several sources (@pxref{Input Sources}). Some words, in particular
7851: defining words, but also words like @code{'}, read parameters from the
7852: input stream instead of from the stack.
7853:
7854: Such words are called parsing words, because they parse the input
7855: stream. Parsing words are hard to use in other words, because it is
7856: hard to pass program-generated parameters through the input stream.
7857: They also usually have an unintuitive combination of interpretation and
7858: compilation semantics when implemented naively, leading to various
7859: approaches that try to produce a more intuitive behaviour
7860: (@pxref{Combined words}).
7861:
7862: It should be obvious by now that parsing words are a bad idea. If you
7863: want to implement a parsing word for convenience, also provide a factor
7864: of the word that does not parse, but takes the parameters on the stack.
7865: To implement the parsing word on top if it, you can use the following
7866: words:
7867:
7868: @c anton: these belong in the input stream section
7869: doc-parse
1.138 anton 7870: doc-parse-name
1.111 anton 7871: doc-parse-word
7872: doc-name
7873: doc-word
7874: doc-\"-parse
7875: doc-refill
7876:
7877: Conversely, if you have the bad luck (or lack of foresight) to have to
7878: deal with parsing words without having such factors, how do you pass a
7879: string that is not in the input stream to it?
7880:
7881: doc-execute-parsing
7882:
1.146 anton 7883: A definition of this word in ANS Forth is provided in
7884: @file{compat/execute-parsing.fs}.
7885:
1.111 anton 7886: If you want to run a parsing word on a file, the following word should
7887: help:
7888:
7889: doc-execute-parsing-file
7890:
7891: @c -------------------------------------------------------------
7892: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7893: @section Word Lists
7894: @cindex word lists
1.32 anton 7895: @cindex header space
1.1 anton 7896:
1.36 anton 7897: A wordlist is a list of named words; you can add new words and look up
7898: words by name (and you can remove words in a restricted way with
7899: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7900:
7901: @cindex search order stack
7902: The text interpreter searches the wordlists present in the search order
7903: (a stack of wordlists), from the top to the bottom. Within each
7904: wordlist, the search starts conceptually at the newest word; i.e., if
7905: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7906:
1.26 crook 7907: @cindex compilation word list
1.36 anton 7908: New words are added to the @dfn{compilation wordlist} (aka current
7909: wordlist).
1.1 anton 7910:
1.36 anton 7911: @cindex wid
7912: A word list is identified by a cell-sized word list identifier (@i{wid})
7913: in much the same way as a file is identified by a file handle. The
7914: numerical value of the wid has no (portable) meaning, and might change
7915: from session to session.
1.1 anton 7916:
1.29 crook 7917: The ANS Forth ``Search order'' word set is intended to provide a set of
7918: low-level tools that allow various different schemes to be
1.74 anton 7919: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7920: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7921: Forth.
1.1 anton 7922:
1.27 crook 7923: @comment TODO: locals section refers to here, saying that every word list (aka
7924: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7925: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7926:
1.45 crook 7927: @comment TODO: document markers, reveal, tables, mappedwordlist
7928:
7929: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7930: @comment word from the source files, rather than some alias.
1.44 crook 7931:
1.26 crook 7932: doc-forth-wordlist
7933: doc-definitions
7934: doc-get-current
7935: doc-set-current
7936: doc-get-order
1.45 crook 7937: doc---gforthman-set-order
1.26 crook 7938: doc-wordlist
1.30 anton 7939: doc-table
1.79 anton 7940: doc->order
1.36 anton 7941: doc-previous
1.26 crook 7942: doc-also
1.45 crook 7943: doc---gforthman-forth
1.26 crook 7944: doc-only
1.45 crook 7945: doc---gforthman-order
1.15 anton 7946:
1.26 crook 7947: doc-find
7948: doc-search-wordlist
1.15 anton 7949:
1.26 crook 7950: doc-words
7951: doc-vlist
1.44 crook 7952: @c doc-words-deferred
1.1 anton 7953:
1.74 anton 7954: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7955: doc-root
7956: doc-vocabulary
7957: doc-seal
7958: doc-vocs
7959: doc-current
7960: doc-context
1.1 anton 7961:
1.44 crook 7962:
1.26 crook 7963: @menu
1.75 anton 7964: * Vocabularies::
1.67 anton 7965: * Why use word lists?::
1.75 anton 7966: * Word list example::
1.26 crook 7967: @end menu
7968:
1.75 anton 7969: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7970: @subsection Vocabularies
7971: @cindex Vocabularies, detailed explanation
7972:
7973: Here is an example of creating and using a new wordlist using ANS
7974: Forth words:
7975:
7976: @example
7977: wordlist constant my-new-words-wordlist
7978: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7979:
7980: \ add it to the search order
7981: also my-new-words
7982:
7983: \ alternatively, add it to the search order and make it
7984: \ the compilation word list
7985: also my-new-words definitions
7986: \ type "order" to see the problem
7987: @end example
7988:
7989: The problem with this example is that @code{order} has no way to
7990: associate the name @code{my-new-words} with the wid of the word list (in
7991: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7992: that has no associated name). There is no Standard way of associating a
7993: name with a wid.
7994:
7995: In Gforth, this example can be re-coded using @code{vocabulary}, which
7996: associates a name with a wid:
7997:
7998: @example
7999: vocabulary my-new-words
8000:
8001: \ add it to the search order
8002: also my-new-words
8003:
8004: \ alternatively, add it to the search order and make it
8005: \ the compilation word list
8006: my-new-words definitions
8007: \ type "order" to see that the problem is solved
8008: @end example
8009:
8010:
8011: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8012: @subsection Why use word lists?
8013: @cindex word lists - why use them?
8014:
1.74 anton 8015: Here are some reasons why people use wordlists:
1.26 crook 8016:
8017: @itemize @bullet
1.74 anton 8018:
8019: @c anton: Gforth's hashing implementation makes the search speed
8020: @c independent from the number of words. But it is linear with the number
8021: @c of wordlists that have to be searched, so in effect using more wordlists
8022: @c actually slows down compilation.
8023:
8024: @c @item
8025: @c To improve compilation speed by reducing the number of header space
8026: @c entries that must be searched. This is achieved by creating a new
8027: @c word list that contains all of the definitions that are used in the
8028: @c definition of a Forth system but which would not usually be used by
8029: @c programs running on that system. That word list would be on the search
8030: @c list when the Forth system was compiled but would be removed from the
8031: @c search list for normal operation. This can be a useful technique for
8032: @c low-performance systems (for example, 8-bit processors in embedded
8033: @c systems) but is unlikely to be necessary in high-performance desktop
8034: @c systems.
8035:
1.26 crook 8036: @item
8037: To prevent a set of words from being used outside the context in which
8038: they are valid. Two classic examples of this are an integrated editor
8039: (all of the edit commands are defined in a separate word list; the
8040: search order is set to the editor word list when the editor is invoked;
8041: the old search order is restored when the editor is terminated) and an
8042: integrated assembler (the op-codes for the machine are defined in a
8043: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8044:
8045: @item
8046: To organize the words of an application or library into a user-visible
8047: set (in @code{forth-wordlist} or some other common wordlist) and a set
8048: of helper words used just for the implementation (hidden in a separate
1.75 anton 8049: wordlist). This keeps @code{words}' output smaller, separates
8050: implementation and interface, and reduces the chance of name conflicts
8051: within the common wordlist.
1.74 anton 8052:
1.26 crook 8053: @item
8054: To prevent a name-space clash between multiple definitions with the same
8055: name. For example, when building a cross-compiler you might have a word
8056: @code{IF} that generates conditional code for your target system. By
8057: placing this definition in a different word list you can control whether
8058: the host system's @code{IF} or the target system's @code{IF} get used in
8059: any particular context by controlling the order of the word lists on the
8060: search order stack.
1.74 anton 8061:
1.26 crook 8062: @end itemize
1.1 anton 8063:
1.74 anton 8064: The downsides of using wordlists are:
8065:
8066: @itemize
8067:
8068: @item
8069: Debugging becomes more cumbersome.
8070:
8071: @item
8072: Name conflicts worked around with wordlists are still there, and you
8073: have to arrange the search order carefully to get the desired results;
8074: if you forget to do that, you get hard-to-find errors (as in any case
8075: where you read the code differently from the compiler; @code{see} can
1.75 anton 8076: help seeing which of several possible words the name resolves to in such
8077: cases). @code{See} displays just the name of the words, not what
8078: wordlist they belong to, so it might be misleading. Using unique names
8079: is a better approach to avoid name conflicts.
1.74 anton 8080:
8081: @item
8082: You have to explicitly undo any changes to the search order. In many
8083: cases it would be more convenient if this happened implicitly. Gforth
8084: currently does not provide such a feature, but it may do so in the
8085: future.
8086: @end itemize
8087:
8088:
1.75 anton 8089: @node Word list example, , Why use word lists?, Word Lists
8090: @subsection Word list example
8091: @cindex word lists - example
1.1 anton 8092:
1.74 anton 8093: The following example is from the
8094: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8095: garbage collector} and uses wordlists to separate public words from
8096: helper words:
8097:
8098: @example
8099: get-current ( wid )
8100: vocabulary garbage-collector also garbage-collector definitions
8101: ... \ define helper words
8102: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8103: ... \ define the public (i.e., API) words
8104: \ they can refer to the helper words
8105: previous \ restore original search order (helper words become invisible)
8106: @end example
8107:
1.26 crook 8108: @c -------------------------------------------------------------
8109: @node Environmental Queries, Files, Word Lists, Words
8110: @section Environmental Queries
8111: @cindex environmental queries
1.21 crook 8112:
1.26 crook 8113: ANS Forth introduced the idea of ``environmental queries'' as a way
8114: for a program running on a system to determine certain characteristics of the system.
8115: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8116:
1.32 anton 8117: The Standard requires that the header space used for environmental queries
8118: be distinct from the header space used for definitions.
1.21 crook 8119:
1.26 crook 8120: Typically, environmental queries are supported by creating a set of
1.29 crook 8121: definitions in a word list that is @i{only} used during environmental
1.26 crook 8122: queries; that is what Gforth does. There is no Standard way of adding
8123: definitions to the set of recognised environmental queries, but any
8124: implementation that supports the loading of optional word sets must have
8125: some mechanism for doing this (after loading the word set, the
8126: associated environmental query string must return @code{true}). In
8127: Gforth, the word list used to honour environmental queries can be
8128: manipulated just like any other word list.
1.21 crook 8129:
1.44 crook 8130:
1.26 crook 8131: doc-environment?
8132: doc-environment-wordlist
1.21 crook 8133:
1.26 crook 8134: doc-gforth
8135: doc-os-class
1.21 crook 8136:
1.44 crook 8137:
1.26 crook 8138: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8139: returning two items on the stack, querying it using @code{environment?}
8140: will return an additional item; the @code{true} flag that shows that the
8141: string was recognised.
1.21 crook 8142:
1.26 crook 8143: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8144:
1.26 crook 8145: Here are some examples of using environmental queries:
1.21 crook 8146:
1.26 crook 8147: @example
8148: s" address-unit-bits" environment? 0=
8149: [IF]
8150: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8151: [ELSE]
8152: drop \ ensure balanced stack effect
1.26 crook 8153: [THEN]
1.21 crook 8154:
1.75 anton 8155: \ this might occur in the prelude of a standard program that uses THROW
8156: s" exception" environment? [IF]
8157: 0= [IF]
8158: : throw abort" exception thrown" ;
8159: [THEN]
8160: [ELSE] \ we don't know, so make sure
8161: : throw abort" exception thrown" ;
8162: [THEN]
1.21 crook 8163:
1.26 crook 8164: s" gforth" environment? [IF] .( Gforth version ) TYPE
8165: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8166:
8167: \ a program using v*
8168: s" gforth" environment? [IF]
8169: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8170: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8171: >r swap 2swap swap 0e r> 0 ?DO
8172: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8173: LOOP
8174: 2drop 2drop ;
8175: [THEN]
8176: [ELSE] \
8177: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8178: ...
8179: [THEN]
1.26 crook 8180: @end example
1.21 crook 8181:
1.26 crook 8182: Here is an example of adding a definition to the environment word list:
1.21 crook 8183:
1.26 crook 8184: @example
8185: get-current environment-wordlist set-current
8186: true constant block
8187: true constant block-ext
8188: set-current
8189: @end example
1.21 crook 8190:
1.26 crook 8191: You can see what definitions are in the environment word list like this:
1.21 crook 8192:
1.26 crook 8193: @example
1.79 anton 8194: environment-wordlist >order words previous
1.26 crook 8195: @end example
1.21 crook 8196:
8197:
1.26 crook 8198: @c -------------------------------------------------------------
8199: @node Files, Blocks, Environmental Queries, Words
8200: @section Files
1.28 crook 8201: @cindex files
8202: @cindex I/O - file-handling
1.21 crook 8203:
1.26 crook 8204: Gforth provides facilities for accessing files that are stored in the
8205: host operating system's file-system. Files that are processed by Gforth
8206: can be divided into two categories:
1.21 crook 8207:
1.23 crook 8208: @itemize @bullet
8209: @item
1.29 crook 8210: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8211: @item
1.29 crook 8212: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8213: @end itemize
8214:
8215: @menu
1.48 anton 8216: * Forth source files::
8217: * General files::
8218: * Search Paths::
1.26 crook 8219: @end menu
8220:
8221: @c -------------------------------------------------------------
8222: @node Forth source files, General files, Files, Files
8223: @subsection Forth source files
8224: @cindex including files
8225: @cindex Forth source files
1.21 crook 8226:
1.26 crook 8227: The simplest way to interpret the contents of a file is to use one of
8228: these two formats:
1.21 crook 8229:
1.26 crook 8230: @example
8231: include mysource.fs
8232: s" mysource.fs" included
8233: @end example
1.21 crook 8234:
1.75 anton 8235: You usually want to include a file only if it is not included already
1.26 crook 8236: (by, say, another source file). In that case, you can use one of these
1.45 crook 8237: three formats:
1.21 crook 8238:
1.26 crook 8239: @example
8240: require mysource.fs
8241: needs mysource.fs
8242: s" mysource.fs" required
8243: @end example
1.21 crook 8244:
1.26 crook 8245: @cindex stack effect of included files
8246: @cindex including files, stack effect
1.45 crook 8247: It is good practice to write your source files such that interpreting them
8248: does not change the stack. Source files designed in this way can be used with
1.26 crook 8249: @code{required} and friends without complications. For example:
1.21 crook 8250:
1.26 crook 8251: @example
1.75 anton 8252: 1024 require foo.fs drop
1.26 crook 8253: @end example
1.21 crook 8254:
1.75 anton 8255: Here you want to pass the argument 1024 (e.g., a buffer size) to
8256: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8257: ), which allows its use with @code{require}. Of course with such
8258: parameters to required files, you have to ensure that the first
8259: @code{require} fits for all uses (i.e., @code{require} it early in the
8260: master load file).
1.44 crook 8261:
1.26 crook 8262: doc-include-file
8263: doc-included
1.28 crook 8264: doc-included?
1.26 crook 8265: doc-include
8266: doc-required
8267: doc-require
8268: doc-needs
1.75 anton 8269: @c doc-init-included-files @c internal
8270: doc-sourcefilename
8271: doc-sourceline#
1.44 crook 8272:
1.26 crook 8273: A definition in ANS Forth for @code{required} is provided in
8274: @file{compat/required.fs}.
1.21 crook 8275:
1.26 crook 8276: @c -------------------------------------------------------------
8277: @node General files, Search Paths, Forth source files, Files
8278: @subsection General files
8279: @cindex general files
8280: @cindex file-handling
1.21 crook 8281:
1.75 anton 8282: Files are opened/created by name and type. The following file access
8283: methods (FAMs) are recognised:
1.44 crook 8284:
1.75 anton 8285: @cindex fam (file access method)
1.26 crook 8286: doc-r/o
8287: doc-r/w
8288: doc-w/o
8289: doc-bin
1.1 anton 8290:
1.44 crook 8291:
1.26 crook 8292: When a file is opened/created, it returns a file identifier,
1.29 crook 8293: @i{wfileid} that is used for all other file commands. All file
8294: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8295: successful operation and an implementation-defined non-zero value in the
8296: case of an error.
1.21 crook 8297:
1.44 crook 8298:
1.26 crook 8299: doc-open-file
8300: doc-create-file
1.21 crook 8301:
1.26 crook 8302: doc-close-file
8303: doc-delete-file
8304: doc-rename-file
8305: doc-read-file
8306: doc-read-line
1.154 anton 8307: doc-key-file
8308: doc-key?-file
1.26 crook 8309: doc-write-file
8310: doc-write-line
8311: doc-emit-file
8312: doc-flush-file
1.21 crook 8313:
1.26 crook 8314: doc-file-status
8315: doc-file-position
8316: doc-reposition-file
8317: doc-file-size
8318: doc-resize-file
1.21 crook 8319:
1.93 anton 8320: doc-slurp-file
8321: doc-slurp-fid
1.112 anton 8322: doc-stdin
8323: doc-stdout
8324: doc-stderr
1.44 crook 8325:
1.26 crook 8326: @c ---------------------------------------------------------
1.48 anton 8327: @node Search Paths, , General files, Files
1.26 crook 8328: @subsection Search Paths
8329: @cindex path for @code{included}
8330: @cindex file search path
8331: @cindex @code{include} search path
8332: @cindex search path for files
1.21 crook 8333:
1.26 crook 8334: If you specify an absolute filename (i.e., a filename starting with
8335: @file{/} or @file{~}, or with @file{:} in the second position (as in
8336: @samp{C:...})) for @code{included} and friends, that file is included
8337: just as you would expect.
1.21 crook 8338:
1.75 anton 8339: If the filename starts with @file{./}, this refers to the directory that
8340: the present file was @code{included} from. This allows files to include
8341: other files relative to their own position (irrespective of the current
8342: working directory or the absolute position). This feature is essential
8343: for libraries consisting of several files, where a file may include
8344: other files from the library. It corresponds to @code{#include "..."}
8345: in C. If the current input source is not a file, @file{.} refers to the
8346: directory of the innermost file being included, or, if there is no file
8347: being included, to the current working directory.
8348:
8349: For relative filenames (not starting with @file{./}), Gforth uses a
8350: search path similar to Forth's search order (@pxref{Word Lists}). It
8351: tries to find the given filename in the directories present in the path,
8352: and includes the first one it finds. There are separate search paths for
8353: Forth source files and general files. If the search path contains the
8354: directory @file{.}, this refers to the directory of the current file, or
8355: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8356:
1.26 crook 8357: Use @file{~+} to refer to the current working directory (as in the
8358: @code{bash}).
1.1 anton 8359:
1.75 anton 8360: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8361:
1.48 anton 8362: @menu
1.75 anton 8363: * Source Search Paths::
1.48 anton 8364: * General Search Paths::
8365: @end menu
8366:
1.26 crook 8367: @c ---------------------------------------------------------
1.75 anton 8368: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8369: @subsubsection Source Search Paths
8370: @cindex search path control, source files
1.5 anton 8371:
1.26 crook 8372: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8373: Gforth}). You can display it and change it using @code{fpath} in
8374: combination with the general path handling words.
1.5 anton 8375:
1.75 anton 8376: doc-fpath
8377: @c the functionality of the following words is easily available through
8378: @c fpath and the general path words. The may go away.
8379: @c doc-.fpath
8380: @c doc-fpath+
8381: @c doc-fpath=
8382: @c doc-open-fpath-file
1.44 crook 8383:
8384: @noindent
1.26 crook 8385: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8386:
1.26 crook 8387: @example
1.75 anton 8388: fpath path= /usr/lib/forth/|./
1.26 crook 8389: require timer.fs
8390: @end example
1.5 anton 8391:
1.75 anton 8392:
1.26 crook 8393: @c ---------------------------------------------------------
1.75 anton 8394: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8395: @subsubsection General Search Paths
1.75 anton 8396: @cindex search path control, source files
1.5 anton 8397:
1.26 crook 8398: Your application may need to search files in several directories, like
8399: @code{included} does. To facilitate this, Gforth allows you to define
8400: and use your own search paths, by providing generic equivalents of the
8401: Forth search path words:
1.5 anton 8402:
1.75 anton 8403: doc-open-path-file
8404: doc-path-allot
8405: doc-clear-path
8406: doc-also-path
1.26 crook 8407: doc-.path
8408: doc-path+
8409: doc-path=
1.5 anton 8410:
1.75 anton 8411: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8412:
1.75 anton 8413: Here's an example of creating an empty search path:
8414: @c
1.26 crook 8415: @example
1.75 anton 8416: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8417: @end example
1.5 anton 8418:
1.26 crook 8419: @c -------------------------------------------------------------
8420: @node Blocks, Other I/O, Files, Words
8421: @section Blocks
1.28 crook 8422: @cindex I/O - blocks
8423: @cindex blocks
8424:
8425: When you run Gforth on a modern desk-top computer, it runs under the
8426: control of an operating system which provides certain services. One of
8427: these services is @var{file services}, which allows Forth source code
8428: and data to be stored in files and read into Gforth (@pxref{Files}).
8429:
8430: Traditionally, Forth has been an important programming language on
8431: systems where it has interfaced directly to the underlying hardware with
8432: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8433: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8434:
8435: A block is a 1024-byte data area, which can be used to hold data or
8436: Forth source code. No structure is imposed on the contents of the
8437: block. A block is identified by its number; blocks are numbered
8438: contiguously from 1 to an implementation-defined maximum.
8439:
8440: A typical system that used blocks but no operating system might use a
8441: single floppy-disk drive for mass storage, with the disks formatted to
8442: provide 256-byte sectors. Blocks would be implemented by assigning the
8443: first four sectors of the disk to block 1, the second four sectors to
8444: block 2 and so on, up to the limit of the capacity of the disk. The disk
8445: would not contain any file system information, just the set of blocks.
8446:
1.29 crook 8447: @cindex blocks file
1.28 crook 8448: On systems that do provide file services, blocks are typically
1.29 crook 8449: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8450: file}. The size of the blocks file will be an exact multiple of 1024
8451: bytes, corresponding to the number of blocks it contains. This is the
8452: mechanism that Gforth uses.
8453:
1.29 crook 8454: @cindex @file{blocks.fb}
1.75 anton 8455: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8456: having specified a blocks file, Gforth defaults to the blocks file
8457: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8458: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8459:
1.29 crook 8460: @cindex block buffers
1.28 crook 8461: When you read and write blocks under program control, Gforth uses a
1.29 crook 8462: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8463: not used when you use @code{load} to interpret the contents of a block.
8464:
1.75 anton 8465: The behaviour of the block buffers is analagous to that of a cache.
8466: Each block buffer has three states:
1.28 crook 8467:
8468: @itemize @bullet
8469: @item
8470: Unassigned
8471: @item
8472: Assigned-clean
8473: @item
8474: Assigned-dirty
8475: @end itemize
8476:
1.29 crook 8477: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8478: block, the block (specified by its block number) must be assigned to a
8479: block buffer.
8480:
8481: The assignment of a block to a block buffer is performed by @code{block}
8482: or @code{buffer}. Use @code{block} when you wish to modify the existing
8483: contents of a block. Use @code{buffer} when you don't care about the
8484: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8485: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8486: with the particular block is already stored in a block buffer due to an
8487: earlier @code{block} command, @code{buffer} will return that block
8488: buffer and the existing contents of the block will be
8489: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8490: block buffer for the block.}.
1.28 crook 8491:
1.47 crook 8492: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8493: @code{buffer}, that block buffer becomes the @i{current block
8494: buffer}. Data may only be manipulated (read or written) within the
8495: current block buffer.
1.47 crook 8496:
8497: When the contents of the current block buffer has been modified it is
1.48 anton 8498: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8499: either abandon the changes (by doing nothing) or mark the block as
8500: changed (assigned-dirty), using @code{update}. Using @code{update} does
8501: not change the blocks file; it simply changes a block buffer's state to
8502: @i{assigned-dirty}. The block will be written implicitly when it's
8503: buffer is needed for another block, or explicitly by @code{flush} or
8504: @code{save-buffers}.
8505:
8506: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8507: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8508: @code{flush}.
1.28 crook 8509:
1.29 crook 8510: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8511: algorithm to assign a block buffer to a block. That means that any
8512: particular block can only be assigned to one specific block buffer,
1.29 crook 8513: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8514: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8515: the new block immediately. If it is @i{assigned-dirty} its current
8516: contents are written back to the blocks file on disk before it is
1.28 crook 8517: allocated to the new block.
8518:
8519: Although no structure is imposed on the contents of a block, it is
8520: traditional to display the contents as 16 lines each of 64 characters. A
8521: block provides a single, continuous stream of input (for example, it
8522: acts as a single parse area) -- there are no end-of-line characters
8523: within a block, and no end-of-file character at the end of a
8524: block. There are two consequences of this:
1.26 crook 8525:
1.28 crook 8526: @itemize @bullet
8527: @item
8528: The last character of one line wraps straight into the first character
8529: of the following line
8530: @item
8531: The word @code{\} -- comment to end of line -- requires special
8532: treatment; in the context of a block it causes all characters until the
8533: end of the current 64-character ``line'' to be ignored.
8534: @end itemize
8535:
8536: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8537: the current blocks file will be extended to the appropriate size and the
1.28 crook 8538: block buffer will be initialised with spaces.
8539:
1.47 crook 8540: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8541: for details) but doesn't encourage the use of blocks; the mechanism is
8542: only provided for backward compatibility -- ANS Forth requires blocks to
8543: be available when files are.
1.28 crook 8544:
8545: Common techniques that are used when working with blocks include:
8546:
8547: @itemize @bullet
8548: @item
8549: A screen editor that allows you to edit blocks without leaving the Forth
8550: environment.
8551: @item
8552: Shadow screens; where every code block has an associated block
8553: containing comments (for example: code in odd block numbers, comments in
8554: even block numbers). Typically, the block editor provides a convenient
8555: mechanism to toggle between code and comments.
8556: @item
8557: Load blocks; a single block (typically block 1) contains a number of
8558: @code{thru} commands which @code{load} the whole of the application.
8559: @end itemize
1.26 crook 8560:
1.29 crook 8561: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8562: integrated into a Forth programming environment.
1.26 crook 8563:
8564: @comment TODO what about errors on open-blocks?
1.44 crook 8565:
1.26 crook 8566: doc-open-blocks
8567: doc-use
1.75 anton 8568: doc-block-offset
1.26 crook 8569: doc-get-block-fid
8570: doc-block-position
1.28 crook 8571:
1.75 anton 8572: doc-list
1.28 crook 8573: doc-scr
8574:
1.45 crook 8575: doc---gforthman-block
1.28 crook 8576: doc-buffer
8577:
1.75 anton 8578: doc-empty-buffers
8579: doc-empty-buffer
1.26 crook 8580: doc-update
1.28 crook 8581: doc-updated?
1.26 crook 8582: doc-save-buffers
1.75 anton 8583: doc-save-buffer
1.26 crook 8584: doc-flush
1.28 crook 8585:
1.26 crook 8586: doc-load
8587: doc-thru
8588: doc-+load
8589: doc-+thru
1.45 crook 8590: doc---gforthman--->
1.26 crook 8591: doc-block-included
8592:
1.44 crook 8593:
1.26 crook 8594: @c -------------------------------------------------------------
1.126 pazsan 8595: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8596: @section Other I/O
1.28 crook 8597: @cindex I/O - keyboard and display
1.26 crook 8598:
8599: @menu
8600: * Simple numeric output:: Predefined formats
8601: * Formatted numeric output:: Formatted (pictured) output
8602: * String Formats:: How Forth stores strings in memory
1.67 anton 8603: * Displaying characters and strings:: Other stuff
1.26 crook 8604: * Input:: Input
1.112 anton 8605: * Pipes:: How to create your own pipes
1.149 pazsan 8606: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8607: @end menu
8608:
8609: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8610: @subsection Simple numeric output
1.28 crook 8611: @cindex numeric output - simple/free-format
1.5 anton 8612:
1.26 crook 8613: The simplest output functions are those that display numbers from the
8614: data or floating-point stacks. Floating-point output is always displayed
8615: using base 10. Numbers displayed from the data stack use the value stored
8616: in @code{base}.
1.5 anton 8617:
1.44 crook 8618:
1.26 crook 8619: doc-.
8620: doc-dec.
8621: doc-hex.
8622: doc-u.
8623: doc-.r
8624: doc-u.r
8625: doc-d.
8626: doc-ud.
8627: doc-d.r
8628: doc-ud.r
8629: doc-f.
8630: doc-fe.
8631: doc-fs.
1.111 anton 8632: doc-f.rdp
1.44 crook 8633:
1.26 crook 8634: Examples of printing the number 1234.5678E23 in the different floating-point output
8635: formats are shown below:
1.5 anton 8636:
8637: @example
1.26 crook 8638: f. 123456779999999000000000000.
8639: fe. 123.456779999999E24
8640: fs. 1.23456779999999E26
1.5 anton 8641: @end example
8642:
8643:
1.26 crook 8644: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8645: @subsection Formatted numeric output
1.28 crook 8646: @cindex formatted numeric output
1.26 crook 8647: @cindex pictured numeric output
1.28 crook 8648: @cindex numeric output - formatted
1.26 crook 8649:
1.29 crook 8650: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8651: output} for formatted printing of integers. In this technique, digits
8652: are extracted from the number (using the current output radix defined by
8653: @code{base}), converted to ASCII codes and appended to a string that is
8654: built in a scratch-pad area of memory (@pxref{core-idef,
8655: Implementation-defined options, Implementation-defined
8656: options}). Arbitrary characters can be appended to the string during the
8657: extraction process. The completed string is specified by an address
8658: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8659: under program control.
1.5 anton 8660:
1.75 anton 8661: All of the integer output words described in the previous section
8662: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8663: numeric output.
1.5 anton 8664:
1.47 crook 8665: Three important things to remember about pictured numeric output:
1.5 anton 8666:
1.26 crook 8667: @itemize @bullet
8668: @item
1.28 crook 8669: It always operates on double-precision numbers; to display a
1.49 anton 8670: single-precision number, convert it first (for ways of doing this
8671: @pxref{Double precision}).
1.26 crook 8672: @item
1.28 crook 8673: It always treats the double-precision number as though it were
8674: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8675: @item
8676: The string is built up from right to left; least significant digit first.
8677: @end itemize
1.5 anton 8678:
1.44 crook 8679:
1.26 crook 8680: doc-<#
1.47 crook 8681: doc-<<#
1.26 crook 8682: doc-#
8683: doc-#s
8684: doc-hold
8685: doc-sign
8686: doc-#>
1.47 crook 8687: doc-#>>
1.5 anton 8688:
1.26 crook 8689: doc-represent
1.111 anton 8690: doc-f>str-rdp
8691: doc-f>buf-rdp
1.5 anton 8692:
1.44 crook 8693:
8694: @noindent
1.26 crook 8695: Here are some examples of using pictured numeric output:
1.5 anton 8696:
8697: @example
1.26 crook 8698: : my-u. ( u -- )
8699: \ Simplest use of pns.. behaves like Standard u.
8700: 0 \ convert to unsigned double
1.75 anton 8701: <<# \ start conversion
1.26 crook 8702: #s \ convert all digits
8703: #> \ complete conversion
1.75 anton 8704: TYPE SPACE \ display, with trailing space
8705: #>> ; \ release hold area
1.5 anton 8706:
1.26 crook 8707: : cents-only ( u -- )
8708: 0 \ convert to unsigned double
1.75 anton 8709: <<# \ start conversion
1.26 crook 8710: # # \ convert two least-significant digits
8711: #> \ complete conversion, discard other digits
1.75 anton 8712: TYPE SPACE \ display, with trailing space
8713: #>> ; \ release hold area
1.5 anton 8714:
1.26 crook 8715: : dollars-and-cents ( u -- )
8716: 0 \ convert to unsigned double
1.75 anton 8717: <<# \ start conversion
1.26 crook 8718: # # \ convert two least-significant digits
8719: [char] . hold \ insert decimal point
8720: #s \ convert remaining digits
8721: [char] $ hold \ append currency symbol
8722: #> \ complete conversion
1.75 anton 8723: TYPE SPACE \ display, with trailing space
8724: #>> ; \ release hold area
1.5 anton 8725:
1.26 crook 8726: : my-. ( n -- )
8727: \ handling negatives.. behaves like Standard .
8728: s>d \ convert to signed double
8729: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8730: <<# \ start conversion
1.26 crook 8731: #s \ convert all digits
8732: rot sign \ get at sign byte, append "-" if needed
8733: #> \ complete conversion
1.75 anton 8734: TYPE SPACE \ display, with trailing space
8735: #>> ; \ release hold area
1.5 anton 8736:
1.26 crook 8737: : account. ( n -- )
1.75 anton 8738: \ accountants don't like minus signs, they use parentheses
1.26 crook 8739: \ for negative numbers
8740: s>d \ convert to signed double
8741: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8742: <<# \ start conversion
1.26 crook 8743: 2 pick \ get copy of sign byte
8744: 0< IF [char] ) hold THEN \ right-most character of output
8745: #s \ convert all digits
8746: rot \ get at sign byte
8747: 0< IF [char] ( hold THEN
8748: #> \ complete conversion
1.75 anton 8749: TYPE SPACE \ display, with trailing space
8750: #>> ; \ release hold area
8751:
1.5 anton 8752: @end example
8753:
1.26 crook 8754: Here are some examples of using these words:
1.5 anton 8755:
8756: @example
1.26 crook 8757: 1 my-u. 1
8758: hex -1 my-u. decimal FFFFFFFF
8759: 1 cents-only 01
8760: 1234 cents-only 34
8761: 2 dollars-and-cents $0.02
8762: 1234 dollars-and-cents $12.34
8763: 123 my-. 123
8764: -123 my. -123
8765: 123 account. 123
8766: -456 account. (456)
1.5 anton 8767: @end example
8768:
8769:
1.26 crook 8770: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8771: @subsection String Formats
1.27 crook 8772: @cindex strings - see character strings
8773: @cindex character strings - formats
1.28 crook 8774: @cindex I/O - see character strings
1.75 anton 8775: @cindex counted strings
8776:
8777: @c anton: this does not really belong here; maybe the memory section,
8778: @c or the principles chapter
1.26 crook 8779:
1.27 crook 8780: Forth commonly uses two different methods for representing character
8781: strings:
1.26 crook 8782:
8783: @itemize @bullet
8784: @item
8785: @cindex address of counted string
1.45 crook 8786: @cindex counted string
1.29 crook 8787: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8788: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8789: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8790: memory.
8791: @item
1.29 crook 8792: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8793: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8794: first byte of the string.
8795: @end itemize
8796:
8797: ANS Forth encourages the use of the second format when representing
1.75 anton 8798: strings.
1.26 crook 8799:
1.44 crook 8800:
1.26 crook 8801: doc-count
8802:
1.44 crook 8803:
1.49 anton 8804: For words that move, copy and search for strings see @ref{Memory
8805: Blocks}. For words that display characters and strings see
8806: @ref{Displaying characters and strings}.
1.26 crook 8807:
8808: @node Displaying characters and strings, Input, String Formats, Other I/O
8809: @subsection Displaying characters and strings
1.27 crook 8810: @cindex characters - compiling and displaying
8811: @cindex character strings - compiling and displaying
1.26 crook 8812:
8813: This section starts with a glossary of Forth words and ends with a set
8814: of examples.
8815:
1.44 crook 8816:
1.26 crook 8817: doc-bl
8818: doc-space
8819: doc-spaces
8820: doc-emit
8821: doc-toupper
8822: doc-."
8823: doc-.(
1.98 anton 8824: doc-.\"
1.26 crook 8825: doc-type
1.44 crook 8826: doc-typewhite
1.26 crook 8827: doc-cr
1.27 crook 8828: @cindex cursor control
1.26 crook 8829: doc-at-xy
8830: doc-page
8831: doc-s"
1.98 anton 8832: doc-s\"
1.26 crook 8833: doc-c"
8834: doc-char
8835: doc-[char]
8836:
1.44 crook 8837:
8838: @noindent
1.26 crook 8839: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8840:
8841: @example
1.26 crook 8842: .( text-1)
8843: : my-word
8844: ." text-2" cr
8845: .( text-3)
8846: ;
8847:
8848: ." text-4"
8849:
8850: : my-char
8851: [char] ALPHABET emit
8852: char emit
8853: ;
1.5 anton 8854: @end example
8855:
1.26 crook 8856: When you load this code into Gforth, the following output is generated:
1.5 anton 8857:
1.26 crook 8858: @example
1.30 anton 8859: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8860: @end example
1.5 anton 8861:
1.26 crook 8862: @itemize @bullet
8863: @item
8864: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8865: is an immediate word; it behaves in the same way whether it is used inside
8866: or outside a colon definition.
8867: @item
8868: Message @code{text-4} is displayed because of Gforth's added interpretation
8869: semantics for @code{."}.
8870: @item
1.29 crook 8871: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8872: performs the compilation semantics for @code{."} within the definition of
8873: @code{my-word}.
8874: @end itemize
1.5 anton 8875:
1.26 crook 8876: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8877:
1.26 crook 8878: @example
1.30 anton 8879: @kbd{my-word @key{RET}} text-2
1.26 crook 8880: ok
1.30 anton 8881: @kbd{my-char fred @key{RET}} Af ok
8882: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8883: @end example
1.5 anton 8884:
8885: @itemize @bullet
8886: @item
1.26 crook 8887: Message @code{text-2} is displayed because of the run-time behaviour of
8888: @code{."}.
8889: @item
8890: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8891: on the stack at run-time. @code{emit} always displays the character
8892: when @code{my-char} is executed.
8893: @item
8894: @code{char} parses a string at run-time and the second @code{emit} displays
8895: the first character of the string.
1.5 anton 8896: @item
1.26 crook 8897: If you type @code{see my-char} you can see that @code{[char]} discarded
8898: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8899: definition of @code{my-char}.
1.5 anton 8900: @end itemize
8901:
8902:
8903:
1.112 anton 8904: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8905: @subsection Input
8906: @cindex input
1.28 crook 8907: @cindex I/O - see input
8908: @cindex parsing a string
1.5 anton 8909:
1.49 anton 8910: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8911:
1.27 crook 8912: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8913: @comment then index them
1.27 crook 8914:
1.44 crook 8915:
1.27 crook 8916: doc-key
8917: doc-key?
1.45 crook 8918: doc-ekey
1.141 anton 8919: doc-ekey>char
1.45 crook 8920: doc-ekey?
1.141 anton 8921:
8922: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
8923: you need the ANSI.SYS driver to get that behaviour). These are the
8924: keyboard events produced by various common keys:
8925:
8926: doc-k-left
8927: doc-k-right
8928: doc-k-up
8929: doc-k-down
8930: doc-k-home
8931: doc-k-end
8932: doc-k-prior
8933: doc-k-next
8934: doc-k-insert
8935: doc-k-delete
8936:
8937: The function keys (aka keypad keys) are:
8938:
8939: doc-k1
8940: doc-k2
8941: doc-k3
8942: doc-k4
8943: doc-k5
8944: doc-k6
8945: doc-k7
8946: doc-k8
8947: doc-k9
8948: doc-k10
8949: doc-k11
8950: doc-k12
8951:
8952: Note that K11 and K12 are not as widely available. The shifted
8953: function keys are also not very widely available:
8954:
8955: doc-s-k1
8956: doc-s-k2
8957: doc-s-k3
8958: doc-s-k4
8959: doc-s-k5
8960: doc-s-k6
8961: doc-s-k7
8962: doc-s-k8
8963: doc-s-k9
8964: doc-s-k10
8965: doc-s-k11
8966: doc-s-k12
8967:
8968: Words for inputting one line from the keyboard:
8969:
8970: doc-accept
8971: doc-edit-line
8972:
8973: Conversion words:
8974:
1.143 anton 8975: doc-s>number?
8976: doc-s>unumber?
1.26 crook 8977: doc->number
8978: doc->float
1.143 anton 8979:
1.141 anton 8980:
1.27 crook 8981: @comment obsolescent words..
1.141 anton 8982: Obsolescent input and conversion words:
8983:
1.27 crook 8984: doc-convert
1.26 crook 8985: doc-expect
1.27 crook 8986: doc-span
1.5 anton 8987:
8988:
1.149 pazsan 8989: @node Pipes, Xchars and Unicode, Input, Other I/O
1.112 anton 8990: @subsection Pipes
8991: @cindex pipes, creating your own
8992:
8993: In addition to using Gforth in pipes created by other processes
8994: (@pxref{Gforth in pipes}), you can create your own pipe with
8995: @code{open-pipe}, and read from or write to it.
8996:
8997: doc-open-pipe
8998: doc-close-pipe
8999:
9000: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9001: you don't catch this exception, Gforth will catch it and exit, usually
9002: silently (@pxref{Gforth in pipes}). Since you probably do not want
9003: this, you should wrap a @code{catch} or @code{try} block around the code
9004: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9005: problem yourself, and then return to regular processing.
9006:
9007: doc-broken-pipe-error
9008:
1.155 anton 9009: @node Xchars and Unicode, , Pipes, Other I/O
9010: @subsection Xchars and Unicode
1.149 pazsan 9011:
9012: This chapter needs completion
1.112 anton 9013:
1.121 anton 9014: @node OS command line arguments, Locals, Other I/O, Words
9015: @section OS command line arguments
9016: @cindex OS command line arguments
9017: @cindex command line arguments, OS
9018: @cindex arguments, OS command line
9019:
9020: The usual way to pass arguments to Gforth programs on the command line
9021: is via the @option{-e} option, e.g.
9022:
9023: @example
9024: gforth -e "123 456" foo.fs -e bye
9025: @end example
9026:
9027: However, you may want to interpret the command-line arguments directly.
9028: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9029: through @code{next-arg}:
1.121 anton 9030:
1.123 anton 9031: doc-next-arg
1.121 anton 9032:
1.123 anton 9033: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9034:
9035: @example
9036: : echo ( -- )
1.122 anton 9037: begin
1.123 anton 9038: next-arg 2dup 0 0 d<> while
9039: type space
9040: repeat
9041: 2drop ;
1.121 anton 9042:
9043: echo cr bye
9044: @end example
9045:
9046: This can be invoked with
9047:
9048: @example
9049: gforth echo.fs hello world
9050: @end example
1.123 anton 9051:
9052: and it will print
9053:
9054: @example
9055: hello world
9056: @end example
9057:
9058: The next lower level of dealing with the OS command line are the
9059: following words:
9060:
9061: doc-arg
9062: doc-shift-args
9063:
9064: Finally, at the lowest level Gforth provides the following words:
9065:
9066: doc-argc
9067: doc-argv
1.121 anton 9068:
1.78 anton 9069: @c -------------------------------------------------------------
1.126 pazsan 9070: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9071: @section Locals
9072: @cindex locals
9073:
9074: Local variables can make Forth programming more enjoyable and Forth
9075: programs easier to read. Unfortunately, the locals of ANS Forth are
9076: laden with restrictions. Therefore, we provide not only the ANS Forth
9077: locals wordset, but also our own, more powerful locals wordset (we
9078: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9079:
1.78 anton 9080: The ideas in this section have also been published in M. Anton Ertl,
9081: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9082: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9083:
9084: @menu
1.78 anton 9085: * Gforth locals::
9086: * ANS Forth locals::
1.5 anton 9087: @end menu
9088:
1.78 anton 9089: @node Gforth locals, ANS Forth locals, Locals, Locals
9090: @subsection Gforth locals
9091: @cindex Gforth locals
9092: @cindex locals, Gforth style
1.5 anton 9093:
1.78 anton 9094: Locals can be defined with
1.44 crook 9095:
1.78 anton 9096: @example
9097: @{ local1 local2 ... -- comment @}
9098: @end example
9099: or
9100: @example
9101: @{ local1 local2 ... @}
9102: @end example
1.5 anton 9103:
1.78 anton 9104: E.g.,
9105: @example
9106: : max @{ n1 n2 -- n3 @}
9107: n1 n2 > if
9108: n1
9109: else
9110: n2
9111: endif ;
9112: @end example
1.44 crook 9113:
1.78 anton 9114: The similarity of locals definitions with stack comments is intended. A
9115: locals definition often replaces the stack comment of a word. The order
9116: of the locals corresponds to the order in a stack comment and everything
9117: after the @code{--} is really a comment.
1.77 anton 9118:
1.78 anton 9119: This similarity has one disadvantage: It is too easy to confuse locals
9120: declarations with stack comments, causing bugs and making them hard to
9121: find. However, this problem can be avoided by appropriate coding
9122: conventions: Do not use both notations in the same program. If you do,
9123: they should be distinguished using additional means, e.g. by position.
1.77 anton 9124:
1.78 anton 9125: @cindex types of locals
9126: @cindex locals types
9127: The name of the local may be preceded by a type specifier, e.g.,
9128: @code{F:} for a floating point value:
1.5 anton 9129:
1.78 anton 9130: @example
9131: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9132: \ complex multiplication
9133: Ar Br f* Ai Bi f* f-
9134: Ar Bi f* Ai Br f* f+ ;
9135: @end example
1.44 crook 9136:
1.78 anton 9137: @cindex flavours of locals
9138: @cindex locals flavours
9139: @cindex value-flavoured locals
9140: @cindex variable-flavoured locals
9141: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9142: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9143: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9144: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9145: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9146: produces its address (which becomes invalid when the variable's scope is
9147: left). E.g., the standard word @code{emit} can be defined in terms of
9148: @code{type} like this:
1.5 anton 9149:
1.78 anton 9150: @example
9151: : emit @{ C^ char* -- @}
9152: char* 1 type ;
9153: @end example
1.5 anton 9154:
1.78 anton 9155: @cindex default type of locals
9156: @cindex locals, default type
9157: A local without type specifier is a @code{W:} local. Both flavours of
9158: locals are initialized with values from the data or FP stack.
1.44 crook 9159:
1.78 anton 9160: Currently there is no way to define locals with user-defined data
9161: structures, but we are working on it.
1.5 anton 9162:
1.78 anton 9163: Gforth allows defining locals everywhere in a colon definition. This
9164: poses the following questions:
1.5 anton 9165:
1.78 anton 9166: @menu
9167: * Where are locals visible by name?::
9168: * How long do locals live?::
9169: * Locals programming style::
9170: * Locals implementation::
9171: @end menu
1.44 crook 9172:
1.78 anton 9173: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9174: @subsubsection Where are locals visible by name?
9175: @cindex locals visibility
9176: @cindex visibility of locals
9177: @cindex scope of locals
1.5 anton 9178:
1.78 anton 9179: Basically, the answer is that locals are visible where you would expect
9180: it in block-structured languages, and sometimes a little longer. If you
9181: want to restrict the scope of a local, enclose its definition in
9182: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9183:
9184:
1.78 anton 9185: doc-scope
9186: doc-endscope
1.5 anton 9187:
9188:
1.78 anton 9189: These words behave like control structure words, so you can use them
9190: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9191: arbitrary ways.
1.77 anton 9192:
1.78 anton 9193: If you want a more exact answer to the visibility question, here's the
9194: basic principle: A local is visible in all places that can only be
9195: reached through the definition of the local@footnote{In compiler
9196: construction terminology, all places dominated by the definition of the
9197: local.}. In other words, it is not visible in places that can be reached
9198: without going through the definition of the local. E.g., locals defined
9199: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9200: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9201: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9202:
1.78 anton 9203: The reasoning behind this solution is: We want to have the locals
9204: visible as long as it is meaningful. The user can always make the
9205: visibility shorter by using explicit scoping. In a place that can
9206: only be reached through the definition of a local, the meaning of a
9207: local name is clear. In other places it is not: How is the local
9208: initialized at the control flow path that does not contain the
9209: definition? Which local is meant, if the same name is defined twice in
9210: two independent control flow paths?
1.77 anton 9211:
1.78 anton 9212: This should be enough detail for nearly all users, so you can skip the
9213: rest of this section. If you really must know all the gory details and
9214: options, read on.
1.77 anton 9215:
1.78 anton 9216: In order to implement this rule, the compiler has to know which places
9217: are unreachable. It knows this automatically after @code{AHEAD},
9218: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9219: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9220: compiler that the control flow never reaches that place. If
9221: @code{UNREACHABLE} is not used where it could, the only consequence is
9222: that the visibility of some locals is more limited than the rule above
9223: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9224: lie to the compiler), buggy code will be produced.
1.77 anton 9225:
1.5 anton 9226:
1.78 anton 9227: doc-unreachable
1.5 anton 9228:
1.23 crook 9229:
1.78 anton 9230: Another problem with this rule is that at @code{BEGIN}, the compiler
9231: does not know which locals will be visible on the incoming
9232: back-edge. All problems discussed in the following are due to this
9233: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9234: loops as examples; the discussion also applies to @code{?DO} and other
9235: loops). Perhaps the most insidious example is:
1.26 crook 9236: @example
1.78 anton 9237: AHEAD
9238: BEGIN
9239: x
9240: [ 1 CS-ROLL ] THEN
9241: @{ x @}
9242: ...
9243: UNTIL
1.26 crook 9244: @end example
1.23 crook 9245:
1.78 anton 9246: This should be legal according to the visibility rule. The use of
9247: @code{x} can only be reached through the definition; but that appears
9248: textually below the use.
9249:
9250: From this example it is clear that the visibility rules cannot be fully
9251: implemented without major headaches. Our implementation treats common
9252: cases as advertised and the exceptions are treated in a safe way: The
9253: compiler makes a reasonable guess about the locals visible after a
9254: @code{BEGIN}; if it is too pessimistic, the
9255: user will get a spurious error about the local not being defined; if the
9256: compiler is too optimistic, it will notice this later and issue a
9257: warning. In the case above the compiler would complain about @code{x}
9258: being undefined at its use. You can see from the obscure examples in
9259: this section that it takes quite unusual control structures to get the
9260: compiler into trouble, and even then it will often do fine.
1.23 crook 9261:
1.78 anton 9262: If the @code{BEGIN} is reachable from above, the most optimistic guess
9263: is that all locals visible before the @code{BEGIN} will also be
9264: visible after the @code{BEGIN}. This guess is valid for all loops that
9265: are entered only through the @code{BEGIN}, in particular, for normal
9266: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9267: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9268: compiler. When the branch to the @code{BEGIN} is finally generated by
9269: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9270: warns the user if it was too optimistic:
1.26 crook 9271: @example
1.78 anton 9272: IF
9273: @{ x @}
9274: BEGIN
9275: \ x ?
9276: [ 1 cs-roll ] THEN
9277: ...
9278: UNTIL
1.26 crook 9279: @end example
1.23 crook 9280:
1.78 anton 9281: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9282: optimistically assumes that it lives until the @code{THEN}. It notices
9283: this difference when it compiles the @code{UNTIL} and issues a
9284: warning. The user can avoid the warning, and make sure that @code{x}
9285: is not used in the wrong area by using explicit scoping:
9286: @example
9287: IF
9288: SCOPE
9289: @{ x @}
9290: ENDSCOPE
9291: BEGIN
9292: [ 1 cs-roll ] THEN
9293: ...
9294: UNTIL
9295: @end example
1.23 crook 9296:
1.78 anton 9297: Since the guess is optimistic, there will be no spurious error messages
9298: about undefined locals.
1.44 crook 9299:
1.78 anton 9300: If the @code{BEGIN} is not reachable from above (e.g., after
9301: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9302: optimistic guess, as the locals visible after the @code{BEGIN} may be
9303: defined later. Therefore, the compiler assumes that no locals are
9304: visible after the @code{BEGIN}. However, the user can use
9305: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9306: visible at the BEGIN as at the point where the top control-flow stack
9307: item was created.
1.23 crook 9308:
1.44 crook 9309:
1.78 anton 9310: doc-assume-live
1.26 crook 9311:
1.23 crook 9312:
1.78 anton 9313: @noindent
9314: E.g.,
9315: @example
9316: @{ x @}
9317: AHEAD
9318: ASSUME-LIVE
9319: BEGIN
9320: x
9321: [ 1 CS-ROLL ] THEN
9322: ...
9323: UNTIL
9324: @end example
1.44 crook 9325:
1.78 anton 9326: Other cases where the locals are defined before the @code{BEGIN} can be
9327: handled by inserting an appropriate @code{CS-ROLL} before the
9328: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9329: behind the @code{ASSUME-LIVE}).
1.23 crook 9330:
1.78 anton 9331: Cases where locals are defined after the @code{BEGIN} (but should be
9332: visible immediately after the @code{BEGIN}) can only be handled by
9333: rearranging the loop. E.g., the ``most insidious'' example above can be
9334: arranged into:
9335: @example
9336: BEGIN
9337: @{ x @}
9338: ... 0=
9339: WHILE
9340: x
9341: REPEAT
9342: @end example
1.44 crook 9343:
1.78 anton 9344: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9345: @subsubsection How long do locals live?
9346: @cindex locals lifetime
9347: @cindex lifetime of locals
1.23 crook 9348:
1.78 anton 9349: The right answer for the lifetime question would be: A local lives at
9350: least as long as it can be accessed. For a value-flavoured local this
9351: means: until the end of its visibility. However, a variable-flavoured
9352: local could be accessed through its address far beyond its visibility
9353: scope. Ultimately, this would mean that such locals would have to be
9354: garbage collected. Since this entails un-Forth-like implementation
9355: complexities, I adopted the same cowardly solution as some other
9356: languages (e.g., C): The local lives only as long as it is visible;
9357: afterwards its address is invalid (and programs that access it
9358: afterwards are erroneous).
1.23 crook 9359:
1.78 anton 9360: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9361: @subsubsection Locals programming style
9362: @cindex locals programming style
9363: @cindex programming style, locals
1.23 crook 9364:
1.78 anton 9365: The freedom to define locals anywhere has the potential to change
9366: programming styles dramatically. In particular, the need to use the
9367: return stack for intermediate storage vanishes. Moreover, all stack
9368: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9369: determined arguments) can be eliminated: If the stack items are in the
9370: wrong order, just write a locals definition for all of them; then
9371: write the items in the order you want.
1.23 crook 9372:
1.78 anton 9373: This seems a little far-fetched and eliminating stack manipulations is
9374: unlikely to become a conscious programming objective. Still, the number
9375: of stack manipulations will be reduced dramatically if local variables
9376: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9377: a traditional implementation of @code{max}).
1.23 crook 9378:
1.78 anton 9379: This shows one potential benefit of locals: making Forth programs more
9380: readable. Of course, this benefit will only be realized if the
9381: programmers continue to honour the principle of factoring instead of
9382: using the added latitude to make the words longer.
1.23 crook 9383:
1.78 anton 9384: @cindex single-assignment style for locals
9385: Using @code{TO} can and should be avoided. Without @code{TO},
9386: every value-flavoured local has only a single assignment and many
9387: advantages of functional languages apply to Forth. I.e., programs are
9388: easier to analyse, to optimize and to read: It is clear from the
9389: definition what the local stands for, it does not turn into something
9390: different later.
1.23 crook 9391:
1.78 anton 9392: E.g., a definition using @code{TO} might look like this:
9393: @example
9394: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9395: u1 u2 min 0
9396: ?do
9397: addr1 c@@ addr2 c@@ -
9398: ?dup-if
9399: unloop exit
9400: then
9401: addr1 char+ TO addr1
9402: addr2 char+ TO addr2
9403: loop
9404: u1 u2 - ;
1.26 crook 9405: @end example
1.78 anton 9406: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9407: every loop iteration. @code{strcmp} is a typical example of the
9408: readability problems of using @code{TO}. When you start reading
9409: @code{strcmp}, you think that @code{addr1} refers to the start of the
9410: string. Only near the end of the loop you realize that it is something
9411: else.
1.23 crook 9412:
1.78 anton 9413: This can be avoided by defining two locals at the start of the loop that
9414: are initialized with the right value for the current iteration.
9415: @example
9416: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9417: addr1 addr2
9418: u1 u2 min 0
9419: ?do @{ s1 s2 @}
9420: s1 c@@ s2 c@@ -
9421: ?dup-if
9422: unloop exit
9423: then
9424: s1 char+ s2 char+
9425: loop
9426: 2drop
9427: u1 u2 - ;
9428: @end example
9429: Here it is clear from the start that @code{s1} has a different value
9430: in every loop iteration.
1.23 crook 9431:
1.78 anton 9432: @node Locals implementation, , Locals programming style, Gforth locals
9433: @subsubsection Locals implementation
9434: @cindex locals implementation
9435: @cindex implementation of locals
1.23 crook 9436:
1.78 anton 9437: @cindex locals stack
9438: Gforth uses an extra locals stack. The most compelling reason for
9439: this is that the return stack is not float-aligned; using an extra stack
9440: also eliminates the problems and restrictions of using the return stack
9441: as locals stack. Like the other stacks, the locals stack grows toward
9442: lower addresses. A few primitives allow an efficient implementation:
9443:
9444:
9445: doc-@local#
9446: doc-f@local#
9447: doc-laddr#
9448: doc-lp+!#
9449: doc-lp!
9450: doc->l
9451: doc-f>l
9452:
9453:
9454: In addition to these primitives, some specializations of these
9455: primitives for commonly occurring inline arguments are provided for
9456: efficiency reasons, e.g., @code{@@local0} as specialization of
9457: @code{@@local#} for the inline argument 0. The following compiling words
9458: compile the right specialized version, or the general version, as
9459: appropriate:
1.23 crook 9460:
1.5 anton 9461:
1.107 dvdkhlng 9462: @c doc-compile-@local
9463: @c doc-compile-f@local
1.78 anton 9464: doc-compile-lp+!
1.5 anton 9465:
9466:
1.78 anton 9467: Combinations of conditional branches and @code{lp+!#} like
9468: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9469: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9470:
1.78 anton 9471: A special area in the dictionary space is reserved for keeping the
9472: local variable names. @code{@{} switches the dictionary pointer to this
9473: area and @code{@}} switches it back and generates the locals
9474: initializing code. @code{W:} etc.@ are normal defining words. This
9475: special area is cleared at the start of every colon definition.
1.5 anton 9476:
1.78 anton 9477: @cindex word list for defining locals
9478: A special feature of Gforth's dictionary is used to implement the
9479: definition of locals without type specifiers: every word list (aka
9480: vocabulary) has its own methods for searching
9481: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9482: with a special search method: When it is searched for a word, it
9483: actually creates that word using @code{W:}. @code{@{} changes the search
9484: order to first search the word list containing @code{@}}, @code{W:} etc.,
9485: and then the word list for defining locals without type specifiers.
1.5 anton 9486:
1.78 anton 9487: The lifetime rules support a stack discipline within a colon
9488: definition: The lifetime of a local is either nested with other locals
9489: lifetimes or it does not overlap them.
1.23 crook 9490:
1.78 anton 9491: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9492: pointer manipulation is generated. Between control structure words
9493: locals definitions can push locals onto the locals stack. @code{AGAIN}
9494: is the simplest of the other three control flow words. It has to
9495: restore the locals stack depth of the corresponding @code{BEGIN}
9496: before branching. The code looks like this:
9497: @format
9498: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9499: @code{branch} <begin>
9500: @end format
1.26 crook 9501:
1.78 anton 9502: @code{UNTIL} is a little more complicated: If it branches back, it
9503: must adjust the stack just like @code{AGAIN}. But if it falls through,
9504: the locals stack must not be changed. The compiler generates the
9505: following code:
9506: @format
9507: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9508: @end format
9509: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9510:
1.78 anton 9511: @code{THEN} can produce somewhat inefficient code:
9512: @format
9513: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9514: <orig target>:
9515: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9516: @end format
9517: The second @code{lp+!#} adjusts the locals stack pointer from the
9518: level at the @i{orig} point to the level after the @code{THEN}. The
9519: first @code{lp+!#} adjusts the locals stack pointer from the current
9520: level to the level at the orig point, so the complete effect is an
9521: adjustment from the current level to the right level after the
9522: @code{THEN}.
1.26 crook 9523:
1.78 anton 9524: @cindex locals information on the control-flow stack
9525: @cindex control-flow stack items, locals information
9526: In a conventional Forth implementation a dest control-flow stack entry
9527: is just the target address and an orig entry is just the address to be
9528: patched. Our locals implementation adds a word list to every orig or dest
9529: item. It is the list of locals visible (or assumed visible) at the point
9530: described by the entry. Our implementation also adds a tag to identify
9531: the kind of entry, in particular to differentiate between live and dead
9532: (reachable and unreachable) orig entries.
1.26 crook 9533:
1.78 anton 9534: A few unusual operations have to be performed on locals word lists:
1.44 crook 9535:
1.5 anton 9536:
1.78 anton 9537: doc-common-list
9538: doc-sub-list?
9539: doc-list-size
1.52 anton 9540:
9541:
1.78 anton 9542: Several features of our locals word list implementation make these
9543: operations easy to implement: The locals word lists are organised as
9544: linked lists; the tails of these lists are shared, if the lists
9545: contain some of the same locals; and the address of a name is greater
9546: than the address of the names behind it in the list.
1.5 anton 9547:
1.78 anton 9548: Another important implementation detail is the variable
9549: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9550: determine if they can be reached directly or only through the branch
9551: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9552: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9553: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9554:
1.78 anton 9555: Counted loops are similar to other loops in most respects, but
9556: @code{LEAVE} requires special attention: It performs basically the same
9557: service as @code{AHEAD}, but it does not create a control-flow stack
9558: entry. Therefore the information has to be stored elsewhere;
9559: traditionally, the information was stored in the target fields of the
9560: branches created by the @code{LEAVE}s, by organizing these fields into a
9561: linked list. Unfortunately, this clever trick does not provide enough
9562: space for storing our extended control flow information. Therefore, we
9563: introduce another stack, the leave stack. It contains the control-flow
9564: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9565:
1.78 anton 9566: Local names are kept until the end of the colon definition, even if
9567: they are no longer visible in any control-flow path. In a few cases
9568: this may lead to increased space needs for the locals name area, but
9569: usually less than reclaiming this space would cost in code size.
1.5 anton 9570:
1.44 crook 9571:
1.78 anton 9572: @node ANS Forth locals, , Gforth locals, Locals
9573: @subsection ANS Forth locals
9574: @cindex locals, ANS Forth style
1.5 anton 9575:
1.78 anton 9576: The ANS Forth locals wordset does not define a syntax for locals, but
9577: words that make it possible to define various syntaxes. One of the
9578: possible syntaxes is a subset of the syntax we used in the Gforth locals
9579: wordset, i.e.:
1.29 crook 9580:
9581: @example
1.78 anton 9582: @{ local1 local2 ... -- comment @}
9583: @end example
9584: @noindent
9585: or
9586: @example
9587: @{ local1 local2 ... @}
1.29 crook 9588: @end example
9589:
1.78 anton 9590: The order of the locals corresponds to the order in a stack comment. The
9591: restrictions are:
1.5 anton 9592:
1.78 anton 9593: @itemize @bullet
9594: @item
9595: Locals can only be cell-sized values (no type specifiers are allowed).
9596: @item
9597: Locals can be defined only outside control structures.
9598: @item
9599: Locals can interfere with explicit usage of the return stack. For the
9600: exact (and long) rules, see the standard. If you don't use return stack
9601: accessing words in a definition using locals, you will be all right. The
9602: purpose of this rule is to make locals implementation on the return
9603: stack easier.
9604: @item
9605: The whole definition must be in one line.
9606: @end itemize
1.5 anton 9607:
1.78 anton 9608: Locals defined in ANS Forth behave like @code{VALUE}s
9609: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9610: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9611:
1.78 anton 9612: Since the syntax above is supported by Gforth directly, you need not do
9613: anything to use it. If you want to port a program using this syntax to
9614: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9615: syntax on the other system.
1.5 anton 9616:
1.78 anton 9617: Note that a syntax shown in the standard, section A.13 looks
9618: similar, but is quite different in having the order of locals
9619: reversed. Beware!
1.5 anton 9620:
1.78 anton 9621: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9622:
1.78 anton 9623: doc-(local)
1.5 anton 9624:
1.78 anton 9625: The ANS Forth locals extension wordset defines a syntax using
9626: @code{locals|}, but it is so awful that we strongly recommend not to use
9627: it. We have implemented this syntax to make porting to Gforth easy, but
9628: do not document it here. The problem with this syntax is that the locals
9629: are defined in an order reversed with respect to the standard stack
9630: comment notation, making programs harder to read, and easier to misread
9631: and miswrite. The only merit of this syntax is that it is easy to
9632: implement using the ANS Forth locals wordset.
1.53 anton 9633:
9634:
1.78 anton 9635: @c ----------------------------------------------------------
9636: @node Structures, Object-oriented Forth, Locals, Words
9637: @section Structures
9638: @cindex structures
9639: @cindex records
1.53 anton 9640:
1.78 anton 9641: This section presents the structure package that comes with Gforth. A
9642: version of the package implemented in ANS Forth is available in
9643: @file{compat/struct.fs}. This package was inspired by a posting on
9644: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9645: possibly John Hayes). A version of this section has been published in
9646: M. Anton Ertl,
9647: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9648: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9649: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9650:
1.78 anton 9651: @menu
9652: * Why explicit structure support?::
9653: * Structure Usage::
9654: * Structure Naming Convention::
9655: * Structure Implementation::
9656: * Structure Glossary::
9657: @end menu
1.55 anton 9658:
1.78 anton 9659: @node Why explicit structure support?, Structure Usage, Structures, Structures
9660: @subsection Why explicit structure support?
1.53 anton 9661:
1.78 anton 9662: @cindex address arithmetic for structures
9663: @cindex structures using address arithmetic
9664: If we want to use a structure containing several fields, we could simply
9665: reserve memory for it, and access the fields using address arithmetic
9666: (@pxref{Address arithmetic}). As an example, consider a structure with
9667: the following fields
1.57 anton 9668:
1.78 anton 9669: @table @code
9670: @item a
9671: is a float
9672: @item b
9673: is a cell
9674: @item c
9675: is a float
9676: @end table
1.57 anton 9677:
1.78 anton 9678: Given the (float-aligned) base address of the structure we get the
9679: address of the field
1.52 anton 9680:
1.78 anton 9681: @table @code
9682: @item a
9683: without doing anything further.
9684: @item b
9685: with @code{float+}
9686: @item c
9687: with @code{float+ cell+ faligned}
9688: @end table
1.52 anton 9689:
1.78 anton 9690: It is easy to see that this can become quite tiring.
1.52 anton 9691:
1.78 anton 9692: Moreover, it is not very readable, because seeing a
9693: @code{cell+} tells us neither which kind of structure is
9694: accessed nor what field is accessed; we have to somehow infer the kind
9695: of structure, and then look up in the documentation, which field of
9696: that structure corresponds to that offset.
1.53 anton 9697:
1.78 anton 9698: Finally, this kind of address arithmetic also causes maintenance
9699: troubles: If you add or delete a field somewhere in the middle of the
9700: structure, you have to find and change all computations for the fields
9701: afterwards.
1.52 anton 9702:
1.78 anton 9703: So, instead of using @code{cell+} and friends directly, how
9704: about storing the offsets in constants:
1.52 anton 9705:
1.78 anton 9706: @example
9707: 0 constant a-offset
9708: 0 float+ constant b-offset
9709: 0 float+ cell+ faligned c-offset
9710: @end example
1.64 pazsan 9711:
1.78 anton 9712: Now we can get the address of field @code{x} with @code{x-offset
9713: +}. This is much better in all respects. Of course, you still
9714: have to change all later offset definitions if you add a field. You can
9715: fix this by declaring the offsets in the following way:
1.57 anton 9716:
1.78 anton 9717: @example
9718: 0 constant a-offset
9719: a-offset float+ constant b-offset
9720: b-offset cell+ faligned constant c-offset
9721: @end example
1.57 anton 9722:
1.78 anton 9723: Since we always use the offsets with @code{+}, we could use a defining
9724: word @code{cfield} that includes the @code{+} in the action of the
9725: defined word:
1.64 pazsan 9726:
1.78 anton 9727: @example
9728: : cfield ( n "name" -- )
9729: create ,
9730: does> ( name execution: addr1 -- addr2 )
9731: @@ + ;
1.64 pazsan 9732:
1.78 anton 9733: 0 cfield a
9734: 0 a float+ cfield b
9735: 0 b cell+ faligned cfield c
9736: @end example
1.64 pazsan 9737:
1.78 anton 9738: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9739:
1.78 anton 9740: The structure field words now can be used quite nicely. However,
9741: their definition is still a bit cumbersome: We have to repeat the
9742: name, the information about size and alignment is distributed before
9743: and after the field definitions etc. The structure package presented
9744: here addresses these problems.
1.64 pazsan 9745:
1.78 anton 9746: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9747: @subsection Structure Usage
9748: @cindex structure usage
1.57 anton 9749:
1.78 anton 9750: @cindex @code{field} usage
9751: @cindex @code{struct} usage
9752: @cindex @code{end-struct} usage
9753: You can define a structure for a (data-less) linked list with:
1.57 anton 9754: @example
1.78 anton 9755: struct
9756: cell% field list-next
9757: end-struct list%
1.57 anton 9758: @end example
9759:
1.78 anton 9760: With the address of the list node on the stack, you can compute the
9761: address of the field that contains the address of the next node with
9762: @code{list-next}. E.g., you can determine the length of a list
9763: with:
1.57 anton 9764:
9765: @example
1.78 anton 9766: : list-length ( list -- n )
9767: \ "list" is a pointer to the first element of a linked list
9768: \ "n" is the length of the list
9769: 0 BEGIN ( list1 n1 )
9770: over
9771: WHILE ( list1 n1 )
9772: 1+ swap list-next @@ swap
9773: REPEAT
9774: nip ;
1.57 anton 9775: @end example
9776:
1.78 anton 9777: You can reserve memory for a list node in the dictionary with
9778: @code{list% %allot}, which leaves the address of the list node on the
9779: stack. For the equivalent allocation on the heap you can use @code{list%
9780: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9781: use @code{list% %allocate}). You can get the the size of a list
9782: node with @code{list% %size} and its alignment with @code{list%
9783: %alignment}.
9784:
9785: Note that in ANS Forth the body of a @code{create}d word is
9786: @code{aligned} but not necessarily @code{faligned};
9787: therefore, if you do a:
1.57 anton 9788:
9789: @example
1.78 anton 9790: create @emph{name} foo% %allot drop
1.57 anton 9791: @end example
9792:
1.78 anton 9793: @noindent
9794: then the memory alloted for @code{foo%} is guaranteed to start at the
9795: body of @code{@emph{name}} only if @code{foo%} contains only character,
9796: cell and double fields. Therefore, if your structure contains floats,
9797: better use
1.57 anton 9798:
9799: @example
1.78 anton 9800: foo% %allot constant @emph{name}
1.57 anton 9801: @end example
9802:
1.78 anton 9803: @cindex structures containing structures
9804: You can include a structure @code{foo%} as a field of
9805: another structure, like this:
1.65 anton 9806: @example
1.78 anton 9807: struct
9808: ...
9809: foo% field ...
9810: ...
9811: end-struct ...
1.65 anton 9812: @end example
1.52 anton 9813:
1.78 anton 9814: @cindex structure extension
9815: @cindex extended records
9816: Instead of starting with an empty structure, you can extend an
9817: existing structure. E.g., a plain linked list without data, as defined
9818: above, is hardly useful; You can extend it to a linked list of integers,
9819: like this:@footnote{This feature is also known as @emph{extended
9820: records}. It is the main innovation in the Oberon language; in other
9821: words, adding this feature to Modula-2 led Wirth to create a new
9822: language, write a new compiler etc. Adding this feature to Forth just
9823: required a few lines of code.}
1.52 anton 9824:
1.78 anton 9825: @example
9826: list%
9827: cell% field intlist-int
9828: end-struct intlist%
9829: @end example
1.55 anton 9830:
1.78 anton 9831: @code{intlist%} is a structure with two fields:
9832: @code{list-next} and @code{intlist-int}.
1.55 anton 9833:
1.78 anton 9834: @cindex structures containing arrays
9835: You can specify an array type containing @emph{n} elements of
9836: type @code{foo%} like this:
1.55 anton 9837:
9838: @example
1.78 anton 9839: foo% @emph{n} *
1.56 anton 9840: @end example
1.55 anton 9841:
1.78 anton 9842: You can use this array type in any place where you can use a normal
9843: type, e.g., when defining a @code{field}, or with
9844: @code{%allot}.
9845:
9846: @cindex first field optimization
9847: The first field is at the base address of a structure and the word for
9848: this field (e.g., @code{list-next}) actually does not change the address
9849: on the stack. You may be tempted to leave it away in the interest of
9850: run-time and space efficiency. This is not necessary, because the
9851: structure package optimizes this case: If you compile a first-field
9852: words, no code is generated. So, in the interest of readability and
9853: maintainability you should include the word for the field when accessing
9854: the field.
1.52 anton 9855:
9856:
1.78 anton 9857: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9858: @subsection Structure Naming Convention
9859: @cindex structure naming convention
1.52 anton 9860:
1.78 anton 9861: The field names that come to (my) mind are often quite generic, and,
9862: if used, would cause frequent name clashes. E.g., many structures
9863: probably contain a @code{counter} field. The structure names
9864: that come to (my) mind are often also the logical choice for the names
9865: of words that create such a structure.
1.52 anton 9866:
1.78 anton 9867: Therefore, I have adopted the following naming conventions:
1.52 anton 9868:
1.78 anton 9869: @itemize @bullet
9870: @cindex field naming convention
9871: @item
9872: The names of fields are of the form
9873: @code{@emph{struct}-@emph{field}}, where
9874: @code{@emph{struct}} is the basic name of the structure, and
9875: @code{@emph{field}} is the basic name of the field. You can
9876: think of field words as converting the (address of the)
9877: structure into the (address of the) field.
1.52 anton 9878:
1.78 anton 9879: @cindex structure naming convention
9880: @item
9881: The names of structures are of the form
9882: @code{@emph{struct}%}, where
9883: @code{@emph{struct}} is the basic name of the structure.
9884: @end itemize
1.52 anton 9885:
1.78 anton 9886: This naming convention does not work that well for fields of extended
9887: structures; e.g., the integer list structure has a field
9888: @code{intlist-int}, but has @code{list-next}, not
9889: @code{intlist-next}.
1.53 anton 9890:
1.78 anton 9891: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9892: @subsection Structure Implementation
9893: @cindex structure implementation
9894: @cindex implementation of structures
1.52 anton 9895:
1.78 anton 9896: The central idea in the implementation is to pass the data about the
9897: structure being built on the stack, not in some global
9898: variable. Everything else falls into place naturally once this design
9899: decision is made.
1.53 anton 9900:
1.78 anton 9901: The type description on the stack is of the form @emph{align
9902: size}. Keeping the size on the top-of-stack makes dealing with arrays
9903: very simple.
1.53 anton 9904:
1.78 anton 9905: @code{field} is a defining word that uses @code{Create}
9906: and @code{DOES>}. The body of the field contains the offset
9907: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9908:
9909: @example
1.78 anton 9910: @@ +
1.53 anton 9911: @end example
9912:
1.78 anton 9913: @noindent
9914: i.e., add the offset to the address, giving the stack effect
9915: @i{addr1 -- addr2} for a field.
9916:
9917: @cindex first field optimization, implementation
9918: This simple structure is slightly complicated by the optimization
9919: for fields with offset 0, which requires a different
9920: @code{DOES>}-part (because we cannot rely on there being
9921: something on the stack if such a field is invoked during
9922: compilation). Therefore, we put the different @code{DOES>}-parts
9923: in separate words, and decide which one to invoke based on the
9924: offset. For a zero offset, the field is basically a noop; it is
9925: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9926:
1.78 anton 9927: @node Structure Glossary, , Structure Implementation, Structures
9928: @subsection Structure Glossary
9929: @cindex structure glossary
1.53 anton 9930:
1.5 anton 9931:
1.78 anton 9932: doc-%align
9933: doc-%alignment
9934: doc-%alloc
9935: doc-%allocate
9936: doc-%allot
9937: doc-cell%
9938: doc-char%
9939: doc-dfloat%
9940: doc-double%
9941: doc-end-struct
9942: doc-field
9943: doc-float%
9944: doc-naligned
9945: doc-sfloat%
9946: doc-%size
9947: doc-struct
1.54 anton 9948:
9949:
1.26 crook 9950: @c -------------------------------------------------------------
1.78 anton 9951: @node Object-oriented Forth, Programming Tools, Structures, Words
9952: @section Object-oriented Forth
9953:
9954: Gforth comes with three packages for object-oriented programming:
9955: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9956: is preloaded, so you have to @code{include} them before use. The most
9957: important differences between these packages (and others) are discussed
9958: in @ref{Comparison with other object models}. All packages are written
9959: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9960:
1.78 anton 9961: @menu
9962: * Why object-oriented programming?::
9963: * Object-Oriented Terminology::
9964: * Objects::
9965: * OOF::
9966: * Mini-OOF::
9967: * Comparison with other object models::
9968: @end menu
1.5 anton 9969:
1.78 anton 9970: @c ----------------------------------------------------------------
9971: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9972: @subsection Why object-oriented programming?
9973: @cindex object-oriented programming motivation
9974: @cindex motivation for object-oriented programming
1.44 crook 9975:
1.78 anton 9976: Often we have to deal with several data structures (@emph{objects}),
9977: that have to be treated similarly in some respects, but differently in
9978: others. Graphical objects are the textbook example: circles, triangles,
9979: dinosaurs, icons, and others, and we may want to add more during program
9980: development. We want to apply some operations to any graphical object,
9981: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9982: has to do something different for every kind of object.
9983: @comment TODO add some other operations eg perimeter, area
9984: @comment and tie in to concrete examples later..
1.5 anton 9985:
1.78 anton 9986: We could implement @code{draw} as a big @code{CASE}
9987: control structure that executes the appropriate code depending on the
9988: kind of object to be drawn. This would be not be very elegant, and,
9989: moreover, we would have to change @code{draw} every time we add
9990: a new kind of graphical object (say, a spaceship).
1.44 crook 9991:
1.78 anton 9992: What we would rather do is: When defining spaceships, we would tell
9993: the system: ``Here's how you @code{draw} a spaceship; you figure
9994: out the rest''.
1.5 anton 9995:
1.78 anton 9996: This is the problem that all systems solve that (rightfully) call
9997: themselves object-oriented; the object-oriented packages presented here
9998: solve this problem (and not much else).
9999: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10000:
1.78 anton 10001: @c ------------------------------------------------------------------------
10002: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10003: @subsection Object-Oriented Terminology
10004: @cindex object-oriented terminology
10005: @cindex terminology for object-oriented programming
1.5 anton 10006:
1.78 anton 10007: This section is mainly for reference, so you don't have to understand
10008: all of it right away. The terminology is mainly Smalltalk-inspired. In
10009: short:
1.44 crook 10010:
1.78 anton 10011: @table @emph
10012: @cindex class
10013: @item class
10014: a data structure definition with some extras.
1.5 anton 10015:
1.78 anton 10016: @cindex object
10017: @item object
10018: an instance of the data structure described by the class definition.
1.5 anton 10019:
1.78 anton 10020: @cindex instance variables
10021: @item instance variables
10022: fields of the data structure.
1.5 anton 10023:
1.78 anton 10024: @cindex selector
10025: @cindex method selector
10026: @cindex virtual function
10027: @item selector
10028: (or @emph{method selector}) a word (e.g.,
10029: @code{draw}) that performs an operation on a variety of data
10030: structures (classes). A selector describes @emph{what} operation to
10031: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10032:
1.78 anton 10033: @cindex method
10034: @item method
10035: the concrete definition that performs the operation
10036: described by the selector for a specific class. A method specifies
10037: @emph{how} the operation is performed for a specific class.
1.5 anton 10038:
1.78 anton 10039: @cindex selector invocation
10040: @cindex message send
10041: @cindex invoking a selector
10042: @item selector invocation
10043: a call of a selector. One argument of the call (the TOS (top-of-stack))
10044: is used for determining which method is used. In Smalltalk terminology:
10045: a message (consisting of the selector and the other arguments) is sent
10046: to the object.
1.5 anton 10047:
1.78 anton 10048: @cindex receiving object
10049: @item receiving object
10050: the object used for determining the method executed by a selector
10051: invocation. In the @file{objects.fs} model, it is the object that is on
10052: the TOS when the selector is invoked. (@emph{Receiving} comes from
10053: the Smalltalk @emph{message} terminology.)
1.5 anton 10054:
1.78 anton 10055: @cindex child class
10056: @cindex parent class
10057: @cindex inheritance
10058: @item child class
10059: a class that has (@emph{inherits}) all properties (instance variables,
10060: selectors, methods) from a @emph{parent class}. In Smalltalk
10061: terminology: The subclass inherits from the superclass. In C++
10062: terminology: The derived class inherits from the base class.
1.5 anton 10063:
1.78 anton 10064: @end table
1.5 anton 10065:
1.78 anton 10066: @c If you wonder about the message sending terminology, it comes from
10067: @c a time when each object had it's own task and objects communicated via
10068: @c message passing; eventually the Smalltalk developers realized that
10069: @c they can do most things through simple (indirect) calls. They kept the
10070: @c terminology.
1.5 anton 10071:
1.78 anton 10072: @c --------------------------------------------------------------
10073: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10074: @subsection The @file{objects.fs} model
10075: @cindex objects
10076: @cindex object-oriented programming
1.26 crook 10077:
1.78 anton 10078: @cindex @file{objects.fs}
10079: @cindex @file{oof.fs}
1.26 crook 10080:
1.78 anton 10081: This section describes the @file{objects.fs} package. This material also
10082: has been published in M. Anton Ertl,
10083: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10084: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10085: 37--43.
10086: @c McKewan's and Zsoter's packages
1.26 crook 10087:
1.78 anton 10088: This section assumes that you have read @ref{Structures}.
1.5 anton 10089:
1.78 anton 10090: The techniques on which this model is based have been used to implement
10091: the parser generator, Gray, and have also been used in Gforth for
10092: implementing the various flavours of word lists (hashed or not,
10093: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10094:
10095:
1.26 crook 10096: @menu
1.78 anton 10097: * Properties of the Objects model::
10098: * Basic Objects Usage::
10099: * The Objects base class::
10100: * Creating objects::
10101: * Object-Oriented Programming Style::
10102: * Class Binding::
10103: * Method conveniences::
10104: * Classes and Scoping::
10105: * Dividing classes::
10106: * Object Interfaces::
10107: * Objects Implementation::
10108: * Objects Glossary::
1.26 crook 10109: @end menu
1.5 anton 10110:
1.78 anton 10111: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10112:
1.78 anton 10113: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10114: @subsubsection Properties of the @file{objects.fs} model
10115: @cindex @file{objects.fs} properties
1.5 anton 10116:
1.78 anton 10117: @itemize @bullet
10118: @item
10119: It is straightforward to pass objects on the stack. Passing
10120: selectors on the stack is a little less convenient, but possible.
1.44 crook 10121:
1.78 anton 10122: @item
10123: Objects are just data structures in memory, and are referenced by their
10124: address. You can create words for objects with normal defining words
10125: like @code{constant}. Likewise, there is no difference between instance
10126: variables that contain objects and those that contain other data.
1.5 anton 10127:
1.78 anton 10128: @item
10129: Late binding is efficient and easy to use.
1.44 crook 10130:
1.78 anton 10131: @item
10132: It avoids parsing, and thus avoids problems with state-smartness
10133: and reduced extensibility; for convenience there are a few parsing
10134: words, but they have non-parsing counterparts. There are also a few
10135: defining words that parse. This is hard to avoid, because all standard
10136: defining words parse (except @code{:noname}); however, such
10137: words are not as bad as many other parsing words, because they are not
10138: state-smart.
1.5 anton 10139:
1.78 anton 10140: @item
10141: It does not try to incorporate everything. It does a few things and does
10142: them well (IMO). In particular, this model was not designed to support
10143: information hiding (although it has features that may help); you can use
10144: a separate package for achieving this.
1.5 anton 10145:
1.78 anton 10146: @item
10147: It is layered; you don't have to learn and use all features to use this
10148: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10149: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10150: are optional and independent of each other.
1.5 anton 10151:
1.78 anton 10152: @item
10153: An implementation in ANS Forth is available.
1.5 anton 10154:
1.78 anton 10155: @end itemize
1.5 anton 10156:
1.44 crook 10157:
1.78 anton 10158: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10159: @subsubsection Basic @file{objects.fs} Usage
10160: @cindex basic objects usage
10161: @cindex objects, basic usage
1.5 anton 10162:
1.78 anton 10163: You can define a class for graphical objects like this:
1.44 crook 10164:
1.78 anton 10165: @cindex @code{class} usage
10166: @cindex @code{end-class} usage
10167: @cindex @code{selector} usage
1.5 anton 10168: @example
1.78 anton 10169: object class \ "object" is the parent class
10170: selector draw ( x y graphical -- )
10171: end-class graphical
10172: @end example
10173:
10174: This code defines a class @code{graphical} with an
10175: operation @code{draw}. We can perform the operation
10176: @code{draw} on any @code{graphical} object, e.g.:
10177:
10178: @example
10179: 100 100 t-rex draw
1.26 crook 10180: @end example
1.5 anton 10181:
1.78 anton 10182: @noindent
10183: where @code{t-rex} is a word (say, a constant) that produces a
10184: graphical object.
10185:
10186: @comment TODO add a 2nd operation eg perimeter.. and use for
10187: @comment a concrete example
1.5 anton 10188:
1.78 anton 10189: @cindex abstract class
10190: How do we create a graphical object? With the present definitions,
10191: we cannot create a useful graphical object. The class
10192: @code{graphical} describes graphical objects in general, but not
10193: any concrete graphical object type (C++ users would call it an
10194: @emph{abstract class}); e.g., there is no method for the selector
10195: @code{draw} in the class @code{graphical}.
1.5 anton 10196:
1.78 anton 10197: For concrete graphical objects, we define child classes of the
10198: class @code{graphical}, e.g.:
1.5 anton 10199:
1.78 anton 10200: @cindex @code{overrides} usage
10201: @cindex @code{field} usage in class definition
1.26 crook 10202: @example
1.78 anton 10203: graphical class \ "graphical" is the parent class
10204: cell% field circle-radius
1.5 anton 10205:
1.78 anton 10206: :noname ( x y circle -- )
10207: circle-radius @@ draw-circle ;
10208: overrides draw
1.5 anton 10209:
1.78 anton 10210: :noname ( n-radius circle -- )
10211: circle-radius ! ;
10212: overrides construct
1.5 anton 10213:
1.78 anton 10214: end-class circle
10215: @end example
1.44 crook 10216:
1.78 anton 10217: Here we define a class @code{circle} as a child of @code{graphical},
10218: with field @code{circle-radius} (which behaves just like a field
10219: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10220: for the selectors @code{draw} and @code{construct} (@code{construct} is
10221: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10222:
1.78 anton 10223: Now we can create a circle on the heap (i.e.,
10224: @code{allocate}d memory) with:
1.44 crook 10225:
1.78 anton 10226: @cindex @code{heap-new} usage
1.5 anton 10227: @example
1.78 anton 10228: 50 circle heap-new constant my-circle
1.5 anton 10229: @end example
10230:
1.78 anton 10231: @noindent
10232: @code{heap-new} invokes @code{construct}, thus
10233: initializing the field @code{circle-radius} with 50. We can draw
10234: this new circle at (100,100) with:
1.5 anton 10235:
10236: @example
1.78 anton 10237: 100 100 my-circle draw
1.5 anton 10238: @end example
10239:
1.78 anton 10240: @cindex selector invocation, restrictions
10241: @cindex class definition, restrictions
10242: Note: You can only invoke a selector if the object on the TOS
10243: (the receiving object) belongs to the class where the selector was
10244: defined or one of its descendents; e.g., you can invoke
10245: @code{draw} only for objects belonging to @code{graphical}
10246: or its descendents (e.g., @code{circle}). Immediately before
10247: @code{end-class}, the search order has to be the same as
10248: immediately after @code{class}.
10249:
10250: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10251: @subsubsection The @file{object.fs} base class
10252: @cindex @code{object} class
10253:
10254: When you define a class, you have to specify a parent class. So how do
10255: you start defining classes? There is one class available from the start:
10256: @code{object}. It is ancestor for all classes and so is the
10257: only class that has no parent. It has two selectors: @code{construct}
10258: and @code{print}.
10259:
10260: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10261: @subsubsection Creating objects
10262: @cindex creating objects
10263: @cindex object creation
10264: @cindex object allocation options
10265:
10266: @cindex @code{heap-new} discussion
10267: @cindex @code{dict-new} discussion
10268: @cindex @code{construct} discussion
10269: You can create and initialize an object of a class on the heap with
10270: @code{heap-new} ( ... class -- object ) and in the dictionary
10271: (allocation with @code{allot}) with @code{dict-new} (
10272: ... class -- object ). Both words invoke @code{construct}, which
10273: consumes the stack items indicated by "..." above.
10274:
10275: @cindex @code{init-object} discussion
10276: @cindex @code{class-inst-size} discussion
10277: If you want to allocate memory for an object yourself, you can get its
10278: alignment and size with @code{class-inst-size 2@@} ( class --
10279: align size ). Once you have memory for an object, you can initialize
10280: it with @code{init-object} ( ... class object -- );
10281: @code{construct} does only a part of the necessary work.
10282:
10283: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10284: @subsubsection Object-Oriented Programming Style
10285: @cindex object-oriented programming style
10286: @cindex programming style, object-oriented
1.5 anton 10287:
1.78 anton 10288: This section is not exhaustive.
1.5 anton 10289:
1.78 anton 10290: @cindex stack effects of selectors
10291: @cindex selectors and stack effects
10292: In general, it is a good idea to ensure that all methods for the
10293: same selector have the same stack effect: when you invoke a selector,
10294: you often have no idea which method will be invoked, so, unless all
10295: methods have the same stack effect, you will not know the stack effect
10296: of the selector invocation.
1.5 anton 10297:
1.78 anton 10298: One exception to this rule is methods for the selector
10299: @code{construct}. We know which method is invoked, because we
10300: specify the class to be constructed at the same place. Actually, I
10301: defined @code{construct} as a selector only to give the users a
10302: convenient way to specify initialization. The way it is used, a
10303: mechanism different from selector invocation would be more natural
10304: (but probably would take more code and more space to explain).
1.5 anton 10305:
1.78 anton 10306: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10307: @subsubsection Class Binding
10308: @cindex class binding
10309: @cindex early binding
1.5 anton 10310:
1.78 anton 10311: @cindex late binding
10312: Normal selector invocations determine the method at run-time depending
10313: on the class of the receiving object. This run-time selection is called
10314: @i{late binding}.
1.5 anton 10315:
1.78 anton 10316: Sometimes it's preferable to invoke a different method. For example,
10317: you might want to use the simple method for @code{print}ing
10318: @code{object}s instead of the possibly long-winded @code{print} method
10319: of the receiver class. You can achieve this by replacing the invocation
10320: of @code{print} with:
1.5 anton 10321:
1.78 anton 10322: @cindex @code{[bind]} usage
1.5 anton 10323: @example
1.78 anton 10324: [bind] object print
1.5 anton 10325: @end example
10326:
1.78 anton 10327: @noindent
10328: in compiled code or:
10329:
10330: @cindex @code{bind} usage
1.5 anton 10331: @example
1.78 anton 10332: bind object print
1.5 anton 10333: @end example
10334:
1.78 anton 10335: @cindex class binding, alternative to
10336: @noindent
10337: in interpreted code. Alternatively, you can define the method with a
10338: name (e.g., @code{print-object}), and then invoke it through the
10339: name. Class binding is just a (often more convenient) way to achieve
10340: the same effect; it avoids name clutter and allows you to invoke
10341: methods directly without naming them first.
1.5 anton 10342:
1.78 anton 10343: @cindex superclass binding
10344: @cindex parent class binding
10345: A frequent use of class binding is this: When we define a method
10346: for a selector, we often want the method to do what the selector does
10347: in the parent class, and a little more. There is a special word for
10348: this purpose: @code{[parent]}; @code{[parent]
10349: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10350: selector}}, where @code{@emph{parent}} is the parent
10351: class of the current class. E.g., a method definition might look like:
1.44 crook 10352:
1.78 anton 10353: @cindex @code{[parent]} usage
10354: @example
10355: :noname
10356: dup [parent] foo \ do parent's foo on the receiving object
10357: ... \ do some more
10358: ; overrides foo
10359: @end example
1.6 pazsan 10360:
1.78 anton 10361: @cindex class binding as optimization
10362: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10363: March 1997), Andrew McKewan presents class binding as an optimization
10364: technique. I recommend not using it for this purpose unless you are in
10365: an emergency. Late binding is pretty fast with this model anyway, so the
10366: benefit of using class binding is small; the cost of using class binding
10367: where it is not appropriate is reduced maintainability.
1.44 crook 10368:
1.78 anton 10369: While we are at programming style questions: You should bind
10370: selectors only to ancestor classes of the receiving object. E.g., say,
10371: you know that the receiving object is of class @code{foo} or its
10372: descendents; then you should bind only to @code{foo} and its
10373: ancestors.
1.12 anton 10374:
1.78 anton 10375: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10376: @subsubsection Method conveniences
10377: @cindex method conveniences
1.44 crook 10378:
1.78 anton 10379: In a method you usually access the receiving object pretty often. If
10380: you define the method as a plain colon definition (e.g., with
10381: @code{:noname}), you may have to do a lot of stack
10382: gymnastics. To avoid this, you can define the method with @code{m:
10383: ... ;m}. E.g., you could define the method for
10384: @code{draw}ing a @code{circle} with
1.6 pazsan 10385:
1.78 anton 10386: @cindex @code{this} usage
10387: @cindex @code{m:} usage
10388: @cindex @code{;m} usage
10389: @example
10390: m: ( x y circle -- )
10391: ( x y ) this circle-radius @@ draw-circle ;m
10392: @end example
1.6 pazsan 10393:
1.78 anton 10394: @cindex @code{exit} in @code{m: ... ;m}
10395: @cindex @code{exitm} discussion
10396: @cindex @code{catch} in @code{m: ... ;m}
10397: When this method is executed, the receiver object is removed from the
10398: stack; you can access it with @code{this} (admittedly, in this
10399: example the use of @code{m: ... ;m} offers no advantage). Note
10400: that I specify the stack effect for the whole method (i.e. including
10401: the receiver object), not just for the code between @code{m:}
10402: and @code{;m}. You cannot use @code{exit} in
10403: @code{m:...;m}; instead, use
10404: @code{exitm}.@footnote{Moreover, for any word that calls
10405: @code{catch} and was defined before loading
10406: @code{objects.fs}, you have to redefine it like I redefined
10407: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10408:
1.78 anton 10409: @cindex @code{inst-var} usage
10410: You will frequently use sequences of the form @code{this
10411: @emph{field}} (in the example above: @code{this
10412: circle-radius}). If you use the field only in this way, you can
10413: define it with @code{inst-var} and eliminate the
10414: @code{this} before the field name. E.g., the @code{circle}
10415: class above could also be defined with:
1.6 pazsan 10416:
1.78 anton 10417: @example
10418: graphical class
10419: cell% inst-var radius
1.6 pazsan 10420:
1.78 anton 10421: m: ( x y circle -- )
10422: radius @@ draw-circle ;m
10423: overrides draw
1.6 pazsan 10424:
1.78 anton 10425: m: ( n-radius circle -- )
10426: radius ! ;m
10427: overrides construct
1.6 pazsan 10428:
1.78 anton 10429: end-class circle
10430: @end example
1.6 pazsan 10431:
1.78 anton 10432: @code{radius} can only be used in @code{circle} and its
10433: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10434:
1.78 anton 10435: @cindex @code{inst-value} usage
10436: You can also define fields with @code{inst-value}, which is
10437: to @code{inst-var} what @code{value} is to
10438: @code{variable}. You can change the value of such a field with
10439: @code{[to-inst]}. E.g., we could also define the class
10440: @code{circle} like this:
1.44 crook 10441:
1.78 anton 10442: @example
10443: graphical class
10444: inst-value radius
1.6 pazsan 10445:
1.78 anton 10446: m: ( x y circle -- )
10447: radius draw-circle ;m
10448: overrides draw
1.44 crook 10449:
1.78 anton 10450: m: ( n-radius circle -- )
10451: [to-inst] radius ;m
10452: overrides construct
1.6 pazsan 10453:
1.78 anton 10454: end-class circle
10455: @end example
1.6 pazsan 10456:
1.78 anton 10457: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10458:
1.78 anton 10459: @c Finally, you can define named methods with @code{:m}. One use of this
10460: @c feature is the definition of words that occur only in one class and are
10461: @c not intended to be overridden, but which still need method context
10462: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10463: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10464:
10465:
1.78 anton 10466: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10467: @subsubsection Classes and Scoping
10468: @cindex classes and scoping
10469: @cindex scoping and classes
1.6 pazsan 10470:
1.78 anton 10471: Inheritance is frequent, unlike structure extension. This exacerbates
10472: the problem with the field name convention (@pxref{Structure Naming
10473: Convention}): One always has to remember in which class the field was
10474: originally defined; changing a part of the class structure would require
10475: changes for renaming in otherwise unaffected code.
1.6 pazsan 10476:
1.78 anton 10477: @cindex @code{inst-var} visibility
10478: @cindex @code{inst-value} visibility
10479: To solve this problem, I added a scoping mechanism (which was not in my
10480: original charter): A field defined with @code{inst-var} (or
10481: @code{inst-value}) is visible only in the class where it is defined and in
10482: the descendent classes of this class. Using such fields only makes
10483: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10484:
1.78 anton 10485: This scoping mechanism allows us to use the unadorned field name,
10486: because name clashes with unrelated words become much less likely.
1.6 pazsan 10487:
1.78 anton 10488: @cindex @code{protected} discussion
10489: @cindex @code{private} discussion
10490: Once we have this mechanism, we can also use it for controlling the
10491: visibility of other words: All words defined after
10492: @code{protected} are visible only in the current class and its
10493: descendents. @code{public} restores the compilation
10494: (i.e. @code{current}) word list that was in effect before. If you
10495: have several @code{protected}s without an intervening
10496: @code{public} or @code{set-current}, @code{public}
10497: will restore the compilation word list in effect before the first of
10498: these @code{protected}s.
1.6 pazsan 10499:
1.78 anton 10500: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10501: @subsubsection Dividing classes
10502: @cindex Dividing classes
10503: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10504:
1.78 anton 10505: You may want to do the definition of methods separate from the
10506: definition of the class, its selectors, fields, and instance variables,
10507: i.e., separate the implementation from the definition. You can do this
10508: in the following way:
1.6 pazsan 10509:
1.78 anton 10510: @example
10511: graphical class
10512: inst-value radius
10513: end-class circle
1.6 pazsan 10514:
1.78 anton 10515: ... \ do some other stuff
1.6 pazsan 10516:
1.78 anton 10517: circle methods \ now we are ready
1.44 crook 10518:
1.78 anton 10519: m: ( x y circle -- )
10520: radius draw-circle ;m
10521: overrides draw
1.6 pazsan 10522:
1.78 anton 10523: m: ( n-radius circle -- )
10524: [to-inst] radius ;m
10525: overrides construct
1.44 crook 10526:
1.78 anton 10527: end-methods
10528: @end example
1.7 pazsan 10529:
1.78 anton 10530: You can use several @code{methods}...@code{end-methods} sections. The
10531: only things you can do to the class in these sections are: defining
10532: methods, and overriding the class's selectors. You must not define new
10533: selectors or fields.
1.7 pazsan 10534:
1.78 anton 10535: Note that you often have to override a selector before using it. In
10536: particular, you usually have to override @code{construct} with a new
10537: method before you can invoke @code{heap-new} and friends. E.g., you
10538: must not create a circle before the @code{overrides construct} sequence
10539: in the example above.
1.7 pazsan 10540:
1.78 anton 10541: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10542: @subsubsection Object Interfaces
10543: @cindex object interfaces
10544: @cindex interfaces for objects
1.7 pazsan 10545:
1.78 anton 10546: In this model you can only call selectors defined in the class of the
10547: receiving objects or in one of its ancestors. If you call a selector
10548: with a receiving object that is not in one of these classes, the
10549: result is undefined; if you are lucky, the program crashes
10550: immediately.
1.7 pazsan 10551:
1.78 anton 10552: @cindex selectors common to hardly-related classes
10553: Now consider the case when you want to have a selector (or several)
10554: available in two classes: You would have to add the selector to a
10555: common ancestor class, in the worst case to @code{object}. You
10556: may not want to do this, e.g., because someone else is responsible for
10557: this ancestor class.
1.7 pazsan 10558:
1.78 anton 10559: The solution for this problem is interfaces. An interface is a
10560: collection of selectors. If a class implements an interface, the
10561: selectors become available to the class and its descendents. A class
10562: can implement an unlimited number of interfaces. For the problem
10563: discussed above, we would define an interface for the selector(s), and
10564: both classes would implement the interface.
1.7 pazsan 10565:
1.78 anton 10566: As an example, consider an interface @code{storage} for
10567: writing objects to disk and getting them back, and a class
10568: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10569:
1.78 anton 10570: @cindex @code{interface} usage
10571: @cindex @code{end-interface} usage
10572: @cindex @code{implementation} usage
10573: @example
10574: interface
10575: selector write ( file object -- )
10576: selector read1 ( file object -- )
10577: end-interface storage
1.13 pazsan 10578:
1.78 anton 10579: bar class
10580: storage implementation
1.13 pazsan 10581:
1.78 anton 10582: ... overrides write
10583: ... overrides read1
10584: ...
10585: end-class foo
10586: @end example
1.13 pazsan 10587:
1.78 anton 10588: @noindent
10589: (I would add a word @code{read} @i{( file -- object )} that uses
10590: @code{read1} internally, but that's beyond the point illustrated
10591: here.)
1.13 pazsan 10592:
1.78 anton 10593: Note that you cannot use @code{protected} in an interface; and
10594: of course you cannot define fields.
1.13 pazsan 10595:
1.78 anton 10596: In the Neon model, all selectors are available for all classes;
10597: therefore it does not need interfaces. The price you pay in this model
10598: is slower late binding, and therefore, added complexity to avoid late
10599: binding.
1.13 pazsan 10600:
1.78 anton 10601: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10602: @subsubsection @file{objects.fs} Implementation
10603: @cindex @file{objects.fs} implementation
1.13 pazsan 10604:
1.78 anton 10605: @cindex @code{object-map} discussion
10606: An object is a piece of memory, like one of the data structures
10607: described with @code{struct...end-struct}. It has a field
10608: @code{object-map} that points to the method map for the object's
10609: class.
1.13 pazsan 10610:
1.78 anton 10611: @cindex method map
10612: @cindex virtual function table
10613: The @emph{method map}@footnote{This is Self terminology; in C++
10614: terminology: virtual function table.} is an array that contains the
10615: execution tokens (@i{xt}s) of the methods for the object's class. Each
10616: selector contains an offset into a method map.
1.13 pazsan 10617:
1.78 anton 10618: @cindex @code{selector} implementation, class
10619: @code{selector} is a defining word that uses
10620: @code{CREATE} and @code{DOES>}. The body of the
10621: selector contains the offset; the @code{DOES>} action for a
10622: class selector is, basically:
1.8 pazsan 10623:
10624: @example
1.78 anton 10625: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10626: @end example
10627:
1.78 anton 10628: Since @code{object-map} is the first field of the object, it
10629: does not generate any code. As you can see, calling a selector has a
10630: small, constant cost.
1.26 crook 10631:
1.78 anton 10632: @cindex @code{current-interface} discussion
10633: @cindex class implementation and representation
10634: A class is basically a @code{struct} combined with a method
10635: map. During the class definition the alignment and size of the class
10636: are passed on the stack, just as with @code{struct}s, so
10637: @code{field} can also be used for defining class
10638: fields. However, passing more items on the stack would be
10639: inconvenient, so @code{class} builds a data structure in memory,
10640: which is accessed through the variable
10641: @code{current-interface}. After its definition is complete, the
10642: class is represented on the stack by a pointer (e.g., as parameter for
10643: a child class definition).
1.26 crook 10644:
1.78 anton 10645: A new class starts off with the alignment and size of its parent,
10646: and a copy of the parent's method map. Defining new fields extends the
10647: size and alignment; likewise, defining new selectors extends the
10648: method map. @code{overrides} just stores a new @i{xt} in the method
10649: map at the offset given by the selector.
1.13 pazsan 10650:
1.78 anton 10651: @cindex class binding, implementation
10652: Class binding just gets the @i{xt} at the offset given by the selector
10653: from the class's method map and @code{compile,}s (in the case of
10654: @code{[bind]}) it.
1.13 pazsan 10655:
1.78 anton 10656: @cindex @code{this} implementation
10657: @cindex @code{catch} and @code{this}
10658: @cindex @code{this} and @code{catch}
10659: I implemented @code{this} as a @code{value}. At the
10660: start of an @code{m:...;m} method the old @code{this} is
10661: stored to the return stack and restored at the end; and the object on
10662: the TOS is stored @code{TO this}. This technique has one
10663: disadvantage: If the user does not leave the method via
10664: @code{;m}, but via @code{throw} or @code{exit},
10665: @code{this} is not restored (and @code{exit} may
10666: crash). To deal with the @code{throw} problem, I have redefined
10667: @code{catch} to save and restore @code{this}; the same
10668: should be done with any word that can catch an exception. As for
10669: @code{exit}, I simply forbid it (as a replacement, there is
10670: @code{exitm}).
1.13 pazsan 10671:
1.78 anton 10672: @cindex @code{inst-var} implementation
10673: @code{inst-var} is just the same as @code{field}, with
10674: a different @code{DOES>} action:
1.13 pazsan 10675: @example
1.78 anton 10676: @@ this +
1.8 pazsan 10677: @end example
1.78 anton 10678: Similar for @code{inst-value}.
1.8 pazsan 10679:
1.78 anton 10680: @cindex class scoping implementation
10681: Each class also has a word list that contains the words defined with
10682: @code{inst-var} and @code{inst-value}, and its protected
10683: words. It also has a pointer to its parent. @code{class} pushes
10684: the word lists of the class and all its ancestors onto the search order stack,
10685: and @code{end-class} drops them.
1.20 pazsan 10686:
1.78 anton 10687: @cindex interface implementation
10688: An interface is like a class without fields, parent and protected
10689: words; i.e., it just has a method map. If a class implements an
10690: interface, its method map contains a pointer to the method map of the
10691: interface. The positive offsets in the map are reserved for class
10692: methods, therefore interface map pointers have negative
10693: offsets. Interfaces have offsets that are unique throughout the
10694: system, unlike class selectors, whose offsets are only unique for the
10695: classes where the selector is available (invokable).
1.20 pazsan 10696:
1.78 anton 10697: This structure means that interface selectors have to perform one
10698: indirection more than class selectors to find their method. Their body
10699: contains the interface map pointer offset in the class method map, and
10700: the method offset in the interface method map. The
10701: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10702:
10703: @example
1.78 anton 10704: ( object selector-body )
10705: 2dup selector-interface @@ ( object selector-body object interface-offset )
10706: swap object-map @@ + @@ ( object selector-body map )
10707: swap selector-offset @@ + @@ execute
1.20 pazsan 10708: @end example
10709:
1.78 anton 10710: where @code{object-map} and @code{selector-offset} are
10711: first fields and generate no code.
1.20 pazsan 10712:
1.78 anton 10713: As a concrete example, consider the following code:
1.20 pazsan 10714:
10715: @example
1.78 anton 10716: interface
10717: selector if1sel1
10718: selector if1sel2
10719: end-interface if1
1.20 pazsan 10720:
1.78 anton 10721: object class
10722: if1 implementation
10723: selector cl1sel1
10724: cell% inst-var cl1iv1
1.20 pazsan 10725:
1.78 anton 10726: ' m1 overrides construct
10727: ' m2 overrides if1sel1
10728: ' m3 overrides if1sel2
10729: ' m4 overrides cl1sel2
10730: end-class cl1
1.20 pazsan 10731:
1.78 anton 10732: create obj1 object dict-new drop
10733: create obj2 cl1 dict-new drop
10734: @end example
1.20 pazsan 10735:
1.78 anton 10736: The data structure created by this code (including the data structure
10737: for @code{object}) is shown in the
10738: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10739: @comment TODO add this diagram..
1.20 pazsan 10740:
1.78 anton 10741: @node Objects Glossary, , Objects Implementation, Objects
10742: @subsubsection @file{objects.fs} Glossary
10743: @cindex @file{objects.fs} Glossary
1.20 pazsan 10744:
10745:
1.78 anton 10746: doc---objects-bind
10747: doc---objects-<bind>
10748: doc---objects-bind'
10749: doc---objects-[bind]
10750: doc---objects-class
10751: doc---objects-class->map
10752: doc---objects-class-inst-size
10753: doc---objects-class-override!
1.79 anton 10754: doc---objects-class-previous
10755: doc---objects-class>order
1.78 anton 10756: doc---objects-construct
10757: doc---objects-current'
10758: doc---objects-[current]
10759: doc---objects-current-interface
10760: doc---objects-dict-new
10761: doc---objects-end-class
10762: doc---objects-end-class-noname
10763: doc---objects-end-interface
10764: doc---objects-end-interface-noname
10765: doc---objects-end-methods
10766: doc---objects-exitm
10767: doc---objects-heap-new
10768: doc---objects-implementation
10769: doc---objects-init-object
10770: doc---objects-inst-value
10771: doc---objects-inst-var
10772: doc---objects-interface
10773: doc---objects-m:
10774: doc---objects-:m
10775: doc---objects-;m
10776: doc---objects-method
10777: doc---objects-methods
10778: doc---objects-object
10779: doc---objects-overrides
10780: doc---objects-[parent]
10781: doc---objects-print
10782: doc---objects-protected
10783: doc---objects-public
10784: doc---objects-selector
10785: doc---objects-this
10786: doc---objects-<to-inst>
10787: doc---objects-[to-inst]
10788: doc---objects-to-this
10789: doc---objects-xt-new
1.20 pazsan 10790:
10791:
1.78 anton 10792: @c -------------------------------------------------------------
10793: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10794: @subsection The @file{oof.fs} model
10795: @cindex oof
10796: @cindex object-oriented programming
1.20 pazsan 10797:
1.78 anton 10798: @cindex @file{objects.fs}
10799: @cindex @file{oof.fs}
1.20 pazsan 10800:
1.78 anton 10801: This section describes the @file{oof.fs} package.
1.20 pazsan 10802:
1.78 anton 10803: The package described in this section has been used in bigFORTH since 1991, and
10804: used for two large applications: a chromatographic system used to
10805: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10806:
1.78 anton 10807: You can find a description (in German) of @file{oof.fs} in @cite{Object
10808: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10809: 10(2), 1994.
1.20 pazsan 10810:
1.78 anton 10811: @menu
10812: * Properties of the OOF model::
10813: * Basic OOF Usage::
10814: * The OOF base class::
10815: * Class Declaration::
10816: * Class Implementation::
10817: @end menu
1.20 pazsan 10818:
1.78 anton 10819: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10820: @subsubsection Properties of the @file{oof.fs} model
10821: @cindex @file{oof.fs} properties
1.20 pazsan 10822:
1.78 anton 10823: @itemize @bullet
10824: @item
10825: This model combines object oriented programming with information
10826: hiding. It helps you writing large application, where scoping is
10827: necessary, because it provides class-oriented scoping.
1.20 pazsan 10828:
1.78 anton 10829: @item
10830: Named objects, object pointers, and object arrays can be created,
10831: selector invocation uses the ``object selector'' syntax. Selector invocation
10832: to objects and/or selectors on the stack is a bit less convenient, but
10833: possible.
1.44 crook 10834:
1.78 anton 10835: @item
10836: Selector invocation and instance variable usage of the active object is
10837: straightforward, since both make use of the active object.
1.44 crook 10838:
1.78 anton 10839: @item
10840: Late binding is efficient and easy to use.
1.20 pazsan 10841:
1.78 anton 10842: @item
10843: State-smart objects parse selectors. However, extensibility is provided
10844: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10845:
1.78 anton 10846: @item
10847: An implementation in ANS Forth is available.
1.20 pazsan 10848:
1.78 anton 10849: @end itemize
1.23 crook 10850:
10851:
1.78 anton 10852: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10853: @subsubsection Basic @file{oof.fs} Usage
10854: @cindex @file{oof.fs} usage
1.23 crook 10855:
1.78 anton 10856: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10857:
1.78 anton 10858: You can define a class for graphical objects like this:
1.23 crook 10859:
1.78 anton 10860: @cindex @code{class} usage
10861: @cindex @code{class;} usage
10862: @cindex @code{method} usage
10863: @example
10864: object class graphical \ "object" is the parent class
1.139 pazsan 10865: method draw ( x y -- )
1.78 anton 10866: class;
10867: @end example
1.23 crook 10868:
1.78 anton 10869: This code defines a class @code{graphical} with an
10870: operation @code{draw}. We can perform the operation
10871: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10872:
1.78 anton 10873: @example
10874: 100 100 t-rex draw
10875: @end example
1.23 crook 10876:
1.78 anton 10877: @noindent
10878: where @code{t-rex} is an object or object pointer, created with e.g.
10879: @code{graphical : t-rex}.
1.23 crook 10880:
1.78 anton 10881: @cindex abstract class
10882: How do we create a graphical object? With the present definitions,
10883: we cannot create a useful graphical object. The class
10884: @code{graphical} describes graphical objects in general, but not
10885: any concrete graphical object type (C++ users would call it an
10886: @emph{abstract class}); e.g., there is no method for the selector
10887: @code{draw} in the class @code{graphical}.
1.23 crook 10888:
1.78 anton 10889: For concrete graphical objects, we define child classes of the
10890: class @code{graphical}, e.g.:
1.23 crook 10891:
1.78 anton 10892: @example
10893: graphical class circle \ "graphical" is the parent class
10894: cell var circle-radius
10895: how:
10896: : draw ( x y -- )
10897: circle-radius @@ draw-circle ;
1.23 crook 10898:
1.139 pazsan 10899: : init ( n-radius -- )
1.78 anton 10900: circle-radius ! ;
10901: class;
10902: @end example
1.1 anton 10903:
1.78 anton 10904: Here we define a class @code{circle} as a child of @code{graphical},
10905: with a field @code{circle-radius}; it defines new methods for the
10906: selectors @code{draw} and @code{init} (@code{init} is defined in
10907: @code{object}, the parent class of @code{graphical}).
1.1 anton 10908:
1.78 anton 10909: Now we can create a circle in the dictionary with:
1.1 anton 10910:
1.78 anton 10911: @example
10912: 50 circle : my-circle
10913: @end example
1.21 crook 10914:
1.78 anton 10915: @noindent
10916: @code{:} invokes @code{init}, thus initializing the field
10917: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10918: with:
1.1 anton 10919:
1.78 anton 10920: @example
10921: 100 100 my-circle draw
10922: @end example
1.1 anton 10923:
1.78 anton 10924: @cindex selector invocation, restrictions
10925: @cindex class definition, restrictions
10926: Note: You can only invoke a selector if the receiving object belongs to
10927: the class where the selector was defined or one of its descendents;
10928: e.g., you can invoke @code{draw} only for objects belonging to
10929: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10930: mechanism will check if you try to invoke a selector that is not
10931: defined in this class hierarchy, so you'll get an error at compilation
10932: time.
1.1 anton 10933:
10934:
1.78 anton 10935: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10936: @subsubsection The @file{oof.fs} base class
10937: @cindex @file{oof.fs} base class
1.1 anton 10938:
1.78 anton 10939: When you define a class, you have to specify a parent class. So how do
10940: you start defining classes? There is one class available from the start:
10941: @code{object}. You have to use it as ancestor for all classes. It is the
10942: only class that has no parent. Classes are also objects, except that
10943: they don't have instance variables; class manipulation such as
10944: inheritance or changing definitions of a class is handled through
10945: selectors of the class @code{object}.
1.1 anton 10946:
1.78 anton 10947: @code{object} provides a number of selectors:
1.1 anton 10948:
1.78 anton 10949: @itemize @bullet
10950: @item
10951: @code{class} for subclassing, @code{definitions} to add definitions
10952: later on, and @code{class?} to get type informations (is the class a
10953: subclass of the class passed on the stack?).
1.1 anton 10954:
1.78 anton 10955: doc---object-class
10956: doc---object-definitions
10957: doc---object-class?
1.1 anton 10958:
10959:
1.26 crook 10960: @item
1.78 anton 10961: @code{init} and @code{dispose} as constructor and destructor of the
10962: object. @code{init} is invocated after the object's memory is allocated,
10963: while @code{dispose} also handles deallocation. Thus if you redefine
10964: @code{dispose}, you have to call the parent's dispose with @code{super
10965: dispose}, too.
10966:
10967: doc---object-init
10968: doc---object-dispose
10969:
1.1 anton 10970:
1.26 crook 10971: @item
1.78 anton 10972: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10973: @code{[]} to create named and unnamed objects and object arrays or
10974: object pointers.
10975:
10976: doc---object-new
10977: doc---object-new[]
10978: doc---object-:
10979: doc---object-ptr
10980: doc---object-asptr
10981: doc---object-[]
10982:
1.1 anton 10983:
1.26 crook 10984: @item
1.78 anton 10985: @code{::} and @code{super} for explicit scoping. You should use explicit
10986: scoping only for super classes or classes with the same set of instance
10987: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10988:
1.78 anton 10989: doc---object-::
10990: doc---object-super
1.21 crook 10991:
10992:
1.26 crook 10993: @item
1.78 anton 10994: @code{self} to get the address of the object
1.21 crook 10995:
1.78 anton 10996: doc---object-self
1.21 crook 10997:
10998:
1.78 anton 10999: @item
11000: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11001: pointers and instance defers.
1.21 crook 11002:
1.78 anton 11003: doc---object-bind
11004: doc---object-bound
11005: doc---object-link
11006: doc---object-is
1.21 crook 11007:
11008:
1.78 anton 11009: @item
11010: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11011: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11012:
1.78 anton 11013: doc---object-'
11014: doc---object-postpone
1.21 crook 11015:
11016:
1.78 anton 11017: @item
11018: @code{with} and @code{endwith} to select the active object from the
11019: stack, and enable its scope. Using @code{with} and @code{endwith}
11020: also allows you to create code using selector @code{postpone} without being
11021: trapped by the state-smart objects.
1.21 crook 11022:
1.78 anton 11023: doc---object-with
11024: doc---object-endwith
1.21 crook 11025:
11026:
1.78 anton 11027: @end itemize
1.21 crook 11028:
1.78 anton 11029: @node Class Declaration, Class Implementation, The OOF base class, OOF
11030: @subsubsection Class Declaration
11031: @cindex class declaration
1.21 crook 11032:
1.78 anton 11033: @itemize @bullet
11034: @item
11035: Instance variables
1.21 crook 11036:
1.78 anton 11037: doc---oof-var
1.21 crook 11038:
11039:
1.78 anton 11040: @item
11041: Object pointers
1.21 crook 11042:
1.78 anton 11043: doc---oof-ptr
11044: doc---oof-asptr
1.21 crook 11045:
11046:
1.78 anton 11047: @item
11048: Instance defers
1.21 crook 11049:
1.78 anton 11050: doc---oof-defer
1.21 crook 11051:
11052:
1.78 anton 11053: @item
11054: Method selectors
1.21 crook 11055:
1.78 anton 11056: doc---oof-early
11057: doc---oof-method
1.21 crook 11058:
11059:
1.78 anton 11060: @item
11061: Class-wide variables
1.21 crook 11062:
1.78 anton 11063: doc---oof-static
1.21 crook 11064:
11065:
1.78 anton 11066: @item
11067: End declaration
1.1 anton 11068:
1.78 anton 11069: doc---oof-how:
11070: doc---oof-class;
1.21 crook 11071:
11072:
1.78 anton 11073: @end itemize
1.21 crook 11074:
1.78 anton 11075: @c -------------------------------------------------------------
11076: @node Class Implementation, , Class Declaration, OOF
11077: @subsubsection Class Implementation
11078: @cindex class implementation
1.21 crook 11079:
1.78 anton 11080: @c -------------------------------------------------------------
11081: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11082: @subsection The @file{mini-oof.fs} model
11083: @cindex mini-oof
1.21 crook 11084:
1.78 anton 11085: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11086: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11087: and reduces to the bare minimum of features. This is based on a posting
11088: of Bernd Paysan in comp.lang.forth.
1.21 crook 11089:
1.78 anton 11090: @menu
11091: * Basic Mini-OOF Usage::
11092: * Mini-OOF Example::
11093: * Mini-OOF Implementation::
11094: @end menu
1.21 crook 11095:
1.78 anton 11096: @c -------------------------------------------------------------
11097: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11098: @subsubsection Basic @file{mini-oof.fs} Usage
11099: @cindex mini-oof usage
1.21 crook 11100:
1.78 anton 11101: There is a base class (@code{class}, which allocates one cell for the
11102: object pointer) plus seven other words: to define a method, a variable,
11103: a class; to end a class, to resolve binding, to allocate an object and
11104: to compile a class method.
11105: @comment TODO better description of the last one
1.26 crook 11106:
1.21 crook 11107:
1.78 anton 11108: doc-object
11109: doc-method
11110: doc-var
11111: doc-class
11112: doc-end-class
11113: doc-defines
11114: doc-new
11115: doc-::
1.21 crook 11116:
11117:
11118:
1.78 anton 11119: @c -------------------------------------------------------------
11120: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11121: @subsubsection Mini-OOF Example
11122: @cindex mini-oof example
1.1 anton 11123:
1.78 anton 11124: A short example shows how to use this package. This example, in slightly
11125: extended form, is supplied as @file{moof-exm.fs}
11126: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11127:
1.26 crook 11128: @example
1.78 anton 11129: object class
11130: method init
11131: method draw
11132: end-class graphical
1.26 crook 11133: @end example
1.20 pazsan 11134:
1.78 anton 11135: This code defines a class @code{graphical} with an
11136: operation @code{draw}. We can perform the operation
11137: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11138:
1.26 crook 11139: @example
1.78 anton 11140: 100 100 t-rex draw
1.26 crook 11141: @end example
1.12 anton 11142:
1.78 anton 11143: where @code{t-rex} is an object or object pointer, created with e.g.
11144: @code{graphical new Constant t-rex}.
1.12 anton 11145:
1.78 anton 11146: For concrete graphical objects, we define child classes of the
11147: class @code{graphical}, e.g.:
1.12 anton 11148:
1.26 crook 11149: @example
11150: graphical class
1.78 anton 11151: cell var circle-radius
11152: end-class circle \ "graphical" is the parent class
1.12 anton 11153:
1.78 anton 11154: :noname ( x y -- )
11155: circle-radius @@ draw-circle ; circle defines draw
11156: :noname ( r -- )
11157: circle-radius ! ; circle defines init
11158: @end example
1.12 anton 11159:
1.78 anton 11160: There is no implicit init method, so we have to define one. The creation
11161: code of the object now has to call init explicitely.
1.21 crook 11162:
1.78 anton 11163: @example
11164: circle new Constant my-circle
11165: 50 my-circle init
1.12 anton 11166: @end example
11167:
1.78 anton 11168: It is also possible to add a function to create named objects with
11169: automatic call of @code{init}, given that all objects have @code{init}
11170: on the same place:
1.38 anton 11171:
1.78 anton 11172: @example
11173: : new: ( .. o "name" -- )
11174: new dup Constant init ;
11175: 80 circle new: large-circle
11176: @end example
1.12 anton 11177:
1.78 anton 11178: We can draw this new circle at (100,100) with:
1.12 anton 11179:
1.78 anton 11180: @example
11181: 100 100 my-circle draw
11182: @end example
1.12 anton 11183:
1.78 anton 11184: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11185: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11186:
1.78 anton 11187: Object-oriented systems with late binding typically use a
11188: ``vtable''-approach: the first variable in each object is a pointer to a
11189: table, which contains the methods as function pointers. The vtable
11190: may also contain other information.
1.12 anton 11191:
1.79 anton 11192: So first, let's declare selectors:
1.37 anton 11193:
11194: @example
1.79 anton 11195: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11196: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11197: @end example
1.37 anton 11198:
1.79 anton 11199: During selector declaration, the number of selectors and instance
11200: variables is on the stack (in address units). @code{method} creates one
11201: selector and increments the selector number. To execute a selector, it
1.78 anton 11202: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11203: executes the method @i{xt} stored there. Each selector takes the object
11204: it is invoked with as top of stack parameter; it passes the parameters
11205: (including the object) unchanged to the appropriate method which should
1.78 anton 11206: consume that object.
1.37 anton 11207:
1.78 anton 11208: Now, we also have to declare instance variables
1.37 anton 11209:
1.78 anton 11210: @example
1.79 anton 11211: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11212: DOES> ( o -- addr ) @@ + ;
1.37 anton 11213: @end example
11214:
1.78 anton 11215: As before, a word is created with the current offset. Instance
11216: variables can have different sizes (cells, floats, doubles, chars), so
11217: all we do is take the size and add it to the offset. If your machine
11218: has alignment restrictions, put the proper @code{aligned} or
11219: @code{faligned} before the variable, to adjust the variable
11220: offset. That's why it is on the top of stack.
1.37 anton 11221:
1.78 anton 11222: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11223:
1.78 anton 11224: @example
11225: Create object 1 cells , 2 cells ,
1.79 anton 11226: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11227: @end example
1.12 anton 11228:
1.78 anton 11229: For inheritance, the vtable of the parent object has to be
11230: copied when a new, derived class is declared. This gives all the
11231: methods of the parent class, which can be overridden, though.
1.12 anton 11232:
1.78 anton 11233: @example
1.79 anton 11234: : end-class ( class selectors vars "name" -- )
1.78 anton 11235: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11236: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11237: @end example
1.12 anton 11238:
1.78 anton 11239: The first line creates the vtable, initialized with
11240: @code{noop}s. The second line is the inheritance mechanism, it
11241: copies the xts from the parent vtable.
1.12 anton 11242:
1.78 anton 11243: We still have no way to define new methods, let's do that now:
1.12 anton 11244:
1.26 crook 11245: @example
1.79 anton 11246: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11247: @end example
1.12 anton 11248:
1.78 anton 11249: To allocate a new object, we need a word, too:
1.12 anton 11250:
1.78 anton 11251: @example
11252: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11253: @end example
11254:
1.78 anton 11255: Sometimes derived classes want to access the method of the
11256: parent object. There are two ways to achieve this with Mini-OOF:
11257: first, you could use named words, and second, you could look up the
11258: vtable of the parent object.
1.12 anton 11259:
1.78 anton 11260: @example
11261: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11262: @end example
1.12 anton 11263:
11264:
1.78 anton 11265: Nothing can be more confusing than a good example, so here is
11266: one. First let's declare a text object (called
11267: @code{button}), that stores text and position:
1.12 anton 11268:
1.78 anton 11269: @example
11270: object class
11271: cell var text
11272: cell var len
11273: cell var x
11274: cell var y
11275: method init
11276: method draw
11277: end-class button
11278: @end example
1.12 anton 11279:
1.78 anton 11280: @noindent
11281: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11282:
1.26 crook 11283: @example
1.78 anton 11284: :noname ( o -- )
11285: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11286: button defines draw
11287: :noname ( addr u o -- )
11288: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11289: button defines init
1.26 crook 11290: @end example
1.12 anton 11291:
1.78 anton 11292: @noindent
11293: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11294: new data and no new selectors:
1.78 anton 11295:
11296: @example
11297: button class
11298: end-class bold-button
1.12 anton 11299:
1.78 anton 11300: : bold 27 emit ." [1m" ;
11301: : normal 27 emit ." [0m" ;
11302: @end example
1.1 anton 11303:
1.78 anton 11304: @noindent
11305: The class @code{bold-button} has a different draw method to
11306: @code{button}, but the new method is defined in terms of the draw method
11307: for @code{button}:
1.20 pazsan 11308:
1.78 anton 11309: @example
11310: :noname bold [ button :: draw ] normal ; bold-button defines draw
11311: @end example
1.21 crook 11312:
1.78 anton 11313: @noindent
1.79 anton 11314: Finally, create two objects and apply selectors:
1.21 crook 11315:
1.26 crook 11316: @example
1.78 anton 11317: button new Constant foo
11318: s" thin foo" foo init
11319: page
11320: foo draw
11321: bold-button new Constant bar
11322: s" fat bar" bar init
11323: 1 bar y !
11324: bar draw
1.26 crook 11325: @end example
1.21 crook 11326:
11327:
1.78 anton 11328: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11329: @subsection Comparison with other object models
11330: @cindex comparison of object models
11331: @cindex object models, comparison
11332:
11333: Many object-oriented Forth extensions have been proposed (@cite{A survey
11334: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11335: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11336: relation of the object models described here to two well-known and two
11337: closely-related (by the use of method maps) models. Andras Zsoter
11338: helped us with this section.
11339:
11340: @cindex Neon model
11341: The most popular model currently seems to be the Neon model (see
11342: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11343: 1997) by Andrew McKewan) but this model has a number of limitations
11344: @footnote{A longer version of this critique can be
11345: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11346: Dimensions, May 1997) by Anton Ertl.}:
11347:
11348: @itemize @bullet
11349: @item
11350: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11351: to pass objects on the stack.
1.21 crook 11352:
1.78 anton 11353: @item
11354: It requires that the selector parses the input stream (at
1.79 anton 11355: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11356: hard to find.
1.21 crook 11357:
1.78 anton 11358: @item
1.79 anton 11359: It allows using every selector on every object; this eliminates the
11360: need for interfaces, but makes it harder to create efficient
11361: implementations.
1.78 anton 11362: @end itemize
1.21 crook 11363:
1.78 anton 11364: @cindex Pountain's object-oriented model
11365: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11366: Press, London, 1987) by Dick Pountain. However, it is not really about
11367: object-oriented programming, because it hardly deals with late
11368: binding. Instead, it focuses on features like information hiding and
11369: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11370:
1.78 anton 11371: @cindex Zsoter's object-oriented model
1.79 anton 11372: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11373: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11374: describes a model that makes heavy use of an active object (like
11375: @code{this} in @file{objects.fs}): The active object is not only used
11376: for accessing all fields, but also specifies the receiving object of
11377: every selector invocation; you have to change the active object
11378: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11379: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11380: the method entry point is unnecessary with Zsoter's model, because the
11381: receiving object is the active object already. On the other hand, the
11382: explicit change is absolutely necessary in that model, because otherwise
11383: no one could ever change the active object. An ANS Forth implementation
11384: of this model is available through
11385: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11386:
1.78 anton 11387: @cindex @file{oof.fs}, differences to other models
11388: The @file{oof.fs} model combines information hiding and overloading
11389: resolution (by keeping names in various word lists) with object-oriented
11390: programming. It sets the active object implicitly on method entry, but
11391: also allows explicit changing (with @code{>o...o>} or with
11392: @code{with...endwith}). It uses parsing and state-smart objects and
11393: classes for resolving overloading and for early binding: the object or
11394: class parses the selector and determines the method from this. If the
11395: selector is not parsed by an object or class, it performs a call to the
11396: selector for the active object (late binding), like Zsoter's model.
11397: Fields are always accessed through the active object. The big
11398: disadvantage of this model is the parsing and the state-smartness, which
11399: reduces extensibility and increases the opportunities for subtle bugs;
11400: essentially, you are only safe if you never tick or @code{postpone} an
11401: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11402:
1.78 anton 11403: @cindex @file{mini-oof.fs}, differences to other models
11404: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11405: version of the @file{objects.fs} model, but syntactically it is a
11406: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11407:
11408:
1.78 anton 11409: @c -------------------------------------------------------------
1.150 anton 11410: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11411: @section Programming Tools
11412: @cindex programming tools
1.21 crook 11413:
1.78 anton 11414: @c !! move this and assembler down below OO stuff.
1.21 crook 11415:
1.78 anton 11416: @menu
1.150 anton 11417: * Examining:: Data and Code.
11418: * Forgetting words:: Usually before reloading.
1.78 anton 11419: * Debugging:: Simple and quick.
11420: * Assertions:: Making your programs self-checking.
11421: * Singlestep Debugger:: Executing your program word by word.
11422: @end menu
1.21 crook 11423:
1.78 anton 11424: @node Examining, Forgetting words, Programming Tools, Programming Tools
11425: @subsection Examining data and code
11426: @cindex examining data and code
11427: @cindex data examination
11428: @cindex code examination
1.44 crook 11429:
1.78 anton 11430: The following words inspect the stack non-destructively:
1.21 crook 11431:
1.78 anton 11432: doc-.s
11433: doc-f.s
1.158 anton 11434: doc-maxdepth-.s
1.44 crook 11435:
1.78 anton 11436: There is a word @code{.r} but it does @i{not} display the return stack!
11437: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11438:
1.78 anton 11439: doc-depth
11440: doc-fdepth
11441: doc-clearstack
1.124 anton 11442: doc-clearstacks
1.21 crook 11443:
1.78 anton 11444: The following words inspect memory.
1.21 crook 11445:
1.78 anton 11446: doc-?
11447: doc-dump
1.21 crook 11448:
1.78 anton 11449: And finally, @code{see} allows to inspect code:
1.21 crook 11450:
1.78 anton 11451: doc-see
11452: doc-xt-see
1.111 anton 11453: doc-simple-see
11454: doc-simple-see-range
1.21 crook 11455:
1.78 anton 11456: @node Forgetting words, Debugging, Examining, Programming Tools
11457: @subsection Forgetting words
11458: @cindex words, forgetting
11459: @cindex forgeting words
1.21 crook 11460:
1.78 anton 11461: @c anton: other, maybe better places for this subsection: Defining Words;
11462: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11463:
1.78 anton 11464: Forth allows you to forget words (and everything that was alloted in the
11465: dictonary after them) in a LIFO manner.
1.21 crook 11466:
1.78 anton 11467: doc-marker
1.21 crook 11468:
1.78 anton 11469: The most common use of this feature is during progam development: when
11470: you change a source file, forget all the words it defined and load it
11471: again (since you also forget everything defined after the source file
11472: was loaded, you have to reload that, too). Note that effects like
11473: storing to variables and destroyed system words are not undone when you
11474: forget words. With a system like Gforth, that is fast enough at
11475: starting up and compiling, I find it more convenient to exit and restart
11476: Gforth, as this gives me a clean slate.
1.21 crook 11477:
1.78 anton 11478: Here's an example of using @code{marker} at the start of a source file
11479: that you are debugging; it ensures that you only ever have one copy of
11480: the file's definitions compiled at any time:
1.21 crook 11481:
1.78 anton 11482: @example
11483: [IFDEF] my-code
11484: my-code
11485: [ENDIF]
1.26 crook 11486:
1.78 anton 11487: marker my-code
11488: init-included-files
1.21 crook 11489:
1.78 anton 11490: \ .. definitions start here
11491: \ .
11492: \ .
11493: \ end
11494: @end example
1.21 crook 11495:
1.26 crook 11496:
1.78 anton 11497: @node Debugging, Assertions, Forgetting words, Programming Tools
11498: @subsection Debugging
11499: @cindex debugging
1.21 crook 11500:
1.78 anton 11501: Languages with a slow edit/compile/link/test development loop tend to
11502: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11503:
1.78 anton 11504: A much better (faster) way in fast-compiling languages is to add
11505: printing code at well-selected places, let the program run, look at
11506: the output, see where things went wrong, add more printing code, etc.,
11507: until the bug is found.
1.21 crook 11508:
1.78 anton 11509: The simple debugging aids provided in @file{debugs.fs}
11510: are meant to support this style of debugging.
1.21 crook 11511:
1.78 anton 11512: The word @code{~~} prints debugging information (by default the source
11513: location and the stack contents). It is easy to insert. If you use Emacs
11514: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11515: query-replace them with nothing). The deferred words
1.101 anton 11516: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11517: @code{~~}. The default source location output format works well with
11518: Emacs' compilation mode, so you can step through the program at the
11519: source level using @kbd{C-x `} (the advantage over a stepping debugger
11520: is that you can step in any direction and you know where the crash has
11521: happened or where the strange data has occurred).
1.21 crook 11522:
1.78 anton 11523: doc-~~
11524: doc-printdebugdata
1.101 anton 11525: doc-.debugline
1.21 crook 11526:
1.106 anton 11527: @cindex filenames in @code{~~} output
11528: @code{~~} (and assertions) will usually print the wrong file name if a
11529: marker is executed in the same file after their occurance. They will
11530: print @samp{*somewhere*} as file name if a marker is executed in the
11531: same file before their occurance.
11532:
11533:
1.78 anton 11534: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11535: @subsection Assertions
11536: @cindex assertions
1.21 crook 11537:
1.78 anton 11538: It is a good idea to make your programs self-checking, especially if you
11539: make an assumption that may become invalid during maintenance (for
11540: example, that a certain field of a data structure is never zero). Gforth
11541: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11542:
11543: @example
1.78 anton 11544: assert( @i{flag} )
1.26 crook 11545: @end example
11546:
1.78 anton 11547: The code between @code{assert(} and @code{)} should compute a flag, that
11548: should be true if everything is alright and false otherwise. It should
11549: not change anything else on the stack. The overall stack effect of the
11550: assertion is @code{( -- )}. E.g.
1.21 crook 11551:
1.26 crook 11552: @example
1.78 anton 11553: assert( 1 1 + 2 = ) \ what we learn in school
11554: assert( dup 0<> ) \ assert that the top of stack is not zero
11555: assert( false ) \ this code should not be reached
1.21 crook 11556: @end example
11557:
1.78 anton 11558: The need for assertions is different at different times. During
11559: debugging, we want more checking, in production we sometimes care more
11560: for speed. Therefore, assertions can be turned off, i.e., the assertion
11561: becomes a comment. Depending on the importance of an assertion and the
11562: time it takes to check it, you may want to turn off some assertions and
11563: keep others turned on. Gforth provides several levels of assertions for
11564: this purpose:
11565:
11566:
11567: doc-assert0(
11568: doc-assert1(
11569: doc-assert2(
11570: doc-assert3(
11571: doc-assert(
11572: doc-)
1.21 crook 11573:
11574:
1.78 anton 11575: The variable @code{assert-level} specifies the highest assertions that
11576: are turned on. I.e., at the default @code{assert-level} of one,
11577: @code{assert0(} and @code{assert1(} assertions perform checking, while
11578: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11579:
1.78 anton 11580: The value of @code{assert-level} is evaluated at compile-time, not at
11581: run-time. Therefore you cannot turn assertions on or off at run-time;
11582: you have to set the @code{assert-level} appropriately before compiling a
11583: piece of code. You can compile different pieces of code at different
11584: @code{assert-level}s (e.g., a trusted library at level 1 and
11585: newly-written code at level 3).
1.26 crook 11586:
11587:
1.78 anton 11588: doc-assert-level
1.26 crook 11589:
11590:
1.78 anton 11591: If an assertion fails, a message compatible with Emacs' compilation mode
11592: is produced and the execution is aborted (currently with @code{ABORT"}.
11593: If there is interest, we will introduce a special throw code. But if you
11594: intend to @code{catch} a specific condition, using @code{throw} is
11595: probably more appropriate than an assertion).
1.106 anton 11596:
11597: @cindex filenames in assertion output
11598: Assertions (and @code{~~}) will usually print the wrong file name if a
11599: marker is executed in the same file after their occurance. They will
11600: print @samp{*somewhere*} as file name if a marker is executed in the
11601: same file before their occurance.
1.44 crook 11602:
1.78 anton 11603: Definitions in ANS Forth for these assertion words are provided
11604: in @file{compat/assert.fs}.
1.26 crook 11605:
1.44 crook 11606:
1.78 anton 11607: @node Singlestep Debugger, , Assertions, Programming Tools
11608: @subsection Singlestep Debugger
11609: @cindex singlestep Debugger
11610: @cindex debugging Singlestep
1.44 crook 11611:
1.159 anton 11612: The singlestep debugger works only with the engine @code{gforth-ditc}.
1.112 anton 11613:
1.78 anton 11614: When you create a new word there's often the need to check whether it
11615: behaves correctly or not. You can do this by typing @code{dbg
11616: badword}. A debug session might look like this:
1.26 crook 11617:
1.78 anton 11618: @example
11619: : badword 0 DO i . LOOP ; ok
11620: 2 dbg badword
11621: : badword
11622: Scanning code...
1.44 crook 11623:
1.78 anton 11624: Nesting debugger ready!
1.44 crook 11625:
1.78 anton 11626: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11627: 400D4740 8049F68 DO -> [ 0 ]
11628: 400D4744 804A0C8 i -> [ 1 ] 00000
11629: 400D4748 400C5E60 . -> 0 [ 0 ]
11630: 400D474C 8049D0C LOOP -> [ 0 ]
11631: 400D4744 804A0C8 i -> [ 1 ] 00001
11632: 400D4748 400C5E60 . -> 1 [ 0 ]
11633: 400D474C 8049D0C LOOP -> [ 0 ]
11634: 400D4758 804B384 ; -> ok
11635: @end example
1.21 crook 11636:
1.78 anton 11637: Each line displayed is one step. You always have to hit return to
11638: execute the next word that is displayed. If you don't want to execute
11639: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11640: an overview what keys are available:
1.44 crook 11641:
1.78 anton 11642: @table @i
1.44 crook 11643:
1.78 anton 11644: @item @key{RET}
11645: Next; Execute the next word.
1.21 crook 11646:
1.78 anton 11647: @item n
11648: Nest; Single step through next word.
1.44 crook 11649:
1.78 anton 11650: @item u
11651: Unnest; Stop debugging and execute rest of word. If we got to this word
11652: with nest, continue debugging with the calling word.
1.44 crook 11653:
1.78 anton 11654: @item d
11655: Done; Stop debugging and execute rest.
1.21 crook 11656:
1.78 anton 11657: @item s
11658: Stop; Abort immediately.
1.44 crook 11659:
1.78 anton 11660: @end table
1.44 crook 11661:
1.78 anton 11662: Debugging large application with this mechanism is very difficult, because
11663: you have to nest very deeply into the program before the interesting part
11664: begins. This takes a lot of time.
1.26 crook 11665:
1.78 anton 11666: To do it more directly put a @code{BREAK:} command into your source code.
11667: When program execution reaches @code{BREAK:} the single step debugger is
11668: invoked and you have all the features described above.
1.44 crook 11669:
1.78 anton 11670: If you have more than one part to debug it is useful to know where the
11671: program has stopped at the moment. You can do this by the
11672: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11673: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11674:
1.26 crook 11675:
1.78 anton 11676: doc-dbg
11677: doc-break:
11678: doc-break"
1.44 crook 11679:
1.150 anton 11680: @c ------------------------------------------------------------
11681: @node C Interface, Assembler and Code Words, Programming Tools, Words
11682: @section C Interface
11683: @cindex C interface
11684: @cindex foreign language interface
11685: @cindex interface to C functions
11686:
11687: Note that the C interface is not yet complete; a better way of
11688: declaring C functions is planned, as well as a way of declaring
11689: structs, unions, and their fields.
11690:
11691: @menu
11692: * Calling C Functions::
11693: * Declaring C Functions::
11694: * Callbacks::
1.155 anton 11695: * Low-Level C Interface Words::
1.150 anton 11696: @end menu
11697:
1.151 pazsan 11698: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 11699: @subsection Calling C functions
1.155 anton 11700: @cindex C functions, calls to
11701: @cindex calling C functions
1.150 anton 11702:
1.151 pazsan 11703: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 11704: can call it as follows: You push the arguments on the stack(s), and
11705: then call the word for the C function. The arguments have to be
11706: pushed in the same order as the arguments appear in the C
11707: documentation (i.e., the first argument is deepest on the stack).
11708: Integer and pointer arguments have to be pushed on the data stack,
11709: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 11710: by the called C function.
1.150 anton 11711:
1.155 anton 11712: On returning from the C function, the return value, if any, resides on
11713: the appropriate stack: an integer return value is pushed on the data
11714: stack, an FP return value on the FP stack, and a void return value
11715: results in not pushing anything. Note that most C functions have a
11716: return value, even if that is often not used in C; in Forth, you have
11717: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 11718:
11719: By default, an integer argument or return value corresponds to a
11720: single cell, and a floating-point argument or return value corresponds
11721: to a Forth float value; the C interface performs the appropriate
11722: conversions where necessary, on a best-effort basis (in some cases,
11723: there may be some loss).
11724:
11725: As an example, consider the POSIX function @code{lseek()}:
11726:
11727: @example
11728: off_t lseek(int fd, off_t offset, int whence);
11729: @end example
11730:
11731: This function takes three integer arguments, and returns an integer
11732: argument, so a Forth call for setting the current file offset to the
11733: start of the file could look like this:
11734:
11735: @example
11736: fd @@ 0 SEEK_SET lseek -1 = if
11737: ... \ error handling
11738: then
11739: @end example
11740:
11741: You might be worried that an @code{off_t} does not fit into a cell, so
11742: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 11743: of the return values. In that case, in your declaration of the
11744: function (@pxref{Declaring C Functions}) you should declare it to use
11745: double-cells for the off_t argument and return value, and maybe give
11746: the resulting Forth word a different name, like @code{dlseek}; the
11747: result could be called like this:
1.150 anton 11748:
11749: @example
11750: fd @@ 0. SEEK_SET dlseek -1. d= if
11751: ... \ error handling
11752: then
11753: @end example
11754:
11755: Passing and returning structs or unions is currently not supported by
11756: our interface@footnote{If you know the calling convention of your C
11757: compiler, you usually can call such functions in some way, but that
11758: way is usually not portable between platforms, and sometimes not even
11759: between C compilers.}.
11760:
11761: Calling functions with a variable number of arguments (e.g.,
11762: @code{printf()}) is currently only supported by having you declare one
11763: function-calling word for each argument pattern, and calling the
11764: appropriate word for the desired pattern.
11765:
1.155 anton 11766:
1.151 pazsan 11767: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
1.150 anton 11768: @subsection Declaring C Functions
1.155 anton 11769: @cindex C functions, declarations
11770: @cindex declaring C functions
1.150 anton 11771:
11772: Before you can call @code{lseek} or @code{dlseek}, you have to declare
11773: it. You have to look up in your system what the concrete type for the
11774: abstract type @code{off_t} is; let's assume it is @code{long}. Then
11775: the declarations for these words are:
11776:
11777: @example
11778: library libc libc.so.6
11779: libc lseek int long int (long) lseek ( fd noffset whence -- noffset2 )
11780: libc dlseek int dlong int (dlong) lseek ( fd doffset whence -- doffset2 )
11781: @end example
11782:
11783: The first line defines a Forth word @code{libc} for accessing the C
11784: functions in the shared library @file{libc.so.6} (the name of the
11785: shared library depends on the library and the OS; this example is the
11786: standard C library (containing most of the standard C and Unix
11787: functions) for GNU/Linux systems since about 1998).
11788:
11789: The next two lines define two Forth words for the same C function
11790: @code{lseek()}; the middle line defines @code{lseek ( n1 n2 n3 -- n
1.155 anton 11791: )}, and the last line defines @code{dlseek ( n1 d2 n3 -- d )}.
1.150 anton 11792:
11793: As you can see, the declarations are relatively platform-dependent
11794: (e.g., on one platform @code{off_t} may be a @code{long}, whereas on
11795: another platform it may be a @code{long long}; actually, in this case
11796: you can have this difference even on the same platform), while the
11797: resulting function-calling words are platform-independent, and calls
11798: to them are portable.
11799:
11800: At some point in the future this interface will be superseded by a
11801: more convenient one with fewer portability issues. But the resulting
1.155 anton 11802: words for calling the C function will still have the same interface,
1.156 anton 11803: so you will not need to change the calls.
1.155 anton 11804:
11805: Anyway, here are the words for the current interface:
1.150 anton 11806:
1.155 anton 11807: doc-library
11808: doc-int
11809: doc-dint
11810: doc-uint
11811: doc-udint
11812: doc-long
11813: doc-dlong
11814: doc-ulong
11815: doc-udlong
11816: doc-longlong
11817: doc-dlonglong
11818: doc-ulonglong
11819: doc-udlonglong
1.156 anton 11820: doc-ptr
1.155 anton 11821: doc-cfloat
11822: doc-cdouble
11823: doc-clongdouble
11824: doc-(int)
11825: doc-(dint)
11826: doc-(uint)
11827: doc-(udint)
11828: doc-(long)
11829: doc-(dlong)
11830: doc-(ulong)
11831: doc-(udlong)
11832: doc-(longlong)
11833: doc-(dlonglong)
11834: doc-(ulonglong)
11835: doc-(udlonglong)
1.156 anton 11836: doc-(ptr)
1.155 anton 11837: doc-(cfloat)
11838: doc-(cdouble)
11839: doc-(clongdouble)
1.150 anton 11840:
1.155 anton 11841:
11842: @node Callbacks, Low-Level C Interface Words, Declaring C Functions, C Interface
1.150 anton 11843: @subsection Callbacks
1.155 anton 11844: @cindex Callback functions written in Forth
11845: @cindex C function pointers to Forth words
11846:
11847: In some cases you have to pass a function pointer to a C function,
11848: i.e., the library wants to call back to your application (and the
11849: pointed-to function is called a callback function). You can pass the
11850: address of an existing C function (that you get with @code{lib-sym},
11851: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
11852: function, you probably want to define the function as a Forth word.
11853:
11854: !!!
11855: @c I don't understand the existing callback interface from the example - anton
11856:
11857: doc-callback
11858: doc-callback;
11859: doc-fptr
1.150 anton 11860:
1.165 anton 11861:
11862: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
11863: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
11864: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
11865: @c > > C-Funktionsadresse auf dem TOS).
11866: @c >
11867: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
11868: @c > gesehen habe, wozu das gut ist.
11869: @c
11870: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
11871: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
11872: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
11873: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
11874: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
11875: @c demselben Prototyp.
11876:
11877:
1.155 anton 11878: @node Low-Level C Interface Words, , Callbacks, C Interface
11879: @subsection Low-Level C Interface Words
1.44 crook 11880:
1.155 anton 11881: doc-open-lib
11882: doc-lib-sym
1.26 crook 11883:
1.78 anton 11884: @c -------------------------------------------------------------
1.150 anton 11885: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 11886: @section Assembler and Code Words
11887: @cindex assembler
11888: @cindex code words
1.44 crook 11889:
1.78 anton 11890: @menu
11891: * Code and ;code::
11892: * Common Assembler:: Assembler Syntax
11893: * Common Disassembler::
11894: * 386 Assembler:: Deviations and special cases
11895: * Alpha Assembler:: Deviations and special cases
11896: * MIPS assembler:: Deviations and special cases
1.161 anton 11897: * PowerPC assembler:: Deviations and special cases
1.78 anton 11898: * Other assemblers:: How to write them
11899: @end menu
1.21 crook 11900:
1.78 anton 11901: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11902: @subsection @code{Code} and @code{;code}
1.26 crook 11903:
1.78 anton 11904: Gforth provides some words for defining primitives (words written in
11905: machine code), and for defining the machine-code equivalent of
11906: @code{DOES>}-based defining words. However, the machine-independent
11907: nature of Gforth poses a few problems: First of all, Gforth runs on
11908: several architectures, so it can provide no standard assembler. What's
11909: worse is that the register allocation not only depends on the processor,
11910: but also on the @code{gcc} version and options used.
1.44 crook 11911:
1.78 anton 11912: The words that Gforth offers encapsulate some system dependences (e.g.,
11913: the header structure), so a system-independent assembler may be used in
11914: Gforth. If you do not have an assembler, you can compile machine code
11915: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11916: because these words emit stuff in @i{data} space; it works because
11917: Gforth has unified code/data spaces. Assembler isn't likely to be
11918: portable anyway.}.
1.21 crook 11919:
1.44 crook 11920:
1.78 anton 11921: doc-assembler
11922: doc-init-asm
11923: doc-code
11924: doc-end-code
11925: doc-;code
11926: doc-flush-icache
1.44 crook 11927:
1.21 crook 11928:
1.78 anton 11929: If @code{flush-icache} does not work correctly, @code{code} words
11930: etc. will not work (reliably), either.
1.44 crook 11931:
1.78 anton 11932: The typical usage of these @code{code} words can be shown most easily by
11933: analogy to the equivalent high-level defining words:
1.44 crook 11934:
1.78 anton 11935: @example
11936: : foo code foo
11937: <high-level Forth words> <assembler>
11938: ; end-code
11939:
11940: : bar : bar
11941: <high-level Forth words> <high-level Forth words>
11942: CREATE CREATE
11943: <high-level Forth words> <high-level Forth words>
11944: DOES> ;code
11945: <high-level Forth words> <assembler>
11946: ; end-code
11947: @end example
1.21 crook 11948:
1.78 anton 11949: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11950:
1.78 anton 11951: @cindex registers of the inner interpreter
11952: In the assembly code you will want to refer to the inner interpreter's
11953: registers (e.g., the data stack pointer) and you may want to use other
11954: registers for temporary storage. Unfortunately, the register allocation
11955: is installation-dependent.
1.44 crook 11956:
1.78 anton 11957: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11958: (return stack pointer) may be in different places in @code{gforth} and
11959: @code{gforth-fast}, or different installations. This means that you
11960: cannot write a @code{NEXT} routine that works reliably on both versions
11961: or different installations; so for doing @code{NEXT}, I recommend
11962: jumping to @code{' noop >code-address}, which contains nothing but a
11963: @code{NEXT}.
1.21 crook 11964:
1.78 anton 11965: For general accesses to the inner interpreter's registers, the easiest
11966: solution is to use explicit register declarations (@pxref{Explicit Reg
11967: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11968: all of the inner interpreter's registers: You have to compile Gforth
11969: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11970: the appropriate declarations must be present in the @code{machine.h}
11971: file (see @code{mips.h} for an example; you can find a full list of all
11972: declarable register symbols with @code{grep register engine.c}). If you
11973: give explicit registers to all variables that are declared at the
11974: beginning of @code{engine()}, you should be able to use the other
11975: caller-saved registers for temporary storage. Alternatively, you can use
11976: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11977: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11978: reserve a register (however, this restriction on register allocation may
11979: slow Gforth significantly).
1.44 crook 11980:
1.78 anton 11981: If this solution is not viable (e.g., because @code{gcc} does not allow
11982: you to explicitly declare all the registers you need), you have to find
11983: out by looking at the code where the inner interpreter's registers
11984: reside and which registers can be used for temporary storage. You can
11985: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11986:
1.78 anton 11987: In any case, it is good practice to abstract your assembly code from the
11988: actual register allocation. E.g., if the data stack pointer resides in
11989: register @code{$17}, create an alias for this register called @code{sp},
11990: and use that in your assembly code.
1.21 crook 11991:
1.78 anton 11992: @cindex code words, portable
11993: Another option for implementing normal and defining words efficiently
11994: is to add the desired functionality to the source of Gforth. For normal
11995: words you just have to edit @file{primitives} (@pxref{Automatic
11996: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11997: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11998: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11999:
1.78 anton 12000: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12001: @subsection Common Assembler
1.44 crook 12002:
1.78 anton 12003: The assemblers in Gforth generally use a postfix syntax, i.e., the
12004: instruction name follows the operands.
1.21 crook 12005:
1.78 anton 12006: The operands are passed in the usual order (the same that is used in the
12007: manual of the architecture). Since they all are Forth words, they have
12008: to be separated by spaces; you can also use Forth words to compute the
12009: operands.
1.44 crook 12010:
1.78 anton 12011: The instruction names usually end with a @code{,}. This makes it easier
12012: to visually separate instructions if you put several of them on one
12013: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12014:
1.78 anton 12015: Registers are usually specified by number; e.g., (decimal) @code{11}
12016: specifies registers R11 and F11 on the Alpha architecture (which one,
12017: depends on the instruction). The usual names are also available, e.g.,
12018: @code{s2} for R11 on Alpha.
1.21 crook 12019:
1.78 anton 12020: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12021: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12022: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12023: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12024: conditions are specified in a way specific to each assembler.
1.1 anton 12025:
1.78 anton 12026: Note that the register assignments of the Gforth engine can change
12027: between Gforth versions, or even between different compilations of the
12028: same Gforth version (e.g., if you use a different GCC version). So if
12029: you want to refer to Gforth's registers (e.g., the stack pointer or
12030: TOS), I recommend defining your own words for refering to these
12031: registers, and using them later on; then you can easily adapt to a
12032: changed register assignment. The stability of the register assignment
12033: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12034:
1.100 anton 12035: The most common use of these registers is to dispatch to the next word
12036: (the @code{next} routine). A portable way to do this is to jump to
12037: @code{' noop >code-address} (of course, this is less efficient than
12038: integrating the @code{next} code and scheduling it well).
1.1 anton 12039:
1.96 anton 12040: Another difference between Gforth version is that the top of stack is
12041: kept in memory in @code{gforth} and, on most platforms, in a register in
12042: @code{gforth-fast}.
12043:
1.78 anton 12044: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12045: @subsection Common Disassembler
1.127 anton 12046: @cindex disassembler, general
12047: @cindex gdb disassembler
1.1 anton 12048:
1.78 anton 12049: You can disassemble a @code{code} word with @code{see}
12050: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12051:
1.127 anton 12052: doc-discode
1.44 crook 12053:
1.127 anton 12054: There are two kinds of disassembler for Gforth: The Forth disassembler
12055: (available on some CPUs) and the gdb disassembler (available on
12056: platforms with @command{gdb} and @command{mktemp}). If both are
12057: available, the Forth disassembler is used by default. If you prefer
12058: the gdb disassembler, say
12059:
12060: @example
12061: ' disasm-gdb is discode
12062: @end example
12063:
12064: If neither is available, @code{discode} performs @code{dump}.
12065:
12066: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12067: assembler (i.e., same syntax, etc.). It also includes additional
12068: information in comments. In particular, the address of the instruction
12069: is given in a comment before the instruction.
1.1 anton 12070:
1.127 anton 12071: The gdb disassembler produces output in the same format as the gdb
12072: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12073: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12074: the 386 and AMD64 architectures).
12075:
1.78 anton 12076: @code{See} may display more or less than the actual code of the word,
12077: because the recognition of the end of the code is unreliable. You can
1.127 anton 12078: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12079: the code word is not immediately followed by a named word. If you have
1.116 anton 12080: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12081: to ensure that the end is recognized.
1.21 crook 12082:
1.78 anton 12083: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12084: @subsection 386 Assembler
1.44 crook 12085:
1.78 anton 12086: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12087: available under GPL, and originally part of bigFORTH.
1.21 crook 12088:
1.78 anton 12089: The 386 disassembler included in Gforth was written by Andrew McKewan
12090: and is in the public domain.
1.21 crook 12091:
1.91 anton 12092: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12093:
1.78 anton 12094: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12095:
1.78 anton 12096: The assembler includes all instruction of the Athlon, i.e. 486 core
12097: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12098: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12099: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12100:
1.78 anton 12101: There are several prefixes to switch between different operation sizes,
12102: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12103: double-word accesses. Addressing modes can be switched with @code{.wa}
12104: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12105: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12106:
1.78 anton 12107: For floating point operations, the prefixes are @code{.fs} (IEEE
12108: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12109: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12110:
1.78 anton 12111: The MMX opcodes don't have size prefixes, they are spelled out like in
12112: the Intel assembler. Instead of move from and to memory, there are
12113: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12114:
1.78 anton 12115: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12116: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12117: e.g., @code{3 #}. Here are some examples of addressing modes in various
12118: syntaxes:
1.21 crook 12119:
1.26 crook 12120: @example
1.91 anton 12121: Gforth Intel (NASM) AT&T (gas) Name
12122: .w ax ax %ax register (16 bit)
12123: ax eax %eax register (32 bit)
12124: 3 # offset 3 $3 immediate
12125: 1000 #) byte ptr 1000 1000 displacement
12126: bx ) [ebx] (%ebx) base
12127: 100 di d) 100[edi] 100(%edi) base+displacement
12128: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12129: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12130: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12131: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12132: @end example
12133:
12134: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12135: @code{DI)} to enforce 32-bit displacement fields (useful for
12136: later patching).
1.21 crook 12137:
1.78 anton 12138: Some example of instructions are:
1.1 anton 12139:
12140: @example
1.78 anton 12141: ax bx mov \ move ebx,eax
12142: 3 # ax mov \ mov eax,3
1.137 pazsan 12143: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12144: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12145: .w ax bx mov \ mov bx,ax
1.1 anton 12146: @end example
12147:
1.78 anton 12148: The following forms are supported for binary instructions:
1.1 anton 12149:
12150: @example
1.78 anton 12151: <reg> <reg> <inst>
12152: <n> # <reg> <inst>
12153: <mem> <reg> <inst>
12154: <reg> <mem> <inst>
1.136 pazsan 12155: <n> # <mem> <inst>
1.1 anton 12156: @end example
12157:
1.136 pazsan 12158: The shift/rotate syntax is:
1.1 anton 12159:
1.26 crook 12160: @example
1.78 anton 12161: <reg/mem> 1 # shl \ shortens to shift without immediate
12162: <reg/mem> 4 # shl
12163: <reg/mem> cl shl
1.26 crook 12164: @end example
1.1 anton 12165:
1.78 anton 12166: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12167: the byte version.
1.1 anton 12168:
1.78 anton 12169: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12170: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12171: pc < >= <= >}. (Note that most of these words shadow some Forth words
12172: when @code{assembler} is in front of @code{forth} in the search path,
12173: e.g., in @code{code} words). Currently the control structure words use
12174: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12175: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12176:
1.78 anton 12177: Here is an example of a @code{code} word (assumes that the stack pointer
12178: is in esi and the TOS is in ebx):
1.21 crook 12179:
1.26 crook 12180: @example
1.78 anton 12181: code my+ ( n1 n2 -- n )
12182: 4 si D) bx add
12183: 4 # si add
12184: Next
12185: end-code
1.26 crook 12186: @end example
1.21 crook 12187:
1.161 anton 12188:
1.78 anton 12189: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12190: @subsection Alpha Assembler
1.21 crook 12191:
1.78 anton 12192: The Alpha assembler and disassembler were originally written by Bernd
12193: Thallner.
1.26 crook 12194:
1.78 anton 12195: The register names @code{a0}--@code{a5} are not available to avoid
12196: shadowing hex numbers.
1.2 jwilke 12197:
1.78 anton 12198: Immediate forms of arithmetic instructions are distinguished by a
12199: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12200: does not count as arithmetic instruction).
1.2 jwilke 12201:
1.78 anton 12202: You have to specify all operands to an instruction, even those that
12203: other assemblers consider optional, e.g., the destination register for
12204: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12205:
1.78 anton 12206: You can specify conditions for @code{if,} by removing the first @code{b}
12207: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12208:
1.26 crook 12209: @example
1.78 anton 12210: 11 fgt if, \ if F11>0e
12211: ...
12212: endif,
1.26 crook 12213: @end example
1.2 jwilke 12214:
1.78 anton 12215: @code{fbgt,} gives @code{fgt}.
12216:
1.161 anton 12217: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12218: @subsection MIPS assembler
1.2 jwilke 12219:
1.78 anton 12220: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12221:
1.78 anton 12222: Currently the assembler and disassembler only cover the MIPS-I
12223: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12224:
1.78 anton 12225: The register names @code{$a0}--@code{$a3} are not available to avoid
12226: shadowing hex numbers.
1.2 jwilke 12227:
1.78 anton 12228: Because there is no way to distinguish registers from immediate values,
12229: you have to explicitly use the immediate forms of instructions, i.e.,
12230: @code{addiu,}, not just @code{addu,} (@command{as} does this
12231: implicitly).
1.2 jwilke 12232:
1.78 anton 12233: If the architecture manual specifies several formats for the instruction
12234: (e.g., for @code{jalr,}), you usually have to use the one with more
12235: arguments (i.e., two for @code{jalr,}). When in doubt, see
12236: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12237:
1.78 anton 12238: Branches and jumps in the MIPS architecture have a delay slot. You have
12239: to fill it yourself (the simplest way is to use @code{nop,}), the
12240: assembler does not do it for you (unlike @command{as}). Even
12241: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12242: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12243: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12244:
1.78 anton 12245: Note that you must not put branches, jumps, or @code{li,} into the delay
12246: slot: @code{li,} may expand to several instructions, and control flow
12247: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12248:
1.78 anton 12249: For branches the argument specifying the target is a relative address;
12250: You have to add the address of the delay slot to get the absolute
12251: address.
1.1 anton 12252:
1.78 anton 12253: The MIPS architecture also has load delay slots and restrictions on
12254: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12255: yourself to satisfy these restrictions, the assembler does not do it for
12256: you.
1.1 anton 12257:
1.78 anton 12258: You can specify the conditions for @code{if,} etc. by taking a
12259: conditional branch and leaving away the @code{b} at the start and the
12260: @code{,} at the end. E.g.,
1.1 anton 12261:
1.26 crook 12262: @example
1.78 anton 12263: 4 5 eq if,
12264: ... \ do something if $4 equals $5
12265: then,
1.26 crook 12266: @end example
1.1 anton 12267:
1.161 anton 12268:
12269: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
12270: @subsection PowerPC assembler
12271:
1.162 anton 12272: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12273: Revucky.
12274:
1.162 anton 12275: This assembler does not follow the convention of ending mnemonic names
12276: with a ``,'', so some mnemonic names shadow regular Forth words (in
12277: particular: @code{and or xor fabs}); so if you want to use the Forth
12278: words, you have to make them visible first, e.g., with @code{also
12279: forth}.
12280:
1.161 anton 12281: Registers are referred to by their number, e.g., @code{9} means the
12282: integer register 9 or the FP register 9 (depending on the
12283: instruction).
12284:
12285: Because there is no way to distinguish registers from immediate values,
12286: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12287: @code{addi,}, not just @code{add,}.
1.161 anton 12288:
1.162 anton 12289: The assembler and disassembler usually support the most general form
1.161 anton 12290: of an instruction, but usually not the shorter forms (especially for
12291: branches).
12292:
12293:
12294:
12295: @node Other assemblers, , PowerPC assembler, Assembler and Code Words
1.78 anton 12296: @subsection Other assemblers
12297:
12298: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12299: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12300: an assembler already. If you are writing them from scratch, please use
12301: a similar syntax style as the one we use (i.e., postfix, commas at the
12302: end of the instruction names, @pxref{Common Assembler}); make the output
12303: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12304: similar to the style we used.
12305:
12306: Hints on implementation: The most important part is to have a good test
12307: suite that contains all instructions. Once you have that, the rest is
12308: easy. For actual coding you can take a look at
12309: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12310: the assembler and disassembler, avoiding redundancy and some potential
12311: bugs. You can also look at that file (and @pxref{Advanced does> usage
12312: example}) to get ideas how to factor a disassembler.
12313:
12314: Start with the disassembler, because it's easier to reuse data from the
12315: disassembler for the assembler than the other way round.
1.1 anton 12316:
1.78 anton 12317: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12318: how simple it can be.
1.1 anton 12319:
1.161 anton 12320:
12321:
12322:
1.78 anton 12323: @c -------------------------------------------------------------
12324: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12325: @section Threading Words
12326: @cindex threading words
1.1 anton 12327:
1.78 anton 12328: @cindex code address
12329: These words provide access to code addresses and other threading stuff
12330: in Gforth (and, possibly, other interpretive Forths). It more or less
12331: abstracts away the differences between direct and indirect threading
12332: (and, for direct threading, the machine dependences). However, at
12333: present this wordset is still incomplete. It is also pretty low-level;
12334: some day it will hopefully be made unnecessary by an internals wordset
12335: that abstracts implementation details away completely.
1.1 anton 12336:
1.78 anton 12337: The terminology used here stems from indirect threaded Forth systems; in
12338: such a system, the XT of a word is represented by the CFA (code field
12339: address) of a word; the CFA points to a cell that contains the code
12340: address. The code address is the address of some machine code that
12341: performs the run-time action of invoking the word (e.g., the
12342: @code{dovar:} routine pushes the address of the body of the word (a
12343: variable) on the stack
12344: ).
1.1 anton 12345:
1.78 anton 12346: @cindex code address
12347: @cindex code field address
12348: In an indirect threaded Forth, you can get the code address of @i{name}
12349: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12350: >code-address}, independent of the threading method.
1.1 anton 12351:
1.78 anton 12352: doc-threading-method
12353: doc->code-address
12354: doc-code-address!
1.1 anton 12355:
1.78 anton 12356: @cindex @code{does>}-handler
12357: @cindex @code{does>}-code
12358: For a word defined with @code{DOES>}, the code address usually points to
12359: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12360: routine (in Gforth on some platforms, it can also point to the dodoes
12361: routine itself). What you are typically interested in, though, is
12362: whether a word is a @code{DOES>}-defined word, and what Forth code it
12363: executes; @code{>does-code} tells you that.
1.1 anton 12364:
1.78 anton 12365: doc->does-code
1.1 anton 12366:
1.78 anton 12367: To create a @code{DOES>}-defined word with the following basic words,
12368: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12369: @code{/does-handler} aus behind you have to place your executable Forth
12370: code. Finally you have to create a word and modify its behaviour with
12371: @code{does-handler!}.
1.1 anton 12372:
1.78 anton 12373: doc-does-code!
12374: doc-does-handler!
12375: doc-/does-handler
1.1 anton 12376:
1.78 anton 12377: The code addresses produced by various defining words are produced by
12378: the following words:
1.1 anton 12379:
1.78 anton 12380: doc-docol:
12381: doc-docon:
12382: doc-dovar:
12383: doc-douser:
12384: doc-dodefer:
12385: doc-dofield:
1.1 anton 12386:
1.99 anton 12387: @cindex definer
12388: The following two words generalize @code{>code-address},
12389: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12390:
12391: doc->definer
12392: doc-definer!
12393:
1.26 crook 12394: @c -------------------------------------------------------------
1.78 anton 12395: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12396: @section Passing Commands to the Operating System
12397: @cindex operating system - passing commands
12398: @cindex shell commands
12399:
12400: Gforth allows you to pass an arbitrary string to the host operating
12401: system shell (if such a thing exists) for execution.
12402:
12403: doc-sh
12404: doc-system
12405: doc-$?
1.23 crook 12406: doc-getenv
1.44 crook 12407:
1.26 crook 12408: @c -------------------------------------------------------------
1.47 crook 12409: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12410: @section Keeping track of Time
12411: @cindex time-related words
12412:
12413: doc-ms
12414: doc-time&date
1.79 anton 12415: doc-utime
12416: doc-cputime
1.47 crook 12417:
12418:
12419: @c -------------------------------------------------------------
12420: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12421: @section Miscellaneous Words
12422: @cindex miscellaneous words
12423:
1.29 crook 12424: @comment TODO find homes for these
12425:
1.26 crook 12426: These section lists the ANS Forth words that are not documented
1.21 crook 12427: elsewhere in this manual. Ultimately, they all need proper homes.
12428:
1.68 anton 12429: doc-quit
1.44 crook 12430:
1.26 crook 12431: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12432: (@pxref{ANS conformance}):
1.21 crook 12433:
12434: @code{EDITOR}
12435: @code{EMIT?}
12436: @code{FORGET}
12437:
1.24 anton 12438: @c ******************************************************************
12439: @node Error messages, Tools, Words, Top
12440: @chapter Error messages
12441: @cindex error messages
12442: @cindex backtrace
12443:
12444: A typical Gforth error message looks like this:
12445:
12446: @example
1.86 anton 12447: in file included from \evaluated string/:-1
1.24 anton 12448: in file included from ./yyy.fs:1
12449: ./xxx.fs:4: Invalid memory address
1.134 anton 12450: >>>bar<<<
1.79 anton 12451: Backtrace:
1.25 anton 12452: $400E664C @@
12453: $400E6664 foo
1.24 anton 12454: @end example
12455:
12456: The message identifying the error is @code{Invalid memory address}. The
12457: error happened when text-interpreting line 4 of the file
12458: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12459: word on the line where the error happened, is pointed out (with
1.134 anton 12460: @code{>>>} and @code{<<<}).
1.24 anton 12461:
12462: The file containing the error was included in line 1 of @file{./yyy.fs},
12463: and @file{yyy.fs} was included from a non-file (in this case, by giving
12464: @file{yyy.fs} as command-line parameter to Gforth).
12465:
12466: At the end of the error message you find a return stack dump that can be
12467: interpreted as a backtrace (possibly empty). On top you find the top of
12468: the return stack when the @code{throw} happened, and at the bottom you
12469: find the return stack entry just above the return stack of the topmost
12470: text interpreter.
12471:
12472: To the right of most return stack entries you see a guess for the word
12473: that pushed that return stack entry as its return address. This gives a
12474: backtrace. In our case we see that @code{bar} called @code{foo}, and
12475: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12476: address} exception).
12477:
12478: Note that the backtrace is not perfect: We don't know which return stack
12479: entries are return addresses (so we may get false positives); and in
12480: some cases (e.g., for @code{abort"}) we cannot determine from the return
12481: address the word that pushed the return address, so for some return
12482: addresses you see no names in the return stack dump.
1.25 anton 12483:
12484: @cindex @code{catch} and backtraces
12485: The return stack dump represents the return stack at the time when a
12486: specific @code{throw} was executed. In programs that make use of
12487: @code{catch}, it is not necessarily clear which @code{throw} should be
12488: used for the return stack dump (e.g., consider one @code{throw} that
12489: indicates an error, which is caught, and during recovery another error
1.160 anton 12490: happens; which @code{throw} should be used for the stack dump?).
12491: Gforth presents the return stack dump for the first @code{throw} after
12492: the last executed (not returned-to) @code{catch} or @code{nothrow};
12493: this works well in the usual case. To get the right backtrace, you
12494: usually want to insert @code{nothrow} or @code{['] false catch drop}
12495: after a @code{catch} if the error is not rethrown.
1.25 anton 12496:
12497: @cindex @code{gforth-fast} and backtraces
12498: @cindex @code{gforth-fast}, difference from @code{gforth}
12499: @cindex backtraces with @code{gforth-fast}
12500: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12501: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12502: from primitives (e.g., invalid memory address, stack empty etc.);
12503: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12504: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12505: exception caused by a primitive in @code{gforth-fast}, you will
12506: typically see no return stack dump at all; however, if the exception is
12507: caught by @code{catch} (e.g., for restoring some state), and then
12508: @code{throw}n again, the return stack dump will be for the first such
12509: @code{throw}.
1.2 jwilke 12510:
1.5 anton 12511: @c ******************************************************************
1.24 anton 12512: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12513: @chapter Tools
12514:
12515: @menu
12516: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12517: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12518: @end menu
12519:
12520: See also @ref{Emacs and Gforth}.
12521:
1.126 pazsan 12522: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12523: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12524: @cindex @file{ans-report.fs}
12525: @cindex report the words used in your program
12526: @cindex words used in your program
12527:
12528: If you want to label a Forth program as ANS Forth Program, you must
12529: document which wordsets the program uses; for extension wordsets, it is
12530: helpful to list the words the program requires from these wordsets
12531: (because Forth systems are allowed to provide only some words of them).
12532:
12533: The @file{ans-report.fs} tool makes it easy for you to determine which
12534: words from which wordset and which non-ANS words your application
12535: uses. You simply have to include @file{ans-report.fs} before loading the
12536: program you want to check. After loading your program, you can get the
12537: report with @code{print-ans-report}. A typical use is to run this as
12538: batch job like this:
12539: @example
12540: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12541: @end example
12542:
12543: The output looks like this (for @file{compat/control.fs}):
12544: @example
12545: The program uses the following words
12546: from CORE :
12547: : POSTPONE THEN ; immediate ?dup IF 0=
12548: from BLOCK-EXT :
12549: \
12550: from FILE :
12551: (
12552: @end example
12553:
12554: @subsection Caveats
12555:
12556: Note that @file{ans-report.fs} just checks which words are used, not whether
12557: they are used in an ANS Forth conforming way!
12558:
12559: Some words are defined in several wordsets in the
12560: standard. @file{ans-report.fs} reports them for only one of the
12561: wordsets, and not necessarily the one you expect. It depends on usage
12562: which wordset is the right one to specify. E.g., if you only use the
12563: compilation semantics of @code{S"}, it is a Core word; if you also use
12564: its interpretation semantics, it is a File word.
1.124 anton 12565:
12566:
1.127 anton 12567: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12568: @section Stack depth changes during interpretation
12569: @cindex @file{depth-changes.fs}
12570: @cindex depth changes during interpretation
12571: @cindex stack depth changes during interpretation
12572: @cindex items on the stack after interpretation
12573:
12574: Sometimes you notice that, after loading a file, there are items left
12575: on the stack. The tool @file{depth-changes.fs} helps you find out
12576: quickly where in the file these stack items are coming from.
12577:
12578: The simplest way of using @file{depth-changes.fs} is to include it
12579: before the file(s) you want to check, e.g.:
12580:
12581: @example
12582: gforth depth-changes.fs my-file.fs
12583: @end example
12584:
12585: This will compare the stack depths of the data and FP stack at every
12586: empty line (in interpretation state) against these depths at the last
12587: empty line (in interpretation state). If the depths are not equal,
12588: the position in the file and the stack contents are printed with
12589: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12590: change has occured in the paragraph of non-empty lines before the
12591: indicated line. It is a good idea to leave an empty line at the end
12592: of the file, so the last paragraph is checked, too.
12593:
12594: Checking only at empty lines usually works well, but sometimes you
12595: have big blocks of non-empty lines (e.g., when building a big table),
12596: and you want to know where in this block the stack depth changed. You
12597: can check all interpreted lines with
12598:
12599: @example
12600: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12601: @end example
12602:
12603: This checks the stack depth at every end-of-line. So the depth change
12604: occured in the line reported by the @code{~~} (not in the line
12605: before).
12606:
12607: Note that, while this offers better accuracy in indicating where the
12608: stack depth changes, it will often report many intentional stack depth
12609: changes (e.g., when an interpreted computation stretches across
12610: several lines). You can suppress the checking of some lines by
12611: putting backslashes at the end of these lines (not followed by white
12612: space), and using
12613:
12614: @example
12615: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12616: @end example
1.1 anton 12617:
12618: @c ******************************************************************
1.65 anton 12619: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12620: @chapter ANS conformance
12621: @cindex ANS conformance of Gforth
12622:
12623: To the best of our knowledge, Gforth is an
12624:
12625: ANS Forth System
12626: @itemize @bullet
12627: @item providing the Core Extensions word set
12628: @item providing the Block word set
12629: @item providing the Block Extensions word set
12630: @item providing the Double-Number word set
12631: @item providing the Double-Number Extensions word set
12632: @item providing the Exception word set
12633: @item providing the Exception Extensions word set
12634: @item providing the Facility word set
1.40 anton 12635: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12636: @item providing the File Access word set
12637: @item providing the File Access Extensions word set
12638: @item providing the Floating-Point word set
12639: @item providing the Floating-Point Extensions word set
12640: @item providing the Locals word set
12641: @item providing the Locals Extensions word set
12642: @item providing the Memory-Allocation word set
12643: @item providing the Memory-Allocation Extensions word set (that one's easy)
12644: @item providing the Programming-Tools word set
12645: @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
12646: @item providing the Search-Order word set
12647: @item providing the Search-Order Extensions word set
12648: @item providing the String word set
12649: @item providing the String Extensions word set (another easy one)
12650: @end itemize
12651:
1.118 anton 12652: Gforth has the following environmental restrictions:
12653:
12654: @cindex environmental restrictions
12655: @itemize @bullet
12656: @item
12657: While processing the OS command line, if an exception is not caught,
12658: Gforth exits with a non-zero exit code instyead of performing QUIT.
12659:
12660: @item
12661: When an @code{throw} is performed after a @code{query}, Gforth does not
12662: allways restore the input source specification in effect at the
12663: corresponding catch.
12664:
12665: @end itemize
12666:
12667:
1.1 anton 12668: @cindex system documentation
12669: In addition, ANS Forth systems are required to document certain
12670: implementation choices. This chapter tries to meet these
12671: requirements. In many cases it gives a way to ask the system for the
12672: information instead of providing the information directly, in
12673: particular, if the information depends on the processor, the operating
12674: system or the installation options chosen, or if they are likely to
12675: change during the maintenance of Gforth.
12676:
12677: @comment The framework for the rest has been taken from pfe.
12678:
12679: @menu
12680: * The Core Words::
12681: * The optional Block word set::
12682: * The optional Double Number word set::
12683: * The optional Exception word set::
12684: * The optional Facility word set::
12685: * The optional File-Access word set::
12686: * The optional Floating-Point word set::
12687: * The optional Locals word set::
12688: * The optional Memory-Allocation word set::
12689: * The optional Programming-Tools word set::
12690: * The optional Search-Order word set::
12691: @end menu
12692:
12693:
12694: @c =====================================================================
12695: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12696: @comment node-name, next, previous, up
12697: @section The Core Words
12698: @c =====================================================================
12699: @cindex core words, system documentation
12700: @cindex system documentation, core words
12701:
12702: @menu
12703: * core-idef:: Implementation Defined Options
12704: * core-ambcond:: Ambiguous Conditions
12705: * core-other:: Other System Documentation
12706: @end menu
12707:
12708: @c ---------------------------------------------------------------------
12709: @node core-idef, core-ambcond, The Core Words, The Core Words
12710: @subsection Implementation Defined Options
12711: @c ---------------------------------------------------------------------
12712: @cindex core words, implementation-defined options
12713: @cindex implementation-defined options, core words
12714:
12715:
12716: @table @i
12717: @item (Cell) aligned addresses:
12718: @cindex cell-aligned addresses
12719: @cindex aligned addresses
12720: processor-dependent. Gforth's alignment words perform natural alignment
12721: (e.g., an address aligned for a datum of size 8 is divisible by
12722: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12723:
12724: @item @code{EMIT} and non-graphic characters:
12725: @cindex @code{EMIT} and non-graphic characters
12726: @cindex non-graphic characters and @code{EMIT}
12727: The character is output using the C library function (actually, macro)
12728: @code{putc}.
12729:
12730: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12731: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12732: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12733: @cindex @code{ACCEPT}, editing
12734: @cindex @code{EXPECT}, editing
12735: This is modeled on the GNU readline library (@pxref{Readline
12736: Interaction, , Command Line Editing, readline, The GNU Readline
12737: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12738: producing a full word completion every time you type it (instead of
1.28 crook 12739: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12740:
12741: @item character set:
12742: @cindex character set
12743: The character set of your computer and display device. Gforth is
12744: 8-bit-clean (but some other component in your system may make trouble).
12745:
12746: @item Character-aligned address requirements:
12747: @cindex character-aligned address requirements
12748: installation-dependent. Currently a character is represented by a C
12749: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12750: (Comments on that requested).
12751:
12752: @item character-set extensions and matching of names:
12753: @cindex character-set extensions and matching of names
1.26 crook 12754: @cindex case-sensitivity for name lookup
12755: @cindex name lookup, case-sensitivity
12756: @cindex locale and case-sensitivity
1.21 crook 12757: Any character except the ASCII NUL character can be used in a
1.1 anton 12758: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12759: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12760: function is probably influenced by the locale. E.g., the @code{C} locale
12761: does not know about accents and umlauts, so they are matched
12762: case-sensitively in that locale. For portability reasons it is best to
12763: write programs such that they work in the @code{C} locale. Then one can
12764: use libraries written by a Polish programmer (who might use words
12765: containing ISO Latin-2 encoded characters) and by a French programmer
12766: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12767: funny results for some of the words (which ones, depends on the font you
12768: are using)). Also, the locale you prefer may not be available in other
12769: operating systems. Hopefully, Unicode will solve these problems one day.
12770:
12771: @item conditions under which control characters match a space delimiter:
12772: @cindex space delimiters
12773: @cindex control characters as delimiters
1.117 anton 12774: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12775: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12776: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12777: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12778: interpreter (aka text interpreter) by default, treats all white-space
12779: characters as delimiters.
12780:
1.26 crook 12781: @item format of the control-flow stack:
12782: @cindex control-flow stack, format
12783: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12784: stack item in cells is given by the constant @code{cs-item-size}. At the
12785: time of this writing, an item consists of a (pointer to a) locals list
12786: (third), an address in the code (second), and a tag for identifying the
12787: item (TOS). The following tags are used: @code{defstart},
12788: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12789: @code{scopestart}.
12790:
12791: @item conversion of digits > 35
12792: @cindex digits > 35
12793: The characters @code{[\]^_'} are the digits with the decimal value
12794: 36@minus{}41. There is no way to input many of the larger digits.
12795:
12796: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12797: @cindex @code{EXPECT}, display after end of input
12798: @cindex @code{ACCEPT}, display after end of input
12799: The cursor is moved to the end of the entered string. If the input is
12800: terminated using the @kbd{Return} key, a space is typed.
12801:
12802: @item exception abort sequence of @code{ABORT"}:
12803: @cindex exception abort sequence of @code{ABORT"}
12804: @cindex @code{ABORT"}, exception abort sequence
12805: The error string is stored into the variable @code{"error} and a
12806: @code{-2 throw} is performed.
12807:
12808: @item input line terminator:
12809: @cindex input line terminator
12810: @cindex line terminator on input
1.26 crook 12811: @cindex newline character on input
1.1 anton 12812: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12813: lines. One of these characters is typically produced when you type the
12814: @kbd{Enter} or @kbd{Return} key.
12815:
12816: @item maximum size of a counted string:
12817: @cindex maximum size of a counted string
12818: @cindex counted string, maximum size
12819: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12820: on all platforms, but this may change.
1.1 anton 12821:
12822: @item maximum size of a parsed string:
12823: @cindex maximum size of a parsed string
12824: @cindex parsed string, maximum size
12825: Given by the constant @code{/line}. Currently 255 characters.
12826:
12827: @item maximum size of a definition name, in characters:
12828: @cindex maximum size of a definition name, in characters
12829: @cindex name, maximum length
1.113 anton 12830: MAXU/8
1.1 anton 12831:
12832: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12833: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12834: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12835: MAXU/8
1.1 anton 12836:
12837: @item method of selecting the user input device:
12838: @cindex user input device, method of selecting
12839: The user input device is the standard input. There is currently no way to
12840: change it from within Gforth. However, the input can typically be
12841: redirected in the command line that starts Gforth.
12842:
12843: @item method of selecting the user output device:
12844: @cindex user output device, method of selecting
12845: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12846: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12847: output when the user output device is a terminal, otherwise the output
12848: is buffered.
1.1 anton 12849:
12850: @item methods of dictionary compilation:
12851: What are we expected to document here?
12852:
12853: @item number of bits in one address unit:
12854: @cindex number of bits in one address unit
12855: @cindex address unit, size in bits
12856: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12857: platforms.
1.1 anton 12858:
12859: @item number representation and arithmetic:
12860: @cindex number representation and arithmetic
1.79 anton 12861: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12862:
12863: @item ranges for integer types:
12864: @cindex ranges for integer types
12865: @cindex integer types, ranges
12866: Installation-dependent. Make environmental queries for @code{MAX-N},
12867: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12868: unsigned (and positive) types is 0. The lower bound for signed types on
12869: two's complement and one's complement machines machines can be computed
12870: by adding 1 to the upper bound.
12871:
12872: @item read-only data space regions:
12873: @cindex read-only data space regions
12874: @cindex data-space, read-only regions
12875: The whole Forth data space is writable.
12876:
12877: @item size of buffer at @code{WORD}:
12878: @cindex size of buffer at @code{WORD}
12879: @cindex @code{WORD} buffer size
12880: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12881: shared with the pictured numeric output string. If overwriting
12882: @code{PAD} is acceptable, it is as large as the remaining dictionary
12883: space, although only as much can be sensibly used as fits in a counted
12884: string.
12885:
12886: @item size of one cell in address units:
12887: @cindex cell size
12888: @code{1 cells .}.
12889:
12890: @item size of one character in address units:
12891: @cindex char size
1.79 anton 12892: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12893:
12894: @item size of the keyboard terminal buffer:
12895: @cindex size of the keyboard terminal buffer
12896: @cindex terminal buffer, size
12897: Varies. You can determine the size at a specific time using @code{lp@@
12898: tib - .}. It is shared with the locals stack and TIBs of files that
12899: include the current file. You can change the amount of space for TIBs
12900: and locals stack at Gforth startup with the command line option
12901: @code{-l}.
12902:
12903: @item size of the pictured numeric output buffer:
12904: @cindex size of the pictured numeric output buffer
12905: @cindex pictured numeric output buffer, size
12906: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12907: shared with @code{WORD}.
12908:
12909: @item size of the scratch area returned by @code{PAD}:
12910: @cindex size of the scratch area returned by @code{PAD}
12911: @cindex @code{PAD} size
12912: The remainder of dictionary space. @code{unused pad here - - .}.
12913:
12914: @item system case-sensitivity characteristics:
12915: @cindex case-sensitivity characteristics
1.26 crook 12916: Dictionary searches are case-insensitive (except in
1.1 anton 12917: @code{TABLE}s). However, as explained above under @i{character-set
12918: extensions}, the matching for non-ASCII characters is determined by the
12919: locale you are using. In the default @code{C} locale all non-ASCII
12920: characters are matched case-sensitively.
12921:
12922: @item system prompt:
12923: @cindex system prompt
12924: @cindex prompt
12925: @code{ ok} in interpret state, @code{ compiled} in compile state.
12926:
12927: @item division rounding:
12928: @cindex division rounding
1.166 ! anton 12929: The ordinary division words @code{/ mod /mod */ */mod} perform floored
! 12930: division (with the default installation of Gforth). You can check
! 12931: this with @code{s" floored" environment? drop .}. If you write
! 12932: programs that need a specific division rounding, best use
! 12933: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 12934:
12935: @item values of @code{STATE} when true:
12936: @cindex @code{STATE} values
12937: -1.
12938:
12939: @item values returned after arithmetic overflow:
12940: On two's complement machines, arithmetic is performed modulo
12941: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 12942: arithmetic (with appropriate mapping for signed types). Division by
12943: zero typically results in a @code{-55 throw} (Floating-point
12944: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 ! anton 12945: division overflow can result in these throws, or in @code{-11 throw};
! 12946: in @code{gforth-fast} division overflow and divide by zero may also
! 12947: result in returning bogus results without producing an exception.
1.1 anton 12948:
12949: @item whether the current definition can be found after @t{DOES>}:
12950: @cindex @t{DOES>}, visibility of current definition
12951: No.
12952:
12953: @end table
12954:
12955: @c ---------------------------------------------------------------------
12956: @node core-ambcond, core-other, core-idef, The Core Words
12957: @subsection Ambiguous conditions
12958: @c ---------------------------------------------------------------------
12959: @cindex core words, ambiguous conditions
12960: @cindex ambiguous conditions, core words
12961:
12962: @table @i
12963:
12964: @item a name is neither a word nor a number:
12965: @cindex name not found
1.26 crook 12966: @cindex undefined word
1.80 anton 12967: @code{-13 throw} (Undefined word).
1.1 anton 12968:
12969: @item a definition name exceeds the maximum length allowed:
1.26 crook 12970: @cindex word name too long
1.1 anton 12971: @code{-19 throw} (Word name too long)
12972:
12973: @item addressing a region not inside the various data spaces of the forth system:
12974: @cindex Invalid memory address
1.32 anton 12975: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12976: typically readable. Accessing other addresses gives results dependent on
12977: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12978: address).
12979:
12980: @item argument type incompatible with parameter:
1.26 crook 12981: @cindex argument type mismatch
1.1 anton 12982: This is usually not caught. Some words perform checks, e.g., the control
12983: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12984: mismatch).
12985:
12986: @item attempting to obtain the execution token of a word with undefined execution semantics:
12987: @cindex Interpreting a compile-only word, for @code{'} etc.
12988: @cindex execution token of words with undefined execution semantics
12989: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12990: get an execution token for @code{compile-only-error} (which performs a
12991: @code{-14 throw} when executed).
12992:
12993: @item dividing by zero:
12994: @cindex dividing by zero
12995: @cindex floating point unidentified fault, integer division
1.80 anton 12996: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12997: zero); on other systems, this typically results in a @code{-55 throw}
12998: (Floating-point unidentified fault).
1.1 anton 12999:
13000: @item insufficient data stack or return stack space:
13001: @cindex insufficient data stack or return stack space
13002: @cindex stack overflow
1.26 crook 13003: @cindex address alignment exception, stack overflow
1.1 anton 13004: @cindex Invalid memory address, stack overflow
13005: Depending on the operating system, the installation, and the invocation
13006: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13007: it is not checked. If it is checked, you typically get a @code{-3 throw}
13008: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13009: throw} (Invalid memory address) (depending on the platform and how you
13010: achieved the overflow) as soon as the overflow happens. If it is not
13011: checked, overflows typically result in mysterious illegal memory
13012: accesses, producing @code{-9 throw} (Invalid memory address) or
13013: @code{-23 throw} (Address alignment exception); they might also destroy
13014: the internal data structure of @code{ALLOCATE} and friends, resulting in
13015: various errors in these words.
1.1 anton 13016:
13017: @item insufficient space for loop control parameters:
13018: @cindex insufficient space for loop control parameters
1.80 anton 13019: Like other return stack overflows.
1.1 anton 13020:
13021: @item insufficient space in the dictionary:
13022: @cindex insufficient space in the dictionary
13023: @cindex dictionary overflow
1.12 anton 13024: If you try to allot (either directly with @code{allot}, or indirectly
13025: with @code{,}, @code{create} etc.) more memory than available in the
13026: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13027: to access memory beyond the end of the dictionary, the results are
13028: similar to stack overflows.
1.1 anton 13029:
13030: @item interpreting a word with undefined interpretation semantics:
13031: @cindex interpreting a word with undefined interpretation semantics
13032: @cindex Interpreting a compile-only word
13033: For some words, we have defined interpretation semantics. For the
13034: others: @code{-14 throw} (Interpreting a compile-only word).
13035:
13036: @item modifying the contents of the input buffer or a string literal:
13037: @cindex modifying the contents of the input buffer or a string literal
13038: These are located in writable memory and can be modified.
13039:
13040: @item overflow of the pictured numeric output string:
13041: @cindex overflow of the pictured numeric output string
13042: @cindex pictured numeric output string, overflow
1.24 anton 13043: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13044:
13045: @item parsed string overflow:
13046: @cindex parsed string overflow
13047: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13048:
13049: @item producing a result out of range:
13050: @cindex result out of range
13051: On two's complement machines, arithmetic is performed modulo
13052: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 ! anton 13053: arithmetic (with appropriate mapping for signed types). Division by
! 13054: zero typically results in a @code{-10 throw} (divide by zero) or
! 13055: @code{-55 throw} (floating point unidentified fault). Overflow on
! 13056: division may result in these errors or in @code{-11 throw} (result out
! 13057: of range). @code{Gforth-fast} may silently produce bogus results on
! 13058: division overflow or division by zero. @code{Convert} and
1.24 anton 13059: @code{>number} currently overflow silently.
1.1 anton 13060:
13061: @item reading from an empty data or return stack:
13062: @cindex stack empty
13063: @cindex stack underflow
1.24 anton 13064: @cindex return stack underflow
1.1 anton 13065: The data stack is checked by the outer (aka text) interpreter after
13066: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13067: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13068: depending on operating system, installation, and invocation. If they are
13069: caught by a check, they typically result in @code{-4 throw} (Stack
13070: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13071: (Invalid memory address), depending on the platform and which stack
13072: underflows and by how much. Note that even if the system uses checking
13073: (through the MMU), your program may have to underflow by a significant
13074: number of stack items to trigger the reaction (the reason for this is
13075: that the MMU, and therefore the checking, works with a page-size
13076: granularity). If there is no checking, the symptoms resulting from an
13077: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13078: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13079: (Invalid memory address) and Illegal Instruction (typically @code{-260
13080: throw}).
1.1 anton 13081:
13082: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13083: @cindex unexpected end of the input buffer
13084: @cindex zero-length string as a name
13085: @cindex Attempt to use zero-length string as a name
13086: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13087: use zero-length string as a name). Words like @code{'} probably will not
13088: find what they search. Note that it is possible to create zero-length
13089: names with @code{nextname} (should it not?).
13090:
13091: @item @code{>IN} greater than input buffer:
13092: @cindex @code{>IN} greater than input buffer
13093: The next invocation of a parsing word returns a string with length 0.
13094:
13095: @item @code{RECURSE} appears after @code{DOES>}:
13096: @cindex @code{RECURSE} appears after @code{DOES>}
13097: Compiles a recursive call to the defining word, not to the defined word.
13098:
13099: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13100: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13101: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13102: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13103: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13104: the end of the file was reached), its source-id may be
13105: reused. Therefore, restoring an input source specification referencing a
13106: closed file may lead to unpredictable results instead of a @code{-12
13107: THROW}.
13108:
13109: In the future, Gforth may be able to restore input source specifications
13110: from other than the current input source.
13111:
13112: @item data space containing definitions gets de-allocated:
13113: @cindex data space containing definitions gets de-allocated
13114: Deallocation with @code{allot} is not checked. This typically results in
13115: memory access faults or execution of illegal instructions.
13116:
13117: @item data space read/write with incorrect alignment:
13118: @cindex data space read/write with incorrect alignment
13119: @cindex alignment faults
1.26 crook 13120: @cindex address alignment exception
1.1 anton 13121: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13122: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13123: alignment turned on, incorrect alignment results in a @code{-9 throw}
13124: (Invalid memory address). There are reportedly some processors with
1.12 anton 13125: alignment restrictions that do not report violations.
1.1 anton 13126:
13127: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13128: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13129: Like other alignment errors.
13130:
13131: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13132: Like other stack underflows.
13133:
13134: @item loop control parameters not available:
13135: @cindex loop control parameters not available
13136: Not checked. The counted loop words simply assume that the top of return
13137: stack items are loop control parameters and behave accordingly.
13138:
13139: @item most recent definition does not have a name (@code{IMMEDIATE}):
13140: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13141: @cindex last word was headerless
13142: @code{abort" last word was headerless"}.
13143:
13144: @item name not defined by @code{VALUE} used by @code{TO}:
13145: @cindex name not defined by @code{VALUE} used by @code{TO}
13146: @cindex @code{TO} on non-@code{VALUE}s
13147: @cindex Invalid name argument, @code{TO}
13148: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13149: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13150:
13151: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13152: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13153: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13154: @code{-13 throw} (Undefined word)
13155:
13156: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13157: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13158: Gforth behaves as if they were of the same type. I.e., you can predict
13159: the behaviour by interpreting all parameters as, e.g., signed.
13160:
13161: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13162: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13163: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13164: compilation semantics of @code{TO}.
13165:
13166: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13167: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13168: @cindex @code{WORD}, string overflow
13169: Not checked. The string will be ok, but the count will, of course,
13170: contain only the least significant bits of the length.
13171:
13172: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13173: @cindex @code{LSHIFT}, large shift counts
13174: @cindex @code{RSHIFT}, large shift counts
13175: Processor-dependent. Typical behaviours are returning 0 and using only
13176: the low bits of the shift count.
13177:
13178: @item word not defined via @code{CREATE}:
13179: @cindex @code{>BODY} of non-@code{CREATE}d words
13180: @code{>BODY} produces the PFA of the word no matter how it was defined.
13181:
13182: @cindex @code{DOES>} of non-@code{CREATE}d words
13183: @code{DOES>} changes the execution semantics of the last defined word no
13184: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13185: @code{CREATE , DOES>}.
13186:
13187: @item words improperly used outside @code{<#} and @code{#>}:
13188: Not checked. As usual, you can expect memory faults.
13189:
13190: @end table
13191:
13192:
13193: @c ---------------------------------------------------------------------
13194: @node core-other, , core-ambcond, The Core Words
13195: @subsection Other system documentation
13196: @c ---------------------------------------------------------------------
13197: @cindex other system documentation, core words
13198: @cindex core words, other system documentation
13199:
13200: @table @i
13201: @item nonstandard words using @code{PAD}:
13202: @cindex @code{PAD} use by nonstandard words
13203: None.
13204:
13205: @item operator's terminal facilities available:
13206: @cindex operator's terminal facilities available
1.80 anton 13207: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13208: and you can give commands to Gforth interactively. The actual facilities
13209: available depend on how you invoke Gforth.
13210:
13211: @item program data space available:
13212: @cindex program data space available
13213: @cindex data space available
13214: @code{UNUSED .} gives the remaining dictionary space. The total
13215: dictionary space can be specified with the @code{-m} switch
13216: (@pxref{Invoking Gforth}) when Gforth starts up.
13217:
13218: @item return stack space available:
13219: @cindex return stack space available
13220: You can compute the total return stack space in cells with
13221: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13222: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13223:
13224: @item stack space available:
13225: @cindex stack space available
13226: You can compute the total data stack space in cells with
13227: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13228: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13229:
13230: @item system dictionary space required, in address units:
13231: @cindex system dictionary space required, in address units
13232: Type @code{here forthstart - .} after startup. At the time of this
13233: writing, this gives 80080 (bytes) on a 32-bit system.
13234: @end table
13235:
13236:
13237: @c =====================================================================
13238: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13239: @section The optional Block word set
13240: @c =====================================================================
13241: @cindex system documentation, block words
13242: @cindex block words, system documentation
13243:
13244: @menu
13245: * block-idef:: Implementation Defined Options
13246: * block-ambcond:: Ambiguous Conditions
13247: * block-other:: Other System Documentation
13248: @end menu
13249:
13250:
13251: @c ---------------------------------------------------------------------
13252: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13253: @subsection Implementation Defined Options
13254: @c ---------------------------------------------------------------------
13255: @cindex implementation-defined options, block words
13256: @cindex block words, implementation-defined options
13257:
13258: @table @i
13259: @item the format for display by @code{LIST}:
13260: @cindex @code{LIST} display format
13261: First the screen number is displayed, then 16 lines of 64 characters,
13262: each line preceded by the line number.
13263:
13264: @item the length of a line affected by @code{\}:
13265: @cindex length of a line affected by @code{\}
13266: @cindex @code{\}, line length in blocks
13267: 64 characters.
13268: @end table
13269:
13270:
13271: @c ---------------------------------------------------------------------
13272: @node block-ambcond, block-other, block-idef, The optional Block word set
13273: @subsection Ambiguous conditions
13274: @c ---------------------------------------------------------------------
13275: @cindex block words, ambiguous conditions
13276: @cindex ambiguous conditions, block words
13277:
13278: @table @i
13279: @item correct block read was not possible:
13280: @cindex block read not possible
13281: Typically results in a @code{throw} of some OS-derived value (between
13282: -512 and -2048). If the blocks file was just not long enough, blanks are
13283: supplied for the missing portion.
13284:
13285: @item I/O exception in block transfer:
13286: @cindex I/O exception in block transfer
13287: @cindex block transfer, I/O exception
13288: Typically results in a @code{throw} of some OS-derived value (between
13289: -512 and -2048).
13290:
13291: @item invalid block number:
13292: @cindex invalid block number
13293: @cindex block number invalid
13294: @code{-35 throw} (Invalid block number)
13295:
13296: @item a program directly alters the contents of @code{BLK}:
13297: @cindex @code{BLK}, altering @code{BLK}
13298: The input stream is switched to that other block, at the same
13299: position. If the storing to @code{BLK} happens when interpreting
13300: non-block input, the system will get quite confused when the block ends.
13301:
13302: @item no current block buffer for @code{UPDATE}:
13303: @cindex @code{UPDATE}, no current block buffer
13304: @code{UPDATE} has no effect.
13305:
13306: @end table
13307:
13308: @c ---------------------------------------------------------------------
13309: @node block-other, , block-ambcond, The optional Block word set
13310: @subsection Other system documentation
13311: @c ---------------------------------------------------------------------
13312: @cindex other system documentation, block words
13313: @cindex block words, other system documentation
13314:
13315: @table @i
13316: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13317: No restrictions (yet).
13318:
13319: @item the number of blocks available for source and data:
13320: depends on your disk space.
13321:
13322: @end table
13323:
13324:
13325: @c =====================================================================
13326: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13327: @section The optional Double Number word set
13328: @c =====================================================================
13329: @cindex system documentation, double words
13330: @cindex double words, system documentation
13331:
13332: @menu
13333: * double-ambcond:: Ambiguous Conditions
13334: @end menu
13335:
13336:
13337: @c ---------------------------------------------------------------------
13338: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13339: @subsection Ambiguous conditions
13340: @c ---------------------------------------------------------------------
13341: @cindex double words, ambiguous conditions
13342: @cindex ambiguous conditions, double words
13343:
13344: @table @i
1.29 crook 13345: @item @i{d} outside of range of @i{n} in @code{D>S}:
13346: @cindex @code{D>S}, @i{d} out of range of @i{n}
13347: The least significant cell of @i{d} is produced.
1.1 anton 13348:
13349: @end table
13350:
13351:
13352: @c =====================================================================
13353: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13354: @section The optional Exception word set
13355: @c =====================================================================
13356: @cindex system documentation, exception words
13357: @cindex exception words, system documentation
13358:
13359: @menu
13360: * exception-idef:: Implementation Defined Options
13361: @end menu
13362:
13363:
13364: @c ---------------------------------------------------------------------
13365: @node exception-idef, , The optional Exception word set, The optional Exception word set
13366: @subsection Implementation Defined Options
13367: @c ---------------------------------------------------------------------
13368: @cindex implementation-defined options, exception words
13369: @cindex exception words, implementation-defined options
13370:
13371: @table @i
13372: @item @code{THROW}-codes used in the system:
13373: @cindex @code{THROW}-codes used in the system
13374: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13375: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13376: codes -512@minus{}-2047 are used for OS errors (for file and memory
13377: allocation operations). The mapping from OS error numbers to throw codes
13378: is -512@minus{}@code{errno}. One side effect of this mapping is that
13379: undefined OS errors produce a message with a strange number; e.g.,
13380: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13381: @end table
13382:
13383: @c =====================================================================
13384: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13385: @section The optional Facility word set
13386: @c =====================================================================
13387: @cindex system documentation, facility words
13388: @cindex facility words, system documentation
13389:
13390: @menu
13391: * facility-idef:: Implementation Defined Options
13392: * facility-ambcond:: Ambiguous Conditions
13393: @end menu
13394:
13395:
13396: @c ---------------------------------------------------------------------
13397: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13398: @subsection Implementation Defined Options
13399: @c ---------------------------------------------------------------------
13400: @cindex implementation-defined options, facility words
13401: @cindex facility words, implementation-defined options
13402:
13403: @table @i
13404: @item encoding of keyboard events (@code{EKEY}):
13405: @cindex keyboard events, encoding in @code{EKEY}
13406: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13407: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13408: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13409: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13410: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13411: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13412:
1.1 anton 13413:
13414: @item duration of a system clock tick:
13415: @cindex duration of a system clock tick
13416: @cindex clock tick duration
13417: System dependent. With respect to @code{MS}, the time is specified in
13418: microseconds. How well the OS and the hardware implement this, is
13419: another question.
13420:
13421: @item repeatability to be expected from the execution of @code{MS}:
13422: @cindex repeatability to be expected from the execution of @code{MS}
13423: @cindex @code{MS}, repeatability to be expected
13424: System dependent. On Unix, a lot depends on load. If the system is
13425: lightly loaded, and the delay is short enough that Gforth does not get
13426: swapped out, the performance should be acceptable. Under MS-DOS and
13427: other single-tasking systems, it should be good.
13428:
13429: @end table
13430:
13431:
13432: @c ---------------------------------------------------------------------
13433: @node facility-ambcond, , facility-idef, The optional Facility word set
13434: @subsection Ambiguous conditions
13435: @c ---------------------------------------------------------------------
13436: @cindex facility words, ambiguous conditions
13437: @cindex ambiguous conditions, facility words
13438:
13439: @table @i
13440: @item @code{AT-XY} can't be performed on user output device:
13441: @cindex @code{AT-XY} can't be performed on user output device
13442: Largely terminal dependent. No range checks are done on the arguments.
13443: No errors are reported. You may see some garbage appearing, you may see
13444: simply nothing happen.
13445:
13446: @end table
13447:
13448:
13449: @c =====================================================================
13450: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13451: @section The optional File-Access word set
13452: @c =====================================================================
13453: @cindex system documentation, file words
13454: @cindex file words, system documentation
13455:
13456: @menu
13457: * file-idef:: Implementation Defined Options
13458: * file-ambcond:: Ambiguous Conditions
13459: @end menu
13460:
13461: @c ---------------------------------------------------------------------
13462: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13463: @subsection Implementation Defined Options
13464: @c ---------------------------------------------------------------------
13465: @cindex implementation-defined options, file words
13466: @cindex file words, implementation-defined options
13467:
13468: @table @i
13469: @item file access methods used:
13470: @cindex file access methods used
13471: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13472: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13473: @code{wb}): The file is cleared, if it exists, and created, if it does
13474: not (with both @code{open-file} and @code{create-file}). Under Unix
13475: @code{create-file} creates a file with 666 permissions modified by your
13476: umask.
13477:
13478: @item file exceptions:
13479: @cindex file exceptions
13480: The file words do not raise exceptions (except, perhaps, memory access
13481: faults when you pass illegal addresses or file-ids).
13482:
13483: @item file line terminator:
13484: @cindex file line terminator
13485: System-dependent. Gforth uses C's newline character as line
13486: terminator. What the actual character code(s) of this are is
13487: system-dependent.
13488:
13489: @item file name format:
13490: @cindex file name format
13491: System dependent. Gforth just uses the file name format of your OS.
13492:
13493: @item information returned by @code{FILE-STATUS}:
13494: @cindex @code{FILE-STATUS}, returned information
13495: @code{FILE-STATUS} returns the most powerful file access mode allowed
13496: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13497: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13498: along with the returned mode.
13499:
13500: @item input file state after an exception when including source:
13501: @cindex exception when including source
13502: All files that are left via the exception are closed.
13503:
1.29 crook 13504: @item @i{ior} values and meaning:
13505: @cindex @i{ior} values and meaning
1.68 anton 13506: @cindex @i{wior} values and meaning
1.29 crook 13507: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13508: intended as throw codes. They typically are in the range
13509: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13510: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13511:
13512: @item maximum depth of file input nesting:
13513: @cindex maximum depth of file input nesting
13514: @cindex file input nesting, maximum depth
13515: limited by the amount of return stack, locals/TIB stack, and the number
13516: of open files available. This should not give you troubles.
13517:
13518: @item maximum size of input line:
13519: @cindex maximum size of input line
13520: @cindex input line size, maximum
13521: @code{/line}. Currently 255.
13522:
13523: @item methods of mapping block ranges to files:
13524: @cindex mapping block ranges to files
13525: @cindex files containing blocks
13526: @cindex blocks in files
13527: By default, blocks are accessed in the file @file{blocks.fb} in the
13528: current working directory. The file can be switched with @code{USE}.
13529:
13530: @item number of string buffers provided by @code{S"}:
13531: @cindex @code{S"}, number of string buffers
13532: 1
13533:
13534: @item size of string buffer used by @code{S"}:
13535: @cindex @code{S"}, size of string buffer
13536: @code{/line}. currently 255.
13537:
13538: @end table
13539:
13540: @c ---------------------------------------------------------------------
13541: @node file-ambcond, , file-idef, The optional File-Access word set
13542: @subsection Ambiguous conditions
13543: @c ---------------------------------------------------------------------
13544: @cindex file words, ambiguous conditions
13545: @cindex ambiguous conditions, file words
13546:
13547: @table @i
13548: @item attempting to position a file outside its boundaries:
13549: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13550: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13551: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13552:
13553: @item attempting to read from file positions not yet written:
13554: @cindex reading from file positions not yet written
13555: End-of-file, i.e., zero characters are read and no error is reported.
13556:
1.29 crook 13557: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13558: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13559: An appropriate exception may be thrown, but a memory fault or other
13560: problem is more probable.
13561:
1.29 crook 13562: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13563: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13564: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13565: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13566: thrown.
13567:
13568: @item named file cannot be opened (@code{INCLUDED}):
13569: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13570: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13571:
13572: @item requesting an unmapped block number:
13573: @cindex unmapped block numbers
13574: There are no unmapped legal block numbers. On some operating systems,
13575: writing a block with a large number may overflow the file system and
13576: have an error message as consequence.
13577:
13578: @item using @code{source-id} when @code{blk} is non-zero:
13579: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13580: @code{source-id} performs its function. Typically it will give the id of
13581: the source which loaded the block. (Better ideas?)
13582:
13583: @end table
13584:
13585:
13586: @c =====================================================================
13587: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13588: @section The optional Floating-Point word set
13589: @c =====================================================================
13590: @cindex system documentation, floating-point words
13591: @cindex floating-point words, system documentation
13592:
13593: @menu
13594: * floating-idef:: Implementation Defined Options
13595: * floating-ambcond:: Ambiguous Conditions
13596: @end menu
13597:
13598:
13599: @c ---------------------------------------------------------------------
13600: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13601: @subsection Implementation Defined Options
13602: @c ---------------------------------------------------------------------
13603: @cindex implementation-defined options, floating-point words
13604: @cindex floating-point words, implementation-defined options
13605:
13606: @table @i
13607: @item format and range of floating point numbers:
13608: @cindex format and range of floating point numbers
13609: @cindex floating point numbers, format and range
13610: System-dependent; the @code{double} type of C.
13611:
1.29 crook 13612: @item results of @code{REPRESENT} when @i{float} is out of range:
13613: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13614: System dependent; @code{REPRESENT} is implemented using the C library
13615: function @code{ecvt()} and inherits its behaviour in this respect.
13616:
13617: @item rounding or truncation of floating-point numbers:
13618: @cindex rounding of floating-point numbers
13619: @cindex truncation of floating-point numbers
13620: @cindex floating-point numbers, rounding or truncation
13621: System dependent; the rounding behaviour is inherited from the hosting C
13622: compiler. IEEE-FP-based (i.e., most) systems by default round to
13623: nearest, and break ties by rounding to even (i.e., such that the last
13624: bit of the mantissa is 0).
13625:
13626: @item size of floating-point stack:
13627: @cindex floating-point stack size
13628: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13629: the floating-point stack (in floats). You can specify this on startup
13630: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13631:
13632: @item width of floating-point stack:
13633: @cindex floating-point stack width
13634: @code{1 floats}.
13635:
13636: @end table
13637:
13638:
13639: @c ---------------------------------------------------------------------
13640: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13641: @subsection Ambiguous conditions
13642: @c ---------------------------------------------------------------------
13643: @cindex floating-point words, ambiguous conditions
13644: @cindex ambiguous conditions, floating-point words
13645:
13646: @table @i
13647: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13648: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13649: System-dependent. Typically results in a @code{-23 THROW} like other
13650: alignment violations.
13651:
13652: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13653: @cindex @code{f@@} used with an address that is not float aligned
13654: @cindex @code{f!} used with an address that is not float aligned
13655: System-dependent. Typically results in a @code{-23 THROW} like other
13656: alignment violations.
13657:
13658: @item floating-point result out of range:
13659: @cindex floating-point result out of range
1.80 anton 13660: System-dependent. Can result in a @code{-43 throw} (floating point
13661: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13662: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13663: unidentified fault), or can produce a special value representing, e.g.,
13664: Infinity.
13665:
13666: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13667: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13668: System-dependent. Typically results in an alignment fault like other
13669: alignment violations.
13670:
1.35 anton 13671: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13672: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13673: The floating-point number is converted into decimal nonetheless.
13674:
13675: @item Both arguments are equal to zero (@code{FATAN2}):
13676: @cindex @code{FATAN2}, both arguments are equal to zero
13677: System-dependent. @code{FATAN2} is implemented using the C library
13678: function @code{atan2()}.
13679:
1.29 crook 13680: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13681: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13682: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13683: because of small errors and the tan will be a very large (or very small)
13684: but finite number.
13685:
1.29 crook 13686: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13687: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13688: The result is rounded to the nearest float.
13689:
13690: @item dividing by zero:
13691: @cindex dividing by zero, floating-point
13692: @cindex floating-point dividing by zero
13693: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13694: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13695: (floating point divide by zero) or @code{-55 throw} (Floating-point
13696: unidentified fault).
1.1 anton 13697:
13698: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13699: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13700: System dependent. On IEEE-FP based systems the number is converted into
13701: an infinity.
13702:
1.29 crook 13703: @item @i{float}<1 (@code{FACOSH}):
13704: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13705: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13706: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13707:
1.29 crook 13708: @item @i{float}=<-1 (@code{FLNP1}):
13709: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13710: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13711: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13712: negative infinity for @i{float}=-1).
1.1 anton 13713:
1.29 crook 13714: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13715: @cindex @code{FLN}, @i{float}=<0
13716: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13717: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13718: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13719: negative infinity for @i{float}=0).
1.1 anton 13720:
1.29 crook 13721: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13722: @cindex @code{FASINH}, @i{float}<0
13723: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13724: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13725: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13726: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13727: C library?).
1.1 anton 13728:
1.29 crook 13729: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13730: @cindex @code{FACOS}, |@i{float}|>1
13731: @cindex @code{FASIN}, |@i{float}|>1
13732: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13733: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13734: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13735:
1.29 crook 13736: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13737: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13738: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13739: Platform-dependent; typically, some double number is produced and no
13740: error is reported.
1.1 anton 13741:
13742: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13743: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13744: @code{Precision} characters of the numeric output area are used. If
13745: @code{precision} is too high, these words will smash the data or code
13746: close to @code{here}.
1.1 anton 13747: @end table
13748:
13749: @c =====================================================================
13750: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13751: @section The optional Locals word set
13752: @c =====================================================================
13753: @cindex system documentation, locals words
13754: @cindex locals words, system documentation
13755:
13756: @menu
13757: * locals-idef:: Implementation Defined Options
13758: * locals-ambcond:: Ambiguous Conditions
13759: @end menu
13760:
13761:
13762: @c ---------------------------------------------------------------------
13763: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13764: @subsection Implementation Defined Options
13765: @c ---------------------------------------------------------------------
13766: @cindex implementation-defined options, locals words
13767: @cindex locals words, implementation-defined options
13768:
13769: @table @i
13770: @item maximum number of locals in a definition:
13771: @cindex maximum number of locals in a definition
13772: @cindex locals, maximum number in a definition
13773: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13774: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13775: characters. The number of locals in a definition is bounded by the size
13776: of locals-buffer, which contains the names of the locals.
13777:
13778: @end table
13779:
13780:
13781: @c ---------------------------------------------------------------------
13782: @node locals-ambcond, , locals-idef, The optional Locals word set
13783: @subsection Ambiguous conditions
13784: @c ---------------------------------------------------------------------
13785: @cindex locals words, ambiguous conditions
13786: @cindex ambiguous conditions, locals words
13787:
13788: @table @i
13789: @item executing a named local in interpretation state:
13790: @cindex local in interpretation state
13791: @cindex Interpreting a compile-only word, for a local
13792: Locals have no interpretation semantics. If you try to perform the
13793: interpretation semantics, you will get a @code{-14 throw} somewhere
13794: (Interpreting a compile-only word). If you perform the compilation
13795: semantics, the locals access will be compiled (irrespective of state).
13796:
1.29 crook 13797: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13798: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13799: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13800: @cindex Invalid name argument, @code{TO}
13801: @code{-32 throw} (Invalid name argument)
13802:
13803: @end table
13804:
13805:
13806: @c =====================================================================
13807: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13808: @section The optional Memory-Allocation word set
13809: @c =====================================================================
13810: @cindex system documentation, memory-allocation words
13811: @cindex memory-allocation words, system documentation
13812:
13813: @menu
13814: * memory-idef:: Implementation Defined Options
13815: @end menu
13816:
13817:
13818: @c ---------------------------------------------------------------------
13819: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13820: @subsection Implementation Defined Options
13821: @c ---------------------------------------------------------------------
13822: @cindex implementation-defined options, memory-allocation words
13823: @cindex memory-allocation words, implementation-defined options
13824:
13825: @table @i
1.29 crook 13826: @item values and meaning of @i{ior}:
13827: @cindex @i{ior} values and meaning
13828: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13829: intended as throw codes. They typically are in the range
13830: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13831: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13832:
13833: @end table
13834:
13835: @c =====================================================================
13836: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13837: @section The optional Programming-Tools word set
13838: @c =====================================================================
13839: @cindex system documentation, programming-tools words
13840: @cindex programming-tools words, system documentation
13841:
13842: @menu
13843: * programming-idef:: Implementation Defined Options
13844: * programming-ambcond:: Ambiguous Conditions
13845: @end menu
13846:
13847:
13848: @c ---------------------------------------------------------------------
13849: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13850: @subsection Implementation Defined Options
13851: @c ---------------------------------------------------------------------
13852: @cindex implementation-defined options, programming-tools words
13853: @cindex programming-tools words, implementation-defined options
13854:
13855: @table @i
13856: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13857: @cindex @code{;CODE} ending sequence
13858: @cindex @code{CODE} ending sequence
13859: @code{END-CODE}
13860:
13861: @item manner of processing input following @code{;CODE} and @code{CODE}:
13862: @cindex @code{;CODE}, processing input
13863: @cindex @code{CODE}, processing input
13864: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13865: the input is processed by the text interpreter, (starting) in interpret
13866: state.
13867:
13868: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13869: @cindex @code{ASSEMBLER}, search order capability
13870: The ANS Forth search order word set.
13871:
13872: @item source and format of display by @code{SEE}:
13873: @cindex @code{SEE}, source and format of output
1.80 anton 13874: The source for @code{see} is the executable code used by the inner
1.1 anton 13875: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13876: (and on some platforms, assembly code for primitives) as well as
13877: possible.
1.1 anton 13878:
13879: @end table
13880:
13881: @c ---------------------------------------------------------------------
13882: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13883: @subsection Ambiguous conditions
13884: @c ---------------------------------------------------------------------
13885: @cindex programming-tools words, ambiguous conditions
13886: @cindex ambiguous conditions, programming-tools words
13887:
13888: @table @i
13889:
1.21 crook 13890: @item deleting the compilation word list (@code{FORGET}):
13891: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13892: Not implemented (yet).
13893:
1.29 crook 13894: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13895: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13896: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13897: @cindex control-flow stack underflow
13898: This typically results in an @code{abort"} with a descriptive error
13899: message (may change into a @code{-22 throw} (Control structure mismatch)
13900: in the future). You may also get a memory access error. If you are
13901: unlucky, this ambiguous condition is not caught.
13902:
1.29 crook 13903: @item @i{name} can't be found (@code{FORGET}):
13904: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13905: Not implemented (yet).
13906:
1.29 crook 13907: @item @i{name} not defined via @code{CREATE}:
13908: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13909: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13910: the execution semantics of the last defined word no matter how it was
13911: defined.
13912:
13913: @item @code{POSTPONE} applied to @code{[IF]}:
13914: @cindex @code{POSTPONE} applied to @code{[IF]}
13915: @cindex @code{[IF]} and @code{POSTPONE}
13916: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13917: equivalent to @code{[IF]}.
13918:
13919: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13920: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13921: Continue in the same state of conditional compilation in the next outer
13922: input source. Currently there is no warning to the user about this.
13923:
13924: @item removing a needed definition (@code{FORGET}):
13925: @cindex @code{FORGET}, removing a needed definition
13926: Not implemented (yet).
13927:
13928: @end table
13929:
13930:
13931: @c =====================================================================
13932: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13933: @section The optional Search-Order word set
13934: @c =====================================================================
13935: @cindex system documentation, search-order words
13936: @cindex search-order words, system documentation
13937:
13938: @menu
13939: * search-idef:: Implementation Defined Options
13940: * search-ambcond:: Ambiguous Conditions
13941: @end menu
13942:
13943:
13944: @c ---------------------------------------------------------------------
13945: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13946: @subsection Implementation Defined Options
13947: @c ---------------------------------------------------------------------
13948: @cindex implementation-defined options, search-order words
13949: @cindex search-order words, implementation-defined options
13950:
13951: @table @i
13952: @item maximum number of word lists in search order:
13953: @cindex maximum number of word lists in search order
13954: @cindex search order, maximum depth
13955: @code{s" wordlists" environment? drop .}. Currently 16.
13956:
13957: @item minimum search order:
13958: @cindex minimum search order
13959: @cindex search order, minimum
13960: @code{root root}.
13961:
13962: @end table
13963:
13964: @c ---------------------------------------------------------------------
13965: @node search-ambcond, , search-idef, The optional Search-Order word set
13966: @subsection Ambiguous conditions
13967: @c ---------------------------------------------------------------------
13968: @cindex search-order words, ambiguous conditions
13969: @cindex ambiguous conditions, search-order words
13970:
13971: @table @i
1.21 crook 13972: @item changing the compilation word list (during compilation):
13973: @cindex changing the compilation word list (during compilation)
13974: @cindex compilation word list, change before definition ends
13975: The word is entered into the word list that was the compilation word list
1.1 anton 13976: at the start of the definition. Any changes to the name field (e.g.,
13977: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13978: are applied to the latest defined word (as reported by @code{latest} or
13979: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13980:
13981: @item search order empty (@code{previous}):
13982: @cindex @code{previous}, search order empty
1.26 crook 13983: @cindex vocstack empty, @code{previous}
1.1 anton 13984: @code{abort" Vocstack empty"}.
13985:
13986: @item too many word lists in search order (@code{also}):
13987: @cindex @code{also}, too many word lists in search order
1.26 crook 13988: @cindex vocstack full, @code{also}
1.1 anton 13989: @code{abort" Vocstack full"}.
13990:
13991: @end table
13992:
13993: @c ***************************************************************
1.65 anton 13994: @node Standard vs Extensions, Model, ANS conformance, Top
13995: @chapter Should I use Gforth extensions?
13996: @cindex Gforth extensions
13997:
13998: As you read through the rest of this manual, you will see documentation
13999: for @i{Standard} words, and documentation for some appealing Gforth
14000: @i{extensions}. You might ask yourself the question: @i{``Should I
14001: restrict myself to the standard, or should I use the extensions?''}
14002:
14003: The answer depends on the goals you have for the program you are working
14004: on:
14005:
14006: @itemize @bullet
14007:
14008: @item Is it just for yourself or do you want to share it with others?
14009:
14010: @item
14011: If you want to share it, do the others all use Gforth?
14012:
14013: @item
14014: If it is just for yourself, do you want to restrict yourself to Gforth?
14015:
14016: @end itemize
14017:
14018: If restricting the program to Gforth is ok, then there is no reason not
14019: to use extensions. It is still a good idea to keep to the standard
14020: where it is easy, in case you want to reuse these parts in another
14021: program that you want to be portable.
14022:
14023: If you want to be able to port the program to other Forth systems, there
14024: are the following points to consider:
14025:
14026: @itemize @bullet
14027:
14028: @item
14029: Most Forth systems that are being maintained support the ANS Forth
14030: standard. So if your program complies with the standard, it will be
14031: portable among many systems.
14032:
14033: @item
14034: A number of the Gforth extensions can be implemented in ANS Forth using
14035: public-domain files provided in the @file{compat/} directory. These are
14036: mentioned in the text in passing. There is no reason not to use these
14037: extensions, your program will still be ANS Forth compliant; just include
14038: the appropriate compat files with your program.
14039:
14040: @item
14041: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14042: analyse your program and determine what non-Standard words it relies
14043: upon. However, it does not check whether you use standard words in a
14044: non-standard way.
14045:
14046: @item
14047: Some techniques are not standardized by ANS Forth, and are hard or
14048: impossible to implement in a standard way, but can be implemented in
14049: most Forth systems easily, and usually in similar ways (e.g., accessing
14050: word headers). Forth has a rich historical precedent for programmers
14051: taking advantage of implementation-dependent features of their tools
14052: (for example, relying on a knowledge of the dictionary
14053: structure). Sometimes these techniques are necessary to extract every
14054: last bit of performance from the hardware, sometimes they are just a
14055: programming shorthand.
14056:
14057: @item
14058: Does using a Gforth extension save more work than the porting this part
14059: to other Forth systems (if any) will cost?
14060:
14061: @item
14062: Is the additional functionality worth the reduction in portability and
14063: the additional porting problems?
14064:
14065: @end itemize
14066:
14067: In order to perform these consideratios, you need to know what's
14068: standard and what's not. This manual generally states if something is
1.81 anton 14069: non-standard, but the authoritative source is the
14070: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14071: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14072: into the thought processes of the technical committee.
14073:
14074: Note also that portability between Forth systems is not the only
14075: portability issue; there is also the issue of portability between
14076: different platforms (processor/OS combinations).
14077:
14078: @c ***************************************************************
14079: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14080: @chapter Model
14081:
14082: This chapter has yet to be written. It will contain information, on
14083: which internal structures you can rely.
14084:
14085: @c ***************************************************************
14086: @node Integrating Gforth, Emacs and Gforth, Model, Top
14087: @chapter Integrating Gforth into C programs
14088:
14089: This is not yet implemented.
14090:
14091: Several people like to use Forth as scripting language for applications
14092: that are otherwise written in C, C++, or some other language.
14093:
14094: The Forth system ATLAST provides facilities for embedding it into
14095: applications; unfortunately it has several disadvantages: most
14096: importantly, it is not based on ANS Forth, and it is apparently dead
14097: (i.e., not developed further and not supported). The facilities
1.21 crook 14098: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14099: making the switch should not be hard.
14100:
14101: We also tried to design the interface such that it can easily be
14102: implemented by other Forth systems, so that we may one day arrive at a
14103: standardized interface. Such a standard interface would allow you to
14104: replace the Forth system without having to rewrite C code.
14105:
14106: You embed the Gforth interpreter by linking with the library
14107: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14108: global symbols in this library that belong to the interface, have the
14109: prefix @code{forth_}. (Global symbols that are used internally have the
14110: prefix @code{gforth_}).
14111:
14112: You can include the declarations of Forth types and the functions and
14113: variables of the interface with @code{#include <forth.h>}.
14114:
14115: Types.
14116:
14117: Variables.
14118:
14119: Data and FP Stack pointer. Area sizes.
14120:
14121: functions.
14122:
14123: forth_init(imagefile)
14124: forth_evaluate(string) exceptions?
14125: forth_goto(address) (or forth_execute(xt)?)
14126: forth_continue() (a corountining mechanism)
14127:
14128: Adding primitives.
14129:
14130: No checking.
14131:
14132: Signals?
14133:
14134: Accessing the Stacks
14135:
1.26 crook 14136: @c ******************************************************************
1.1 anton 14137: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14138: @chapter Emacs and Gforth
14139: @cindex Emacs and Gforth
14140:
14141: @cindex @file{gforth.el}
14142: @cindex @file{forth.el}
14143: @cindex Rydqvist, Goran
1.107 dvdkhlng 14144: @cindex Kuehling, David
1.1 anton 14145: @cindex comment editing commands
14146: @cindex @code{\}, editing with Emacs
14147: @cindex debug tracer editing commands
14148: @cindex @code{~~}, removal with Emacs
14149: @cindex Forth mode in Emacs
1.107 dvdkhlng 14150:
1.1 anton 14151: Gforth comes with @file{gforth.el}, an improved version of
14152: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14153: improvements are:
14154:
14155: @itemize @bullet
14156: @item
1.107 dvdkhlng 14157: A better handling of indentation.
14158: @item
14159: A custom hilighting engine for Forth-code.
1.26 crook 14160: @item
14161: Comment paragraph filling (@kbd{M-q})
14162: @item
14163: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14164: @item
14165: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14166: @item
14167: Support of the @code{info-lookup} feature for looking up the
14168: documentation of a word.
1.107 dvdkhlng 14169: @item
14170: Support for reading and writing blocks files.
1.26 crook 14171: @end itemize
14172:
1.107 dvdkhlng 14173: To get a basic description of these features, enter Forth mode and
14174: type @kbd{C-h m}.
1.1 anton 14175:
14176: @cindex source location of error or debugging output in Emacs
14177: @cindex error output, finding the source location in Emacs
14178: @cindex debugging output, finding the source location in Emacs
14179: In addition, Gforth supports Emacs quite well: The source code locations
14180: given in error messages, debugging output (from @code{~~}) and failed
14181: assertion messages are in the right format for Emacs' compilation mode
14182: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14183: Manual}) so the source location corresponding to an error or other
14184: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14185: @kbd{C-c C-c} for the error under the cursor).
14186:
1.107 dvdkhlng 14187: @cindex viewing the documentation of a word in Emacs
14188: @cindex context-sensitive help
14189: Moreover, for words documented in this manual, you can look up the
14190: glossary entry quickly by using @kbd{C-h TAB}
14191: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14192: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14193: later and does not work for words containing @code{:}.
14194:
14195: @menu
14196: * Installing gforth.el:: Making Emacs aware of Forth.
14197: * Emacs Tags:: Viewing the source of a word in Emacs.
14198: * Hilighting:: Making Forth code look prettier.
14199: * Auto-Indentation:: Customizing auto-indentation.
14200: * Blocks Files:: Reading and writing blocks files.
14201: @end menu
14202:
14203: @c ----------------------------------
1.109 anton 14204: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14205: @section Installing gforth.el
14206: @cindex @file{.emacs}
14207: @cindex @file{gforth.el}, installation
14208: To make the features from @file{gforth.el} available in Emacs, add
14209: the following lines to your @file{.emacs} file:
14210:
14211: @example
14212: (autoload 'forth-mode "gforth.el")
14213: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14214: auto-mode-alist))
14215: (autoload 'forth-block-mode "gforth.el")
14216: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14217: auto-mode-alist))
14218: (add-hook 'forth-mode-hook (function (lambda ()
14219: ;; customize variables here:
14220: (setq forth-indent-level 4)
14221: (setq forth-minor-indent-level 2)
14222: (setq forth-hilight-level 3)
14223: ;;; ...
14224: )))
14225: @end example
14226:
14227: @c ----------------------------------
14228: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14229: @section Emacs Tags
1.1 anton 14230: @cindex @file{TAGS} file
14231: @cindex @file{etags.fs}
14232: @cindex viewing the source of a word in Emacs
1.43 anton 14233: @cindex @code{require}, placement in files
14234: @cindex @code{include}, placement in files
1.107 dvdkhlng 14235: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14236: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14237: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14238: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14239: several tags files at the same time (e.g., one for the Gforth sources
14240: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14241: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14242: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14243: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14244: with @file{etags.fs}, you should avoid putting definitions both before
14245: and after @code{require} etc., otherwise you will see the same file
14246: visited several times by commands like @code{tags-search}.
1.1 anton 14247:
1.107 dvdkhlng 14248: @c ----------------------------------
14249: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14250: @section Hilighting
14251: @cindex hilighting Forth code in Emacs
14252: @cindex highlighting Forth code in Emacs
14253: @file{gforth.el} comes with a custom source hilighting engine. When
14254: you open a file in @code{forth-mode}, it will be completely parsed,
14255: assigning faces to keywords, comments, strings etc. While you edit
14256: the file, modified regions get parsed and updated on-the-fly.
14257:
14258: Use the variable `forth-hilight-level' to change the level of
14259: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14260: you set the hilighting level to 0, the parser will still work in the
14261: background, collecting information about whether regions of text are
14262: ``compiled'' or ``interpreted''. Those information are required for
14263: auto-indentation to work properly. Set `forth-disable-parser' to
14264: non-nil if your computer is too slow to handle parsing. This will
14265: have an impact on the smartness of the auto-indentation engine,
14266: though.
14267:
14268: Sometimes Forth sources define new features that should be hilighted,
14269: new control structures, defining-words etc. You can use the variable
14270: `forth-custom-words' to make @code{forth-mode} hilight additional
14271: words and constructs. See the docstring of `forth-words' for details
14272: (in Emacs, type @kbd{C-h v forth-words}).
14273:
14274: `forth-custom-words' is meant to be customized in your
14275: @file{.emacs} file. To customize hilighing in a file-specific manner,
14276: set `forth-local-words' in a local-variables section at the end of
14277: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14278:
14279: Example:
14280: @example
14281: 0 [IF]
14282: Local Variables:
14283: forth-local-words:
14284: ((("t:") definition-starter (font-lock-keyword-face . 1)
14285: "[ \t\n]" t name (font-lock-function-name-face . 3))
14286: ((";t") definition-ender (font-lock-keyword-face . 1)))
14287: End:
14288: [THEN]
14289: @end example
14290:
14291: @c ----------------------------------
14292: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14293: @section Auto-Indentation
14294: @cindex auto-indentation of Forth code in Emacs
14295: @cindex indentation of Forth code in Emacs
14296: @code{forth-mode} automatically tries to indent lines in a smart way,
14297: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14298:
14299: Simple customization can be achieved by setting
14300: `forth-indent-level' and `forth-minor-indent-level' in your
14301: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14302: per default by multiples of 4 columns. To use the more traditional
14303: 3-column indentation, add the following lines to your @file{.emacs}:
14304:
14305: @example
14306: (add-hook 'forth-mode-hook (function (lambda ()
14307: ;; customize variables here:
14308: (setq forth-indent-level 3)
14309: (setq forth-minor-indent-level 1)
14310: )))
14311: @end example
14312:
14313: If you want indentation to recognize non-default words, customize it
14314: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14315: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14316: v forth-indent-words}).
14317:
14318: To customize indentation in a file-specific manner, set
14319: `forth-local-indent-words' in a local-variables section at the end of
14320: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14321: Emacs Manual}).
14322:
14323: Example:
14324: @example
14325: 0 [IF]
14326: Local Variables:
14327: forth-local-indent-words:
14328: ((("t:") (0 . 2) (0 . 2))
14329: ((";t") (-2 . 0) (0 . -2)))
14330: End:
14331: [THEN]
14332: @end example
14333:
14334: @c ----------------------------------
1.109 anton 14335: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14336: @section Blocks Files
14337: @cindex blocks files, use with Emacs
14338: @code{forth-mode} Autodetects blocks files by checking whether the
14339: length of the first line exceeds 1023 characters. It then tries to
14340: convert the file into normal text format. When you save the file, it
14341: will be written to disk as normal stream-source file.
14342:
14343: If you want to write blocks files, use @code{forth-blocks-mode}. It
14344: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14345:
1.107 dvdkhlng 14346: @itemize @bullet
14347: @item
14348: Files are written to disk in blocks file format.
14349: @item
14350: Screen numbers are displayed in the mode line (enumerated beginning
14351: with the value of `forth-block-base')
14352: @item
14353: Warnings are displayed when lines exceed 64 characters.
14354: @item
14355: The beginning of the currently edited block is marked with an
14356: overlay-arrow.
14357: @end itemize
1.41 anton 14358:
1.107 dvdkhlng 14359: There are some restrictions you should be aware of. When you open a
14360: blocks file that contains tabulator or newline characters, these
14361: characters will be translated into spaces when the file is written
14362: back to disk. If tabs or newlines are encountered during blocks file
14363: reading, an error is output to the echo area. So have a look at the
14364: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14365:
1.107 dvdkhlng 14366: Please consult the docstring of @code{forth-blocks-mode} for more
14367: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14368:
1.26 crook 14369: @c ******************************************************************
1.1 anton 14370: @node Image Files, Engine, Emacs and Gforth, Top
14371: @chapter Image Files
1.26 crook 14372: @cindex image file
14373: @cindex @file{.fi} files
1.1 anton 14374: @cindex precompiled Forth code
14375: @cindex dictionary in persistent form
14376: @cindex persistent form of dictionary
14377:
14378: An image file is a file containing an image of the Forth dictionary,
14379: i.e., compiled Forth code and data residing in the dictionary. By
14380: convention, we use the extension @code{.fi} for image files.
14381:
14382: @menu
1.18 anton 14383: * Image Licensing Issues:: Distribution terms for images.
14384: * Image File Background:: Why have image files?
1.67 anton 14385: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14386: * Data-Relocatable Image Files:: are better.
1.67 anton 14387: * Fully Relocatable Image Files:: better yet.
1.18 anton 14388: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14389: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14390: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14391: @end menu
14392:
1.18 anton 14393: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14394: @section Image Licensing Issues
14395: @cindex license for images
14396: @cindex image license
14397:
14398: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14399: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14400: original image; i.e., according to copyright law it is a derived work of
14401: the original image.
14402:
14403: Since Gforth is distributed under the GNU GPL, the newly created image
14404: falls under the GNU GPL, too. In particular, this means that if you
14405: distribute the image, you have to make all of the sources for the image
1.113 anton 14406: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14407: GNU General Public License (Section 3)}.
14408:
14409: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14410: contains only code compiled from the sources you gave it; if none of
14411: these sources is under the GPL, the terms discussed above do not apply
14412: to the image. However, if your image needs an engine (a gforth binary)
14413: that is under the GPL, you should make sure that you distribute both in
14414: a way that is at most a @emph{mere aggregation}, if you don't want the
14415: terms of the GPL to apply to the image.
14416:
14417: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14418: @section Image File Background
14419: @cindex image file background
14420:
1.80 anton 14421: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14422: definitions written in Forth. Since the Forth compiler itself belongs to
14423: those definitions, it is not possible to start the system with the
1.80 anton 14424: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14425: code as an image file in nearly executable form. When Gforth starts up,
14426: a C routine loads the image file into memory, optionally relocates the
14427: addresses, then sets up the memory (stacks etc.) according to
14428: information in the image file, and (finally) starts executing Forth
14429: code.
1.1 anton 14430:
14431: The image file variants represent different compromises between the
14432: goals of making it easy to generate image files and making them
14433: portable.
14434:
14435: @cindex relocation at run-time
1.26 crook 14436: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14437: run-time. This avoids many of the complications discussed below (image
14438: files are data relocatable without further ado), but costs performance
14439: (one addition per memory access).
14440:
14441: @cindex relocation at load-time
1.26 crook 14442: By contrast, the Gforth loader performs relocation at image load time. The
14443: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14444: appropriate code-field addresses (or code addresses in the case of
14445: direct threading).
14446:
14447: There are three kinds of image files, with different degrees of
14448: relocatability: non-relocatable, data-relocatable, and fully relocatable
14449: image files.
14450:
14451: @cindex image file loader
14452: @cindex relocating loader
14453: @cindex loader for image files
14454: These image file variants have several restrictions in common; they are
14455: caused by the design of the image file loader:
14456:
14457: @itemize @bullet
14458: @item
14459: There is only one segment; in particular, this means, that an image file
14460: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14461: them). The contents of the stacks are not represented, either.
1.1 anton 14462:
14463: @item
14464: The only kinds of relocation supported are: adding the same offset to
14465: all cells that represent data addresses; and replacing special tokens
14466: with code addresses or with pieces of machine code.
14467:
14468: If any complex computations involving addresses are performed, the
14469: results cannot be represented in the image file. Several applications that
14470: use such computations come to mind:
14471: @itemize @minus
14472: @item
14473: Hashing addresses (or data structures which contain addresses) for table
14474: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14475: purpose, you will have no problem, because the hash tables are
14476: recomputed automatically when the system is started. If you use your own
14477: hash tables, you will have to do something similar.
14478:
14479: @item
14480: There's a cute implementation of doubly-linked lists that uses
14481: @code{XOR}ed addresses. You could represent such lists as singly-linked
14482: in the image file, and restore the doubly-linked representation on
14483: startup.@footnote{In my opinion, though, you should think thrice before
14484: using a doubly-linked list (whatever implementation).}
14485:
14486: @item
14487: The code addresses of run-time routines like @code{docol:} cannot be
14488: represented in the image file (because their tokens would be replaced by
14489: machine code in direct threaded implementations). As a workaround,
14490: compute these addresses at run-time with @code{>code-address} from the
14491: executions tokens of appropriate words (see the definitions of
1.80 anton 14492: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14493:
14494: @item
14495: On many architectures addresses are represented in machine code in some
14496: shifted or mangled form. You cannot put @code{CODE} words that contain
14497: absolute addresses in this form in a relocatable image file. Workarounds
14498: are representing the address in some relative form (e.g., relative to
14499: the CFA, which is present in some register), or loading the address from
14500: a place where it is stored in a non-mangled form.
14501: @end itemize
14502: @end itemize
14503:
14504: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14505: @section Non-Relocatable Image Files
14506: @cindex non-relocatable image files
1.26 crook 14507: @cindex image file, non-relocatable
1.1 anton 14508:
14509: These files are simple memory dumps of the dictionary. They are specific
14510: to the executable (i.e., @file{gforth} file) they were created
14511: with. What's worse, they are specific to the place on which the
14512: dictionary resided when the image was created. Now, there is no
14513: guarantee that the dictionary will reside at the same place the next
14514: time you start Gforth, so there's no guarantee that a non-relocatable
14515: image will work the next time (Gforth will complain instead of crashing,
14516: though).
14517:
14518: You can create a non-relocatable image file with
14519:
1.44 crook 14520:
1.1 anton 14521: doc-savesystem
14522:
1.44 crook 14523:
1.1 anton 14524: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14525: @section Data-Relocatable Image Files
14526: @cindex data-relocatable image files
1.26 crook 14527: @cindex image file, data-relocatable
1.1 anton 14528:
14529: These files contain relocatable data addresses, but fixed code addresses
14530: (instead of tokens). They are specific to the executable (i.e.,
14531: @file{gforth} file) they were created with. For direct threading on some
14532: architectures (e.g., the i386), data-relocatable images do not work. You
14533: get a data-relocatable image, if you use @file{gforthmi} with a
14534: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14535: Relocatable Image Files}).
14536:
14537: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14538: @section Fully Relocatable Image Files
14539: @cindex fully relocatable image files
1.26 crook 14540: @cindex image file, fully relocatable
1.1 anton 14541:
14542: @cindex @file{kern*.fi}, relocatability
14543: @cindex @file{gforth.fi}, relocatability
14544: These image files have relocatable data addresses, and tokens for code
14545: addresses. They can be used with different binaries (e.g., with and
14546: without debugging) on the same machine, and even across machines with
14547: the same data formats (byte order, cell size, floating point
14548: format). However, they are usually specific to the version of Gforth
14549: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14550: are fully relocatable.
14551:
14552: There are two ways to create a fully relocatable image file:
14553:
14554: @menu
1.29 crook 14555: * gforthmi:: The normal way
1.1 anton 14556: * cross.fs:: The hard way
14557: @end menu
14558:
14559: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14560: @subsection @file{gforthmi}
14561: @cindex @file{comp-i.fs}
14562: @cindex @file{gforthmi}
14563:
14564: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14565: image @i{file} that contains everything you would load by invoking
14566: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14567: @example
1.29 crook 14568: gforthmi @i{file} @i{options}
1.1 anton 14569: @end example
14570:
14571: E.g., if you want to create an image @file{asm.fi} that has the file
14572: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14573: like this:
14574:
14575: @example
14576: gforthmi asm.fi asm.fs
14577: @end example
14578:
1.27 crook 14579: @file{gforthmi} is implemented as a sh script and works like this: It
14580: produces two non-relocatable images for different addresses and then
14581: compares them. Its output reflects this: first you see the output (if
1.62 crook 14582: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14583: files, then you see the output of the comparing program: It displays the
14584: offset used for data addresses and the offset used for code addresses;
1.1 anton 14585: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14586: image files, it displays a line like this:
1.1 anton 14587:
14588: @example
14589: 78DC BFFFFA50 BFFFFA40
14590: @end example
14591:
14592: This means that at offset $78dc from @code{forthstart}, one input image
14593: contains $bffffa50, and the other contains $bffffa40. Since these cells
14594: cannot be represented correctly in the output image, you should examine
14595: these places in the dictionary and verify that these cells are dead
14596: (i.e., not read before they are written).
1.39 anton 14597:
14598: @cindex --application, @code{gforthmi} option
14599: If you insert the option @code{--application} in front of the image file
14600: name, you will get an image that uses the @code{--appl-image} option
14601: instead of the @code{--image-file} option (@pxref{Invoking
14602: Gforth}). When you execute such an image on Unix (by typing the image
14603: name as command), the Gforth engine will pass all options to the image
14604: instead of trying to interpret them as engine options.
1.1 anton 14605:
1.27 crook 14606: If you type @file{gforthmi} with no arguments, it prints some usage
14607: instructions.
14608:
1.1 anton 14609: @cindex @code{savesystem} during @file{gforthmi}
14610: @cindex @code{bye} during @file{gforthmi}
14611: @cindex doubly indirect threaded code
1.44 crook 14612: @cindex environment variables
14613: @cindex @code{GFORTHD} -- environment variable
14614: @cindex @code{GFORTH} -- environment variable
1.1 anton 14615: @cindex @code{gforth-ditc}
1.29 crook 14616: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14617: words @code{savesystem} and @code{bye} must be visible. A special doubly
14618: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14619: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14620: this executable through the environment variable @code{GFORTHD}
14621: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14622: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14623: data-relocatable image (because there is no code address offset). The
14624: normal @file{gforth} executable is used for creating the relocatable
14625: image; you can pass the exact filename of this executable through the
14626: environment variable @code{GFORTH}.
1.1 anton 14627:
14628: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14629: @subsection @file{cross.fs}
14630: @cindex @file{cross.fs}
14631: @cindex cross-compiler
14632: @cindex metacompiler
1.47 crook 14633: @cindex target compiler
1.1 anton 14634:
14635: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14636: programming language (@pxref{Cross Compiler}).
1.1 anton 14637:
1.47 crook 14638: @code{cross} allows you to create image files for machines with
1.1 anton 14639: different data sizes and data formats than the one used for generating
14640: the image file. You can also use it to create an application image that
14641: does not contain a Forth compiler. These features are bought with
14642: restrictions and inconveniences in programming. E.g., addresses have to
14643: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14644: order to make the code relocatable.
14645:
14646:
14647: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14648: @section Stack and Dictionary Sizes
14649: @cindex image file, stack and dictionary sizes
14650: @cindex dictionary size default
14651: @cindex stack size default
14652:
14653: If you invoke Gforth with a command line flag for the size
14654: (@pxref{Invoking Gforth}), the size you specify is stored in the
14655: dictionary. If you save the dictionary with @code{savesystem} or create
14656: an image with @file{gforthmi}, this size will become the default
14657: for the resulting image file. E.g., the following will create a
1.21 crook 14658: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14659:
14660: @example
14661: gforthmi gforth.fi -m 1M
14662: @end example
14663:
14664: In other words, if you want to set the default size for the dictionary
14665: and the stacks of an image, just invoke @file{gforthmi} with the
14666: appropriate options when creating the image.
14667:
14668: @cindex stack size, cache-friendly
14669: Note: For cache-friendly behaviour (i.e., good performance), you should
14670: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14671: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14672: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14673:
14674: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14675: @section Running Image Files
14676: @cindex running image files
14677: @cindex invoking image files
14678: @cindex image file invocation
14679:
14680: @cindex -i, invoke image file
14681: @cindex --image file, invoke image file
1.29 crook 14682: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14683: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14684: @example
1.29 crook 14685: gforth -i @i{image}
1.1 anton 14686: @end example
14687:
14688: @cindex executable image file
1.26 crook 14689: @cindex image file, executable
1.1 anton 14690: If your operating system supports starting scripts with a line of the
14691: form @code{#! ...}, you just have to type the image file name to start
14692: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14693: just a convention). I.e., to run Gforth with the image file @i{image},
14694: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14695: This works because every @code{.fi} file starts with a line of this
14696: format:
14697:
14698: @example
14699: #! /usr/local/bin/gforth-0.4.0 -i
14700: @end example
14701:
14702: The file and pathname for the Gforth engine specified on this line is
14703: the specific Gforth executable that it was built against; i.e. the value
14704: of the environment variable @code{GFORTH} at the time that
14705: @file{gforthmi} was executed.
1.1 anton 14706:
1.27 crook 14707: You can make use of the same shell capability to make a Forth source
14708: file into an executable. For example, if you place this text in a file:
1.26 crook 14709:
14710: @example
14711: #! /usr/local/bin/gforth
14712:
14713: ." Hello, world" CR
14714: bye
14715: @end example
14716:
14717: @noindent
1.27 crook 14718: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14719: directly from the command line. The sequence @code{#!} is used in two
14720: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14721: system@footnote{The Unix kernel actually recognises two types of files:
14722: executable files and files of data, where the data is processed by an
14723: interpreter that is specified on the ``interpreter line'' -- the first
14724: line of the file, starting with the sequence #!. There may be a small
14725: limit (e.g., 32) on the number of characters that may be specified on
14726: the interpreter line.} secondly it is treated as a comment character by
14727: Gforth. Because of the second usage, a space is required between
1.80 anton 14728: @code{#!} and the path to the executable (moreover, some Unixes
14729: require the sequence @code{#! /}).
1.27 crook 14730:
14731: The disadvantage of this latter technique, compared with using
1.80 anton 14732: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14733: compiled on-the-fly, each time the program is invoked.
1.26 crook 14734:
1.1 anton 14735: doc-#!
14736:
1.44 crook 14737:
1.1 anton 14738: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14739: @section Modifying the Startup Sequence
14740: @cindex startup sequence for image file
14741: @cindex image file initialization sequence
14742: @cindex initialization sequence of image file
14743:
1.120 anton 14744: You can add your own initialization to the startup sequence of an image
14745: through the deferred word @code{'cold}. @code{'cold} is invoked just
14746: before the image-specific command line processing (i.e., loading files
14747: and evaluating (@code{-e}) strings) starts.
1.1 anton 14748:
14749: A sequence for adding your initialization usually looks like this:
14750:
14751: @example
14752: :noname
14753: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14754: ... \ your stuff
14755: ; IS 'cold
14756: @end example
14757:
1.157 anton 14758: After @code{'cold}, Gforth processes the image options
14759: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
14760: another deferred word. This normally prints Gforth's startup message
14761: and does nothing else.
14762:
1.1 anton 14763: @cindex turnkey image files
1.26 crook 14764: @cindex image file, turnkey applications
1.157 anton 14765: So, if you want to make a turnkey image (i.e., an image for an
14766: application instead of an extended Forth system), you can do this in
14767: two ways:
14768:
14769: @itemize @bullet
14770:
14771: @item
14772: If you want to do your interpretation of the OS command-line
14773: arguments, hook into @code{'cold}. In that case you probably also
14774: want to build the image with @code{gforthmi --application}
14775: (@pxref{gforthmi}) to keep the engine from processing OS command line
14776: options. You can then do your own command-line processing with
14777: @code{next-arg}
14778:
14779: @item
14780: If you want to have the normal Gforth processing of OS command-line
14781: arguments, hook into @code{bootmessage}.
14782:
14783: @end itemize
14784:
14785: In either case, you probably do not want the word that you execute in
14786: these hooks to exit normally, but use @code{bye} or @code{throw}.
14787: Otherwise the Gforth startup process would continue and eventually
14788: present the Forth command line to the user.
1.26 crook 14789:
14790: doc-'cold
1.157 anton 14791: doc-bootmessage
1.44 crook 14792:
1.1 anton 14793: @c ******************************************************************
1.113 anton 14794: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14795: @chapter Engine
14796: @cindex engine
14797: @cindex virtual machine
14798:
1.26 crook 14799: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14800: may be helpful for finding your way in the Gforth sources.
14801:
1.109 anton 14802: The ideas in this section have also been published in the following
14803: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14804: Forth-Tagung '93; M. Anton Ertl,
14805: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14806: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14807: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14808: Threaded code variations and optimizations (extended version)}},
14809: Forth-Tagung '02.
1.1 anton 14810:
14811: @menu
14812: * Portability::
14813: * Threading::
14814: * Primitives::
14815: * Performance::
14816: @end menu
14817:
14818: @node Portability, Threading, Engine, Engine
14819: @section Portability
14820: @cindex engine portability
14821:
1.26 crook 14822: An important goal of the Gforth Project is availability across a wide
14823: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14824: achieved this goal by manually coding the engine in assembly language
14825: for several then-popular processors. This approach is very
14826: labor-intensive and the results are short-lived due to progress in
14827: computer architecture.
1.1 anton 14828:
14829: @cindex C, using C for the engine
14830: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14831: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14832: particularly popular for UNIX-based Forths due to the large variety of
14833: architectures of UNIX machines. Unfortunately an implementation in C
14834: does not mix well with the goals of efficiency and with using
14835: traditional techniques: Indirect or direct threading cannot be expressed
14836: in C, and switch threading, the fastest technique available in C, is
14837: significantly slower. Another problem with C is that it is very
14838: cumbersome to express double integer arithmetic.
14839:
14840: @cindex GNU C for the engine
14841: @cindex long long
14842: Fortunately, there is a portable language that does not have these
14843: limitations: GNU C, the version of C processed by the GNU C compiler
14844: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14845: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14846: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14847: threading possible, its @code{long long} type (@pxref{Long Long, ,
14848: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14849: double numbers on many systems. GNU C is freely available on all
1.1 anton 14850: important (and many unimportant) UNIX machines, VMS, 80386s running
14851: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14852: on all these machines.
14853:
14854: Writing in a portable language has the reputation of producing code that
14855: is slower than assembly. For our Forth engine we repeatedly looked at
14856: the code produced by the compiler and eliminated most compiler-induced
14857: inefficiencies by appropriate changes in the source code.
14858:
14859: @cindex explicit register declarations
14860: @cindex --enable-force-reg, configuration flag
14861: @cindex -DFORCE_REG
14862: However, register allocation cannot be portably influenced by the
14863: programmer, leading to some inefficiencies on register-starved
14864: machines. We use explicit register declarations (@pxref{Explicit Reg
14865: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14866: improve the speed on some machines. They are turned on by using the
14867: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14868: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14869: machine, but also on the compiler version: On some machines some
14870: compiler versions produce incorrect code when certain explicit register
14871: declarations are used. So by default @code{-DFORCE_REG} is not used.
14872:
14873: @node Threading, Primitives, Portability, Engine
14874: @section Threading
14875: @cindex inner interpreter implementation
14876: @cindex threaded code implementation
14877:
14878: @cindex labels as values
14879: GNU C's labels as values extension (available since @code{gcc-2.0},
14880: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14881: makes it possible to take the address of @i{label} by writing
14882: @code{&&@i{label}}. This address can then be used in a statement like
14883: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14884: @code{goto x}.
14885:
1.26 crook 14886: @cindex @code{NEXT}, indirect threaded
1.1 anton 14887: @cindex indirect threaded inner interpreter
14888: @cindex inner interpreter, indirect threaded
1.26 crook 14889: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14890: @example
14891: cfa = *ip++;
14892: ca = *cfa;
14893: goto *ca;
14894: @end example
14895: @cindex instruction pointer
14896: For those unfamiliar with the names: @code{ip} is the Forth instruction
14897: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14898: execution token and points to the code field of the next word to be
14899: executed; The @code{ca} (code address) fetched from there points to some
14900: executable code, e.g., a primitive or the colon definition handler
14901: @code{docol}.
14902:
1.26 crook 14903: @cindex @code{NEXT}, direct threaded
1.1 anton 14904: @cindex direct threaded inner interpreter
14905: @cindex inner interpreter, direct threaded
14906: Direct threading is even simpler:
14907: @example
14908: ca = *ip++;
14909: goto *ca;
14910: @end example
14911:
14912: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14913: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14914:
14915: @menu
14916: * Scheduling::
14917: * Direct or Indirect Threaded?::
1.109 anton 14918: * Dynamic Superinstructions::
1.1 anton 14919: * DOES>::
14920: @end menu
14921:
14922: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14923: @subsection Scheduling
14924: @cindex inner interpreter optimization
14925:
14926: There is a little complication: Pipelined and superscalar processors,
14927: i.e., RISC and some modern CISC machines can process independent
14928: instructions while waiting for the results of an instruction. The
14929: compiler usually reorders (schedules) the instructions in a way that
14930: achieves good usage of these delay slots. However, on our first tries
14931: the compiler did not do well on scheduling primitives. E.g., for
14932: @code{+} implemented as
14933: @example
14934: n=sp[0]+sp[1];
14935: sp++;
14936: sp[0]=n;
14937: NEXT;
14938: @end example
1.81 anton 14939: the @code{NEXT} comes strictly after the other code, i.e., there is
14940: nearly no scheduling. After a little thought the problem becomes clear:
14941: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14942: addresses (and the version of @code{gcc} we used would not know it even
14943: if it was possible), so it could not move the load of the cfa above the
14944: store to the TOS. Indeed the pointers could be the same, if code on or
14945: very near the top of stack were executed. In the interest of speed we
14946: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14947: in scheduling: @code{NEXT} is divided into several parts:
14948: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14949: like:
1.1 anton 14950: @example
1.81 anton 14951: NEXT_P0;
1.1 anton 14952: n=sp[0]+sp[1];
14953: sp++;
14954: NEXT_P1;
14955: sp[0]=n;
14956: NEXT_P2;
14957: @end example
14958:
1.81 anton 14959: There are various schemes that distribute the different operations of
14960: NEXT between these parts in several ways; in general, different schemes
14961: perform best on different processors. We use a scheme for most
14962: architectures that performs well for most processors of this
1.109 anton 14963: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14964: the scheme on installation time.
14965:
1.1 anton 14966:
1.109 anton 14967: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14968: @subsection Direct or Indirect Threaded?
14969: @cindex threading, direct or indirect?
14970:
1.109 anton 14971: Threaded forth code consists of references to primitives (simple machine
14972: code routines like @code{+}) and to non-primitives (e.g., colon
14973: definitions, variables, constants); for a specific class of
14974: non-primitives (e.g., variables) there is one code routine (e.g.,
14975: @code{dovar}), but each variable needs a separate reference to its data.
14976:
14977: Traditionally Forth has been implemented as indirect threaded code,
14978: because this allows to use only one cell to reference a non-primitive
14979: (basically you point to the data, and find the code address there).
14980:
14981: @cindex primitive-centric threaded code
14982: However, threaded code in Gforth (since 0.6.0) uses two cells for
14983: non-primitives, one for the code address, and one for the data address;
14984: the data pointer is an immediate argument for the virtual machine
14985: instruction represented by the code address. We call this
14986: @emph{primitive-centric} threaded code, because all code addresses point
14987: to simple primitives. E.g., for a variable, the code address is for
14988: @code{lit} (also used for integer literals like @code{99}).
14989:
14990: Primitive-centric threaded code allows us to use (faster) direct
14991: threading as dispatch method, completely portably (direct threaded code
14992: in Gforth before 0.6.0 required architecture-specific code). It also
14993: eliminates the performance problems related to I-cache consistency that
14994: 386 implementations have with direct threaded code, and allows
14995: additional optimizations.
14996:
14997: @cindex hybrid direct/indirect threaded code
14998: There is a catch, however: the @var{xt} parameter of @code{execute} can
14999: occupy only one cell, so how do we pass non-primitives with their code
15000: @emph{and} data addresses to them? Our answer is to use indirect
15001: threaded dispatch for @code{execute} and other words that use a
15002: single-cell xt. So, normal threaded code in colon definitions uses
15003: direct threading, and @code{execute} and similar words, which dispatch
15004: to xts on the data stack, use indirect threaded code. We call this
15005: @emph{hybrid direct/indirect} threaded code.
15006:
15007: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15008: @cindex gforth engine
15009: @cindex gforth-fast engine
15010: The engines @command{gforth} and @command{gforth-fast} use hybrid
15011: direct/indirect threaded code. This means that with these engines you
15012: cannot use @code{,} to compile an xt. Instead, you have to use
15013: @code{compile,}.
15014:
15015: @cindex gforth-itc engine
1.115 anton 15016: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15017: This engine uses plain old indirect threaded code. It still compiles in
15018: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15019: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15020: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15021: and execute @code{' , is compile,}. Your program can check if it is
15022: running on a hybrid direct/indirect threaded engine or a pure indirect
15023: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15024:
15025:
15026: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15027: @subsection Dynamic Superinstructions
15028: @cindex Dynamic superinstructions with replication
15029: @cindex Superinstructions
15030: @cindex Replication
15031:
15032: The engines @command{gforth} and @command{gforth-fast} use another
15033: optimization: Dynamic superinstructions with replication. As an
15034: example, consider the following colon definition:
15035:
15036: @example
15037: : squared ( n1 -- n2 )
15038: dup * ;
15039: @end example
15040:
15041: Gforth compiles this into the threaded code sequence
15042:
15043: @example
15044: dup
15045: *
15046: ;s
15047: @end example
15048:
15049: In normal direct threaded code there is a code address occupying one
15050: cell for each of these primitives. Each code address points to a
15051: machine code routine, and the interpreter jumps to this machine code in
15052: order to execute the primitive. The routines for these three
15053: primitives are (in @command{gforth-fast} on the 386):
15054:
15055: @example
15056: Code dup
15057: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15058: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15059: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15060: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15061: end-code
15062: Code *
15063: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15064: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15065: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15066: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15067: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15068: end-code
15069: Code ;s
15070: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15071: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15072: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15073: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15074: end-code
15075: @end example
15076:
15077: With dynamic superinstructions and replication the compiler does not
15078: just lay down the threaded code, but also copies the machine code
15079: fragments, usually without the jump at the end.
15080:
15081: @example
15082: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15083: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15084: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15085: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15086: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15087: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15088: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15089: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15090: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15091: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15092: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15093: @end example
15094:
15095: Only when a threaded-code control-flow change happens (e.g., in
15096: @code{;s}), the jump is appended. This optimization eliminates many of
15097: these jumps and makes the rest much more predictable. The speedup
15098: depends on the processor and the application; on the Athlon and Pentium
15099: III this optimization typically produces a speedup by a factor of 2.
15100:
15101: The code addresses in the direct-threaded code are set to point to the
15102: appropriate points in the copied machine code, in this example like
15103: this:
1.1 anton 15104:
1.109 anton 15105: @example
15106: primitive code address
15107: dup $4057D27D
15108: * $4057D286
15109: ;s $4057D292
15110: @end example
15111:
15112: Thus there can be threaded-code jumps to any place in this piece of
15113: code. This also simplifies decompilation quite a bit.
15114:
15115: @cindex --no-dynamic command-line option
15116: @cindex --no-super command-line option
15117: You can disable this optimization with @option{--no-dynamic}. You can
15118: use the copying without eliminating the jumps (i.e., dynamic
15119: replication, but without superinstructions) with @option{--no-super};
15120: this gives the branch prediction benefit alone; the effect on
1.110 anton 15121: performance depends on the CPU; on the Athlon and Pentium III the
15122: speedup is a little less than for dynamic superinstructions with
15123: replication.
15124:
15125: @cindex patching threaded code
15126: One use of these options is if you want to patch the threaded code.
15127: With superinstructions, many of the dispatch jumps are eliminated, so
15128: patching often has no effect. These options preserve all the dispatch
15129: jumps.
1.109 anton 15130:
15131: @cindex --dynamic command-line option
1.110 anton 15132: On some machines dynamic superinstructions are disabled by default,
15133: because it is unsafe on these machines. However, if you feel
15134: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15135:
15136: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15137: @subsection DOES>
15138: @cindex @code{DOES>} implementation
15139:
1.26 crook 15140: @cindex @code{dodoes} routine
15141: @cindex @code{DOES>}-code
1.1 anton 15142: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15143: the chunk of code executed by every word defined by a
1.109 anton 15144: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15145: this is only needed if the xt of the word is @code{execute}d. The main
15146: problem here is: How to find the Forth code to be executed, i.e. the
15147: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15148: solutions:
1.1 anton 15149:
1.21 crook 15150: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15151: @code{DOES>}-code address is stored in the cell after the code address
15152: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15153: illegal in the Forth-79 and all later standards, because in fig-Forth
15154: this address lies in the body (which is illegal in these
15155: standards). However, by making the code field larger for all words this
15156: solution becomes legal again. We use this approach. Leaving a cell
15157: unused in most words is a bit wasteful, but on the machines we are
15158: targeting this is hardly a problem.
15159:
1.1 anton 15160:
15161: @node Primitives, Performance, Threading, Engine
15162: @section Primitives
15163: @cindex primitives, implementation
15164: @cindex virtual machine instructions, implementation
15165:
15166: @menu
15167: * Automatic Generation::
15168: * TOS Optimization::
15169: * Produced code::
15170: @end menu
15171:
15172: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15173: @subsection Automatic Generation
15174: @cindex primitives, automatic generation
15175:
15176: @cindex @file{prims2x.fs}
1.109 anton 15177:
1.1 anton 15178: Since the primitives are implemented in a portable language, there is no
15179: longer any need to minimize the number of primitives. On the contrary,
15180: having many primitives has an advantage: speed. In order to reduce the
15181: number of errors in primitives and to make programming them easier, we
1.109 anton 15182: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15183: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15184: generates most (and sometimes all) of the C code for a primitive from
15185: the stack effect notation. The source for a primitive has the following
15186: form:
1.1 anton 15187:
15188: @cindex primitive source format
15189: @format
1.58 anton 15190: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15191: [@code{""}@i{glossary entry}@code{""}]
15192: @i{C code}
1.1 anton 15193: [@code{:}
1.29 crook 15194: @i{Forth code}]
1.1 anton 15195: @end format
15196:
15197: The items in brackets are optional. The category and glossary fields
15198: are there for generating the documentation, the Forth code is there
15199: for manual implementations on machines without GNU C. E.g., the source
15200: for the primitive @code{+} is:
15201: @example
1.58 anton 15202: + ( n1 n2 -- n ) core plus
1.1 anton 15203: n = n1+n2;
15204: @end example
15205:
15206: This looks like a specification, but in fact @code{n = n1+n2} is C
15207: code. Our primitive generation tool extracts a lot of information from
15208: the stack effect notations@footnote{We use a one-stack notation, even
15209: though we have separate data and floating-point stacks; The separate
15210: notation can be generated easily from the unified notation.}: The number
15211: of items popped from and pushed on the stack, their type, and by what
15212: name they are referred to in the C code. It then generates a C code
15213: prelude and postlude for each primitive. The final C code for @code{+}
15214: looks like this:
15215:
15216: @example
1.46 pazsan 15217: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15218: /* */ /* documentation */
1.81 anton 15219: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15220: @{
15221: DEF_CA /* definition of variable ca (indirect threading) */
15222: Cell n1; /* definitions of variables */
15223: Cell n2;
15224: Cell n;
1.81 anton 15225: NEXT_P0; /* NEXT part 0 */
1.1 anton 15226: n1 = (Cell) sp[1]; /* input */
15227: n2 = (Cell) TOS;
15228: sp += 1; /* stack adjustment */
15229: @{
15230: n = n1+n2; /* C code taken from the source */
15231: @}
15232: NEXT_P1; /* NEXT part 1 */
15233: TOS = (Cell)n; /* output */
15234: NEXT_P2; /* NEXT part 2 */
15235: @}
15236: @end example
15237:
15238: This looks long and inefficient, but the GNU C compiler optimizes quite
15239: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15240: HP RISC machines: Defining the @code{n}s does not produce any code, and
15241: using them as intermediate storage also adds no cost.
15242:
1.26 crook 15243: There are also other optimizations that are not illustrated by this
15244: example: assignments between simple variables are usually for free (copy
1.1 anton 15245: propagation). If one of the stack items is not used by the primitive
15246: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15247: (dead code elimination). On the other hand, there are some things that
15248: the compiler does not do, therefore they are performed by
15249: @file{prims2x.fs}: The compiler does not optimize code away that stores
15250: a stack item to the place where it just came from (e.g., @code{over}).
15251:
15252: While programming a primitive is usually easy, there are a few cases
15253: where the programmer has to take the actions of the generator into
15254: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15255: fall through to @code{NEXT}.
1.109 anton 15256:
15257: For more information
1.1 anton 15258:
15259: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15260: @subsection TOS Optimization
15261: @cindex TOS optimization for primitives
15262: @cindex primitives, keeping the TOS in a register
15263:
15264: An important optimization for stack machine emulators, e.g., Forth
15265: engines, is keeping one or more of the top stack items in
1.29 crook 15266: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15267: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15268: @itemize @bullet
15269: @item
1.29 crook 15270: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15271: due to fewer loads from and stores to the stack.
1.29 crook 15272: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15273: @i{y<n}, due to additional moves between registers.
1.1 anton 15274: @end itemize
15275:
15276: @cindex -DUSE_TOS
15277: @cindex -DUSE_NO_TOS
15278: In particular, keeping one item in a register is never a disadvantage,
15279: if there are enough registers. Keeping two items in registers is a
15280: disadvantage for frequent words like @code{?branch}, constants,
15281: variables, literals and @code{i}. Therefore our generator only produces
15282: code that keeps zero or one items in registers. The generated C code
15283: covers both cases; the selection between these alternatives is made at
15284: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15285: code for @code{+} is just a simple variable name in the one-item case,
15286: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15287: GNU C compiler tries to keep simple variables like @code{TOS} in
15288: registers, and it usually succeeds, if there are enough registers.
15289:
15290: @cindex -DUSE_FTOS
15291: @cindex -DUSE_NO_FTOS
15292: The primitive generator performs the TOS optimization for the
15293: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15294: operations the benefit of this optimization is even larger:
15295: floating-point operations take quite long on most processors, but can be
15296: performed in parallel with other operations as long as their results are
15297: not used. If the FP-TOS is kept in a register, this works. If
15298: it is kept on the stack, i.e., in memory, the store into memory has to
15299: wait for the result of the floating-point operation, lengthening the
15300: execution time of the primitive considerably.
15301:
15302: The TOS optimization makes the automatic generation of primitives a
15303: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15304: @code{TOS} is not sufficient. There are some special cases to
15305: consider:
15306: @itemize @bullet
15307: @item In the case of @code{dup ( w -- w w )} the generator must not
15308: eliminate the store to the original location of the item on the stack,
15309: if the TOS optimization is turned on.
15310: @item Primitives with stack effects of the form @code{--}
1.29 crook 15311: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15312: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15313: must load the TOS from the stack at the end. But for the null stack
15314: effect @code{--} no stores or loads should be generated.
15315: @end itemize
15316:
15317: @node Produced code, , TOS Optimization, Primitives
15318: @subsection Produced code
15319: @cindex primitives, assembly code listing
15320:
15321: @cindex @file{engine.s}
15322: To see what assembly code is produced for the primitives on your machine
15323: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15324: look at the resulting file @file{engine.s}. Alternatively, you can also
15325: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15326:
15327: @node Performance, , Primitives, Engine
15328: @section Performance
15329: @cindex performance of some Forth interpreters
15330: @cindex engine performance
15331: @cindex benchmarking Forth systems
15332: @cindex Gforth performance
15333:
15334: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15335: impossible to write a significantly faster threaded-code engine.
1.1 anton 15336:
15337: On register-starved machines like the 386 architecture processors
15338: improvements are possible, because @code{gcc} does not utilize the
15339: registers as well as a human, even with explicit register declarations;
15340: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15341: and hand-tuned it for the 486; this system is 1.19 times faster on the
15342: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15343: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15344: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15345: registers fit in real registers (and we can even afford to use the TOS
15346: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15347: earlier results. And dynamic superinstructions provide another speedup
15348: (but only around a factor 1.2 on the 486).
1.1 anton 15349:
15350: @cindex Win32Forth performance
15351: @cindex NT Forth performance
15352: @cindex eforth performance
15353: @cindex ThisForth performance
15354: @cindex PFE performance
15355: @cindex TILE performance
1.81 anton 15356: The potential advantage of assembly language implementations is not
1.112 anton 15357: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15358: (direct threaded, compiled with @code{gcc-2.95.1} and
15359: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15360: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15361: (with and without peephole (aka pinhole) optimization of the threaded
15362: code); all these systems were written in assembly language. We also
15363: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15364: with @code{gcc-2.6.3} with the default configuration for Linux:
15365: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15366: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15367: employs peephole optimization of the threaded code) and TILE (compiled
15368: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15369: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15370: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15371: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15372: then extended it to run the benchmarks, added the peephole optimizer,
15373: ran the benchmarks and reported the results.
1.40 anton 15374:
1.1 anton 15375: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15376: matrix multiplication come from the Stanford integer benchmarks and have
15377: been translated into Forth by Martin Fraeman; we used the versions
15378: included in the TILE Forth package, but with bigger data set sizes; and
15379: a recursive Fibonacci number computation for benchmarking calling
15380: performance. The following table shows the time taken for the benchmarks
15381: scaled by the time taken by Gforth (in other words, it shows the speedup
15382: factor that Gforth achieved over the other systems).
15383:
15384: @example
1.112 anton 15385: relative Win32- NT eforth This-
15386: time Gforth Forth Forth eforth +opt PFE Forth TILE
15387: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15388: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15389: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15390: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15391: @end example
15392:
1.26 crook 15393: You may be quite surprised by the good performance of Gforth when
15394: compared with systems written in assembly language. One important reason
15395: for the disappointing performance of these other systems is probably
15396: that they are not written optimally for the 486 (e.g., they use the
15397: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15398: but costly method for relocating the Forth image: like @code{cforth}, it
15399: computes the actual addresses at run time, resulting in two address
15400: computations per @code{NEXT} (@pxref{Image File Background}).
15401:
1.1 anton 15402: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15403: explained with the self-imposed restriction of the latter systems to
15404: standard C, which makes efficient threading impossible (however, the
1.4 anton 15405: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15406: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15407: Moreover, current C compilers have a hard time optimizing other aspects
15408: of the ThisForth and the TILE source.
15409:
1.26 crook 15410: The performance of Gforth on 386 architecture processors varies widely
15411: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15412: allocate any of the virtual machine registers into real machine
15413: registers by itself and would not work correctly with explicit register
1.112 anton 15414: declarations, giving a significantly slower engine (on a 486DX2/66
15415: running the Sieve) than the one measured above.
1.1 anton 15416:
1.26 crook 15417: Note that there have been several releases of Win32Forth since the
15418: release presented here, so the results presented above may have little
1.40 anton 15419: predictive value for the performance of Win32Forth today (results for
15420: the current release on an i486DX2/66 are welcome).
1.1 anton 15421:
15422: @cindex @file{Benchres}
1.66 anton 15423: In
15424: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15425: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15426: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15427: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15428: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15429: than the version used here. You can find a newer version of these
15430: measurements at
1.47 crook 15431: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15432: find numbers for Gforth on various machines in @file{Benchres}.
15433:
1.26 crook 15434: @c ******************************************************************
1.113 anton 15435: @c @node Binding to System Library, Cross Compiler, Engine, Top
15436: @c @chapter Binding to System Library
1.13 pazsan 15437:
1.113 anton 15438: @c ****************************************************************
15439: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15440: @chapter Cross Compiler
1.47 crook 15441: @cindex @file{cross.fs}
15442: @cindex cross-compiler
15443: @cindex metacompiler
15444: @cindex target compiler
1.13 pazsan 15445:
1.46 pazsan 15446: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15447: mostly written in Forth, including crucial parts like the outer
15448: interpreter and compiler, it needs compiled Forth code to get
15449: started. The cross compiler allows to create new images for other
15450: architectures, even running under another Forth system.
1.13 pazsan 15451:
15452: @menu
1.67 anton 15453: * Using the Cross Compiler::
15454: * How the Cross Compiler Works::
1.13 pazsan 15455: @end menu
15456:
1.21 crook 15457: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15458: @section Using the Cross Compiler
1.46 pazsan 15459:
15460: The cross compiler uses a language that resembles Forth, but isn't. The
15461: main difference is that you can execute Forth code after definition,
15462: while you usually can't execute the code compiled by cross, because the
15463: code you are compiling is typically for a different computer than the
15464: one you are compiling on.
15465:
1.81 anton 15466: @c anton: This chapter is somewhat different from waht I would expect: I
15467: @c would expect an explanation of the cross language and how to create an
15468: @c application image with it. The section explains some aspects of
15469: @c creating a Gforth kernel.
15470:
1.46 pazsan 15471: The Makefile is already set up to allow you to create kernels for new
15472: architectures with a simple make command. The generic kernels using the
15473: GCC compiled virtual machine are created in the normal build process
15474: with @code{make}. To create a embedded Gforth executable for e.g. the
15475: 8086 processor (running on a DOS machine), type
15476:
15477: @example
15478: make kernl-8086.fi
15479: @end example
15480:
15481: This will use the machine description from the @file{arch/8086}
15482: directory to create a new kernel. A machine file may look like that:
15483:
15484: @example
15485: \ Parameter for target systems 06oct92py
15486:
15487: 4 Constant cell \ cell size in bytes
15488: 2 Constant cell<< \ cell shift to bytes
15489: 5 Constant cell>bit \ cell shift to bits
15490: 8 Constant bits/char \ bits per character
15491: 8 Constant bits/byte \ bits per byte [default: 8]
15492: 8 Constant float \ bytes per float
15493: 8 Constant /maxalign \ maximum alignment in bytes
15494: false Constant bigendian \ byte order
15495: ( true=big, false=little )
15496:
15497: include machpc.fs \ feature list
15498: @end example
15499:
15500: This part is obligatory for the cross compiler itself, the feature list
15501: is used by the kernel to conditionally compile some features in and out,
15502: depending on whether the target supports these features.
15503:
15504: There are some optional features, if you define your own primitives,
15505: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15506: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15507: @code{prims-include} includes primitives, and @code{>boot} prepares for
15508: booting.
15509:
15510: @example
15511: : asm-include ." Include assembler" cr
15512: s" arch/8086/asm.fs" included ;
15513:
15514: : prims-include ." Include primitives" cr
15515: s" arch/8086/prim.fs" included ;
15516:
15517: : >boot ." Prepare booting" cr
15518: s" ' boot >body into-forth 1+ !" evaluate ;
15519: @end example
15520:
15521: These words are used as sort of macro during the cross compilation in
1.81 anton 15522: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15523: be possible --- but more complicated --- to write a new kernel project
15524: file, too.
15525:
15526: @file{kernel/main.fs} expects the machine description file name on the
15527: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15528: @code{mach-file} leaves a counted string on the stack, or
15529: @code{machine-file} leaves an address, count pair of the filename on the
15530: stack.
15531:
15532: The feature list is typically controlled using @code{SetValue}, generic
15533: files that are used by several projects can use @code{DefaultValue}
15534: instead. Both functions work like @code{Value}, when the value isn't
15535: defined, but @code{SetValue} works like @code{to} if the value is
15536: defined, and @code{DefaultValue} doesn't set anything, if the value is
15537: defined.
15538:
15539: @example
15540: \ generic mach file for pc gforth 03sep97jaw
15541:
15542: true DefaultValue NIL \ relocating
15543:
15544: >ENVIRON
15545:
15546: true DefaultValue file \ controls the presence of the
15547: \ file access wordset
15548: true DefaultValue OS \ flag to indicate a operating system
15549:
15550: true DefaultValue prims \ true: primitives are c-code
15551:
15552: true DefaultValue floating \ floating point wordset is present
15553:
15554: true DefaultValue glocals \ gforth locals are present
15555: \ will be loaded
15556: true DefaultValue dcomps \ double number comparisons
15557:
15558: true DefaultValue hash \ hashing primitives are loaded/present
15559:
15560: true DefaultValue xconds \ used together with glocals,
15561: \ special conditionals supporting gforths'
15562: \ local variables
15563: true DefaultValue header \ save a header information
15564:
15565: true DefaultValue backtrace \ enables backtrace code
15566:
15567: false DefaultValue ec
15568: false DefaultValue crlf
15569:
15570: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15571:
15572: &16 KB DefaultValue stack-size
15573: &15 KB &512 + DefaultValue fstack-size
15574: &15 KB DefaultValue rstack-size
15575: &14 KB &512 + DefaultValue lstack-size
15576: @end example
1.13 pazsan 15577:
1.48 anton 15578: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15579: @section How the Cross Compiler Works
1.13 pazsan 15580:
15581: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15582: @appendix Bugs
1.1 anton 15583: @cindex bug reporting
15584:
1.21 crook 15585: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15586:
1.103 anton 15587: If you find a bug, please submit a bug report through
15588: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15589:
15590: @itemize @bullet
15591: @item
1.81 anton 15592: A program (or a sequence of keyboard commands) that reproduces the bug.
15593: @item
15594: A description of what you think constitutes the buggy behaviour.
15595: @item
1.21 crook 15596: The Gforth version used (it is announced at the start of an
15597: interactive Gforth session).
15598: @item
15599: The machine and operating system (on Unix
15600: systems @code{uname -a} will report this information).
15601: @item
1.81 anton 15602: The installation options (you can find the configure options at the
15603: start of @file{config.status}) and configuration (@code{configure}
15604: output or @file{config.cache}).
1.21 crook 15605: @item
15606: A complete list of changes (if any) you (or your installer) have made to the
15607: Gforth sources.
15608: @end itemize
1.1 anton 15609:
15610: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15611: to Report Bugs, gcc.info, GNU C Manual}.
15612:
15613:
1.21 crook 15614: @node Origin, Forth-related information, Bugs, Top
15615: @appendix Authors and Ancestors of Gforth
1.1 anton 15616:
15617: @section Authors and Contributors
15618: @cindex authors of Gforth
15619: @cindex contributors to Gforth
15620:
15621: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15622: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15623: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 15624: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
15625: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
15626: and Stuart Ramsden inspired us with their continuous feedback. Lennart
15627: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
15628: working on automatic support for calling C libraries. Helpful comments
15629: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
15630: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
15631: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
15632: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
15633: comments from many others; thank you all, sorry for not listing you
15634: here (but digging through my mailbox to extract your names is on my
15635: to-do list).
1.1 anton 15636:
15637: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15638: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15639: was developed across the Internet, and its authors did not meet
1.20 pazsan 15640: physically for the first 4 years of development.
1.1 anton 15641:
15642: @section Pedigree
1.26 crook 15643: @cindex pedigree of Gforth
1.1 anton 15644:
1.81 anton 15645: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15646: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15647:
1.20 pazsan 15648: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15649: 32 bit native code version of VolksForth for the Atari ST, written
15650: mostly by Dietrich Weineck.
15651:
1.81 anton 15652: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15653: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 15654: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 15655:
1.147 anton 15656: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15657: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 15658:
15659: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15660: 1979. Robert Selzer and Bill Ragsdale developed the original
15661: implementation of fig-Forth for the 6502 based on microForth.
15662:
15663: The principal architect of microForth was Dean Sanderson. microForth was
15664: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15665: the 1802, and subsequently implemented on the 8080, the 6800 and the
15666: Z80.
15667:
15668: All earlier Forth systems were custom-made, usually by Charles Moore,
15669: who discovered (as he puts it) Forth during the late 60s. The first full
15670: Forth existed in 1971.
15671:
1.81 anton 15672: A part of the information in this section comes from
15673: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15674: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 15675: Charles H. Moore, presented at the HOPL-II conference and preprinted
15676: in SIGPLAN Notices 28(3), 1993. You can find more historical and
15677: genealogical information about Forth there. For a more general (and
15678: graphical) Forth family tree look see
15679: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15680: Forth Family Tree and Timeline}.
1.1 anton 15681:
1.81 anton 15682: @c ------------------------------------------------------------------
1.113 anton 15683: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15684: @appendix Other Forth-related information
15685: @cindex Forth-related information
15686:
1.81 anton 15687: @c anton: I threw most of this stuff out, because it can be found through
15688: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15689:
15690: @cindex comp.lang.forth
15691: @cindex frequently asked questions
1.81 anton 15692: There is an active news group (comp.lang.forth) discussing Forth
15693: (including Gforth) and Forth-related issues. Its
15694: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15695: (frequently asked questions and their answers) contains a lot of
15696: information on Forth. You should read it before posting to
15697: comp.lang.forth.
1.21 crook 15698:
1.81 anton 15699: The ANS Forth standard is most usable in its
15700: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15701:
1.113 anton 15702: @c ---------------------------------------------------
15703: @node Licenses, Word Index, Forth-related information, Top
15704: @appendix Licenses
15705:
15706: @menu
15707: * GNU Free Documentation License:: License for copying this manual.
15708: * Copying:: GPL (for copying this software).
15709: @end menu
15710:
15711: @include fdl.texi
15712:
15713: @include gpl.texi
15714:
15715:
15716:
1.81 anton 15717: @c ------------------------------------------------------------------
1.113 anton 15718: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15719: @unnumbered Word Index
15720:
1.26 crook 15721: This index is a list of Forth words that have ``glossary'' entries
15722: within this manual. Each word is listed with its stack effect and
15723: wordset.
1.1 anton 15724:
15725: @printindex fn
15726:
1.81 anton 15727: @c anton: the name index seems superfluous given the word and concept indices.
15728:
15729: @c @node Name Index, Concept Index, Word Index, Top
15730: @c @unnumbered Name Index
1.41 anton 15731:
1.81 anton 15732: @c This index is a list of Forth words that have ``glossary'' entries
15733: @c within this manual.
1.41 anton 15734:
1.81 anton 15735: @c @printindex ky
1.41 anton 15736:
1.113 anton 15737: @c -------------------------------------------------------
1.81 anton 15738: @node Concept Index, , Word Index, Top
1.1 anton 15739: @unnumbered Concept and Word Index
15740:
1.26 crook 15741: Not all entries listed in this index are present verbatim in the
15742: text. This index also duplicates, in abbreviated form, all of the words
15743: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15744:
15745: @printindex cp
15746:
15747: @bye
1.81 anton 15748:
15749:
1.1 anton 15750:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>