Annotation of gforth/doc/gforth.ds, revision 1.188
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.113 anton 14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
1.29 crook 21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
1.29 crook 63:
1.169 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.87 anton 177: * Files Tutorial::
1.48 anton 178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
1.29 crook 188:
1.24 anton 189: An Introduction to ANS Forth
190:
1.67 anton 191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
1.24 anton 199:
1.12 anton 200: Forth Words
201:
202: * Notation::
1.65 anton 203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
1.12 anton 206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
1.65 anton 211: * Interpretation and Compilation Semantics::
1.47 crook 212: * Tokens for Words::
1.81 anton 213: * Compiling words::
1.65 anton 214: * The Text Interpreter::
1.111 anton 215: * The Input Stream::
1.65 anton 216: * Word Lists::
217: * Environmental Queries::
1.12 anton 218: * Files::
219: * Blocks::
220: * Other I/O::
1.121 anton 221: * OS command line arguments::
1.78 anton 222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
1.12 anton 225: * Programming Tools::
1.150 anton 226: * C Interface::
1.12 anton 227: * Assembler and Code Words::
228: * Threading Words::
1.65 anton 229: * Passing Commands to the OS::
230: * Keeping track of Time::
231: * Miscellaneous Words::
1.12 anton 232:
233: Arithmetic
234:
235: * Single precision::
1.67 anton 236: * Double precision:: Double-cell integer arithmetic
1.12 anton 237: * Bitwise operations::
1.67 anton 238: * Numeric comparison::
1.32 anton 239: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 240: * Floating Point::
241:
242: Stack Manipulation
243:
244: * Data stack::
245: * Floating point stack::
246: * Return stack::
247: * Locals stack::
248: * Stack pointer manipulation::
249:
250: Memory
251:
1.32 anton 252: * Memory model::
253: * Dictionary allocation::
254: * Heap Allocation::
255: * Memory Access::
256: * Address arithmetic::
257: * Memory Blocks::
1.12 anton 258:
259: Control Structures
260:
1.41 anton 261: * Selection:: IF ... ELSE ... ENDIF
262: * Simple Loops:: BEGIN ...
1.32 anton 263: * Counted Loops:: DO
1.67 anton 264: * Arbitrary control structures::
265: * Calls and returns::
1.12 anton 266: * Exception Handling::
267:
268: Defining Words
269:
1.67 anton 270: * CREATE::
1.44 crook 271: * Variables:: Variables and user variables
1.67 anton 272: * Constants::
1.44 crook 273: * Values:: Initialised variables
1.67 anton 274: * Colon Definitions::
1.44 crook 275: * Anonymous Definitions:: Definitions without names
1.71 anton 276: * Supplying names:: Passing definition names as strings
1.67 anton 277: * User-defined Defining Words::
1.170 pazsan 278: * Deferred Words:: Allow forward references
1.67 anton 279: * Aliases::
1.47 crook 280:
1.63 anton 281: User-defined Defining Words
282:
283: * CREATE..DOES> applications::
284: * CREATE..DOES> details::
285: * Advanced does> usage example::
1.155 anton 286: * Const-does>::
1.63 anton 287:
1.47 crook 288: Interpretation and Compilation Semantics
289:
1.67 anton 290: * Combined words::
1.12 anton 291:
1.71 anton 292: Tokens for Words
293:
294: * Execution token:: represents execution/interpretation semantics
295: * Compilation token:: represents compilation semantics
296: * Name token:: represents named words
297:
1.82 anton 298: Compiling words
299:
300: * Literals:: Compiling data values
301: * Macros:: Compiling words
302:
1.21 crook 303: The Text Interpreter
304:
1.67 anton 305: * Input Sources::
306: * Number Conversion::
307: * Interpret/Compile states::
308: * Interpreter Directives::
1.21 crook 309:
1.26 crook 310: Word Lists
311:
1.75 anton 312: * Vocabularies::
1.67 anton 313: * Why use word lists?::
1.75 anton 314: * Word list example::
1.26 crook 315:
316: Files
317:
1.48 anton 318: * Forth source files::
319: * General files::
1.167 anton 320: * Redirection::
1.48 anton 321: * Search Paths::
322:
323: Search Paths
324:
1.75 anton 325: * Source Search Paths::
1.26 crook 326: * General Search Paths::
327:
328: Other I/O
329:
1.32 anton 330: * Simple numeric output:: Predefined formats
331: * Formatted numeric output:: Formatted (pictured) output
332: * String Formats:: How Forth stores strings in memory
1.67 anton 333: * Displaying characters and strings:: Other stuff
1.178 anton 334: * Terminal output:: Cursor positioning etc.
1.181 anton 335: * Single-key input::
336: * Line input and conversion::
1.112 anton 337: * Pipes:: How to create your own pipes
1.149 pazsan 338: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 339:
340: Locals
341:
342: * Gforth locals::
343: * ANS Forth locals::
344:
345: Gforth locals
346:
347: * Where are locals visible by name?::
348: * How long do locals live?::
1.78 anton 349: * Locals programming style::
350: * Locals implementation::
1.26 crook 351:
1.12 anton 352: Structures
353:
354: * Why explicit structure support?::
355: * Structure Usage::
356: * Structure Naming Convention::
357: * Structure Implementation::
358: * Structure Glossary::
1.183 anton 359: * Forth200x Structures::
1.12 anton 360:
361: Object-oriented Forth
362:
1.48 anton 363: * Why object-oriented programming?::
364: * Object-Oriented Terminology::
365: * Objects::
366: * OOF::
367: * Mini-OOF::
1.23 crook 368: * Comparison with other object models::
1.12 anton 369:
1.24 anton 370: The @file{objects.fs} model
1.12 anton 371:
372: * Properties of the Objects model::
373: * Basic Objects Usage::
1.41 anton 374: * The Objects base class::
1.12 anton 375: * Creating objects::
376: * Object-Oriented Programming Style::
377: * Class Binding::
378: * Method conveniences::
379: * Classes and Scoping::
1.41 anton 380: * Dividing classes::
1.12 anton 381: * Object Interfaces::
382: * Objects Implementation::
383: * Objects Glossary::
384:
1.24 anton 385: The @file{oof.fs} model
1.12 anton 386:
1.67 anton 387: * Properties of the OOF model::
388: * Basic OOF Usage::
389: * The OOF base class::
390: * Class Declaration::
391: * Class Implementation::
1.12 anton 392:
1.24 anton 393: The @file{mini-oof.fs} model
1.23 crook 394:
1.48 anton 395: * Basic Mini-OOF Usage::
396: * Mini-OOF Example::
397: * Mini-OOF Implementation::
1.23 crook 398:
1.78 anton 399: Programming Tools
400:
1.150 anton 401: * Examining:: Data and Code.
402: * Forgetting words:: Usually before reloading.
1.78 anton 403: * Debugging:: Simple and quick.
404: * Assertions:: Making your programs self-checking.
405: * Singlestep Debugger:: Executing your program word by word.
406:
1.155 anton 407: C Interface
408:
409: * Calling C Functions::
410: * Declaring C Functions::
1.180 anton 411: * Calling C function pointers::
1.155 anton 412: * Callbacks::
1.178 anton 413: * C interface internals::
1.155 anton 414: * Low-Level C Interface Words::
415:
1.78 anton 416: Assembler and Code Words
417:
418: * Code and ;code::
419: * Common Assembler:: Assembler Syntax
420: * Common Disassembler::
421: * 386 Assembler:: Deviations and special cases
422: * Alpha Assembler:: Deviations and special cases
423: * MIPS assembler:: Deviations and special cases
1.167 anton 424: * PowerPC assembler:: Deviations and special cases
1.78 anton 425: * Other assemblers:: How to write them
426:
1.12 anton 427: Tools
428:
429: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 430: * Stack depth changes:: Where does this stack item come from?
1.12 anton 431:
432: ANS conformance
433:
434: * The Core Words::
435: * The optional Block word set::
436: * The optional Double Number word set::
437: * The optional Exception word set::
438: * The optional Facility word set::
439: * The optional File-Access word set::
440: * The optional Floating-Point word set::
441: * The optional Locals word set::
442: * The optional Memory-Allocation word set::
443: * The optional Programming-Tools word set::
444: * The optional Search-Order word set::
445:
446: The Core Words
447:
448: * core-idef:: Implementation Defined Options
449: * core-ambcond:: Ambiguous Conditions
450: * core-other:: Other System Documentation
451:
452: The optional Block word set
453:
454: * block-idef:: Implementation Defined Options
455: * block-ambcond:: Ambiguous Conditions
456: * block-other:: Other System Documentation
457:
458: The optional Double Number word set
459:
460: * double-ambcond:: Ambiguous Conditions
461:
462: The optional Exception word set
463:
464: * exception-idef:: Implementation Defined Options
465:
466: The optional Facility word set
467:
468: * facility-idef:: Implementation Defined Options
469: * facility-ambcond:: Ambiguous Conditions
470:
471: The optional File-Access word set
472:
473: * file-idef:: Implementation Defined Options
474: * file-ambcond:: Ambiguous Conditions
475:
476: The optional Floating-Point word set
477:
478: * floating-idef:: Implementation Defined Options
479: * floating-ambcond:: Ambiguous Conditions
480:
481: The optional Locals word set
482:
483: * locals-idef:: Implementation Defined Options
484: * locals-ambcond:: Ambiguous Conditions
485:
486: The optional Memory-Allocation word set
487:
488: * memory-idef:: Implementation Defined Options
489:
490: The optional Programming-Tools word set
491:
492: * programming-idef:: Implementation Defined Options
493: * programming-ambcond:: Ambiguous Conditions
494:
495: The optional Search-Order word set
496:
497: * search-idef:: Implementation Defined Options
498: * search-ambcond:: Ambiguous Conditions
499:
1.109 anton 500: Emacs and Gforth
501:
502: * Installing gforth.el:: Making Emacs aware of Forth.
503: * Emacs Tags:: Viewing the source of a word in Emacs.
504: * Hilighting:: Making Forth code look prettier.
505: * Auto-Indentation:: Customizing auto-indentation.
506: * Blocks Files:: Reading and writing blocks files.
507:
1.12 anton 508: Image Files
509:
1.24 anton 510: * Image Licensing Issues:: Distribution terms for images.
511: * Image File Background:: Why have image files?
1.67 anton 512: * Non-Relocatable Image Files:: don't always work.
1.24 anton 513: * Data-Relocatable Image Files:: are better.
1.67 anton 514: * Fully Relocatable Image Files:: better yet.
1.24 anton 515: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 516: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 517: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 518:
519: Fully Relocatable Image Files
520:
1.27 crook 521: * gforthmi:: The normal way
1.12 anton 522: * cross.fs:: The hard way
523:
524: Engine
525:
526: * Portability::
527: * Threading::
528: * Primitives::
529: * Performance::
530:
531: Threading
532:
533: * Scheduling::
534: * Direct or Indirect Threaded?::
1.109 anton 535: * Dynamic Superinstructions::
1.12 anton 536: * DOES>::
537:
538: Primitives
539:
540: * Automatic Generation::
541: * TOS Optimization::
542: * Produced code::
1.13 pazsan 543:
544: Cross Compiler
545:
1.67 anton 546: * Using the Cross Compiler::
547: * How the Cross Compiler Works::
1.13 pazsan 548:
1.113 anton 549: Licenses
550:
551: * GNU Free Documentation License:: License for copying this manual.
552: * Copying:: GPL (for copying this software).
553:
1.24 anton 554: @end detailmenu
1.1 anton 555: @end menu
556:
1.113 anton 557: @c ----------------------------------------------------------
1.1 anton 558: @iftex
559: @unnumbered Preface
560: @cindex Preface
1.21 crook 561: This manual documents Gforth. Some introductory material is provided for
562: readers who are unfamiliar with Forth or who are migrating to Gforth
563: from other Forth compilers. However, this manual is primarily a
564: reference manual.
1.1 anton 565: @end iftex
566:
1.28 crook 567: @comment TODO much more blurb here.
1.26 crook 568:
569: @c ******************************************************************
1.113 anton 570: @node Goals, Gforth Environment, Top, Top
1.26 crook 571: @comment node-name, next, previous, up
572: @chapter Goals of Gforth
573: @cindex goals of the Gforth project
574: The goal of the Gforth Project is to develop a standard model for
575: ANS Forth. This can be split into several subgoals:
576:
577: @itemize @bullet
578: @item
579: Gforth should conform to the ANS Forth Standard.
580: @item
581: It should be a model, i.e. it should define all the
582: implementation-dependent things.
583: @item
584: It should become standard, i.e. widely accepted and used. This goal
585: is the most difficult one.
586: @end itemize
587:
588: To achieve these goals Gforth should be
589: @itemize @bullet
590: @item
591: Similar to previous models (fig-Forth, F83)
592: @item
593: Powerful. It should provide for all the things that are considered
594: necessary today and even some that are not yet considered necessary.
595: @item
596: Efficient. It should not get the reputation of being exceptionally
597: slow.
598: @item
599: Free.
600: @item
601: Available on many machines/easy to port.
602: @end itemize
603:
604: Have we achieved these goals? Gforth conforms to the ANS Forth
605: standard. It may be considered a model, but we have not yet documented
606: which parts of the model are stable and which parts we are likely to
607: change. It certainly has not yet become a de facto standard, but it
608: appears to be quite popular. It has some similarities to and some
609: differences from previous models. It has some powerful features, but not
610: yet everything that we envisioned. We certainly have achieved our
1.65 anton 611: execution speed goals (@pxref{Performance})@footnote{However, in 1998
612: the bar was raised when the major commercial Forth vendors switched to
613: native code compilers.}. It is free and available on many machines.
1.29 crook 614:
1.26 crook 615: @c ******************************************************************
1.48 anton 616: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 617: @chapter Gforth Environment
618: @cindex Gforth environment
1.21 crook 619:
1.45 crook 620: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 621: material in this chapter.
1.21 crook 622:
623: @menu
1.29 crook 624: * Invoking Gforth:: Getting in
625: * Leaving Gforth:: Getting out
626: * Command-line editing::
1.48 anton 627: * Environment variables:: that affect how Gforth starts up
1.29 crook 628: * Gforth Files:: What gets installed and where
1.112 anton 629: * Gforth in pipes::
1.48 anton 630: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 631: @end menu
632:
1.49 anton 633: For related information about the creation of images see @ref{Image Files}.
1.29 crook 634:
1.21 crook 635: @comment ----------------------------------------------
1.48 anton 636: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 637: @section Invoking Gforth
638: @cindex invoking Gforth
639: @cindex running Gforth
640: @cindex command-line options
641: @cindex options on the command line
642: @cindex flags on the command line
1.21 crook 643:
1.30 anton 644: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 645: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 646: will usually just say @code{gforth} -- this automatically loads the
647: default image file @file{gforth.fi}. In many other cases the default
648: Gforth image will be invoked like this:
1.21 crook 649: @example
1.30 anton 650: gforth [file | -e forth-code] ...
1.21 crook 651: @end example
1.29 crook 652: @noindent
653: This interprets the contents of the files and the Forth code in the order they
654: are given.
1.21 crook 655:
1.109 anton 656: In addition to the @command{gforth} engine, there is also an engine
657: called @command{gforth-fast}, which is faster, but gives less
658: informative error messages (@pxref{Error messages}) and may catch some
1.166 anton 659: errors (in particular, stack underflows and integer division errors)
660: later or not at all. You should use it for debugged,
1.109 anton 661: performance-critical programs.
662:
663: Moreover, there is an engine called @command{gforth-itc}, which is
664: useful in some backwards-compatibility situations (@pxref{Direct or
665: Indirect Threaded?}).
1.30 anton 666:
1.29 crook 667: In general, the command line looks like this:
1.21 crook 668:
669: @example
1.30 anton 670: gforth[-fast] [engine options] [image options]
1.21 crook 671: @end example
672:
1.30 anton 673: The engine options must come before the rest of the command
1.29 crook 674: line. They are:
1.26 crook 675:
1.29 crook 676: @table @code
677: @cindex -i, command-line option
678: @cindex --image-file, command-line option
679: @item --image-file @i{file}
680: @itemx -i @i{file}
681: Loads the Forth image @i{file} instead of the default
682: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 683:
1.39 anton 684: @cindex --appl-image, command-line option
685: @item --appl-image @i{file}
686: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 687: to the image (instead of processing them as engine options). This is
688: useful for building executable application images on Unix, built with
1.39 anton 689: @code{gforthmi --application ...}.
690:
1.29 crook 691: @cindex --path, command-line option
692: @cindex -p, command-line option
693: @item --path @i{path}
694: @itemx -p @i{path}
695: Uses @i{path} for searching the image file and Forth source code files
696: instead of the default in the environment variable @code{GFORTHPATH} or
697: the path specified at installation time (e.g.,
698: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
699: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 700:
1.29 crook 701: @cindex --dictionary-size, command-line option
702: @cindex -m, command-line option
703: @cindex @i{size} parameters for command-line options
704: @cindex size of the dictionary and the stacks
705: @item --dictionary-size @i{size}
706: @itemx -m @i{size}
707: Allocate @i{size} space for the Forth dictionary space instead of
708: using the default specified in the image (typically 256K). The
709: @i{size} specification for this and subsequent options consists of
710: an integer and a unit (e.g.,
711: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
712: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
713: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
714: @code{e} is used.
1.21 crook 715:
1.29 crook 716: @cindex --data-stack-size, command-line option
717: @cindex -d, command-line option
718: @item --data-stack-size @i{size}
719: @itemx -d @i{size}
720: Allocate @i{size} space for the data stack instead of using the
721: default specified in the image (typically 16K).
1.21 crook 722:
1.29 crook 723: @cindex --return-stack-size, command-line option
724: @cindex -r, command-line option
725: @item --return-stack-size @i{size}
726: @itemx -r @i{size}
727: Allocate @i{size} space for the return stack instead of using the
728: default specified in the image (typically 15K).
1.21 crook 729:
1.29 crook 730: @cindex --fp-stack-size, command-line option
731: @cindex -f, command-line option
732: @item --fp-stack-size @i{size}
733: @itemx -f @i{size}
734: Allocate @i{size} space for the floating point stack instead of
735: using the default specified in the image (typically 15.5K). In this case
736: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 737:
1.48 anton 738: @cindex --locals-stack-size, command-line option
739: @cindex -l, command-line option
740: @item --locals-stack-size @i{size}
741: @itemx -l @i{size}
742: Allocate @i{size} space for the locals stack instead of using the
743: default specified in the image (typically 14.5K).
744:
1.176 anton 745: @cindex --vm-commit, command-line option
746: @cindex overcommit memory for dictionary and stacks
747: @cindex memory overcommit for dictionary and stacks
748: @item --vm-commit
749: Normally, Gforth tries to start up even if there is not enough virtual
750: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
751: on OSs that support it); so you can ask for a really big dictionary
752: and/or stacks, and as long as you don't use more virtual memory than
753: is available, everything will be fine (but if you use more, processes
754: get killed). With this option you just use the default allocation
755: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
756: means that you cannot and should not ask for as big dictionary and
757: stacks, but once Gforth successfully starts up, out-of-memory won't
758: kill it.
759:
1.48 anton 760: @cindex -h, command-line option
761: @cindex --help, command-line option
762: @item --help
763: @itemx -h
764: Print a message about the command-line options
765:
766: @cindex -v, command-line option
767: @cindex --version, command-line option
768: @item --version
769: @itemx -v
770: Print version and exit
771:
772: @cindex --debug, command-line option
773: @item --debug
774: Print some information useful for debugging on startup.
775:
776: @cindex --offset-image, command-line option
777: @item --offset-image
778: Start the dictionary at a slightly different position than would be used
779: otherwise (useful for creating data-relocatable images,
780: @pxref{Data-Relocatable Image Files}).
781:
782: @cindex --no-offset-im, command-line option
783: @item --no-offset-im
784: Start the dictionary at the normal position.
785:
786: @cindex --clear-dictionary, command-line option
787: @item --clear-dictionary
788: Initialize all bytes in the dictionary to 0 before loading the image
789: (@pxref{Data-Relocatable Image Files}).
790:
791: @cindex --die-on-signal, command-line-option
792: @item --die-on-signal
793: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
794: or the segmentation violation SIGSEGV) by translating it into a Forth
795: @code{THROW}. With this option, Gforth exits if it receives such a
796: signal. This option is useful when the engine and/or the image might be
797: severely broken (such that it causes another signal before recovering
798: from the first); this option avoids endless loops in such cases.
1.109 anton 799:
1.119 anton 800: @cindex --no-dynamic, command-line option
801: @cindex --dynamic, command-line option
1.109 anton 802: @item --no-dynamic
803: @item --dynamic
804: Disable or enable dynamic superinstructions with replication
805: (@pxref{Dynamic Superinstructions}).
806:
1.119 anton 807: @cindex --no-super, command-line option
1.109 anton 808: @item --no-super
1.110 anton 809: Disable dynamic superinstructions, use just dynamic replication; this is
810: useful if you want to patch threaded code (@pxref{Dynamic
811: Superinstructions}).
1.119 anton 812:
813: @cindex --ss-number, command-line option
814: @item --ss-number=@var{N}
815: Use only the first @var{N} static superinstructions compiled into the
816: engine (default: use them all; note that only @code{gforth-fast} has
817: any). This option is useful for measuring the performance impact of
818: static superinstructions.
819:
820: @cindex --ss-min-..., command-line options
821: @item --ss-min-codesize
822: @item --ss-min-ls
823: @item --ss-min-lsu
824: @item --ss-min-nexts
825: Use specified metric for determining the cost of a primitive or static
826: superinstruction for static superinstruction selection. @code{Codesize}
827: is the native code size of the primive or static superinstruction,
828: @code{ls} is the number of loads and stores, @code{lsu} is the number of
829: loads, stores, and updates, and @code{nexts} is the number of dispatches
830: (not taking dynamic superinstructions into account), i.e. every
831: primitive or static superinstruction has cost 1. Default:
832: @code{codesize} if you use dynamic code generation, otherwise
833: @code{nexts}.
834:
835: @cindex --ss-greedy, command-line option
836: @item --ss-greedy
837: This option is useful for measuring the performance impact of static
838: superinstructions. By default, an optimal shortest-path algorithm is
839: used for selecting static superinstructions. With @option{--ss-greedy}
840: this algorithm is modified to assume that anything after the static
841: superinstruction currently under consideration is not combined into
842: static superinstructions. With @option{--ss-min-nexts} this produces
843: the same result as a greedy algorithm that always selects the longest
844: superinstruction available at the moment. E.g., if there are
845: superinstructions AB and BCD, then for the sequence A B C D the optimal
846: algorithm will select A BCD and the greedy algorithm will select AB C D.
847:
848: @cindex --print-metrics, command-line option
849: @item --print-metrics
850: Prints some metrics used during static superinstruction selection:
851: @code{code size} is the actual size of the dynamically generated code.
852: @code{Metric codesize} is the sum of the codesize metrics as seen by
853: static superinstruction selection; there is a difference from @code{code
854: size}, because not all primitives and static superinstructions are
855: compiled into dynamically generated code, and because of markers. The
856: other metrics correspond to the @option{ss-min-...} options. This
857: option is useful for evaluating the effects of the @option{--ss-...}
858: options.
1.109 anton 859:
1.48 anton 860: @end table
861:
862: @cindex loading files at startup
863: @cindex executing code on startup
864: @cindex batch processing with Gforth
865: As explained above, the image-specific command-line arguments for the
866: default image @file{gforth.fi} consist of a sequence of filenames and
867: @code{-e @var{forth-code}} options that are interpreted in the sequence
868: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 869: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
870: option takes only one argument; if you want to evaluate more Forth
871: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 872: after processing the command line (instead of entering interactive mode)
1.121 anton 873: append @code{-e bye} to the command line. You can also process the
874: command-line arguments with a Forth program (@pxref{OS command line
875: arguments}).
1.48 anton 876:
877: @cindex versions, invoking other versions of Gforth
878: If you have several versions of Gforth installed, @code{gforth} will
879: invoke the version that was installed last. @code{gforth-@i{version}}
880: invokes a specific version. If your environment contains the variable
881: @code{GFORTHPATH}, you may want to override it by using the
882: @code{--path} option.
883:
884: Not yet implemented:
885: On startup the system first executes the system initialization file
886: (unless the option @code{--no-init-file} is given; note that the system
887: resulting from using this option may not be ANS Forth conformant). Then
888: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 889: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 890: then in @file{~}, then in the normal path (see above).
891:
892:
893:
894: @comment ----------------------------------------------
895: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
896: @section Leaving Gforth
897: @cindex Gforth - leaving
898: @cindex leaving Gforth
899:
900: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
901: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
902: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 903: data are discarded. For ways of saving the state of the system before
904: leaving Gforth see @ref{Image Files}.
1.48 anton 905:
906: doc-bye
907:
908:
909: @comment ----------------------------------------------
1.65 anton 910: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 911: @section Command-line editing
912: @cindex command-line editing
913:
914: Gforth maintains a history file that records every line that you type to
915: the text interpreter. This file is preserved between sessions, and is
916: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
917: repeatedly you can recall successively older commands from this (or
918: previous) session(s). The full list of command-line editing facilities is:
919:
920: @itemize @bullet
921: @item
922: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
923: commands from the history buffer.
924: @item
925: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
926: from the history buffer.
927: @item
928: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
929: @item
930: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
931: @item
932: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
933: closing up the line.
934: @item
935: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
936: @item
937: @kbd{Ctrl-a} to move the cursor to the start of the line.
938: @item
939: @kbd{Ctrl-e} to move the cursor to the end of the line.
940: @item
941: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
942: line.
943: @item
944: @key{TAB} to step through all possible full-word completions of the word
945: currently being typed.
946: @item
1.65 anton 947: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
948: using @code{bye}).
949: @item
950: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
951: character under the cursor.
1.48 anton 952: @end itemize
953:
954: When editing, displayable characters are inserted to the left of the
955: cursor position; the line is always in ``insert'' (as opposed to
956: ``overstrike'') mode.
957:
958: @cindex history file
959: @cindex @file{.gforth-history}
960: On Unix systems, the history file is @file{~/.gforth-history} by
961: default@footnote{i.e. it is stored in the user's home directory.}. You
962: can find out the name and location of your history file using:
963:
964: @example
965: history-file type \ Unix-class systems
966:
967: history-file type \ Other systems
968: history-dir type
969: @end example
970:
971: If you enter long definitions by hand, you can use a text editor to
972: paste them out of the history file into a Forth source file for reuse at
973: a later time.
974:
975: Gforth never trims the size of the history file, so you should do this
976: periodically, if necessary.
977:
978: @comment this is all defined in history.fs
979: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
980: @comment chosen?
981:
982:
983: @comment ----------------------------------------------
1.65 anton 984: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 985: @section Environment variables
986: @cindex environment variables
987:
988: Gforth uses these environment variables:
989:
990: @itemize @bullet
991: @item
992: @cindex @code{GFORTHHIST} -- environment variable
993: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
994: open/create the history file, @file{.gforth-history}. Default:
995: @code{$HOME}.
996:
997: @item
998: @cindex @code{GFORTHPATH} -- environment variable
999: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1000: for Forth source-code files.
1001:
1002: @item
1.147 anton 1003: @cindex @code{LANG} -- environment variable
1004: @code{LANG} -- see @code{LC_CTYPE}
1005:
1006: @item
1007: @cindex @code{LC_ALL} -- environment variable
1008: @code{LC_ALL} -- see @code{LC_CTYPE}
1009:
1010: @item
1011: @cindex @code{LC_CTYPE} -- environment variable
1012: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1013: startup, Gforth uses the UTF-8 encoding for strings internally and
1014: expects its input and produces its output in UTF-8 encoding, otherwise
1015: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1016: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1017: that is unset, in @code{LANG}.
1018:
1019: @item
1.129 anton 1020: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1021:
1022: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1023: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1024: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1025: and the command are directly concatenated, so if a space between them is
1026: necessary, append it to the prefix.
1027:
1028: @item
1.48 anton 1029: @cindex @code{GFORTH} -- environment variable
1.49 anton 1030: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1031:
1032: @item
1033: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1034: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1035:
1036: @item
1037: @cindex @code{TMP}, @code{TEMP} - environment variable
1038: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1039: location for the history file.
1040: @end itemize
1041:
1042: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1043: @comment mentioning these.
1044:
1045: All the Gforth environment variables default to sensible values if they
1046: are not set.
1047:
1048:
1049: @comment ----------------------------------------------
1.112 anton 1050: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1051: @section Gforth files
1052: @cindex Gforth files
1053:
1054: When you install Gforth on a Unix system, it installs files in these
1055: locations by default:
1056:
1057: @itemize @bullet
1058: @item
1059: @file{/usr/local/bin/gforth}
1060: @item
1061: @file{/usr/local/bin/gforthmi}
1062: @item
1063: @file{/usr/local/man/man1/gforth.1} - man page.
1064: @item
1065: @file{/usr/local/info} - the Info version of this manual.
1066: @item
1067: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1068: @item
1069: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1070: @item
1071: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1072: @item
1073: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1074: @end itemize
1075:
1076: You can select different places for installation by using
1077: @code{configure} options (listed with @code{configure --help}).
1078:
1079: @comment ----------------------------------------------
1.112 anton 1080: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1081: @section Gforth in pipes
1082: @cindex pipes, Gforth as part of
1083:
1084: Gforth can be used in pipes created elsewhere (described here). It can
1085: also create pipes on its own (@pxref{Pipes}).
1086:
1087: @cindex input from pipes
1088: If you pipe into Gforth, your program should read with @code{read-file}
1089: or @code{read-line} from @code{stdin} (@pxref{General files}).
1090: @code{Key} does not recognize the end of input. Words like
1091: @code{accept} echo the input and are therefore usually not useful for
1092: reading from a pipe. You have to invoke the Forth program with an OS
1093: command-line option, as you have no chance to use the Forth command line
1094: (the text interpreter would try to interpret the pipe input).
1095:
1096: @cindex output in pipes
1097: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1098:
1099: @cindex silent exiting from Gforth
1100: When you write to a pipe that has been closed at the other end, Gforth
1101: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1102: into the exception @code{broken-pipe-error}. If your application does
1103: not catch that exception, the system catches it and exits, usually
1104: silently (unless you were working on the Forth command line; then it
1105: prints an error message and exits). This is usually the desired
1106: behaviour.
1107:
1108: If you do not like this behaviour, you have to catch the exception
1109: yourself, and react to it.
1110:
1111: Here's an example of an invocation of Gforth that is usable in a pipe:
1112:
1113: @example
1114: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1115: type repeat ; foo bye"
1116: @end example
1117:
1118: This example just copies the input verbatim to the output. A very
1119: simple pipe containing this example looks like this:
1120:
1121: @example
1122: cat startup.fs |
1123: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1124: type repeat ; foo bye"|
1125: head
1126: @end example
1127:
1128: @cindex stderr and pipes
1129: Pipes involving Gforth's @code{stderr} output do not work.
1130:
1131: @comment ----------------------------------------------
1132: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1133: @section Startup speed
1134: @cindex Startup speed
1135: @cindex speed, startup
1136:
1137: If Gforth is used for CGI scripts or in shell scripts, its startup
1138: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1139: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1140: system time.
1141:
1142: If startup speed is a problem, you may consider the following ways to
1143: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1144: (for example, by using Fast-CGI).
1.48 anton 1145:
1.112 anton 1146: An easy step that influences Gforth startup speed is the use of the
1147: @option{--no-dynamic} option; this decreases image loading speed, but
1148: increases compile-time and run-time.
1149:
1150: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1151: building it with @code{XLDFLAGS=-static}. This requires more memory for
1152: the code and will therefore slow down the first invocation, but
1153: subsequent invocations avoid the dynamic linking overhead. Another
1154: disadvantage is that Gforth won't profit from library upgrades. As a
1155: result, @code{gforth-static -e bye} takes about 17.1ms user and
1156: 8.2ms system time.
1157:
1158: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1159: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1160: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1161: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1162: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1163: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1164: address for the dictionary, for whatever reason; so you better provide a
1165: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1166: bye} takes about 15.3ms user and 7.5ms system time.
1167:
1168: The final step is to disable dictionary hashing in Gforth. Gforth
1169: builds the hash table on startup, which takes much of the startup
1170: overhead. You can do this by commenting out the @code{include hash.fs}
1171: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1172: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1173: The disadvantages are that functionality like @code{table} and
1174: @code{ekey} is missing and that text interpretation (e.g., compiling)
1175: now takes much longer. So, you should only use this method if there is
1176: no significant text interpretation to perform (the script should be
1.62 crook 1177: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1178: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1179:
1180: @c ******************************************************************
1181: @node Tutorial, Introduction, Gforth Environment, Top
1182: @chapter Forth Tutorial
1183: @cindex Tutorial
1184: @cindex Forth Tutorial
1185:
1.67 anton 1186: @c Topics from nac's Introduction that could be mentioned:
1187: @c press <ret> after each line
1188: @c Prompt
1189: @c numbers vs. words in dictionary on text interpretation
1190: @c what happens on redefinition
1191: @c parsing words (in particular, defining words)
1192:
1.83 anton 1193: The difference of this chapter from the Introduction
1194: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1195: be used while sitting in front of a computer, and covers much more
1196: material, but does not explain how the Forth system works.
1197:
1.62 crook 1198: This tutorial can be used with any ANS-compliant Forth; any
1199: Gforth-specific features are marked as such and you can skip them if you
1200: work with another Forth. This tutorial does not explain all features of
1201: Forth, just enough to get you started and give you some ideas about the
1202: facilities available in Forth. Read the rest of the manual and the
1203: standard when you are through this.
1.48 anton 1204:
1205: The intended way to use this tutorial is that you work through it while
1206: sitting in front of the console, take a look at the examples and predict
1207: what they will do, then try them out; if the outcome is not as expected,
1208: find out why (e.g., by trying out variations of the example), so you
1209: understand what's going on. There are also some assignments that you
1210: should solve.
1211:
1212: This tutorial assumes that you have programmed before and know what,
1213: e.g., a loop is.
1214:
1215: @c !! explain compat library
1216:
1217: @menu
1218: * Starting Gforth Tutorial::
1219: * Syntax Tutorial::
1220: * Crash Course Tutorial::
1221: * Stack Tutorial::
1222: * Arithmetics Tutorial::
1223: * Stack Manipulation Tutorial::
1224: * Using files for Forth code Tutorial::
1225: * Comments Tutorial::
1226: * Colon Definitions Tutorial::
1227: * Decompilation Tutorial::
1228: * Stack-Effect Comments Tutorial::
1229: * Types Tutorial::
1230: * Factoring Tutorial::
1231: * Designing the stack effect Tutorial::
1232: * Local Variables Tutorial::
1233: * Conditional execution Tutorial::
1234: * Flags and Comparisons Tutorial::
1235: * General Loops Tutorial::
1236: * Counted loops Tutorial::
1237: * Recursion Tutorial::
1238: * Leaving definitions or loops Tutorial::
1239: * Return Stack Tutorial::
1240: * Memory Tutorial::
1241: * Characters and Strings Tutorial::
1242: * Alignment Tutorial::
1.87 anton 1243: * Files Tutorial::
1.48 anton 1244: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1245: * Execution Tokens Tutorial::
1246: * Exceptions Tutorial::
1247: * Defining Words Tutorial::
1248: * Arrays and Records Tutorial::
1249: * POSTPONE Tutorial::
1250: * Literal Tutorial::
1251: * Advanced macros Tutorial::
1252: * Compilation Tokens Tutorial::
1253: * Wordlists and Search Order Tutorial::
1254: @end menu
1255:
1256: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1257: @section Starting Gforth
1.66 anton 1258: @cindex starting Gforth tutorial
1.48 anton 1259: You can start Gforth by typing its name:
1260:
1261: @example
1262: gforth
1263: @end example
1264:
1265: That puts you into interactive mode; you can leave Gforth by typing
1266: @code{bye}. While in Gforth, you can edit the command line and access
1267: the command line history with cursor keys, similar to bash.
1268:
1269:
1270: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1271: @section Syntax
1.66 anton 1272: @cindex syntax tutorial
1.48 anton 1273:
1.171 anton 1274: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1275: space). Words are separated by white space. E.g., each of the
1276: following lines contains exactly one word:
1277:
1278: @example
1279: word
1280: !@@#$%^&*()
1281: 1234567890
1282: 5!a
1283: @end example
1284:
1285: A frequent beginner's error is to leave away necessary white space,
1286: resulting in an error like @samp{Undefined word}; so if you see such an
1287: error, check if you have put spaces wherever necessary.
1288:
1289: @example
1290: ." hello, world" \ correct
1291: ."hello, world" \ gives an "Undefined word" error
1292: @end example
1293:
1.65 anton 1294: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1295: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1296: your system is case-sensitive, you may have to type all the examples
1297: given here in upper case.
1298:
1299:
1300: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1301: @section Crash Course
1302:
1303: Type
1304:
1305: @example
1306: 0 0 !
1307: here execute
1308: ' catch >body 20 erase abort
1309: ' (quit) >body 20 erase
1310: @end example
1311:
1312: The last two examples are guaranteed to destroy parts of Gforth (and
1313: most other systems), so you better leave Gforth afterwards (if it has
1314: not finished by itself). On some systems you may have to kill gforth
1315: from outside (e.g., in Unix with @code{kill}).
1316:
1317: Now that you know how to produce crashes (and that there's not much to
1318: them), let's learn how to produce meaningful programs.
1319:
1320:
1321: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1322: @section Stack
1.66 anton 1323: @cindex stack tutorial
1.48 anton 1324:
1325: The most obvious feature of Forth is the stack. When you type in a
1326: number, it is pushed on the stack. You can display the content of the
1327: stack with @code{.s}.
1328:
1329: @example
1330: 1 2 .s
1331: 3 .s
1332: @end example
1333:
1334: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1335: appear in @code{.s} output as they appeared in the input.
1336:
1337: You can print the top of stack element with @code{.}.
1338:
1339: @example
1340: 1 2 3 . . .
1341: @end example
1342:
1343: In general, words consume their stack arguments (@code{.s} is an
1344: exception).
1345:
1.141 anton 1346: @quotation Assignment
1.48 anton 1347: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1348: @end quotation
1.48 anton 1349:
1350:
1351: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1352: @section Arithmetics
1.66 anton 1353: @cindex arithmetics tutorial
1.48 anton 1354:
1355: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1356: operate on the top two stack items:
1357:
1358: @example
1.67 anton 1359: 2 2 .s
1360: + .s
1361: .
1.48 anton 1362: 2 1 - .
1363: 7 3 mod .
1364: @end example
1365:
1366: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1367: as in the corresponding infix expression (this is generally the case in
1368: Forth).
1369:
1370: Parentheses are superfluous (and not available), because the order of
1371: the words unambiguously determines the order of evaluation and the
1372: operands:
1373:
1374: @example
1375: 3 4 + 5 * .
1376: 3 4 5 * + .
1377: @end example
1378:
1.141 anton 1379: @quotation Assignment
1.48 anton 1380: What are the infix expressions corresponding to the Forth code above?
1381: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1382: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1383: @end quotation
1.48 anton 1384:
1385: To change the sign, use @code{negate}:
1386:
1387: @example
1388: 2 negate .
1389: @end example
1390:
1.141 anton 1391: @quotation Assignment
1.48 anton 1392: Convert -(-3)*4-5 to Forth.
1.141 anton 1393: @end quotation
1.48 anton 1394:
1395: @code{/mod} performs both @code{/} and @code{mod}.
1396:
1397: @example
1398: 7 3 /mod . .
1399: @end example
1400:
1.66 anton 1401: Reference: @ref{Arithmetic}.
1402:
1403:
1.48 anton 1404: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1405: @section Stack Manipulation
1.66 anton 1406: @cindex stack manipulation tutorial
1.48 anton 1407:
1408: Stack manipulation words rearrange the data on the stack.
1409:
1410: @example
1411: 1 .s drop .s
1412: 1 .s dup .s drop drop .s
1413: 1 2 .s over .s drop drop drop
1414: 1 2 .s swap .s drop drop
1415: 1 2 3 .s rot .s drop drop drop
1416: @end example
1417:
1418: These are the most important stack manipulation words. There are also
1419: variants that manipulate twice as many stack items:
1420:
1421: @example
1422: 1 2 3 4 .s 2swap .s 2drop 2drop
1423: @end example
1424:
1425: Two more stack manipulation words are:
1426:
1427: @example
1428: 1 2 .s nip .s drop
1429: 1 2 .s tuck .s 2drop drop
1430: @end example
1431:
1.141 anton 1432: @quotation Assignment
1.48 anton 1433: Replace @code{nip} and @code{tuck} with combinations of other stack
1434: manipulation words.
1435:
1436: @example
1437: Given: How do you get:
1438: 1 2 3 3 2 1
1439: 1 2 3 1 2 3 2
1440: 1 2 3 1 2 3 3
1441: 1 2 3 1 3 3
1442: 1 2 3 2 1 3
1443: 1 2 3 4 4 3 2 1
1444: 1 2 3 1 2 3 1 2 3
1445: 1 2 3 4 1 2 3 4 1 2
1446: 1 2 3
1447: 1 2 3 1 2 3 4
1448: 1 2 3 1 3
1449: @end example
1.141 anton 1450: @end quotation
1.48 anton 1451:
1452: @example
1453: 5 dup * .
1454: @end example
1455:
1.141 anton 1456: @quotation Assignment
1.48 anton 1457: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1458: Write a piece of Forth code that expects two numbers on the stack
1459: (@var{a} and @var{b}, with @var{b} on top) and computes
1460: @code{(a-b)(a+1)}.
1.141 anton 1461: @end quotation
1.48 anton 1462:
1.66 anton 1463: Reference: @ref{Stack Manipulation}.
1464:
1465:
1.48 anton 1466: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1467: @section Using files for Forth code
1.66 anton 1468: @cindex loading Forth code, tutorial
1469: @cindex files containing Forth code, tutorial
1.48 anton 1470:
1471: While working at the Forth command line is convenient for one-line
1472: examples and short one-off code, you probably want to store your source
1473: code in files for convenient editing and persistence. You can use your
1474: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1475: Gforth}) to create @var{file.fs} and use
1.48 anton 1476:
1477: @example
1.102 anton 1478: s" @var{file.fs}" included
1.48 anton 1479: @end example
1480:
1481: to load it into your Forth system. The file name extension I use for
1482: Forth files is @samp{.fs}.
1483:
1484: You can easily start Gforth with some files loaded like this:
1485:
1486: @example
1.102 anton 1487: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1488: @end example
1489:
1490: If an error occurs during loading these files, Gforth terminates,
1491: whereas an error during @code{INCLUDED} within Gforth usually gives you
1492: a Gforth command line. Starting the Forth system every time gives you a
1493: clean start every time, without interference from the results of earlier
1494: tries.
1495:
1496: I often put all the tests in a file, then load the code and run the
1497: tests with
1498:
1499: @example
1.102 anton 1500: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1501: @end example
1502:
1503: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1504: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1505: restart this command without ado.
1506:
1507: The advantage of this approach is that the tests can be repeated easily
1508: every time the program ist changed, making it easy to catch bugs
1509: introduced by the change.
1510:
1.66 anton 1511: Reference: @ref{Forth source files}.
1512:
1.48 anton 1513:
1514: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1515: @section Comments
1.66 anton 1516: @cindex comments tutorial
1.48 anton 1517:
1518: @example
1519: \ That's a comment; it ends at the end of the line
1520: ( Another comment; it ends here: ) .s
1521: @end example
1522:
1523: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1524: separated with white space from the following text.
1525:
1526: @example
1527: \This gives an "Undefined word" error
1528: @end example
1529:
1530: The first @code{)} ends a comment started with @code{(}, so you cannot
1531: nest @code{(}-comments; and you cannot comment out text containing a
1532: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1533: avoid @code{)} in word names.}.
1534:
1535: I use @code{\}-comments for descriptive text and for commenting out code
1536: of one or more line; I use @code{(}-comments for describing the stack
1537: effect, the stack contents, or for commenting out sub-line pieces of
1538: code.
1539:
1540: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1541: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1542: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1543: with @kbd{M-q}.
1544:
1.66 anton 1545: Reference: @ref{Comments}.
1546:
1.48 anton 1547:
1548: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1549: @section Colon Definitions
1.66 anton 1550: @cindex colon definitions, tutorial
1551: @cindex definitions, tutorial
1552: @cindex procedures, tutorial
1553: @cindex functions, tutorial
1.48 anton 1554:
1555: are similar to procedures and functions in other programming languages.
1556:
1557: @example
1558: : squared ( n -- n^2 )
1559: dup * ;
1560: 5 squared .
1561: 7 squared .
1562: @end example
1563:
1564: @code{:} starts the colon definition; its name is @code{squared}. The
1565: following comment describes its stack effect. The words @code{dup *}
1566: are not executed, but compiled into the definition. @code{;} ends the
1567: colon definition.
1568:
1569: The newly-defined word can be used like any other word, including using
1570: it in other definitions:
1571:
1572: @example
1573: : cubed ( n -- n^3 )
1574: dup squared * ;
1575: -5 cubed .
1576: : fourth-power ( n -- n^4 )
1577: squared squared ;
1578: 3 fourth-power .
1579: @end example
1580:
1.141 anton 1581: @quotation Assignment
1.48 anton 1582: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1583: @code{/mod} in terms of other Forth words, and check if they work (hint:
1584: test your tests on the originals first). Don't let the
1585: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1586: @end quotation
1.48 anton 1587:
1.66 anton 1588: Reference: @ref{Colon Definitions}.
1589:
1.48 anton 1590:
1591: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1592: @section Decompilation
1.66 anton 1593: @cindex decompilation tutorial
1594: @cindex see tutorial
1.48 anton 1595:
1596: You can decompile colon definitions with @code{see}:
1597:
1598: @example
1599: see squared
1600: see cubed
1601: @end example
1602:
1603: In Gforth @code{see} shows you a reconstruction of the source code from
1604: the executable code. Informations that were present in the source, but
1605: not in the executable code, are lost (e.g., comments).
1606:
1.65 anton 1607: You can also decompile the predefined words:
1608:
1609: @example
1610: see .
1611: see +
1612: @end example
1613:
1614:
1.48 anton 1615: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1616: @section Stack-Effect Comments
1.66 anton 1617: @cindex stack-effect comments, tutorial
1618: @cindex --, tutorial
1.48 anton 1619: By convention the comment after the name of a definition describes the
1.171 anton 1620: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1621: the stack before the execution of the definition, i.e., the parameters
1622: that are passed into the colon definition; the part behind the @samp{--}
1623: is the state of the stack after the execution of the definition, i.e.,
1624: the results of the definition. The stack comment only shows the top
1625: stack items that the definition accesses and/or changes.
1626:
1627: You should put a correct stack effect on every definition, even if it is
1628: just @code{( -- )}. You should also add some descriptive comment to
1629: more complicated words (I usually do this in the lines following
1630: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1631: you have to work through every definition before you can understand
1.48 anton 1632: any).
1633:
1.141 anton 1634: @quotation Assignment
1.48 anton 1635: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1636: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1637: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1638: are done, you can compare your stack effects to those in this manual
1.48 anton 1639: (@pxref{Word Index}).
1.141 anton 1640: @end quotation
1.48 anton 1641:
1642: Sometimes programmers put comments at various places in colon
1643: definitions that describe the contents of the stack at that place (stack
1644: comments); i.e., they are like the first part of a stack-effect
1645: comment. E.g.,
1646:
1647: @example
1648: : cubed ( n -- n^3 )
1649: dup squared ( n n^2 ) * ;
1650: @end example
1651:
1652: In this case the stack comment is pretty superfluous, because the word
1653: is simple enough. If you think it would be a good idea to add such a
1654: comment to increase readability, you should also consider factoring the
1655: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1656: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1657: however, if you decide not to refactor it, then having such a comment is
1658: better than not having it.
1659:
1660: The names of the stack items in stack-effect and stack comments in the
1661: standard, in this manual, and in many programs specify the type through
1662: a type prefix, similar to Fortran and Hungarian notation. The most
1663: frequent prefixes are:
1664:
1665: @table @code
1666: @item n
1667: signed integer
1668: @item u
1669: unsigned integer
1670: @item c
1671: character
1672: @item f
1673: Boolean flags, i.e. @code{false} or @code{true}.
1674: @item a-addr,a-
1675: Cell-aligned address
1676: @item c-addr,c-
1677: Char-aligned address (note that a Char may have two bytes in Windows NT)
1678: @item xt
1679: Execution token, same size as Cell
1680: @item w,x
1681: Cell, can contain an integer or an address. It usually takes 32, 64 or
1682: 16 bits (depending on your platform and Forth system). A cell is more
1683: commonly known as machine word, but the term @emph{word} already means
1684: something different in Forth.
1685: @item d
1686: signed double-cell integer
1687: @item ud
1688: unsigned double-cell integer
1689: @item r
1690: Float (on the FP stack)
1691: @end table
1692:
1693: You can find a more complete list in @ref{Notation}.
1694:
1.141 anton 1695: @quotation Assignment
1.48 anton 1696: Write stack-effect comments for all definitions you have written up to
1697: now.
1.141 anton 1698: @end quotation
1.48 anton 1699:
1700:
1701: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1702: @section Types
1.66 anton 1703: @cindex types tutorial
1.48 anton 1704:
1705: In Forth the names of the operations are not overloaded; so similar
1706: operations on different types need different names; e.g., @code{+} adds
1707: integers, and you have to use @code{f+} to add floating-point numbers.
1708: The following prefixes are often used for related operations on
1709: different types:
1710:
1711: @table @code
1712: @item (none)
1713: signed integer
1714: @item u
1715: unsigned integer
1716: @item c
1717: character
1718: @item d
1719: signed double-cell integer
1720: @item ud, du
1721: unsigned double-cell integer
1722: @item 2
1723: two cells (not-necessarily double-cell numbers)
1724: @item m, um
1725: mixed single-cell and double-cell operations
1726: @item f
1727: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1728: and @samp{r} represents FP numbers).
1.48 anton 1729: @end table
1730:
1731: If there are no differences between the signed and the unsigned variant
1732: (e.g., for @code{+}), there is only the prefix-less variant.
1733:
1734: Forth does not perform type checking, neither at compile time, nor at
1735: run time. If you use the wrong oeration, the data are interpreted
1736: incorrectly:
1737:
1738: @example
1739: -1 u.
1740: @end example
1741:
1742: If you have only experience with type-checked languages until now, and
1743: have heard how important type-checking is, don't panic! In my
1744: experience (and that of other Forthers), type errors in Forth code are
1745: usually easy to find (once you get used to it), the increased vigilance
1746: of the programmer tends to catch some harder errors in addition to most
1747: type errors, and you never have to work around the type system, so in
1748: most situations the lack of type-checking seems to be a win (projects to
1749: add type checking to Forth have not caught on).
1750:
1751:
1752: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1753: @section Factoring
1.66 anton 1754: @cindex factoring tutorial
1.48 anton 1755:
1756: If you try to write longer definitions, you will soon find it hard to
1757: keep track of the stack contents. Therefore, good Forth programmers
1758: tend to write only short definitions (e.g., three lines). The art of
1759: finding meaningful short definitions is known as factoring (as in
1760: factoring polynomials).
1761:
1762: Well-factored programs offer additional advantages: smaller, more
1763: general words, are easier to test and debug and can be reused more and
1764: better than larger, specialized words.
1765:
1766: So, if you run into difficulties with stack management, when writing
1767: code, try to define meaningful factors for the word, and define the word
1768: in terms of those. Even if a factor contains only two words, it is
1769: often helpful.
1770:
1.65 anton 1771: Good factoring is not easy, and it takes some practice to get the knack
1772: for it; but even experienced Forth programmers often don't find the
1773: right solution right away, but only when rewriting the program. So, if
1774: you don't come up with a good solution immediately, keep trying, don't
1775: despair.
1.48 anton 1776:
1777: @c example !!
1778:
1779:
1780: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1781: @section Designing the stack effect
1.66 anton 1782: @cindex Stack effect design, tutorial
1783: @cindex design of stack effects, tutorial
1.48 anton 1784:
1785: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1786: function; and since there is only one result, you don't have to deal with
1.48 anton 1787: the order of results, either.
1788:
1.117 anton 1789: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1790: parameter and result order of a definition is important and should be
1791: designed well. The general guideline is to design the stack effect such
1792: that the word is simple to use in most cases, even if that complicates
1793: the implementation of the word. Some concrete rules are:
1794:
1795: @itemize @bullet
1796:
1797: @item
1798: Words consume all of their parameters (e.g., @code{.}).
1799:
1800: @item
1801: If there is a convention on the order of parameters (e.g., from
1802: mathematics or another programming language), stick with it (e.g.,
1803: @code{-}).
1804:
1805: @item
1806: If one parameter usually requires only a short computation (e.g., it is
1807: a constant), pass it on the top of the stack. Conversely, parameters
1808: that usually require a long sequence of code to compute should be passed
1809: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1810: read, because the reader does not need to keep track of the bottom item
1.48 anton 1811: through a long sequence of code (or, alternatively, through stack
1.49 anton 1812: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1813: address on top of the stack because it is usually simpler to compute
1814: than the stored value (often the address is just a variable).
1815:
1816: @item
1817: Similarly, results that are usually consumed quickly should be returned
1818: on the top of stack, whereas a result that is often used in long
1819: computations should be passed as bottom result. E.g., the file words
1820: like @code{open-file} return the error code on the top of stack, because
1821: it is usually consumed quickly by @code{throw}; moreover, the error code
1822: has to be checked before doing anything with the other results.
1823:
1824: @end itemize
1825:
1826: These rules are just general guidelines, don't lose sight of the overall
1827: goal to make the words easy to use. E.g., if the convention rule
1828: conflicts with the computation-length rule, you might decide in favour
1829: of the convention if the word will be used rarely, and in favour of the
1830: computation-length rule if the word will be used frequently (because
1831: with frequent use the cost of breaking the computation-length rule would
1832: be quite high, and frequent use makes it easier to remember an
1833: unconventional order).
1834:
1835: @c example !! structure package
1836:
1.65 anton 1837:
1.48 anton 1838: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1839: @section Local Variables
1.66 anton 1840: @cindex local variables, tutorial
1.48 anton 1841:
1842: You can define local variables (@emph{locals}) in a colon definition:
1843:
1844: @example
1845: : swap @{ a b -- b a @}
1846: b a ;
1847: 1 2 swap .s 2drop
1848: @end example
1849:
1850: (If your Forth system does not support this syntax, include
1.187 anton 1851: @file{compat/anslocal.fs} first).
1.48 anton 1852:
1853: In this example @code{@{ a b -- b a @}} is the locals definition; it
1854: takes two cells from the stack, puts the top of stack in @code{b} and
1855: the next stack element in @code{a}. @code{--} starts a comment ending
1856: with @code{@}}. After the locals definition, using the name of the
1857: local will push its value on the stack. You can leave the comment
1858: part (@code{-- b a}) away:
1859:
1860: @example
1861: : swap ( x1 x2 -- x2 x1 )
1862: @{ a b @} b a ;
1863: @end example
1864:
1865: In Gforth you can have several locals definitions, anywhere in a colon
1866: definition; in contrast, in a standard program you can have only one
1867: locals definition per colon definition, and that locals definition must
1.163 anton 1868: be outside any control structure.
1.48 anton 1869:
1870: With locals you can write slightly longer definitions without running
1871: into stack trouble. However, I recommend trying to write colon
1872: definitions without locals for exercise purposes to help you gain the
1873: essential factoring skills.
1874:
1.141 anton 1875: @quotation Assignment
1.48 anton 1876: Rewrite your definitions until now with locals
1.141 anton 1877: @end quotation
1.48 anton 1878:
1.66 anton 1879: Reference: @ref{Locals}.
1880:
1.48 anton 1881:
1882: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1883: @section Conditional execution
1.66 anton 1884: @cindex conditionals, tutorial
1885: @cindex if, tutorial
1.48 anton 1886:
1887: In Forth you can use control structures only inside colon definitions.
1888: An @code{if}-structure looks like this:
1889:
1890: @example
1891: : abs ( n1 -- +n2 )
1892: dup 0 < if
1893: negate
1894: endif ;
1895: 5 abs .
1896: -5 abs .
1897: @end example
1898:
1899: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1900: the following code is performed, otherwise execution continues after the
1.51 pazsan 1901: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1902: elements and produces a flag:
1.48 anton 1903:
1904: @example
1905: 1 2 < .
1906: 2 1 < .
1907: 1 1 < .
1908: @end example
1909:
1910: Actually the standard name for @code{endif} is @code{then}. This
1911: tutorial presents the examples using @code{endif}, because this is often
1912: less confusing for people familiar with other programming languages
1913: where @code{then} has a different meaning. If your system does not have
1914: @code{endif}, define it with
1915:
1916: @example
1917: : endif postpone then ; immediate
1918: @end example
1919:
1920: You can optionally use an @code{else}-part:
1921:
1922: @example
1923: : min ( n1 n2 -- n )
1924: 2dup < if
1925: drop
1926: else
1927: nip
1928: endif ;
1929: 2 3 min .
1930: 3 2 min .
1931: @end example
1932:
1.141 anton 1933: @quotation Assignment
1.48 anton 1934: Write @code{min} without @code{else}-part (hint: what's the definition
1935: of @code{nip}?).
1.141 anton 1936: @end quotation
1.48 anton 1937:
1.66 anton 1938: Reference: @ref{Selection}.
1939:
1.48 anton 1940:
1941: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1942: @section Flags and Comparisons
1.66 anton 1943: @cindex flags tutorial
1944: @cindex comparison tutorial
1.48 anton 1945:
1946: In a false-flag all bits are clear (0 when interpreted as integer). In
1947: a canonical true-flag all bits are set (-1 as a twos-complement signed
1948: integer); in many contexts (e.g., @code{if}) any non-zero value is
1949: treated as true flag.
1950:
1951: @example
1952: false .
1953: true .
1954: true hex u. decimal
1955: @end example
1956:
1957: Comparison words produce canonical flags:
1958:
1959: @example
1960: 1 1 = .
1961: 1 0= .
1962: 0 1 < .
1963: 0 0 < .
1964: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1965: -1 1 < .
1966: @end example
1967:
1.66 anton 1968: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1969: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1970: these combinations are standard (for details see the standard,
1971: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1972:
1.171 anton 1973: You can use @code{and or xor invert} as operations on canonical flags.
1974: Actually they are bitwise operations:
1.48 anton 1975:
1976: @example
1977: 1 2 and .
1978: 1 2 or .
1979: 1 3 xor .
1980: 1 invert .
1981: @end example
1982:
1983: You can convert a zero/non-zero flag into a canonical flag with
1984: @code{0<>} (and complement it on the way with @code{0=}).
1985:
1986: @example
1987: 1 0= .
1988: 1 0<> .
1989: @end example
1990:
1.65 anton 1991: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1992: operation of the Boolean operations to avoid @code{if}s:
1993:
1994: @example
1995: : foo ( n1 -- n2 )
1996: 0= if
1997: 14
1998: else
1999: 0
2000: endif ;
2001: 0 foo .
2002: 1 foo .
2003:
2004: : foo ( n1 -- n2 )
2005: 0= 14 and ;
2006: 0 foo .
2007: 1 foo .
2008: @end example
2009:
1.141 anton 2010: @quotation Assignment
1.48 anton 2011: Write @code{min} without @code{if}.
1.141 anton 2012: @end quotation
1.48 anton 2013:
1.66 anton 2014: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2015: @ref{Bitwise operations}.
2016:
1.48 anton 2017:
2018: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2019: @section General Loops
1.66 anton 2020: @cindex loops, indefinite, tutorial
1.48 anton 2021:
2022: The endless loop is the most simple one:
2023:
2024: @example
2025: : endless ( -- )
2026: 0 begin
2027: dup . 1+
2028: again ;
2029: endless
2030: @end example
2031:
2032: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2033: does nothing at run-time, @code{again} jumps back to @code{begin}.
2034:
2035: A loop with one exit at any place looks like this:
2036:
2037: @example
2038: : log2 ( +n1 -- n2 )
2039: \ logarithmus dualis of n1>0, rounded down to the next integer
2040: assert( dup 0> )
2041: 2/ 0 begin
2042: over 0> while
2043: 1+ swap 2/ swap
2044: repeat
2045: nip ;
2046: 7 log2 .
2047: 8 log2 .
2048: @end example
2049:
2050: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2051: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2052: continues behind the @code{while}. @code{Repeat} jumps back to
2053: @code{begin}, just like @code{again}.
2054:
2055: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2056: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2057: one bit (arithmetic shift right):
2058:
2059: @example
2060: -5 2 / .
2061: -5 2/ .
2062: @end example
2063:
2064: @code{assert(} is no standard word, but you can get it on systems other
2065: then Gforth by including @file{compat/assert.fs}. You can see what it
2066: does by trying
2067:
2068: @example
2069: 0 log2 .
2070: @end example
2071:
2072: Here's a loop with an exit at the end:
2073:
2074: @example
2075: : log2 ( +n1 -- n2 )
2076: \ logarithmus dualis of n1>0, rounded down to the next integer
2077: assert( dup 0 > )
2078: -1 begin
2079: 1+ swap 2/ swap
2080: over 0 <=
2081: until
2082: nip ;
2083: @end example
2084:
2085: @code{Until} consumes a flag; if it is non-zero, execution continues at
2086: the @code{begin}, otherwise after the @code{until}.
2087:
1.141 anton 2088: @quotation Assignment
1.48 anton 2089: Write a definition for computing the greatest common divisor.
1.141 anton 2090: @end quotation
1.48 anton 2091:
1.66 anton 2092: Reference: @ref{Simple Loops}.
2093:
1.48 anton 2094:
2095: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2096: @section Counted loops
1.66 anton 2097: @cindex loops, counted, tutorial
1.48 anton 2098:
2099: @example
2100: : ^ ( n1 u -- n )
1.171 anton 2101: \ n = the uth power of n1
1.48 anton 2102: 1 swap 0 u+do
2103: over *
2104: loop
2105: nip ;
2106: 3 2 ^ .
2107: 4 3 ^ .
2108: @end example
2109:
2110: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2111: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2112: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2113: times (or not at all, if @code{u3-u4<0}).
2114:
2115: You can see the stack effect design rules at work in the stack effect of
2116: the loop start words: Since the start value of the loop is more
2117: frequently constant than the end value, the start value is passed on
2118: the top-of-stack.
2119:
2120: You can access the counter of a counted loop with @code{i}:
2121:
2122: @example
2123: : fac ( u -- u! )
2124: 1 swap 1+ 1 u+do
2125: i *
2126: loop ;
2127: 5 fac .
2128: 7 fac .
2129: @end example
2130:
2131: There is also @code{+do}, which expects signed numbers (important for
2132: deciding whether to enter the loop).
2133:
1.141 anton 2134: @quotation Assignment
1.48 anton 2135: Write a definition for computing the nth Fibonacci number.
1.141 anton 2136: @end quotation
1.48 anton 2137:
1.65 anton 2138: You can also use increments other than 1:
2139:
2140: @example
2141: : up2 ( n1 n2 -- )
2142: +do
2143: i .
2144: 2 +loop ;
2145: 10 0 up2
2146:
2147: : down2 ( n1 n2 -- )
2148: -do
2149: i .
2150: 2 -loop ;
2151: 0 10 down2
2152: @end example
1.48 anton 2153:
1.66 anton 2154: Reference: @ref{Counted Loops}.
2155:
1.48 anton 2156:
2157: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2158: @section Recursion
1.66 anton 2159: @cindex recursion tutorial
1.48 anton 2160:
2161: Usually the name of a definition is not visible in the definition; but
2162: earlier definitions are usually visible:
2163:
2164: @example
1.166 anton 2165: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2166: : / ( n1 n2 -- n )
2167: dup 0= if
2168: -10 throw \ report division by zero
2169: endif
2170: / \ old version
2171: ;
2172: 1 0 /
2173: @end example
2174:
2175: For recursive definitions you can use @code{recursive} (non-standard) or
2176: @code{recurse}:
2177:
2178: @example
2179: : fac1 ( n -- n! ) recursive
2180: dup 0> if
2181: dup 1- fac1 *
2182: else
2183: drop 1
2184: endif ;
2185: 7 fac1 .
2186:
2187: : fac2 ( n -- n! )
2188: dup 0> if
2189: dup 1- recurse *
2190: else
2191: drop 1
2192: endif ;
2193: 8 fac2 .
2194: @end example
2195:
1.141 anton 2196: @quotation Assignment
1.48 anton 2197: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2198: @end quotation
1.48 anton 2199:
1.66 anton 2200: Reference (including indirect recursion): @xref{Calls and returns}.
2201:
1.48 anton 2202:
2203: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2204: @section Leaving definitions or loops
1.66 anton 2205: @cindex leaving definitions, tutorial
2206: @cindex leaving loops, tutorial
1.48 anton 2207:
2208: @code{EXIT} exits the current definition right away. For every counted
2209: loop that is left in this way, an @code{UNLOOP} has to be performed
2210: before the @code{EXIT}:
2211:
2212: @c !! real examples
2213: @example
2214: : ...
2215: ... u+do
2216: ... if
2217: ... unloop exit
2218: endif
2219: ...
2220: loop
2221: ... ;
2222: @end example
2223:
2224: @code{LEAVE} leaves the innermost counted loop right away:
2225:
2226: @example
2227: : ...
2228: ... u+do
2229: ... if
2230: ... leave
2231: endif
2232: ...
2233: loop
2234: ... ;
2235: @end example
2236:
1.65 anton 2237: @c !! example
1.48 anton 2238:
1.66 anton 2239: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2240:
2241:
1.48 anton 2242: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2243: @section Return Stack
1.66 anton 2244: @cindex return stack tutorial
1.48 anton 2245:
2246: In addition to the data stack Forth also has a second stack, the return
2247: stack; most Forth systems store the return addresses of procedure calls
2248: there (thus its name). Programmers can also use this stack:
2249:
2250: @example
2251: : foo ( n1 n2 -- )
2252: .s
2253: >r .s
1.50 anton 2254: r@@ .
1.48 anton 2255: >r .s
1.50 anton 2256: r@@ .
1.48 anton 2257: r> .
1.50 anton 2258: r@@ .
1.48 anton 2259: r> . ;
2260: 1 2 foo
2261: @end example
2262:
2263: @code{>r} takes an element from the data stack and pushes it onto the
2264: return stack; conversely, @code{r>} moves an elementm from the return to
2265: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2266: on the data stack.
1.48 anton 2267:
2268: Forth programmers usually use the return stack for storing data
2269: temporarily, if using the data stack alone would be too complex, and
2270: factoring and locals are not an option:
2271:
2272: @example
2273: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2274: rot >r rot r> ;
2275: @end example
2276:
2277: The return address of the definition and the loop control parameters of
2278: counted loops usually reside on the return stack, so you have to take
2279: all items, that you have pushed on the return stack in a colon
2280: definition or counted loop, from the return stack before the definition
2281: or loop ends. You cannot access items that you pushed on the return
2282: stack outside some definition or loop within the definition of loop.
2283:
2284: If you miscount the return stack items, this usually ends in a crash:
2285:
2286: @example
2287: : crash ( n -- )
2288: >r ;
2289: 5 crash
2290: @end example
2291:
2292: You cannot mix using locals and using the return stack (according to the
2293: standard; Gforth has no problem). However, they solve the same
2294: problems, so this shouldn't be an issue.
2295:
1.141 anton 2296: @quotation Assignment
1.48 anton 2297: Can you rewrite any of the definitions you wrote until now in a better
2298: way using the return stack?
1.141 anton 2299: @end quotation
1.48 anton 2300:
1.66 anton 2301: Reference: @ref{Return stack}.
2302:
1.48 anton 2303:
2304: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2305: @section Memory
1.66 anton 2306: @cindex memory access/allocation tutorial
1.48 anton 2307:
2308: You can create a global variable @code{v} with
2309:
2310: @example
2311: variable v ( -- addr )
2312: @end example
2313:
2314: @code{v} pushes the address of a cell in memory on the stack. This cell
2315: was reserved by @code{variable}. You can use @code{!} (store) to store
2316: values into this cell and @code{@@} (fetch) to load the value from the
2317: stack into memory:
2318:
2319: @example
2320: v .
2321: 5 v ! .s
1.50 anton 2322: v @@ .
1.48 anton 2323: @end example
2324:
1.65 anton 2325: You can see a raw dump of memory with @code{dump}:
2326:
2327: @example
2328: v 1 cells .s dump
2329: @end example
2330:
2331: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2332: generally, address units (aus)) that @code{n1 cells} occupy. You can
2333: also reserve more memory:
1.48 anton 2334:
2335: @example
2336: create v2 20 cells allot
1.65 anton 2337: v2 20 cells dump
1.48 anton 2338: @end example
2339:
1.65 anton 2340: creates a word @code{v2} and reserves 20 uninitialized cells; the
2341: address pushed by @code{v2} points to the start of these 20 cells. You
2342: can use address arithmetic to access these cells:
1.48 anton 2343:
2344: @example
2345: 3 v2 5 cells + !
1.65 anton 2346: v2 20 cells dump
1.48 anton 2347: @end example
2348:
2349: You can reserve and initialize memory with @code{,}:
2350:
2351: @example
2352: create v3
2353: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2354: v3 @@ .
2355: v3 cell+ @@ .
2356: v3 2 cells + @@ .
1.65 anton 2357: v3 5 cells dump
1.48 anton 2358: @end example
2359:
1.141 anton 2360: @quotation Assignment
1.48 anton 2361: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2362: @code{u} cells, with the first of these cells at @code{addr}, the next
2363: one at @code{addr cell+} etc.
1.141 anton 2364: @end quotation
1.48 anton 2365:
2366: You can also reserve memory without creating a new word:
2367:
2368: @example
1.60 anton 2369: here 10 cells allot .
2370: here .
1.48 anton 2371: @end example
2372:
2373: @code{Here} pushes the start address of the memory area. You should
2374: store it somewhere, or you will have a hard time finding the memory area
2375: again.
2376:
2377: @code{Allot} manages dictionary memory. The dictionary memory contains
2378: the system's data structures for words etc. on Gforth and most other
2379: Forth systems. It is managed like a stack: You can free the memory that
2380: you have just @code{allot}ed with
2381:
2382: @example
2383: -10 cells allot
1.60 anton 2384: here .
1.48 anton 2385: @end example
2386:
2387: Note that you cannot do this if you have created a new word in the
2388: meantime (because then your @code{allot}ed memory is no longer on the
2389: top of the dictionary ``stack'').
2390:
2391: Alternatively, you can use @code{allocate} and @code{free} which allow
2392: freeing memory in any order:
2393:
2394: @example
2395: 10 cells allocate throw .s
2396: 20 cells allocate throw .s
2397: swap
2398: free throw
2399: free throw
2400: @end example
2401:
2402: The @code{throw}s deal with errors (e.g., out of memory).
2403:
1.65 anton 2404: And there is also a
2405: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2406: garbage collector}, which eliminates the need to @code{free} memory
2407: explicitly.
1.48 anton 2408:
1.66 anton 2409: Reference: @ref{Memory}.
2410:
1.48 anton 2411:
2412: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2413: @section Characters and Strings
1.66 anton 2414: @cindex strings tutorial
2415: @cindex characters tutorial
1.48 anton 2416:
2417: On the stack characters take up a cell, like numbers. In memory they
2418: have their own size (one 8-bit byte on most systems), and therefore
2419: require their own words for memory access:
2420:
2421: @example
2422: create v4
2423: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2424: v4 4 chars + c@@ .
1.65 anton 2425: v4 5 chars dump
1.48 anton 2426: @end example
2427:
2428: The preferred representation of strings on the stack is @code{addr
2429: u-count}, where @code{addr} is the address of the first character and
2430: @code{u-count} is the number of characters in the string.
2431:
2432: @example
2433: v4 5 type
2434: @end example
2435:
2436: You get a string constant with
2437:
2438: @example
2439: s" hello, world" .s
2440: type
2441: @end example
2442:
2443: Make sure you have a space between @code{s"} and the string; @code{s"}
2444: is a normal Forth word and must be delimited with white space (try what
2445: happens when you remove the space).
2446:
2447: However, this interpretive use of @code{s"} is quite restricted: the
2448: string exists only until the next call of @code{s"} (some Forth systems
2449: keep more than one of these strings, but usually they still have a
1.62 crook 2450: limited lifetime).
1.48 anton 2451:
2452: @example
2453: s" hello," s" world" .s
2454: type
2455: type
2456: @end example
2457:
1.62 crook 2458: You can also use @code{s"} in a definition, and the resulting
2459: strings then live forever (well, for as long as the definition):
1.48 anton 2460:
2461: @example
2462: : foo s" hello," s" world" ;
2463: foo .s
2464: type
2465: type
2466: @end example
2467:
1.141 anton 2468: @quotation Assignment
1.48 anton 2469: @code{Emit ( c -- )} types @code{c} as character (not a number).
2470: Implement @code{type ( addr u -- )}.
1.141 anton 2471: @end quotation
1.48 anton 2472:
1.66 anton 2473: Reference: @ref{Memory Blocks}.
2474:
2475:
1.84 pazsan 2476: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2477: @section Alignment
1.66 anton 2478: @cindex alignment tutorial
2479: @cindex memory alignment tutorial
1.48 anton 2480:
2481: On many processors cells have to be aligned in memory, if you want to
2482: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2483: not require alignment, access to aligned cells is faster).
1.48 anton 2484:
2485: @code{Create} aligns @code{here} (i.e., the place where the next
2486: allocation will occur, and that the @code{create}d word points to).
2487: Likewise, the memory produced by @code{allocate} starts at an aligned
2488: address. Adding a number of @code{cells} to an aligned address produces
2489: another aligned address.
2490:
2491: However, address arithmetic involving @code{char+} and @code{chars} can
2492: create an address that is not cell-aligned. @code{Aligned ( addr --
2493: a-addr )} produces the next aligned address:
2494:
2495: @example
1.50 anton 2496: v3 char+ aligned .s @@ .
2497: v3 char+ .s @@ .
1.48 anton 2498: @end example
2499:
2500: Similarly, @code{align} advances @code{here} to the next aligned
2501: address:
2502:
2503: @example
2504: create v5 97 c,
2505: here .
2506: align here .
2507: 1000 ,
2508: @end example
2509:
2510: Note that you should use aligned addresses even if your processor does
2511: not require them, if you want your program to be portable.
2512:
1.66 anton 2513: Reference: @ref{Address arithmetic}.
2514:
1.48 anton 2515:
1.84 pazsan 2516: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2517: @section Files
2518: @cindex files tutorial
2519:
2520: This section gives a short introduction into how to use files inside
2521: Forth. It's broken up into five easy steps:
2522:
2523: @enumerate 1
2524: @item Opened an ASCII text file for input
2525: @item Opened a file for output
2526: @item Read input file until string matched (or some other condition matched)
2527: @item Wrote some lines from input ( modified or not) to output
2528: @item Closed the files.
2529: @end enumerate
2530:
1.153 anton 2531: Reference: @ref{General files}.
2532:
1.84 pazsan 2533: @subsection Open file for input
2534:
2535: @example
2536: s" foo.in" r/o open-file throw Value fd-in
2537: @end example
2538:
2539: @subsection Create file for output
2540:
2541: @example
2542: s" foo.out" w/o create-file throw Value fd-out
2543: @end example
2544:
2545: The available file modes are r/o for read-only access, r/w for
2546: read-write access, and w/o for write-only access. You could open both
2547: files with r/w, too, if you like. All file words return error codes; for
2548: most applications, it's best to pass there error codes with @code{throw}
2549: to the outer error handler.
2550:
2551: If you want words for opening and assigning, define them as follows:
2552:
2553: @example
2554: 0 Value fd-in
2555: 0 Value fd-out
2556: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2557: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2558: @end example
2559:
2560: Usage example:
2561:
2562: @example
2563: s" foo.in" open-input
2564: s" foo.out" open-output
2565: @end example
2566:
2567: @subsection Scan file for a particular line
2568:
2569: @example
2570: 256 Constant max-line
2571: Create line-buffer max-line 2 + allot
2572:
2573: : scan-file ( addr u -- )
2574: begin
2575: line-buffer max-line fd-in read-line throw
2576: while
2577: >r 2dup line-buffer r> compare 0=
2578: until
2579: else
2580: drop
2581: then
2582: 2drop ;
2583: @end example
2584:
2585: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2586: the buffer at addr, and returns the number of bytes read, a flag that is
2587: false when the end of file is reached, and an error code.
1.84 pazsan 2588:
2589: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2590: returns zero if both strings are equal. It returns a positive number if
2591: the first string is lexically greater, a negative if the second string
2592: is lexically greater.
2593:
2594: We haven't seen this loop here; it has two exits. Since the @code{while}
2595: exits with the number of bytes read on the stack, we have to clean up
2596: that separately; that's after the @code{else}.
2597:
2598: Usage example:
2599:
2600: @example
2601: s" The text I search is here" scan-file
2602: @end example
2603:
2604: @subsection Copy input to output
2605:
2606: @example
2607: : copy-file ( -- )
2608: begin
2609: line-buffer max-line fd-in read-line throw
2610: while
2611: line-buffer swap fd-out write-file throw
2612: repeat ;
2613: @end example
2614:
2615: @subsection Close files
2616:
2617: @example
2618: fd-in close-file throw
2619: fd-out close-file throw
2620: @end example
2621:
2622: Likewise, you can put that into definitions, too:
2623:
2624: @example
2625: : close-input ( -- ) fd-in close-file throw ;
2626: : close-output ( -- ) fd-out close-file throw ;
2627: @end example
2628:
1.141 anton 2629: @quotation Assignment
1.84 pazsan 2630: How could you modify @code{copy-file} so that it copies until a second line is
2631: matched? Can you write a program that extracts a section of a text file,
2632: given the line that starts and the line that terminates that section?
1.141 anton 2633: @end quotation
1.84 pazsan 2634:
2635: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2636: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2637: @cindex semantics tutorial
2638: @cindex interpretation semantics tutorial
2639: @cindex compilation semantics tutorial
2640: @cindex immediate, tutorial
1.48 anton 2641:
2642: When a word is compiled, it behaves differently from being interpreted.
2643: E.g., consider @code{+}:
2644:
2645: @example
2646: 1 2 + .
2647: : foo + ;
2648: @end example
2649:
2650: These two behaviours are known as compilation and interpretation
2651: semantics. For normal words (e.g., @code{+}), the compilation semantics
2652: is to append the interpretation semantics to the currently defined word
2653: (@code{foo} in the example above). I.e., when @code{foo} is executed
2654: later, the interpretation semantics of @code{+} (i.e., adding two
2655: numbers) will be performed.
2656:
2657: However, there are words with non-default compilation semantics, e.g.,
2658: the control-flow words like @code{if}. You can use @code{immediate} to
2659: change the compilation semantics of the last defined word to be equal to
2660: the interpretation semantics:
2661:
2662: @example
2663: : [FOO] ( -- )
2664: 5 . ; immediate
2665:
2666: [FOO]
2667: : bar ( -- )
2668: [FOO] ;
2669: bar
2670: see bar
2671: @end example
2672:
2673: Two conventions to mark words with non-default compilation semnatics are
2674: names with brackets (more frequently used) and to write them all in
2675: upper case (less frequently used).
2676:
2677: In Gforth (and many other systems) you can also remove the
2678: interpretation semantics with @code{compile-only} (the compilation
2679: semantics is derived from the original interpretation semantics):
2680:
2681: @example
2682: : flip ( -- )
2683: 6 . ; compile-only \ but not immediate
2684: flip
2685:
2686: : flop ( -- )
2687: flip ;
2688: flop
2689: @end example
2690:
2691: In this example the interpretation semantics of @code{flop} is equal to
2692: the original interpretation semantics of @code{flip}.
2693:
2694: The text interpreter has two states: in interpret state, it performs the
2695: interpretation semantics of words it encounters; in compile state, it
2696: performs the compilation semantics of these words.
2697:
2698: Among other things, @code{:} switches into compile state, and @code{;}
2699: switches back to interpret state. They contain the factors @code{]}
2700: (switch to compile state) and @code{[} (switch to interpret state), that
2701: do nothing but switch the state.
2702:
2703: @example
2704: : xxx ( -- )
2705: [ 5 . ]
2706: ;
2707:
2708: xxx
2709: see xxx
2710: @end example
2711:
2712: These brackets are also the source of the naming convention mentioned
2713: above.
2714:
1.66 anton 2715: Reference: @ref{Interpretation and Compilation Semantics}.
2716:
1.48 anton 2717:
2718: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2719: @section Execution Tokens
1.66 anton 2720: @cindex execution tokens tutorial
2721: @cindex XT tutorial
1.48 anton 2722:
2723: @code{' word} gives you the execution token (XT) of a word. The XT is a
2724: cell representing the interpretation semantics of a word. You can
2725: execute this semantics with @code{execute}:
2726:
2727: @example
2728: ' + .s
2729: 1 2 rot execute .
2730: @end example
2731:
2732: The XT is similar to a function pointer in C. However, parameter
2733: passing through the stack makes it a little more flexible:
2734:
2735: @example
2736: : map-array ( ... addr u xt -- ... )
1.50 anton 2737: \ executes xt ( ... x -- ... ) for every element of the array starting
2738: \ at addr and containing u elements
1.48 anton 2739: @{ xt @}
2740: cells over + swap ?do
1.50 anton 2741: i @@ xt execute
1.48 anton 2742: 1 cells +loop ;
2743:
2744: create a 3 , 4 , 2 , -1 , 4 ,
2745: a 5 ' . map-array .s
2746: 0 a 5 ' + map-array .
2747: s" max-n" environment? drop .s
2748: a 5 ' min map-array .
2749: @end example
2750:
2751: You can use map-array with the XTs of words that consume one element
2752: more than they produce. In theory you can also use it with other XTs,
2753: but the stack effect then depends on the size of the array, which is
2754: hard to understand.
2755:
1.51 pazsan 2756: Since XTs are cell-sized, you can store them in memory and manipulate
2757: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2758: word with @code{compile,}:
2759:
2760: @example
2761: : foo1 ( n1 n2 -- n )
2762: [ ' + compile, ] ;
2763: see foo
2764: @end example
2765:
2766: This is non-standard, because @code{compile,} has no compilation
2767: semantics in the standard, but it works in good Forth systems. For the
2768: broken ones, use
2769:
2770: @example
2771: : [compile,] compile, ; immediate
2772:
2773: : foo1 ( n1 n2 -- n )
2774: [ ' + ] [compile,] ;
2775: see foo
2776: @end example
2777:
2778: @code{'} is a word with default compilation semantics; it parses the
2779: next word when its interpretation semantics are executed, not during
2780: compilation:
2781:
2782: @example
2783: : foo ( -- xt )
2784: ' ;
2785: see foo
2786: : bar ( ... "word" -- ... )
2787: ' execute ;
2788: see bar
1.60 anton 2789: 1 2 bar + .
1.48 anton 2790: @end example
2791:
2792: You often want to parse a word during compilation and compile its XT so
2793: it will be pushed on the stack at run-time. @code{[']} does this:
2794:
2795: @example
2796: : xt-+ ( -- xt )
2797: ['] + ;
2798: see xt-+
2799: 1 2 xt-+ execute .
2800: @end example
2801:
2802: Many programmers tend to see @code{'} and the word it parses as one
2803: unit, and expect it to behave like @code{[']} when compiled, and are
2804: confused by the actual behaviour. If you are, just remember that the
2805: Forth system just takes @code{'} as one unit and has no idea that it is
2806: a parsing word (attempts to convenience programmers in this issue have
2807: usually resulted in even worse pitfalls, see
1.66 anton 2808: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2809: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2810:
2811: Note that the state of the interpreter does not come into play when
1.51 pazsan 2812: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2813: compile state, it still gives you the interpretation semantics. And
2814: whatever that state is, @code{execute} performs the semantics
1.66 anton 2815: represented by the XT (i.e., for XTs produced with @code{'} the
2816: interpretation semantics).
2817:
2818: Reference: @ref{Tokens for Words}.
1.48 anton 2819:
2820:
2821: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2822: @section Exceptions
1.66 anton 2823: @cindex exceptions tutorial
1.48 anton 2824:
2825: @code{throw ( n -- )} causes an exception unless n is zero.
2826:
2827: @example
2828: 100 throw .s
2829: 0 throw .s
2830: @end example
2831:
2832: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2833: it catches exceptions and pushes the number of the exception on the
2834: stack (or 0, if the xt executed without exception). If there was an
2835: exception, the stacks have the same depth as when entering @code{catch}:
2836:
2837: @example
2838: .s
2839: 3 0 ' / catch .s
2840: 3 2 ' / catch .s
2841: @end example
2842:
1.141 anton 2843: @quotation Assignment
1.48 anton 2844: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2845: @end quotation
1.48 anton 2846:
2847: @code{Throw} always jumps to the dynamically next enclosing
2848: @code{catch}, even if it has to leave several call levels to achieve
2849: this:
2850:
2851: @example
2852: : foo 100 throw ;
2853: : foo1 foo ." after foo" ;
1.51 pazsan 2854: : bar ['] foo1 catch ;
1.60 anton 2855: bar .
1.48 anton 2856: @end example
2857:
2858: It is often important to restore a value upon leaving a definition, even
2859: if the definition is left through an exception. You can ensure this
2860: like this:
2861:
2862: @example
2863: : ...
2864: save-x
1.51 pazsan 2865: ['] word-changing-x catch ( ... n )
1.48 anton 2866: restore-x
2867: ( ... n ) throw ;
2868: @end example
2869:
1.172 anton 2870: However, this is still not safe against, e.g., the user pressing
2871: @kbd{Ctrl-C} when execution is between the @code{catch} and
2872: @code{restore-x}.
2873:
2874: Gforth provides an alternative exception handling syntax that is safe
2875: against such cases: @code{try ... restore ... endtry}. If the code
2876: between @code{try} and @code{endtry} has an exception, the stack
2877: depths are restored, the exception number is pushed on the stack, and
2878: the execution continues right after @code{restore}.
1.48 anton 2879:
1.172 anton 2880: The safer equivalent to the restoration code above is
1.48 anton 2881:
2882: @example
2883: : ...
2884: save-x
2885: try
1.92 anton 2886: word-changing-x 0
1.172 anton 2887: restore
2888: restore-x
2889: endtry
1.48 anton 2890: throw ;
2891: @end example
2892:
1.66 anton 2893: Reference: @ref{Exception Handling}.
2894:
1.48 anton 2895:
2896: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2897: @section Defining Words
1.66 anton 2898: @cindex defining words tutorial
2899: @cindex does> tutorial
2900: @cindex create...does> tutorial
2901:
2902: @c before semantics?
1.48 anton 2903:
2904: @code{:}, @code{create}, and @code{variable} are definition words: They
2905: define other words. @code{Constant} is another definition word:
2906:
2907: @example
2908: 5 constant foo
2909: foo .
2910: @end example
2911:
2912: You can also use the prefixes @code{2} (double-cell) and @code{f}
2913: (floating point) with @code{variable} and @code{constant}.
2914:
2915: You can also define your own defining words. E.g.:
2916:
2917: @example
2918: : variable ( "name" -- )
2919: create 0 , ;
2920: @end example
2921:
2922: You can also define defining words that create words that do something
2923: other than just producing their address:
2924:
2925: @example
2926: : constant ( n "name" -- )
2927: create ,
2928: does> ( -- n )
1.50 anton 2929: ( addr ) @@ ;
1.48 anton 2930:
2931: 5 constant foo
2932: foo .
2933: @end example
2934:
2935: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2936: @code{does>} replaces @code{;}, but it also does something else: It
2937: changes the last defined word such that it pushes the address of the
2938: body of the word and then performs the code after the @code{does>}
2939: whenever it is called.
2940:
2941: In the example above, @code{constant} uses @code{,} to store 5 into the
2942: body of @code{foo}. When @code{foo} executes, it pushes the address of
2943: the body onto the stack, then (in the code after the @code{does>})
2944: fetches the 5 from there.
2945:
2946: The stack comment near the @code{does>} reflects the stack effect of the
2947: defined word, not the stack effect of the code after the @code{does>}
2948: (the difference is that the code expects the address of the body that
2949: the stack comment does not show).
2950:
2951: You can use these definition words to do factoring in cases that involve
2952: (other) definition words. E.g., a field offset is always added to an
2953: address. Instead of defining
2954:
2955: @example
2956: 2 cells constant offset-field1
2957: @end example
2958:
2959: and using this like
2960:
2961: @example
2962: ( addr ) offset-field1 +
2963: @end example
2964:
2965: you can define a definition word
2966:
2967: @example
2968: : simple-field ( n "name" -- )
2969: create ,
2970: does> ( n1 -- n1+n )
1.50 anton 2971: ( addr ) @@ + ;
1.48 anton 2972: @end example
1.21 crook 2973:
1.48 anton 2974: Definition and use of field offsets now look like this:
1.21 crook 2975:
1.48 anton 2976: @example
2977: 2 cells simple-field field1
1.60 anton 2978: create mystruct 4 cells allot
2979: mystruct .s field1 .s drop
1.48 anton 2980: @end example
1.21 crook 2981:
1.48 anton 2982: If you want to do something with the word without performing the code
2983: after the @code{does>}, you can access the body of a @code{create}d word
2984: with @code{>body ( xt -- addr )}:
1.21 crook 2985:
1.48 anton 2986: @example
2987: : value ( n "name" -- )
2988: create ,
2989: does> ( -- n1 )
1.50 anton 2990: @@ ;
1.48 anton 2991: : to ( n "name" -- )
2992: ' >body ! ;
1.21 crook 2993:
1.48 anton 2994: 5 value foo
2995: foo .
2996: 7 to foo
2997: foo .
2998: @end example
1.21 crook 2999:
1.141 anton 3000: @quotation Assignment
1.48 anton 3001: Define @code{defer ( "name" -- )}, which creates a word that stores an
3002: XT (at the start the XT of @code{abort}), and upon execution
3003: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3004: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3005: recursion is one application of @code{defer}.
1.141 anton 3006: @end quotation
1.29 crook 3007:
1.66 anton 3008: Reference: @ref{User-defined Defining Words}.
3009:
3010:
1.48 anton 3011: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3012: @section Arrays and Records
1.66 anton 3013: @cindex arrays tutorial
3014: @cindex records tutorial
3015: @cindex structs tutorial
1.29 crook 3016:
1.48 anton 3017: Forth has no standard words for defining data structures such as arrays
3018: and records (structs in C terminology), but you can build them yourself
3019: based on address arithmetic. You can also define words for defining
3020: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3021:
1.48 anton 3022: One of the first projects a Forth newcomer sets out upon when learning
3023: about defining words is an array defining word (possibly for
3024: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3025: learn something from it. However, don't be disappointed when you later
3026: learn that you have little use for these words (inappropriate use would
3027: be even worse). I have not yet found a set of useful array words yet;
3028: the needs are just too diverse, and named, global arrays (the result of
3029: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3030: consider how to pass them as parameters). Another such project is a set
3031: of words to help dealing with strings.
1.29 crook 3032:
1.48 anton 3033: On the other hand, there is a useful set of record words, and it has
3034: been defined in @file{compat/struct.fs}; these words are predefined in
3035: Gforth. They are explained in depth elsewhere in this manual (see
3036: @pxref{Structures}). The @code{simple-field} example above is
3037: simplified variant of fields in this package.
1.21 crook 3038:
3039:
1.48 anton 3040: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3041: @section @code{POSTPONE}
1.66 anton 3042: @cindex postpone tutorial
1.21 crook 3043:
1.48 anton 3044: You can compile the compilation semantics (instead of compiling the
3045: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3046:
1.48 anton 3047: @example
3048: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3049: POSTPONE + ; immediate
1.48 anton 3050: : foo ( n1 n2 -- n )
3051: MY-+ ;
3052: 1 2 foo .
3053: see foo
3054: @end example
1.21 crook 3055:
1.48 anton 3056: During the definition of @code{foo} the text interpreter performs the
3057: compilation semantics of @code{MY-+}, which performs the compilation
3058: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3059:
3060: This example also displays separate stack comments for the compilation
3061: semantics and for the stack effect of the compiled code. For words with
3062: default compilation semantics these stack effects are usually not
3063: displayed; the stack effect of the compilation semantics is always
3064: @code{( -- )} for these words, the stack effect for the compiled code is
3065: the stack effect of the interpretation semantics.
3066:
3067: Note that the state of the interpreter does not come into play when
3068: performing the compilation semantics in this way. You can also perform
3069: it interpretively, e.g.:
3070:
3071: @example
3072: : foo2 ( n1 n2 -- n )
3073: [ MY-+ ] ;
3074: 1 2 foo .
3075: see foo
3076: @end example
1.21 crook 3077:
1.48 anton 3078: However, there are some broken Forth systems where this does not always
1.62 crook 3079: work, and therefore this practice was been declared non-standard in
1.48 anton 3080: 1999.
3081: @c !! repair.fs
3082:
3083: Here is another example for using @code{POSTPONE}:
1.44 crook 3084:
1.48 anton 3085: @example
3086: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3087: POSTPONE negate POSTPONE + ; immediate compile-only
3088: : bar ( n1 n2 -- n )
3089: MY-- ;
3090: 2 1 bar .
3091: see bar
3092: @end example
1.21 crook 3093:
1.48 anton 3094: You can define @code{ENDIF} in this way:
1.21 crook 3095:
1.48 anton 3096: @example
3097: : ENDIF ( Compilation: orig -- )
3098: POSTPONE then ; immediate
3099: @end example
1.21 crook 3100:
1.141 anton 3101: @quotation Assignment
1.48 anton 3102: Write @code{MY-2DUP} that has compilation semantics equivalent to
3103: @code{2dup}, but compiles @code{over over}.
1.141 anton 3104: @end quotation
1.29 crook 3105:
1.66 anton 3106: @c !! @xref{Macros} for reference
3107:
3108:
1.48 anton 3109: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3110: @section @code{Literal}
1.66 anton 3111: @cindex literal tutorial
1.29 crook 3112:
1.48 anton 3113: You cannot @code{POSTPONE} numbers:
1.21 crook 3114:
1.48 anton 3115: @example
3116: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3117: @end example
3118:
1.48 anton 3119: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3120:
1.48 anton 3121: @example
3122: : [FOO] ( compilation: --; run-time: -- n )
3123: 500 POSTPONE literal ; immediate
1.29 crook 3124:
1.60 anton 3125: : flip [FOO] ;
1.48 anton 3126: flip .
3127: see flip
3128: @end example
1.29 crook 3129:
1.48 anton 3130: @code{LITERAL} consumes a number at compile-time (when it's compilation
3131: semantics are executed) and pushes it at run-time (when the code it
3132: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3133: number computed at compile time into the current word:
1.29 crook 3134:
1.48 anton 3135: @example
3136: : bar ( -- n )
3137: [ 2 2 + ] literal ;
3138: see bar
3139: @end example
1.29 crook 3140:
1.141 anton 3141: @quotation Assignment
1.48 anton 3142: Write @code{]L} which allows writing the example above as @code{: bar (
3143: -- n ) [ 2 2 + ]L ;}
1.141 anton 3144: @end quotation
1.48 anton 3145:
1.66 anton 3146: @c !! @xref{Macros} for reference
3147:
1.48 anton 3148:
3149: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3150: @section Advanced macros
1.66 anton 3151: @cindex macros, advanced tutorial
3152: @cindex run-time code generation, tutorial
1.48 anton 3153:
1.66 anton 3154: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3155: Execution Tokens}. It frequently performs @code{execute}, a relatively
3156: expensive operation in some Forth implementations. You can use
1.48 anton 3157: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3158: and produce a word that contains the word to be performed directly:
3159:
3160: @c use ]] ... [[
3161: @example
3162: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3163: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3164: \ array beginning at addr and containing u elements
3165: @{ xt @}
3166: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3167: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3168: 1 cells POSTPONE literal POSTPONE +loop ;
3169:
3170: : sum-array ( addr u -- n )
3171: 0 rot rot [ ' + compile-map-array ] ;
3172: see sum-array
3173: a 5 sum-array .
3174: @end example
3175:
3176: You can use the full power of Forth for generating the code; here's an
3177: example where the code is generated in a loop:
3178:
3179: @example
3180: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3181: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3182: POSTPONE tuck POSTPONE @@
1.48 anton 3183: POSTPONE literal POSTPONE * POSTPONE +
3184: POSTPONE swap POSTPONE cell+ ;
3185:
3186: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3187: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3188: 0 postpone literal postpone swap
3189: [ ' compile-vmul-step compile-map-array ]
3190: postpone drop ;
3191: see compile-vmul
3192:
3193: : a-vmul ( addr -- n )
1.51 pazsan 3194: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3195: [ a 5 compile-vmul ] ;
3196: see a-vmul
3197: a a-vmul .
3198: @end example
3199:
3200: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3201: also use @code{map-array} instead (try it now!).
1.48 anton 3202:
3203: You can use this technique for efficient multiplication of large
3204: matrices. In matrix multiplication, you multiply every line of one
3205: matrix with every column of the other matrix. You can generate the code
3206: for one line once, and use it for every column. The only downside of
3207: this technique is that it is cumbersome to recover the memory consumed
3208: by the generated code when you are done (and in more complicated cases
3209: it is not possible portably).
3210:
1.66 anton 3211: @c !! @xref{Macros} for reference
3212:
3213:
1.48 anton 3214: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3215: @section Compilation Tokens
1.66 anton 3216: @cindex compilation tokens, tutorial
3217: @cindex CT, tutorial
1.48 anton 3218:
3219: This section is Gforth-specific. You can skip it.
3220:
3221: @code{' word compile,} compiles the interpretation semantics. For words
3222: with default compilation semantics this is the same as performing the
3223: compilation semantics. To represent the compilation semantics of other
3224: words (e.g., words like @code{if} that have no interpretation
3225: semantics), Gforth has the concept of a compilation token (CT,
3226: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3227: You can perform the compilation semantics represented by a CT with
3228: @code{execute}:
1.29 crook 3229:
1.48 anton 3230: @example
3231: : foo2 ( n1 n2 -- n )
3232: [ comp' + execute ] ;
3233: see foo
3234: @end example
1.29 crook 3235:
1.48 anton 3236: You can compile the compilation semantics represented by a CT with
3237: @code{postpone,}:
1.30 anton 3238:
1.48 anton 3239: @example
3240: : foo3 ( -- )
3241: [ comp' + postpone, ] ;
3242: see foo3
3243: @end example
1.30 anton 3244:
1.51 pazsan 3245: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3246: @code{comp'} is particularly useful for words that have no
3247: interpretation semantics:
1.29 crook 3248:
1.30 anton 3249: @example
1.48 anton 3250: ' if
1.60 anton 3251: comp' if .s 2drop
1.30 anton 3252: @end example
3253:
1.66 anton 3254: Reference: @ref{Tokens for Words}.
3255:
1.29 crook 3256:
1.48 anton 3257: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3258: @section Wordlists and Search Order
1.66 anton 3259: @cindex wordlists tutorial
3260: @cindex search order, tutorial
1.48 anton 3261:
3262: The dictionary is not just a memory area that allows you to allocate
3263: memory with @code{allot}, it also contains the Forth words, arranged in
3264: several wordlists. When searching for a word in a wordlist,
3265: conceptually you start searching at the youngest and proceed towards
3266: older words (in reality most systems nowadays use hash-tables); i.e., if
3267: you define a word with the same name as an older word, the new word
3268: shadows the older word.
3269:
3270: Which wordlists are searched in which order is determined by the search
3271: order. You can display the search order with @code{order}. It displays
3272: first the search order, starting with the wordlist searched first, then
3273: it displays the wordlist that will contain newly defined words.
1.21 crook 3274:
1.48 anton 3275: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3276:
1.48 anton 3277: @example
3278: wordlist constant mywords
3279: @end example
1.21 crook 3280:
1.48 anton 3281: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3282: defined words (the @emph{current} wordlist):
1.21 crook 3283:
1.48 anton 3284: @example
3285: mywords set-current
3286: order
3287: @end example
1.26 crook 3288:
1.48 anton 3289: Gforth does not display a name for the wordlist in @code{mywords}
3290: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3291:
1.48 anton 3292: You can get the current wordlist with @code{get-current ( -- wid)}. If
3293: you want to put something into a specific wordlist without overall
3294: effect on the current wordlist, this typically looks like this:
1.21 crook 3295:
1.48 anton 3296: @example
3297: get-current mywords set-current ( wid )
3298: create someword
3299: ( wid ) set-current
3300: @end example
1.21 crook 3301:
1.48 anton 3302: You can write the search order with @code{set-order ( wid1 .. widn n --
3303: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3304: searched wordlist is topmost.
1.21 crook 3305:
1.48 anton 3306: @example
3307: get-order mywords swap 1+ set-order
3308: order
3309: @end example
1.21 crook 3310:
1.48 anton 3311: Yes, the order of wordlists in the output of @code{order} is reversed
3312: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3313:
1.141 anton 3314: @quotation Assignment
1.48 anton 3315: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3316: wordlist to the search order. Define @code{previous ( -- )}, which
3317: removes the first searched wordlist from the search order. Experiment
3318: with boundary conditions (you will see some crashes or situations that
3319: are hard or impossible to leave).
1.141 anton 3320: @end quotation
1.21 crook 3321:
1.48 anton 3322: The search order is a powerful foundation for providing features similar
3323: to Modula-2 modules and C++ namespaces. However, trying to modularize
3324: programs in this way has disadvantages for debugging and reuse/factoring
3325: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3326: though). These disadvantages are not so clear in other
1.82 anton 3327: languages/programming environments, because these languages are not so
1.48 anton 3328: strong in debugging and reuse.
1.21 crook 3329:
1.66 anton 3330: @c !! example
3331:
3332: Reference: @ref{Word Lists}.
1.21 crook 3333:
1.29 crook 3334: @c ******************************************************************
1.48 anton 3335: @node Introduction, Words, Tutorial, Top
1.29 crook 3336: @comment node-name, next, previous, up
3337: @chapter An Introduction to ANS Forth
3338: @cindex Forth - an introduction
1.21 crook 3339:
1.83 anton 3340: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3341: that it is slower-paced in its examples, but uses them to dive deep into
3342: explaining Forth internals (not covered by the Tutorial). Apart from
3343: that, this chapter covers far less material. It is suitable for reading
3344: without using a computer.
3345:
1.29 crook 3346: The primary purpose of this manual is to document Gforth. However, since
3347: Forth is not a widely-known language and there is a lack of up-to-date
3348: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3349: material. For other sources of Forth-related
3350: information, see @ref{Forth-related information}.
1.21 crook 3351:
1.29 crook 3352: The examples in this section should work on any ANS Forth; the
3353: output shown was produced using Gforth. Each example attempts to
3354: reproduce the exact output that Gforth produces. If you try out the
3355: examples (and you should), what you should type is shown @kbd{like this}
3356: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3357: that, where the example shows @key{RET} it means that you should
1.29 crook 3358: press the ``carriage return'' key. Unfortunately, some output formats for
3359: this manual cannot show the difference between @kbd{this} and
3360: @code{this} which will make trying out the examples harder (but not
3361: impossible).
1.21 crook 3362:
1.29 crook 3363: Forth is an unusual language. It provides an interactive development
3364: environment which includes both an interpreter and compiler. Forth
3365: programming style encourages you to break a problem down into many
3366: @cindex factoring
3367: small fragments (@dfn{factoring}), and then to develop and test each
3368: fragment interactively. Forth advocates assert that breaking the
3369: edit-compile-test cycle used by conventional programming languages can
3370: lead to great productivity improvements.
1.21 crook 3371:
1.29 crook 3372: @menu
1.67 anton 3373: * Introducing the Text Interpreter::
3374: * Stacks and Postfix notation::
3375: * Your first definition::
3376: * How does that work?::
3377: * Forth is written in Forth::
3378: * Review - elements of a Forth system::
3379: * Where to go next::
3380: * Exercises::
1.29 crook 3381: @end menu
1.21 crook 3382:
1.29 crook 3383: @comment ----------------------------------------------
3384: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3385: @section Introducing the Text Interpreter
3386: @cindex text interpreter
3387: @cindex outer interpreter
1.21 crook 3388:
1.30 anton 3389: @c IMO this is too detailed and the pace is too slow for
3390: @c an introduction. If you know German, take a look at
3391: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3392: @c to see how I do it - anton
3393:
1.44 crook 3394: @c nac-> Where I have accepted your comments 100% and modified the text
3395: @c accordingly, I have deleted your comments. Elsewhere I have added a
3396: @c response like this to attempt to rationalise what I have done. Of
3397: @c course, this is a very clumsy mechanism for something that would be
3398: @c done far more efficiently over a beer. Please delete any dialogue
3399: @c you consider closed.
3400:
1.29 crook 3401: When you invoke the Forth image, you will see a startup banner printed
3402: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3403: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3404: its command line interpreter, which is called the @dfn{Text Interpreter}
3405: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3406: about the text interpreter as you read through this chapter, for more
3407: detail @pxref{The Text Interpreter}).
1.21 crook 3408:
1.29 crook 3409: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3410: input. Type a number and press the @key{RET} key:
1.21 crook 3411:
1.26 crook 3412: @example
1.30 anton 3413: @kbd{45@key{RET}} ok
1.26 crook 3414: @end example
1.21 crook 3415:
1.29 crook 3416: Rather than give you a prompt to invite you to input something, the text
3417: interpreter prints a status message @i{after} it has processed a line
3418: of input. The status message in this case (``@code{ ok}'' followed by
3419: carriage-return) indicates that the text interpreter was able to process
3420: all of your input successfully. Now type something illegal:
3421:
3422: @example
1.30 anton 3423: @kbd{qwer341@key{RET}}
1.134 anton 3424: *the terminal*:2: Undefined word
3425: >>>qwer341<<<
3426: Backtrace:
3427: $2A95B42A20 throw
3428: $2A95B57FB8 no.extensions
1.29 crook 3429: @end example
1.23 crook 3430:
1.134 anton 3431: The exact text, other than the ``Undefined word'' may differ slightly
3432: on your system, but the effect is the same; when the text interpreter
1.29 crook 3433: detects an error, it discards any remaining text on a line, resets
1.134 anton 3434: certain internal state and prints an error message. For a detailed
3435: description of error messages see @ref{Error messages}.
1.23 crook 3436:
1.29 crook 3437: The text interpreter waits for you to press carriage-return, and then
3438: processes your input line. Starting at the beginning of the line, it
3439: breaks the line into groups of characters separated by spaces. For each
3440: group of characters in turn, it makes two attempts to do something:
1.23 crook 3441:
1.29 crook 3442: @itemize @bullet
3443: @item
1.44 crook 3444: @cindex name dictionary
1.29 crook 3445: It tries to treat it as a command. It does this by searching a @dfn{name
3446: dictionary}. If the group of characters matches an entry in the name
3447: dictionary, the name dictionary provides the text interpreter with
3448: information that allows the text interpreter perform some actions. In
3449: Forth jargon, we say that the group
3450: @cindex word
3451: @cindex definition
3452: @cindex execution token
3453: @cindex xt
3454: of characters names a @dfn{word}, that the dictionary search returns an
3455: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3456: word, and that the text interpreter executes the xt. Often, the terms
3457: @dfn{word} and @dfn{definition} are used interchangeably.
3458: @item
3459: If the text interpreter fails to find a match in the name dictionary, it
3460: tries to treat the group of characters as a number in the current number
3461: base (when you start up Forth, the current number base is base 10). If
3462: the group of characters legitimately represents a number, the text
3463: interpreter pushes the number onto a stack (we'll learn more about that
3464: in the next section).
3465: @end itemize
1.23 crook 3466:
1.29 crook 3467: If the text interpreter is unable to do either of these things with any
3468: group of characters, it discards the group of characters and the rest of
3469: the line, then prints an error message. If the text interpreter reaches
3470: the end of the line without error, it prints the status message ``@code{ ok}''
3471: followed by carriage-return.
1.21 crook 3472:
1.29 crook 3473: This is the simplest command we can give to the text interpreter:
1.23 crook 3474:
3475: @example
1.30 anton 3476: @key{RET} ok
1.23 crook 3477: @end example
1.21 crook 3478:
1.29 crook 3479: The text interpreter did everything we asked it to do (nothing) without
3480: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3481: command:
1.21 crook 3482:
1.23 crook 3483: @example
1.30 anton 3484: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3485: *the terminal*:3: Undefined word
3486: 12 dup >>>fred<<< dup
3487: Backtrace:
3488: $2A95B42A20 throw
3489: $2A95B57FB8 no.extensions
1.23 crook 3490: @end example
1.21 crook 3491:
1.29 crook 3492: When you press the carriage-return key, the text interpreter starts to
3493: work its way along the line:
1.21 crook 3494:
1.29 crook 3495: @itemize @bullet
3496: @item
3497: When it gets to the space after the @code{2}, it takes the group of
3498: characters @code{12} and looks them up in the name
3499: dictionary@footnote{We can't tell if it found them or not, but assume
3500: for now that it did not}. There is no match for this group of characters
3501: in the name dictionary, so it tries to treat them as a number. It is
3502: able to do this successfully, so it puts the number, 12, ``on the stack''
3503: (whatever that means).
3504: @item
3505: The text interpreter resumes scanning the line and gets the next group
3506: of characters, @code{dup}. It looks it up in the name dictionary and
3507: (you'll have to take my word for this) finds it, and executes the word
3508: @code{dup} (whatever that means).
3509: @item
3510: Once again, the text interpreter resumes scanning the line and gets the
3511: group of characters @code{fred}. It looks them up in the name
3512: dictionary, but can't find them. It tries to treat them as a number, but
3513: they don't represent any legal number.
3514: @end itemize
1.21 crook 3515:
1.29 crook 3516: At this point, the text interpreter gives up and prints an error
3517: message. The error message shows exactly how far the text interpreter
3518: got in processing the line. In particular, it shows that the text
3519: interpreter made no attempt to do anything with the final character
3520: group, @code{dup}, even though we have good reason to believe that the
3521: text interpreter would have no problem looking that word up and
3522: executing it a second time.
1.21 crook 3523:
3524:
1.29 crook 3525: @comment ----------------------------------------------
3526: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3527: @section Stacks, postfix notation and parameter passing
3528: @cindex text interpreter
3529: @cindex outer interpreter
1.21 crook 3530:
1.29 crook 3531: In procedural programming languages (like C and Pascal), the
3532: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3533: functions or procedures are called with @dfn{explicit parameters}. For
3534: example, in C we might write:
1.21 crook 3535:
1.23 crook 3536: @example
1.29 crook 3537: total = total + new_volume(length,height,depth);
1.23 crook 3538: @end example
1.21 crook 3539:
1.23 crook 3540: @noindent
1.29 crook 3541: where new_volume is a function-call to another piece of code, and total,
3542: length, height and depth are all variables. length, height and depth are
3543: parameters to the function-call.
1.21 crook 3544:
1.29 crook 3545: In Forth, the equivalent of the function or procedure is the
3546: @dfn{definition} and parameters are implicitly passed between
3547: definitions using a shared stack that is visible to the
3548: programmer. Although Forth does support variables, the existence of the
3549: stack means that they are used far less often than in most other
3550: programming languages. When the text interpreter encounters a number, it
3551: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3552: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3553: used for any operation is implied unambiguously by the operation being
3554: performed. The stack used for all integer operations is called the @dfn{data
3555: stack} and, since this is the stack used most commonly, references to
3556: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3557:
1.29 crook 3558: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3559:
1.23 crook 3560: @example
1.30 anton 3561: @kbd{1 2 3@key{RET}} ok
1.23 crook 3562: @end example
1.21 crook 3563:
1.29 crook 3564: Then this instructs the text interpreter to placed three numbers on the
3565: (data) stack. An analogy for the behaviour of the stack is to take a
3566: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3567: the table. The 3 was the last card onto the pile (``last-in'') and if
3568: you take a card off the pile then, unless you're prepared to fiddle a
3569: bit, the card that you take off will be the 3 (``first-out''). The
3570: number that will be first-out of the stack is called the @dfn{top of
3571: stack}, which
3572: @cindex TOS definition
3573: is often abbreviated to @dfn{TOS}.
1.21 crook 3574:
1.29 crook 3575: To understand how parameters are passed in Forth, consider the
3576: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3577: be surprised to learn that this definition performs addition. More
3578: precisely, it adds two number together and produces a result. Where does
3579: it get the two numbers from? It takes the top two numbers off the
3580: stack. Where does it place the result? On the stack. You can act-out the
3581: behaviour of @code{+} with your playing cards like this:
1.21 crook 3582:
3583: @itemize @bullet
3584: @item
1.29 crook 3585: Pick up two cards from the stack on the table
1.21 crook 3586: @item
1.29 crook 3587: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3588: numbers''
1.21 crook 3589: @item
1.29 crook 3590: Decide that the answer is 5
1.21 crook 3591: @item
1.29 crook 3592: Shuffle the two cards back into the pack and find a 5
1.21 crook 3593: @item
1.29 crook 3594: Put a 5 on the remaining ace that's on the table.
1.21 crook 3595: @end itemize
3596:
1.29 crook 3597: If you don't have a pack of cards handy but you do have Forth running,
3598: you can use the definition @code{.s} to show the current state of the stack,
3599: without affecting the stack. Type:
1.21 crook 3600:
3601: @example
1.124 anton 3602: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3603: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3604: @end example
3605:
1.124 anton 3606: The text interpreter looks up the word @code{clearstacks} and executes
3607: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3608: left on it by earlier examples. The text interpreter pushes each of the
3609: three numbers in turn onto the stack. Finally, the text interpreter
3610: looks up the word @code{.s} and executes it. The effect of executing
3611: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3612: followed by a list of all the items on the stack; the item on the far
3613: right-hand side is the TOS.
1.21 crook 3614:
1.29 crook 3615: You can now type:
1.21 crook 3616:
1.29 crook 3617: @example
1.30 anton 3618: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3619: @end example
1.21 crook 3620:
1.29 crook 3621: @noindent
3622: which is correct; there are now 2 items on the stack and the result of
3623: the addition is 5.
1.23 crook 3624:
1.29 crook 3625: If you're playing with cards, try doing a second addition: pick up the
3626: two cards, work out that their sum is 6, shuffle them into the pack,
3627: look for a 6 and place that on the table. You now have just one item on
3628: the stack. What happens if you try to do a third addition? Pick up the
3629: first card, pick up the second card -- ah! There is no second card. This
3630: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3631: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3632: Underflow or an Invalid Memory Address error).
1.23 crook 3633:
1.29 crook 3634: The opposite situation to a stack underflow is a @dfn{stack overflow},
3635: which simply accepts that there is a finite amount of storage space
3636: reserved for the stack. To stretch the playing card analogy, if you had
3637: enough packs of cards and you piled the cards up on the table, you would
3638: eventually be unable to add another card; you'd hit the ceiling. Gforth
3639: allows you to set the maximum size of the stacks. In general, the only
3640: time that you will get a stack overflow is because a definition has a
3641: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3642:
1.29 crook 3643: There's one final use for the playing card analogy. If you model your
3644: stack using a pack of playing cards, the maximum number of items on
3645: your stack will be 52 (I assume you didn't use the Joker). The maximum
3646: @i{value} of any item on the stack is 13 (the King). In fact, the only
3647: possible numbers are positive integer numbers 1 through 13; you can't
3648: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3649: think about some of the cards, you can accommodate different
3650: numbers. For example, you could think of the Jack as representing 0,
3651: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3652: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3653: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3654:
1.29 crook 3655: In that analogy, the limit was the amount of information that a single
3656: stack entry could hold, and Forth has a similar limit. In Forth, the
3657: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3658: implementation dependent and affects the maximum value that a stack
3659: entry can hold. A Standard Forth provides a cell size of at least
3660: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3661:
1.29 crook 3662: Forth does not do any type checking for you, so you are free to
3663: manipulate and combine stack items in any way you wish. A convenient way
3664: of treating stack items is as 2's complement signed integers, and that
3665: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3666:
1.29 crook 3667: @example
1.30 anton 3668: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3669: @end example
1.21 crook 3670:
1.29 crook 3671: If you use numbers and definitions like @code{+} in order to turn Forth
3672: into a great big pocket calculator, you will realise that it's rather
3673: different from a normal calculator. Rather than typing 2 + 3 = you had
3674: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3675: result). The terminology used to describe this difference is to say that
3676: your calculator uses @dfn{Infix Notation} (parameters and operators are
3677: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3678: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3679:
1.29 crook 3680: Whilst postfix notation might look confusing to begin with, it has
3681: several important advantages:
1.21 crook 3682:
1.23 crook 3683: @itemize @bullet
3684: @item
1.29 crook 3685: it is unambiguous
1.23 crook 3686: @item
1.29 crook 3687: it is more concise
1.23 crook 3688: @item
1.29 crook 3689: it fits naturally with a stack-based system
1.23 crook 3690: @end itemize
1.21 crook 3691:
1.29 crook 3692: To examine these claims in more detail, consider these sums:
1.21 crook 3693:
1.29 crook 3694: @example
3695: 6 + 5 * 4 =
3696: 4 * 5 + 6 =
3697: @end example
1.21 crook 3698:
1.29 crook 3699: If you're just learning maths or your maths is very rusty, you will
3700: probably come up with the answer 44 for the first and 26 for the
3701: second. If you are a bit of a whizz at maths you will remember the
3702: @i{convention} that multiplication takes precendence over addition, and
3703: you'd come up with the answer 26 both times. To explain the answer 26
3704: to someone who got the answer 44, you'd probably rewrite the first sum
3705: like this:
1.21 crook 3706:
1.29 crook 3707: @example
3708: 6 + (5 * 4) =
3709: @end example
1.21 crook 3710:
1.29 crook 3711: If what you really wanted was to perform the addition before the
3712: multiplication, you would have to use parentheses to force it.
1.21 crook 3713:
1.29 crook 3714: If you did the first two sums on a pocket calculator you would probably
3715: get the right answers, unless you were very cautious and entered them using
3716: these keystroke sequences:
1.21 crook 3717:
1.29 crook 3718: 6 + 5 = * 4 =
3719: 4 * 5 = + 6 =
1.21 crook 3720:
1.29 crook 3721: Postfix notation is unambiguous because the order that the operators
3722: are applied is always explicit; that also means that parentheses are
3723: never required. The operators are @i{active} (the act of quoting the
3724: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3725:
1.29 crook 3726: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3727: equivalent ways:
1.26 crook 3728:
3729: @example
1.29 crook 3730: 6 5 4 * + or:
3731: 5 4 * 6 +
1.26 crook 3732: @end example
1.23 crook 3733:
1.29 crook 3734: An important thing that you should notice about this notation is that
3735: the @i{order} of the numbers does not change; if you want to subtract
3736: 2 from 10 you type @code{10 2 -}.
1.1 anton 3737:
1.29 crook 3738: The reason that Forth uses postfix notation is very simple to explain: it
3739: makes the implementation extremely simple, and it follows naturally from
3740: using the stack as a mechanism for passing parameters. Another way of
3741: thinking about this is to realise that all Forth definitions are
3742: @i{active}; they execute as they are encountered by the text
3743: interpreter. The result of this is that the syntax of Forth is trivially
3744: simple.
1.1 anton 3745:
3746:
3747:
1.29 crook 3748: @comment ----------------------------------------------
3749: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3750: @section Your first Forth definition
3751: @cindex first definition
1.1 anton 3752:
1.29 crook 3753: Until now, the examples we've seen have been trivial; we've just been
3754: using Forth as a bigger-than-pocket calculator. Also, each calculation
3755: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3756: again@footnote{That's not quite true. If you press the up-arrow key on
3757: your keyboard you should be able to scroll back to any earlier command,
3758: edit it and re-enter it.} In this section we'll see how to add new
3759: words to Forth's vocabulary.
1.1 anton 3760:
1.29 crook 3761: The easiest way to create a new word is to use a @dfn{colon
3762: definition}. We'll define a few and try them out before worrying too
3763: much about how they work. Try typing in these examples; be careful to
3764: copy the spaces accurately:
1.1 anton 3765:
1.29 crook 3766: @example
3767: : add-two 2 + . ;
3768: : greet ." Hello and welcome" ;
3769: : demo 5 add-two ;
3770: @end example
1.1 anton 3771:
1.29 crook 3772: @noindent
3773: Now try them out:
1.1 anton 3774:
1.29 crook 3775: @example
1.30 anton 3776: @kbd{greet@key{RET}} Hello and welcome ok
3777: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3778: @kbd{4 add-two@key{RET}} 6 ok
3779: @kbd{demo@key{RET}} 7 ok
3780: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3781: @end example
1.1 anton 3782:
1.29 crook 3783: The first new thing that we've introduced here is the pair of words
3784: @code{:} and @code{;}. These are used to start and terminate a new
3785: definition, respectively. The first word after the @code{:} is the name
3786: for the new definition.
1.1 anton 3787:
1.29 crook 3788: As you can see from the examples, a definition is built up of words that
3789: have already been defined; Forth makes no distinction between
3790: definitions that existed when you started the system up, and those that
3791: you define yourself.
1.1 anton 3792:
1.29 crook 3793: The examples also introduce the words @code{.} (dot), @code{."}
3794: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3795: the stack and displays it. It's like @code{.s} except that it only
3796: displays the top item of the stack and it is destructive; after it has
3797: executed, the number is no longer on the stack. There is always one
3798: space printed after the number, and no spaces before it. Dot-quote
3799: defines a string (a sequence of characters) that will be printed when
3800: the word is executed. The string can contain any printable characters
3801: except @code{"}. A @code{"} has a special function; it is not a Forth
3802: word but it acts as a delimiter (the way that delimiters work is
3803: described in the next section). Finally, @code{dup} duplicates the value
3804: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3805:
1.29 crook 3806: We already know that the text interpreter searches through the
3807: dictionary to locate names. If you've followed the examples earlier, you
3808: will already have a definition called @code{add-two}. Lets try modifying
3809: it by typing in a new definition:
1.1 anton 3810:
1.29 crook 3811: @example
1.30 anton 3812: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3813: @end example
1.5 anton 3814:
1.29 crook 3815: Forth recognised that we were defining a word that already exists, and
3816: printed a message to warn us of that fact. Let's try out the new
3817: definition:
1.5 anton 3818:
1.29 crook 3819: @example
1.30 anton 3820: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3821: @end example
1.1 anton 3822:
1.29 crook 3823: @noindent
3824: All that we've actually done here, though, is to create a new
3825: definition, with a particular name. The fact that there was already a
3826: definition with the same name did not make any difference to the way
3827: that the new definition was created (except that Forth printed a warning
3828: message). The old definition of add-two still exists (try @code{demo}
3829: again to see that this is true). Any new definition will use the new
3830: definition of @code{add-two}, but old definitions continue to use the
3831: version that already existed at the time that they were @code{compiled}.
1.1 anton 3832:
1.29 crook 3833: Before you go on to the next section, try defining and redefining some
3834: words of your own.
1.1 anton 3835:
1.29 crook 3836: @comment ----------------------------------------------
3837: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3838: @section How does that work?
3839: @cindex parsing words
1.1 anton 3840:
1.30 anton 3841: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3842:
3843: @c Is it a good idea to talk about the interpretation semantics of a
3844: @c number? We don't have an xt to go along with it. - anton
3845:
3846: @c Now that I have eliminated execution semantics, I wonder if it would not
3847: @c be better to keep them (or add run-time semantics), to make it easier to
3848: @c explain what compilation semantics usually does. - anton
3849:
1.44 crook 3850: @c nac-> I removed the term ``default compilation sematics'' from the
3851: @c introductory chapter. Removing ``execution semantics'' was making
3852: @c everything simpler to explain, then I think the use of this term made
3853: @c everything more complex again. I replaced it with ``default
3854: @c semantics'' (which is used elsewhere in the manual) by which I mean
3855: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3856: @c flag set''.
3857:
3858: @c anton: I have eliminated default semantics (except in one place where it
3859: @c means "default interpretation and compilation semantics"), because it
3860: @c makes no sense in the presence of combined words. I reverted to
3861: @c "execution semantics" where necessary.
3862:
3863: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3864: @c section (and, unusually for me, I think I even made it shorter!). See
3865: @c what you think -- I know I have not addressed your primary concern
3866: @c that it is too heavy-going for an introduction. From what I understood
3867: @c of your course notes it looks as though they might be a good framework.
3868: @c Things that I've tried to capture here are some things that came as a
3869: @c great revelation here when I first understood them. Also, I like the
3870: @c fact that a very simple code example shows up almost all of the issues
3871: @c that you need to understand to see how Forth works. That's unique and
3872: @c worthwhile to emphasise.
3873:
1.83 anton 3874: @c anton: I think it's a good idea to present the details, especially those
3875: @c that you found to be a revelation, and probably the tutorial tries to be
3876: @c too superficial and does not get some of the things across that make
3877: @c Forth special. I do believe that most of the time these things should
3878: @c be discussed at the end of a section or in separate sections instead of
3879: @c in the middle of a section (e.g., the stuff you added in "User-defined
3880: @c defining words" leads in a completely different direction from the rest
3881: @c of the section).
3882:
1.29 crook 3883: Now we're going to take another look at the definition of @code{add-two}
3884: from the previous section. From our knowledge of the way that the text
3885: interpreter works, we would have expected this result when we tried to
3886: define @code{add-two}:
1.21 crook 3887:
1.29 crook 3888: @example
1.44 crook 3889: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3890: *the terminal*:4: Undefined word
3891: : >>>add-two<<< 2 + . ;
1.29 crook 3892: @end example
1.28 crook 3893:
1.29 crook 3894: The reason that this didn't happen is bound up in the way that @code{:}
3895: works. The word @code{:} does two special things. The first special
3896: thing that it does prevents the text interpreter from ever seeing the
3897: characters @code{add-two}. The text interpreter uses a variable called
3898: @cindex modifying >IN
1.44 crook 3899: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3900: input line. When it encounters the word @code{:} it behaves in exactly
3901: the same way as it does for any other word; it looks it up in the name
3902: dictionary, finds its xt and executes it. When @code{:} executes, it
3903: looks at the input buffer, finds the word @code{add-two} and advances the
3904: value of @code{>IN} to point past it. It then does some other stuff
3905: associated with creating the new definition (including creating an entry
3906: for @code{add-two} in the name dictionary). When the execution of @code{:}
3907: completes, control returns to the text interpreter, which is oblivious
3908: to the fact that it has been tricked into ignoring part of the input
3909: line.
1.21 crook 3910:
1.29 crook 3911: @cindex parsing words
3912: Words like @code{:} -- words that advance the value of @code{>IN} and so
3913: prevent the text interpreter from acting on the whole of the input line
3914: -- are called @dfn{parsing words}.
1.21 crook 3915:
1.29 crook 3916: @cindex @code{state} - effect on the text interpreter
3917: @cindex text interpreter - effect of state
3918: The second special thing that @code{:} does is change the value of a
3919: variable called @code{state}, which affects the way that the text
3920: interpreter behaves. When Gforth starts up, @code{state} has the value
3921: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3922: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3923: the text interpreter is said to be @dfn{compiling}.
3924:
3925: In this example, the text interpreter is compiling when it processes the
3926: string ``@code{2 + . ;}''. It still breaks the string down into
3927: character sequences in the same way. However, instead of pushing the
3928: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3929: into the definition of @code{add-two} that will make the number @code{2} get
3930: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3931: the behaviours of @code{+} and @code{.} are also compiled into the
3932: definition.
3933:
3934: One category of words don't get compiled. These so-called @dfn{immediate
3935: words} get executed (performed @i{now}) regardless of whether the text
3936: interpreter is interpreting or compiling. The word @code{;} is an
3937: immediate word. Rather than being compiled into the definition, it
3938: executes. Its effect is to terminate the current definition, which
3939: includes changing the value of @code{state} back to 0.
3940:
3941: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3942: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3943: definition.
1.28 crook 3944:
1.30 anton 3945: In Forth, every word or number can be described in terms of two
1.29 crook 3946: properties:
1.28 crook 3947:
3948: @itemize @bullet
3949: @item
1.29 crook 3950: @cindex interpretation semantics
1.44 crook 3951: Its @dfn{interpretation semantics} describe how it will behave when the
3952: text interpreter encounters it in @dfn{interpret} state. The
3953: interpretation semantics of a word are represented by an @dfn{execution
3954: token}.
1.28 crook 3955: @item
1.29 crook 3956: @cindex compilation semantics
1.44 crook 3957: Its @dfn{compilation semantics} describe how it will behave when the
3958: text interpreter encounters it in @dfn{compile} state. The compilation
3959: semantics of a word are represented in an implementation-dependent way;
3960: Gforth uses a @dfn{compilation token}.
1.29 crook 3961: @end itemize
3962:
3963: @noindent
3964: Numbers are always treated in a fixed way:
3965:
3966: @itemize @bullet
1.28 crook 3967: @item
1.44 crook 3968: When the number is @dfn{interpreted}, its behaviour is to push the
3969: number onto the stack.
1.28 crook 3970: @item
1.30 anton 3971: When the number is @dfn{compiled}, a piece of code is appended to the
3972: current definition that pushes the number when it runs. (In other words,
3973: the compilation semantics of a number are to postpone its interpretation
3974: semantics until the run-time of the definition that it is being compiled
3975: into.)
1.29 crook 3976: @end itemize
3977:
1.44 crook 3978: Words don't behave in such a regular way, but most have @i{default
3979: semantics} which means that they behave like this:
1.29 crook 3980:
3981: @itemize @bullet
1.28 crook 3982: @item
1.30 anton 3983: The @dfn{interpretation semantics} of the word are to do something useful.
3984: @item
1.29 crook 3985: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3986: @dfn{interpretation semantics} to the current definition (so that its
3987: run-time behaviour is to do something useful).
1.28 crook 3988: @end itemize
3989:
1.30 anton 3990: @cindex immediate words
1.44 crook 3991: The actual behaviour of any particular word can be controlled by using
3992: the words @code{immediate} and @code{compile-only} when the word is
3993: defined. These words set flags in the name dictionary entry of the most
3994: recently defined word, and these flags are retrieved by the text
3995: interpreter when it finds the word in the name dictionary.
3996:
3997: A word that is marked as @dfn{immediate} has compilation semantics that
3998: are identical to its interpretation semantics. In other words, it
3999: behaves like this:
1.29 crook 4000:
4001: @itemize @bullet
4002: @item
1.30 anton 4003: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4004: @item
1.30 anton 4005: The @dfn{compilation semantics} of the word are to do something useful
4006: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4007: @end itemize
1.28 crook 4008:
1.44 crook 4009: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4010: performing the interpretation semantics of the word directly; an attempt
4011: to do so will generate an error. It is never necessary to use
4012: @code{compile-only} (and it is not even part of ANS Forth, though it is
4013: provided by many implementations) but it is good etiquette to apply it
4014: to a word that will not behave correctly (and might have unexpected
4015: side-effects) in interpret state. For example, it is only legal to use
4016: the conditional word @code{IF} within a definition. If you forget this
4017: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4018: @code{compile-only} allows the text interpreter to generate a helpful
4019: error message rather than subjecting you to the consequences of your
4020: folly.
4021:
1.29 crook 4022: This example shows the difference between an immediate and a
4023: non-immediate word:
1.28 crook 4024:
1.29 crook 4025: @example
4026: : show-state state @@ . ;
4027: : show-state-now show-state ; immediate
4028: : word1 show-state ;
4029: : word2 show-state-now ;
1.28 crook 4030: @end example
1.23 crook 4031:
1.29 crook 4032: The word @code{immediate} after the definition of @code{show-state-now}
4033: makes that word an immediate word. These definitions introduce a new
4034: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4035: variable, and leaves it on the stack. Therefore, the behaviour of
4036: @code{show-state} is to print a number that represents the current value
4037: of @code{state}.
1.28 crook 4038:
1.29 crook 4039: When you execute @code{word1}, it prints the number 0, indicating that
4040: the system is interpreting. When the text interpreter compiled the
4041: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4042: compilation semantics are to append its interpretation semantics to the
1.29 crook 4043: current definition. When you execute @code{word1}, it performs the
1.30 anton 4044: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4045: (and therefore @code{show-state}) are executed, the system is
4046: interpreting.
1.28 crook 4047:
1.30 anton 4048: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4049: you should have seen the number -1 printed, followed by ``@code{
4050: ok}''. When the text interpreter compiled the definition of
4051: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4052: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4053: semantics. It is executed straight away (even before the text
4054: interpreter has moved on to process another group of characters; the
4055: @code{;} in this example). The effect of executing it are to display the
4056: value of @code{state} @i{at the time that the definition of}
4057: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4058: system is compiling at this time. If you execute @code{word2} it does
4059: nothing at all.
1.28 crook 4060:
1.29 crook 4061: @cindex @code{."}, how it works
4062: Before leaving the subject of immediate words, consider the behaviour of
4063: @code{."} in the definition of @code{greet}, in the previous
4064: section. This word is both a parsing word and an immediate word. Notice
4065: that there is a space between @code{."} and the start of the text
4066: @code{Hello and welcome}, but that there is no space between the last
4067: letter of @code{welcome} and the @code{"} character. The reason for this
4068: is that @code{."} is a Forth word; it must have a space after it so that
4069: the text interpreter can identify it. The @code{"} is not a Forth word;
4070: it is a @dfn{delimiter}. The examples earlier show that, when the string
4071: is displayed, there is neither a space before the @code{H} nor after the
4072: @code{e}. Since @code{."} is an immediate word, it executes at the time
4073: that @code{greet} is defined. When it executes, its behaviour is to
4074: search forward in the input line looking for the delimiter. When it
4075: finds the delimiter, it updates @code{>IN} to point past the
4076: delimiter. It also compiles some magic code into the definition of
4077: @code{greet}; the xt of a run-time routine that prints a text string. It
4078: compiles the string @code{Hello and welcome} into memory so that it is
4079: available to be printed later. When the text interpreter gains control,
4080: the next word it finds in the input stream is @code{;} and so it
4081: terminates the definition of @code{greet}.
1.28 crook 4082:
4083:
4084: @comment ----------------------------------------------
1.29 crook 4085: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4086: @section Forth is written in Forth
4087: @cindex structure of Forth programs
4088:
4089: When you start up a Forth compiler, a large number of definitions
4090: already exist. In Forth, you develop a new application using bottom-up
4091: programming techniques to create new definitions that are defined in
4092: terms of existing definitions. As you create each definition you can
4093: test and debug it interactively.
4094:
4095: If you have tried out the examples in this section, you will probably
4096: have typed them in by hand; when you leave Gforth, your definitions will
4097: be lost. You can avoid this by using a text editor to enter Forth source
4098: code into a file, and then loading code from the file using
1.49 anton 4099: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4100: processed by the text interpreter, just as though you had typed it in by
4101: hand@footnote{Actually, there are some subtle differences -- see
4102: @ref{The Text Interpreter}.}.
4103:
4104: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4105: files for program entry (@pxref{Blocks}).
1.28 crook 4106:
1.29 crook 4107: In common with many, if not most, Forth compilers, most of Gforth is
4108: actually written in Forth. All of the @file{.fs} files in the
4109: installation directory@footnote{For example,
1.30 anton 4110: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4111: study to see examples of Forth programming.
1.28 crook 4112:
1.29 crook 4113: Gforth maintains a history file that records every line that you type to
4114: the text interpreter. This file is preserved between sessions, and is
4115: used to provide a command-line recall facility. If you enter long
4116: definitions by hand, you can use a text editor to paste them out of the
4117: history file into a Forth source file for reuse at a later time
1.49 anton 4118: (for more information @pxref{Command-line editing}).
1.28 crook 4119:
4120:
4121: @comment ----------------------------------------------
1.29 crook 4122: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4123: @section Review - elements of a Forth system
4124: @cindex elements of a Forth system
1.28 crook 4125:
1.29 crook 4126: To summarise this chapter:
1.28 crook 4127:
4128: @itemize @bullet
4129: @item
1.29 crook 4130: Forth programs use @dfn{factoring} to break a problem down into small
4131: fragments called @dfn{words} or @dfn{definitions}.
4132: @item
4133: Forth program development is an interactive process.
4134: @item
4135: The main command loop that accepts input, and controls both
4136: interpretation and compilation, is called the @dfn{text interpreter}
4137: (also known as the @dfn{outer interpreter}).
4138: @item
4139: Forth has a very simple syntax, consisting of words and numbers
4140: separated by spaces or carriage-return characters. Any additional syntax
4141: is imposed by @dfn{parsing words}.
4142: @item
4143: Forth uses a stack to pass parameters between words. As a result, it
4144: uses postfix notation.
4145: @item
4146: To use a word that has previously been defined, the text interpreter
4147: searches for the word in the @dfn{name dictionary}.
4148: @item
1.30 anton 4149: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4150: @item
1.29 crook 4151: The text interpreter uses the value of @code{state} to select between
4152: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4153: semantics} of a word that it encounters.
1.28 crook 4154: @item
1.30 anton 4155: The relationship between the @dfn{interpretation semantics} and
4156: @dfn{compilation semantics} for a word
1.29 crook 4157: depend upon the way in which the word was defined (for example, whether
4158: it is an @dfn{immediate} word).
1.28 crook 4159: @item
1.29 crook 4160: Forth definitions can be implemented in Forth (called @dfn{high-level
4161: definitions}) or in some other way (usually a lower-level language and
4162: as a result often called @dfn{low-level definitions}, @dfn{code
4163: definitions} or @dfn{primitives}).
1.28 crook 4164: @item
1.29 crook 4165: Many Forth systems are implemented mainly in Forth.
1.28 crook 4166: @end itemize
4167:
4168:
1.29 crook 4169: @comment ----------------------------------------------
1.48 anton 4170: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4171: @section Where To Go Next
4172: @cindex where to go next
1.28 crook 4173:
1.29 crook 4174: Amazing as it may seem, if you have read (and understood) this far, you
4175: know almost all the fundamentals about the inner workings of a Forth
4176: system. You certainly know enough to be able to read and understand the
4177: rest of this manual and the ANS Forth document, to learn more about the
4178: facilities that Forth in general and Gforth in particular provide. Even
4179: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4180: However, that's not a good idea just yet... better to try writing some
1.29 crook 4181: programs in Gforth.
1.28 crook 4182:
1.29 crook 4183: Forth has such a rich vocabulary that it can be hard to know where to
4184: start in learning it. This section suggests a few sets of words that are
4185: enough to write small but useful programs. Use the word index in this
4186: document to learn more about each word, then try it out and try to write
4187: small definitions using it. Start by experimenting with these words:
1.28 crook 4188:
4189: @itemize @bullet
4190: @item
1.29 crook 4191: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4192: @item
4193: Comparison: @code{MIN MAX =}
4194: @item
4195: Logic: @code{AND OR XOR NOT}
4196: @item
4197: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4198: @item
1.29 crook 4199: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4200: @item
1.29 crook 4201: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4202: @item
1.29 crook 4203: Defining words: @code{: ; CREATE}
1.28 crook 4204: @item
1.29 crook 4205: Memory allocation words: @code{ALLOT ,}
1.28 crook 4206: @item
1.29 crook 4207: Tools: @code{SEE WORDS .S MARKER}
4208: @end itemize
4209:
4210: When you have mastered those, go on to:
4211:
4212: @itemize @bullet
1.28 crook 4213: @item
1.29 crook 4214: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4215: @item
1.29 crook 4216: Memory access: @code{@@ !}
1.28 crook 4217: @end itemize
1.23 crook 4218:
1.29 crook 4219: When you have mastered these, there's nothing for it but to read through
4220: the whole of this manual and find out what you've missed.
4221:
4222: @comment ----------------------------------------------
1.48 anton 4223: @node Exercises, , Where to go next, Introduction
1.29 crook 4224: @section Exercises
4225: @cindex exercises
4226:
4227: TODO: provide a set of programming excercises linked into the stuff done
4228: already and into other sections of the manual. Provide solutions to all
4229: the exercises in a .fs file in the distribution.
4230:
4231: @c Get some inspiration from Starting Forth and Kelly&Spies.
4232:
4233: @c excercises:
4234: @c 1. take inches and convert to feet and inches.
4235: @c 2. take temperature and convert from fahrenheight to celcius;
4236: @c may need to care about symmetric vs floored??
4237: @c 3. take input line and do character substitution
4238: @c to encipher or decipher
4239: @c 4. as above but work on a file for in and out
4240: @c 5. take input line and convert to pig-latin
4241: @c
4242: @c thing of sets of things to exercise then come up with
4243: @c problems that need those things.
4244:
4245:
1.26 crook 4246: @c ******************************************************************
1.29 crook 4247: @node Words, Error messages, Introduction, Top
1.1 anton 4248: @chapter Forth Words
1.26 crook 4249: @cindex words
1.1 anton 4250:
4251: @menu
4252: * Notation::
1.65 anton 4253: * Case insensitivity::
4254: * Comments::
4255: * Boolean Flags::
1.1 anton 4256: * Arithmetic::
4257: * Stack Manipulation::
1.5 anton 4258: * Memory::
1.1 anton 4259: * Control Structures::
4260: * Defining Words::
1.65 anton 4261: * Interpretation and Compilation Semantics::
1.47 crook 4262: * Tokens for Words::
1.81 anton 4263: * Compiling words::
1.65 anton 4264: * The Text Interpreter::
1.111 anton 4265: * The Input Stream::
1.65 anton 4266: * Word Lists::
4267: * Environmental Queries::
1.12 anton 4268: * Files::
4269: * Blocks::
4270: * Other I/O::
1.121 anton 4271: * OS command line arguments::
1.78 anton 4272: * Locals::
4273: * Structures::
4274: * Object-oriented Forth::
1.12 anton 4275: * Programming Tools::
1.150 anton 4276: * C Interface::
1.12 anton 4277: * Assembler and Code Words::
4278: * Threading Words::
1.65 anton 4279: * Passing Commands to the OS::
4280: * Keeping track of Time::
4281: * Miscellaneous Words::
1.1 anton 4282: @end menu
4283:
1.65 anton 4284: @node Notation, Case insensitivity, Words, Words
1.1 anton 4285: @section Notation
4286: @cindex notation of glossary entries
4287: @cindex format of glossary entries
4288: @cindex glossary notation format
4289: @cindex word glossary entry format
4290:
4291: The Forth words are described in this section in the glossary notation
1.67 anton 4292: that has become a de-facto standard for Forth texts:
1.1 anton 4293:
4294: @format
1.29 crook 4295: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4296: @end format
1.29 crook 4297: @i{Description}
1.1 anton 4298:
4299: @table @var
4300: @item word
1.28 crook 4301: The name of the word.
1.1 anton 4302:
4303: @item Stack effect
4304: @cindex stack effect
1.29 crook 4305: The stack effect is written in the notation @code{@i{before} --
4306: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4307: stack entries before and after the execution of the word. The rest of
4308: the stack is not touched by the word. The top of stack is rightmost,
4309: i.e., a stack sequence is written as it is typed in. Note that Gforth
4310: uses a separate floating point stack, but a unified stack
1.29 crook 4311: notation. Also, return stack effects are not shown in @i{stack
4312: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4313: the type and/or the function of the item. See below for a discussion of
4314: the types.
4315:
4316: All words have two stack effects: A compile-time stack effect and a
4317: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4318: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4319: this standard behaviour, or the word does other unusual things at
4320: compile time, both stack effects are shown; otherwise only the run-time
4321: stack effect is shown.
4322:
4323: @cindex pronounciation of words
4324: @item pronunciation
4325: How the word is pronounced.
4326:
4327: @cindex wordset
1.67 anton 4328: @cindex environment wordset
1.1 anton 4329: @item wordset
1.21 crook 4330: The ANS Forth standard is divided into several word sets. A standard
4331: system need not support all of them. Therefore, in theory, the fewer
4332: word sets your program uses the more portable it will be. However, we
4333: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4334: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4335: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4336: describes words that will work in future releases of Gforth;
4337: @code{gforth-internal} words are more volatile. Environmental query
4338: strings are also displayed like words; you can recognize them by the
1.21 crook 4339: @code{environment} in the word set field.
1.1 anton 4340:
4341: @item Description
4342: A description of the behaviour of the word.
4343: @end table
4344:
4345: @cindex types of stack items
4346: @cindex stack item types
4347: The type of a stack item is specified by the character(s) the name
4348: starts with:
4349:
4350: @table @code
4351: @item f
4352: @cindex @code{f}, stack item type
4353: Boolean flags, i.e. @code{false} or @code{true}.
4354: @item c
4355: @cindex @code{c}, stack item type
4356: Char
4357: @item w
4358: @cindex @code{w}, stack item type
4359: Cell, can contain an integer or an address
4360: @item n
4361: @cindex @code{n}, stack item type
4362: signed integer
4363: @item u
4364: @cindex @code{u}, stack item type
4365: unsigned integer
4366: @item d
4367: @cindex @code{d}, stack item type
4368: double sized signed integer
4369: @item ud
4370: @cindex @code{ud}, stack item type
4371: double sized unsigned integer
4372: @item r
4373: @cindex @code{r}, stack item type
4374: Float (on the FP stack)
1.21 crook 4375: @item a-
1.1 anton 4376: @cindex @code{a_}, stack item type
4377: Cell-aligned address
1.21 crook 4378: @item c-
1.1 anton 4379: @cindex @code{c_}, stack item type
4380: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4381: @item f-
1.1 anton 4382: @cindex @code{f_}, stack item type
4383: Float-aligned address
1.21 crook 4384: @item df-
1.1 anton 4385: @cindex @code{df_}, stack item type
4386: Address aligned for IEEE double precision float
1.21 crook 4387: @item sf-
1.1 anton 4388: @cindex @code{sf_}, stack item type
4389: Address aligned for IEEE single precision float
4390: @item xt
4391: @cindex @code{xt}, stack item type
4392: Execution token, same size as Cell
4393: @item wid
4394: @cindex @code{wid}, stack item type
1.21 crook 4395: Word list ID, same size as Cell
1.68 anton 4396: @item ior, wior
4397: @cindex ior type description
4398: @cindex wior type description
4399: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4400: @item f83name
4401: @cindex @code{f83name}, stack item type
4402: Pointer to a name structure
4403: @item "
4404: @cindex @code{"}, stack item type
1.12 anton 4405: string in the input stream (not on the stack). The terminating character
4406: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4407: quotes.
4408: @end table
4409:
1.65 anton 4410: @comment ----------------------------------------------
4411: @node Case insensitivity, Comments, Notation, Words
4412: @section Case insensitivity
4413: @cindex case sensitivity
4414: @cindex upper and lower case
4415:
4416: Gforth is case-insensitive; you can enter definitions and invoke
4417: Standard words using upper, lower or mixed case (however,
4418: @pxref{core-idef, Implementation-defined options, Implementation-defined
4419: options}).
4420:
4421: ANS Forth only @i{requires} implementations to recognise Standard words
4422: when they are typed entirely in upper case. Therefore, a Standard
4423: program must use upper case for all Standard words. You can use whatever
4424: case you like for words that you define, but in a Standard program you
4425: have to use the words in the same case that you defined them.
4426:
4427: Gforth supports case sensitivity through @code{table}s (case-sensitive
4428: wordlists, @pxref{Word Lists}).
4429:
4430: Two people have asked how to convert Gforth to be case-sensitive; while
4431: we think this is a bad idea, you can change all wordlists into tables
4432: like this:
4433:
4434: @example
4435: ' table-find forth-wordlist wordlist-map @ !
4436: @end example
4437:
4438: Note that you now have to type the predefined words in the same case
4439: that we defined them, which are varying. You may want to convert them
4440: to your favourite case before doing this operation (I won't explain how,
4441: because if you are even contemplating doing this, you'd better have
4442: enough knowledge of Forth systems to know this already).
4443:
4444: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4445: @section Comments
1.26 crook 4446: @cindex comments
1.21 crook 4447:
1.29 crook 4448: Forth supports two styles of comment; the traditional @i{in-line} comment,
4449: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4450:
1.44 crook 4451:
1.23 crook 4452: doc-(
1.21 crook 4453: doc-\
1.23 crook 4454: doc-\G
1.21 crook 4455:
1.44 crook 4456:
1.21 crook 4457: @node Boolean Flags, Arithmetic, Comments, Words
4458: @section Boolean Flags
1.26 crook 4459: @cindex Boolean flags
1.21 crook 4460:
4461: A Boolean flag is cell-sized. A cell with all bits clear represents the
4462: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4463: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4464: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4465: @c on and off to Memory?
4466: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4467:
1.21 crook 4468: doc-true
4469: doc-false
1.29 crook 4470: doc-on
4471: doc-off
1.21 crook 4472:
1.44 crook 4473:
1.21 crook 4474: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4475: @section Arithmetic
4476: @cindex arithmetic words
4477:
4478: @cindex division with potentially negative operands
4479: Forth arithmetic is not checked, i.e., you will not hear about integer
4480: overflow on addition or multiplication, you may hear about division by
4481: zero if you are lucky. The operator is written after the operands, but
4482: the operands are still in the original order. I.e., the infix @code{2-1}
4483: corresponds to @code{2 1 -}. Forth offers a variety of division
4484: operators. If you perform division with potentially negative operands,
4485: you do not want to use @code{/} or @code{/mod} with its undefined
4486: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4487: former, @pxref{Mixed precision}).
1.26 crook 4488: @comment TODO discuss the different division forms and the std approach
1.1 anton 4489:
4490: @menu
4491: * Single precision::
1.67 anton 4492: * Double precision:: Double-cell integer arithmetic
1.1 anton 4493: * Bitwise operations::
1.67 anton 4494: * Numeric comparison::
1.29 crook 4495: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4496: * Floating Point::
4497: @end menu
4498:
1.67 anton 4499: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4500: @subsection Single precision
4501: @cindex single precision arithmetic words
4502:
1.67 anton 4503: @c !! cell undefined
4504:
4505: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4506: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4507: treat them. For the rules used by the text interpreter for recognising
4508: single-precision integers see @ref{Number Conversion}.
1.21 crook 4509:
1.67 anton 4510: These words are all defined for signed operands, but some of them also
4511: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4512: @code{*}.
1.44 crook 4513:
1.1 anton 4514: doc-+
1.21 crook 4515: doc-1+
1.128 anton 4516: doc-under+
1.1 anton 4517: doc--
1.21 crook 4518: doc-1-
1.1 anton 4519: doc-*
4520: doc-/
4521: doc-mod
4522: doc-/mod
4523: doc-negate
4524: doc-abs
4525: doc-min
4526: doc-max
1.27 crook 4527: doc-floored
1.1 anton 4528:
1.44 crook 4529:
1.67 anton 4530: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4531: @subsection Double precision
4532: @cindex double precision arithmetic words
4533:
1.49 anton 4534: For the rules used by the text interpreter for
4535: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4536:
4537: A double precision number is represented by a cell pair, with the most
1.67 anton 4538: significant cell at the TOS. It is trivial to convert an unsigned single
4539: to a double: simply push a @code{0} onto the TOS. Since numbers are
4540: represented by Gforth using 2's complement arithmetic, converting a
4541: signed single to a (signed) double requires sign-extension across the
4542: most significant cell. This can be achieved using @code{s>d}. The moral
4543: of the story is that you cannot convert a number without knowing whether
4544: it represents an unsigned or a signed number.
1.21 crook 4545:
1.67 anton 4546: These words are all defined for signed operands, but some of them also
4547: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4548:
1.21 crook 4549: doc-s>d
1.67 anton 4550: doc-d>s
1.21 crook 4551: doc-d+
4552: doc-d-
4553: doc-dnegate
4554: doc-dabs
4555: doc-dmin
4556: doc-dmax
4557:
1.44 crook 4558:
1.67 anton 4559: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4560: @subsection Bitwise operations
4561: @cindex bitwise operation words
4562:
4563:
4564: doc-and
4565: doc-or
4566: doc-xor
4567: doc-invert
4568: doc-lshift
4569: doc-rshift
4570: doc-2*
4571: doc-d2*
4572: doc-2/
4573: doc-d2/
4574:
4575:
4576: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4577: @subsection Numeric comparison
4578: @cindex numeric comparison words
4579:
1.67 anton 4580: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4581: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4582:
1.28 crook 4583: doc-<
4584: doc-<=
4585: doc-<>
4586: doc-=
4587: doc->
4588: doc->=
4589:
1.21 crook 4590: doc-0<
1.23 crook 4591: doc-0<=
1.21 crook 4592: doc-0<>
4593: doc-0=
1.23 crook 4594: doc-0>
4595: doc-0>=
1.28 crook 4596:
4597: doc-u<
4598: doc-u<=
1.44 crook 4599: @c u<> and u= exist but are the same as <> and =
1.31 anton 4600: @c doc-u<>
4601: @c doc-u=
1.28 crook 4602: doc-u>
4603: doc-u>=
4604:
4605: doc-within
4606:
4607: doc-d<
4608: doc-d<=
4609: doc-d<>
4610: doc-d=
4611: doc-d>
4612: doc-d>=
1.23 crook 4613:
1.21 crook 4614: doc-d0<
1.23 crook 4615: doc-d0<=
4616: doc-d0<>
1.21 crook 4617: doc-d0=
1.23 crook 4618: doc-d0>
4619: doc-d0>=
4620:
1.21 crook 4621: doc-du<
1.28 crook 4622: doc-du<=
1.44 crook 4623: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4624: @c doc-du<>
4625: @c doc-du=
1.28 crook 4626: doc-du>
4627: doc-du>=
1.1 anton 4628:
1.44 crook 4629:
1.21 crook 4630: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4631: @subsection Mixed precision
4632: @cindex mixed precision arithmetic words
4633:
1.44 crook 4634:
1.1 anton 4635: doc-m+
4636: doc-*/
4637: doc-*/mod
4638: doc-m*
4639: doc-um*
4640: doc-m*/
4641: doc-um/mod
4642: doc-fm/mod
4643: doc-sm/rem
4644:
1.44 crook 4645:
1.21 crook 4646: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4647: @subsection Floating Point
4648: @cindex floating point arithmetic words
4649:
1.49 anton 4650: For the rules used by the text interpreter for
4651: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4652:
1.67 anton 4653: Gforth has a separate floating point stack, but the documentation uses
4654: the unified notation.@footnote{It's easy to generate the separate
4655: notation from that by just separating the floating-point numbers out:
4656: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4657: r3 )}.}
1.1 anton 4658:
4659: @cindex floating-point arithmetic, pitfalls
4660: Floating point numbers have a number of unpleasant surprises for the
4661: unwary (e.g., floating point addition is not associative) and even a few
4662: for the wary. You should not use them unless you know what you are doing
4663: or you don't care that the results you get are totally bogus. If you
4664: want to learn about the problems of floating point numbers (and how to
1.66 anton 4665: avoid them), you might start with @cite{David Goldberg,
4666: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4667: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4668: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4669:
1.44 crook 4670:
1.21 crook 4671: doc-d>f
4672: doc-f>d
1.1 anton 4673: doc-f+
4674: doc-f-
4675: doc-f*
4676: doc-f/
4677: doc-fnegate
4678: doc-fabs
4679: doc-fmax
4680: doc-fmin
4681: doc-floor
4682: doc-fround
4683: doc-f**
4684: doc-fsqrt
4685: doc-fexp
4686: doc-fexpm1
4687: doc-fln
4688: doc-flnp1
4689: doc-flog
4690: doc-falog
1.32 anton 4691: doc-f2*
4692: doc-f2/
4693: doc-1/f
4694: doc-precision
4695: doc-set-precision
4696:
4697: @cindex angles in trigonometric operations
4698: @cindex trigonometric operations
4699: Angles in floating point operations are given in radians (a full circle
4700: has 2 pi radians).
4701:
1.1 anton 4702: doc-fsin
4703: doc-fcos
4704: doc-fsincos
4705: doc-ftan
4706: doc-fasin
4707: doc-facos
4708: doc-fatan
4709: doc-fatan2
4710: doc-fsinh
4711: doc-fcosh
4712: doc-ftanh
4713: doc-fasinh
4714: doc-facosh
4715: doc-fatanh
1.21 crook 4716: doc-pi
1.28 crook 4717:
1.32 anton 4718: @cindex equality of floats
4719: @cindex floating-point comparisons
1.31 anton 4720: One particular problem with floating-point arithmetic is that comparison
4721: for equality often fails when you would expect it to succeed. For this
4722: reason approximate equality is often preferred (but you still have to
1.67 anton 4723: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4724: differently from what you might expect. The comparison words are:
1.31 anton 4725:
4726: doc-f~rel
4727: doc-f~abs
1.68 anton 4728: doc-f~
1.31 anton 4729: doc-f=
4730: doc-f<>
4731:
4732: doc-f<
4733: doc-f<=
4734: doc-f>
4735: doc-f>=
4736:
1.21 crook 4737: doc-f0<
1.28 crook 4738: doc-f0<=
4739: doc-f0<>
1.21 crook 4740: doc-f0=
1.28 crook 4741: doc-f0>
4742: doc-f0>=
4743:
1.1 anton 4744:
4745: @node Stack Manipulation, Memory, Arithmetic, Words
4746: @section Stack Manipulation
4747: @cindex stack manipulation words
4748:
4749: @cindex floating-point stack in the standard
1.21 crook 4750: Gforth maintains a number of separate stacks:
4751:
1.29 crook 4752: @cindex data stack
4753: @cindex parameter stack
1.21 crook 4754: @itemize @bullet
4755: @item
1.29 crook 4756: A data stack (also known as the @dfn{parameter stack}) -- for
4757: characters, cells, addresses, and double cells.
1.21 crook 4758:
1.29 crook 4759: @cindex floating-point stack
1.21 crook 4760: @item
1.44 crook 4761: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4762:
1.29 crook 4763: @cindex return stack
1.21 crook 4764: @item
1.44 crook 4765: A return stack -- for holding the return addresses of colon
1.32 anton 4766: definitions and other (non-FP) data.
1.21 crook 4767:
1.29 crook 4768: @cindex locals stack
1.21 crook 4769: @item
1.44 crook 4770: A locals stack -- for holding local variables.
1.21 crook 4771: @end itemize
4772:
1.1 anton 4773: @menu
4774: * Data stack::
4775: * Floating point stack::
4776: * Return stack::
4777: * Locals stack::
4778: * Stack pointer manipulation::
4779: @end menu
4780:
4781: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4782: @subsection Data stack
4783: @cindex data stack manipulation words
4784: @cindex stack manipulations words, data stack
4785:
1.44 crook 4786:
1.1 anton 4787: doc-drop
4788: doc-nip
4789: doc-dup
4790: doc-over
4791: doc-tuck
4792: doc-swap
1.21 crook 4793: doc-pick
1.1 anton 4794: doc-rot
4795: doc--rot
4796: doc-?dup
4797: doc-roll
4798: doc-2drop
4799: doc-2nip
4800: doc-2dup
4801: doc-2over
4802: doc-2tuck
4803: doc-2swap
4804: doc-2rot
4805:
1.44 crook 4806:
1.1 anton 4807: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4808: @subsection Floating point stack
4809: @cindex floating-point stack manipulation words
4810: @cindex stack manipulation words, floating-point stack
4811:
1.32 anton 4812: Whilst every sane Forth has a separate floating-point stack, it is not
4813: strictly required; an ANS Forth system could theoretically keep
4814: floating-point numbers on the data stack. As an additional difficulty,
4815: you don't know how many cells a floating-point number takes. It is
4816: reportedly possible to write words in a way that they work also for a
4817: unified stack model, but we do not recommend trying it. Instead, just
4818: say that your program has an environmental dependency on a separate
4819: floating-point stack.
4820:
4821: doc-floating-stack
4822:
1.1 anton 4823: doc-fdrop
4824: doc-fnip
4825: doc-fdup
4826: doc-fover
4827: doc-ftuck
4828: doc-fswap
1.21 crook 4829: doc-fpick
1.1 anton 4830: doc-frot
4831:
1.44 crook 4832:
1.1 anton 4833: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4834: @subsection Return stack
4835: @cindex return stack manipulation words
4836: @cindex stack manipulation words, return stack
4837:
1.32 anton 4838: @cindex return stack and locals
4839: @cindex locals and return stack
4840: A Forth system is allowed to keep local variables on the
4841: return stack. This is reasonable, as local variables usually eliminate
4842: the need to use the return stack explicitly. So, if you want to produce
4843: a standard compliant program and you are using local variables in a
4844: word, forget about return stack manipulations in that word (refer to the
4845: standard document for the exact rules).
4846:
1.1 anton 4847: doc->r
4848: doc-r>
4849: doc-r@
4850: doc-rdrop
4851: doc-2>r
4852: doc-2r>
4853: doc-2r@
4854: doc-2rdrop
4855:
1.44 crook 4856:
1.1 anton 4857: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4858: @subsection Locals stack
4859:
1.78 anton 4860: Gforth uses an extra locals stack. It is described, along with the
4861: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4862:
1.1 anton 4863: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4864: @subsection Stack pointer manipulation
4865: @cindex stack pointer manipulation words
4866:
1.44 crook 4867: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4868: doc-sp0
1.1 anton 4869: doc-sp@
4870: doc-sp!
1.21 crook 4871: doc-fp0
1.1 anton 4872: doc-fp@
4873: doc-fp!
1.21 crook 4874: doc-rp0
1.1 anton 4875: doc-rp@
4876: doc-rp!
1.21 crook 4877: doc-lp0
1.1 anton 4878: doc-lp@
4879: doc-lp!
4880:
1.44 crook 4881:
1.1 anton 4882: @node Memory, Control Structures, Stack Manipulation, Words
4883: @section Memory
1.26 crook 4884: @cindex memory words
1.1 anton 4885:
1.32 anton 4886: @menu
4887: * Memory model::
4888: * Dictionary allocation::
4889: * Heap Allocation::
4890: * Memory Access::
4891: * Address arithmetic::
4892: * Memory Blocks::
4893: @end menu
4894:
1.67 anton 4895: In addition to the standard Forth memory allocation words, there is also
4896: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4897: garbage collector}.
4898:
1.32 anton 4899: @node Memory model, Dictionary allocation, Memory, Memory
4900: @subsection ANS Forth and Gforth memory models
4901:
4902: @c The ANS Forth description is a mess (e.g., is the heap part of
4903: @c the dictionary?), so let's not stick to closely with it.
4904:
1.67 anton 4905: ANS Forth considers a Forth system as consisting of several address
4906: spaces, of which only @dfn{data space} is managed and accessible with
4907: the memory words. Memory not necessarily in data space includes the
4908: stacks, the code (called code space) and the headers (called name
4909: space). In Gforth everything is in data space, but the code for the
4910: primitives is usually read-only.
1.32 anton 4911:
4912: Data space is divided into a number of areas: The (data space portion of
4913: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4914: refer to the search data structure embodied in word lists and headers,
4915: because it is used for looking up names, just as you would in a
4916: conventional dictionary.}, the heap, and a number of system-allocated
4917: buffers.
4918:
1.68 anton 4919: @cindex address arithmetic restrictions, ANS vs. Gforth
4920: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4921: In ANS Forth data space is also divided into contiguous regions. You
4922: can only use address arithmetic within a contiguous region, not between
4923: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4924: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4925: allocation}).
4926:
4927: Gforth provides one big address space, and address arithmetic can be
4928: performed between any addresses. However, in the dictionary headers or
4929: code are interleaved with data, so almost the only contiguous data space
4930: regions there are those described by ANS Forth as contiguous; but you
4931: can be sure that the dictionary is allocated towards increasing
4932: addresses even between contiguous regions. The memory order of
4933: allocations in the heap is platform-dependent (and possibly different
4934: from one run to the next).
4935:
1.27 crook 4936:
1.32 anton 4937: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4938: @subsection Dictionary allocation
1.27 crook 4939: @cindex reserving data space
4940: @cindex data space - reserving some
4941:
1.32 anton 4942: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4943: you want to deallocate X, you also deallocate everything
4944: allocated after X.
4945:
1.68 anton 4946: @cindex contiguous regions in dictionary allocation
1.32 anton 4947: The allocations using the words below are contiguous and grow the region
4948: towards increasing addresses. Other words that allocate dictionary
4949: memory of any kind (i.e., defining words including @code{:noname}) end
4950: the contiguous region and start a new one.
4951:
4952: In ANS Forth only @code{create}d words are guaranteed to produce an
4953: address that is the start of the following contiguous region. In
4954: particular, the cell allocated by @code{variable} is not guaranteed to
4955: be contiguous with following @code{allot}ed memory.
4956:
4957: You can deallocate memory by using @code{allot} with a negative argument
4958: (with some restrictions, see @code{allot}). For larger deallocations use
4959: @code{marker}.
1.27 crook 4960:
1.29 crook 4961:
1.27 crook 4962: doc-here
4963: doc-unused
4964: doc-allot
4965: doc-c,
1.29 crook 4966: doc-f,
1.27 crook 4967: doc-,
4968: doc-2,
4969:
1.32 anton 4970: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4971: course you should allocate memory in an aligned way, too. I.e., before
4972: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4973: The words below align @code{here} if it is not already. Basically it is
4974: only already aligned for a type, if the last allocation was a multiple
4975: of the size of this type and if @code{here} was aligned for this type
4976: before.
4977:
4978: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4979: ANS Forth (@code{maxalign}ed in Gforth).
4980:
4981: doc-align
4982: doc-falign
4983: doc-sfalign
4984: doc-dfalign
4985: doc-maxalign
4986: doc-cfalign
4987:
4988:
4989: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4990: @subsection Heap allocation
4991: @cindex heap allocation
4992: @cindex dynamic allocation of memory
4993: @cindex memory-allocation word set
4994:
1.68 anton 4995: @cindex contiguous regions and heap allocation
1.32 anton 4996: Heap allocation supports deallocation of allocated memory in any
4997: order. Dictionary allocation is not affected by it (i.e., it does not
4998: end a contiguous region). In Gforth, these words are implemented using
4999: the standard C library calls malloc(), free() and resize().
5000:
1.68 anton 5001: The memory region produced by one invocation of @code{allocate} or
5002: @code{resize} is internally contiguous. There is no contiguity between
5003: such a region and any other region (including others allocated from the
5004: heap).
5005:
1.32 anton 5006: doc-allocate
5007: doc-free
5008: doc-resize
5009:
1.27 crook 5010:
1.32 anton 5011: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5012: @subsection Memory Access
5013: @cindex memory access words
5014:
5015: doc-@
5016: doc-!
5017: doc-+!
5018: doc-c@
5019: doc-c!
5020: doc-2@
5021: doc-2!
5022: doc-f@
5023: doc-f!
5024: doc-sf@
5025: doc-sf!
5026: doc-df@
5027: doc-df!
1.144 anton 5028: doc-sw@
5029: doc-uw@
5030: doc-w!
5031: doc-sl@
5032: doc-ul@
5033: doc-l!
1.68 anton 5034:
1.32 anton 5035: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5036: @subsection Address arithmetic
1.1 anton 5037: @cindex address arithmetic words
5038:
1.67 anton 5039: Address arithmetic is the foundation on which you can build data
5040: structures like arrays, records (@pxref{Structures}) and objects
5041: (@pxref{Object-oriented Forth}).
1.32 anton 5042:
1.68 anton 5043: @cindex address unit
5044: @cindex au (address unit)
1.1 anton 5045: ANS Forth does not specify the sizes of the data types. Instead, it
5046: offers a number of words for computing sizes and doing address
1.29 crook 5047: arithmetic. Address arithmetic is performed in terms of address units
5048: (aus); on most systems the address unit is one byte. Note that a
5049: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5050: platforms where it is a noop, it compiles to nothing).
1.1 anton 5051:
1.67 anton 5052: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5053: you have the address of a cell, perform @code{1 cells +}, and you will
5054: have the address of the next cell.
5055:
1.68 anton 5056: @cindex contiguous regions and address arithmetic
1.67 anton 5057: In ANS Forth you can perform address arithmetic only within a contiguous
5058: region, i.e., if you have an address into one region, you can only add
5059: and subtract such that the result is still within the region; you can
5060: only subtract or compare addresses from within the same contiguous
5061: region. Reasons: several contiguous regions can be arranged in memory
5062: in any way; on segmented systems addresses may have unusual
5063: representations, such that address arithmetic only works within a
5064: region. Gforth provides a few more guarantees (linear address space,
5065: dictionary grows upwards), but in general I have found it easy to stay
5066: within contiguous regions (exception: computing and comparing to the
5067: address just beyond the end of an array).
5068:
1.1 anton 5069: @cindex alignment of addresses for types
5070: ANS Forth also defines words for aligning addresses for specific
5071: types. Many computers require that accesses to specific data types
5072: must only occur at specific addresses; e.g., that cells may only be
5073: accessed at addresses divisible by 4. Even if a machine allows unaligned
5074: accesses, it can usually perform aligned accesses faster.
5075:
5076: For the performance-conscious: alignment operations are usually only
5077: necessary during the definition of a data structure, not during the
5078: (more frequent) accesses to it.
5079:
5080: ANS Forth defines no words for character-aligning addresses. This is not
5081: an oversight, but reflects the fact that addresses that are not
5082: char-aligned have no use in the standard and therefore will not be
5083: created.
5084:
5085: @cindex @code{CREATE} and alignment
1.29 crook 5086: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5087: are cell-aligned; in addition, Gforth guarantees that these addresses
5088: are aligned for all purposes.
5089:
1.26 crook 5090: Note that the ANS Forth word @code{char} has nothing to do with address
5091: arithmetic.
1.1 anton 5092:
1.44 crook 5093:
1.1 anton 5094: doc-chars
5095: doc-char+
5096: doc-cells
5097: doc-cell+
5098: doc-cell
5099: doc-aligned
5100: doc-floats
5101: doc-float+
5102: doc-float
5103: doc-faligned
5104: doc-sfloats
5105: doc-sfloat+
5106: doc-sfaligned
5107: doc-dfloats
5108: doc-dfloat+
5109: doc-dfaligned
5110: doc-maxaligned
5111: doc-cfaligned
5112: doc-address-unit-bits
1.145 anton 5113: doc-/w
5114: doc-/l
1.44 crook 5115:
1.32 anton 5116: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5117: @subsection Memory Blocks
5118: @cindex memory block words
1.27 crook 5119: @cindex character strings - moving and copying
5120:
1.49 anton 5121: Memory blocks often represent character strings; For ways of storing
5122: character strings in memory see @ref{String Formats}. For other
5123: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5124:
1.67 anton 5125: A few of these words work on address unit blocks. In that case, you
5126: usually have to insert @code{CHARS} before the word when working on
5127: character strings. Most words work on character blocks, and expect a
5128: char-aligned address.
5129:
5130: When copying characters between overlapping memory regions, use
5131: @code{chars move} or choose carefully between @code{cmove} and
5132: @code{cmove>}.
1.44 crook 5133:
1.1 anton 5134: doc-move
5135: doc-erase
5136: doc-cmove
5137: doc-cmove>
5138: doc-fill
5139: doc-blank
1.21 crook 5140: doc-compare
1.111 anton 5141: doc-str=
5142: doc-str<
5143: doc-string-prefix?
1.21 crook 5144: doc-search
1.27 crook 5145: doc--trailing
5146: doc-/string
1.82 anton 5147: doc-bounds
1.141 anton 5148: doc-pad
1.111 anton 5149:
1.27 crook 5150: @comment TODO examples
5151:
1.1 anton 5152:
1.26 crook 5153: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5154: @section Control Structures
5155: @cindex control structures
5156:
1.33 anton 5157: Control structures in Forth cannot be used interpretively, only in a
5158: colon definition@footnote{To be precise, they have no interpretation
5159: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5160: not like this limitation, but have not seen a satisfying way around it
5161: yet, although many schemes have been proposed.
1.1 anton 5162:
5163: @menu
1.33 anton 5164: * Selection:: IF ... ELSE ... ENDIF
5165: * Simple Loops:: BEGIN ...
1.29 crook 5166: * Counted Loops:: DO
1.67 anton 5167: * Arbitrary control structures::
5168: * Calls and returns::
1.1 anton 5169: * Exception Handling::
5170: @end menu
5171:
5172: @node Selection, Simple Loops, Control Structures, Control Structures
5173: @subsection Selection
5174: @cindex selection control structures
5175: @cindex control structures for selection
5176:
5177: @cindex @code{IF} control structure
5178: @example
1.29 crook 5179: @i{flag}
1.1 anton 5180: IF
1.29 crook 5181: @i{code}
1.1 anton 5182: ENDIF
5183: @end example
1.21 crook 5184: @noindent
1.33 anton 5185:
1.44 crook 5186: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5187: with any bit set represents truth) @i{code} is executed.
1.33 anton 5188:
1.1 anton 5189: @example
1.29 crook 5190: @i{flag}
1.1 anton 5191: IF
1.29 crook 5192: @i{code1}
1.1 anton 5193: ELSE
1.29 crook 5194: @i{code2}
1.1 anton 5195: ENDIF
5196: @end example
5197:
1.44 crook 5198: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5199: executed.
1.33 anton 5200:
1.1 anton 5201: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5202: standard, and @code{ENDIF} is not, although it is quite popular. We
5203: recommend using @code{ENDIF}, because it is less confusing for people
5204: who also know other languages (and is not prone to reinforcing negative
5205: prejudices against Forth in these people). Adding @code{ENDIF} to a
5206: system that only supplies @code{THEN} is simple:
5207: @example
1.82 anton 5208: : ENDIF POSTPONE then ; immediate
1.1 anton 5209: @end example
5210:
5211: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5212: (adv.)} has the following meanings:
5213: @quotation
5214: ... 2b: following next after in order ... 3d: as a necessary consequence
5215: (if you were there, then you saw them).
5216: @end quotation
5217: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5218: and many other programming languages has the meaning 3d.]
5219:
1.21 crook 5220: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5221: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5222: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5223: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5224: @file{compat/control.fs}.
5225:
5226: @cindex @code{CASE} control structure
5227: @example
1.29 crook 5228: @i{n}
1.1 anton 5229: CASE
1.29 crook 5230: @i{n1} OF @i{code1} ENDOF
5231: @i{n2} OF @i{code2} ENDOF
1.1 anton 5232: @dots{}
1.68 anton 5233: ( n ) @i{default-code} ( n )
1.131 anton 5234: ENDCASE ( )
1.1 anton 5235: @end example
5236:
1.131 anton 5237: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5238: no @i{ni} matches, the optional @i{default-code} is executed. The
5239: optional default case can be added by simply writing the code after
5240: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5241: but must not consume it. The value @i{n} is consumed by this
5242: construction (either by a OF that matches, or by the ENDCASE, if no OF
5243: matches).
1.1 anton 5244:
1.69 anton 5245: @progstyle
1.131 anton 5246: To keep the code understandable, you should ensure that you change the
5247: stack in the same way (wrt. number and types of stack items consumed
5248: and pushed) on all paths through a selection construct.
1.69 anton 5249:
1.1 anton 5250: @node Simple Loops, Counted Loops, Selection, Control Structures
5251: @subsection Simple Loops
5252: @cindex simple loops
5253: @cindex loops without count
5254:
5255: @cindex @code{WHILE} loop
5256: @example
5257: BEGIN
1.29 crook 5258: @i{code1}
5259: @i{flag}
1.1 anton 5260: WHILE
1.29 crook 5261: @i{code2}
1.1 anton 5262: REPEAT
5263: @end example
5264:
1.29 crook 5265: @i{code1} is executed and @i{flag} is computed. If it is true,
5266: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5267: false, execution continues after the @code{REPEAT}.
5268:
5269: @cindex @code{UNTIL} loop
5270: @example
5271: BEGIN
1.29 crook 5272: @i{code}
5273: @i{flag}
1.1 anton 5274: UNTIL
5275: @end example
5276:
1.29 crook 5277: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5278:
1.69 anton 5279: @progstyle
5280: To keep the code understandable, a complete iteration of the loop should
5281: not change the number and types of the items on the stacks.
5282:
1.1 anton 5283: @cindex endless loop
5284: @cindex loops, endless
5285: @example
5286: BEGIN
1.29 crook 5287: @i{code}
1.1 anton 5288: AGAIN
5289: @end example
5290:
5291: This is an endless loop.
5292:
5293: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5294: @subsection Counted Loops
5295: @cindex counted loops
5296: @cindex loops, counted
5297: @cindex @code{DO} loops
5298:
5299: The basic counted loop is:
5300: @example
1.29 crook 5301: @i{limit} @i{start}
1.1 anton 5302: ?DO
1.29 crook 5303: @i{body}
1.1 anton 5304: LOOP
5305: @end example
5306:
1.29 crook 5307: This performs one iteration for every integer, starting from @i{start}
5308: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5309: accessed with @code{i}. For example, the loop:
1.1 anton 5310: @example
5311: 10 0 ?DO
5312: i .
5313: LOOP
5314: @end example
1.21 crook 5315: @noindent
5316: prints @code{0 1 2 3 4 5 6 7 8 9}
5317:
1.1 anton 5318: The index of the innermost loop can be accessed with @code{i}, the index
5319: of the next loop with @code{j}, and the index of the third loop with
5320: @code{k}.
5321:
1.44 crook 5322:
1.1 anton 5323: doc-i
5324: doc-j
5325: doc-k
5326:
1.44 crook 5327:
1.1 anton 5328: The loop control data are kept on the return stack, so there are some
1.21 crook 5329: restrictions on mixing return stack accesses and counted loop words. In
5330: particuler, if you put values on the return stack outside the loop, you
5331: cannot read them inside the loop@footnote{well, not in a way that is
5332: portable.}. If you put values on the return stack within a loop, you
5333: have to remove them before the end of the loop and before accessing the
5334: index of the loop.
1.1 anton 5335:
5336: There are several variations on the counted loop:
5337:
1.21 crook 5338: @itemize @bullet
5339: @item
5340: @code{LEAVE} leaves the innermost counted loop immediately; execution
5341: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5342:
5343: @example
5344: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5345: @end example
5346: prints @code{0 1 2 3}
5347:
1.1 anton 5348:
1.21 crook 5349: @item
5350: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5351: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5352: return stack so @code{EXIT} can get to its return address. For example:
5353:
5354: @example
5355: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5356: @end example
5357: prints @code{0 1 2 3}
5358:
5359:
5360: @item
1.29 crook 5361: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5362: (and @code{LOOP} iterates until they become equal by wrap-around
5363: arithmetic). This behaviour is usually not what you want. Therefore,
5364: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5365: @code{?DO}), which do not enter the loop if @i{start} is greater than
5366: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5367: unsigned loop parameters.
5368:
1.21 crook 5369: @item
5370: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5371: the loop, independent of the loop parameters. Do not use @code{DO}, even
5372: if you know that the loop is entered in any case. Such knowledge tends
5373: to become invalid during maintenance of a program, and then the
5374: @code{DO} will make trouble.
5375:
5376: @item
1.29 crook 5377: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5378: index by @i{n} instead of by 1. The loop is terminated when the border
5379: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5380:
1.21 crook 5381: @example
5382: 4 0 +DO i . 2 +LOOP
5383: @end example
5384: @noindent
5385: prints @code{0 2}
5386:
5387: @example
5388: 4 1 +DO i . 2 +LOOP
5389: @end example
5390: @noindent
5391: prints @code{1 3}
1.1 anton 5392:
1.68 anton 5393: @item
1.1 anton 5394: @cindex negative increment for counted loops
5395: @cindex counted loops with negative increment
1.29 crook 5396: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5397:
1.21 crook 5398: @example
5399: -1 0 ?DO i . -1 +LOOP
5400: @end example
5401: @noindent
5402: prints @code{0 -1}
1.1 anton 5403:
1.21 crook 5404: @example
5405: 0 0 ?DO i . -1 +LOOP
5406: @end example
5407: prints nothing.
1.1 anton 5408:
1.29 crook 5409: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5410: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5411: index by @i{u} each iteration. The loop is terminated when the border
5412: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5413: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5414:
1.21 crook 5415: @example
5416: -2 0 -DO i . 1 -LOOP
5417: @end example
5418: @noindent
5419: prints @code{0 -1}
1.1 anton 5420:
1.21 crook 5421: @example
5422: -1 0 -DO i . 1 -LOOP
5423: @end example
5424: @noindent
5425: prints @code{0}
5426:
5427: @example
5428: 0 0 -DO i . 1 -LOOP
5429: @end example
5430: @noindent
5431: prints nothing.
1.1 anton 5432:
1.21 crook 5433: @end itemize
1.1 anton 5434:
5435: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5436: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5437: for these words that uses only standard words is provided in
5438: @file{compat/loops.fs}.
1.1 anton 5439:
5440:
5441: @cindex @code{FOR} loops
1.26 crook 5442: Another counted loop is:
1.1 anton 5443: @example
1.29 crook 5444: @i{n}
1.1 anton 5445: FOR
1.29 crook 5446: @i{body}
1.1 anton 5447: NEXT
5448: @end example
5449: This is the preferred loop of native code compiler writers who are too
1.26 crook 5450: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5451: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5452: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5453: Forth systems may behave differently, even if they support @code{FOR}
5454: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5455:
5456: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5457: @subsection Arbitrary control structures
5458: @cindex control structures, user-defined
5459:
5460: @cindex control-flow stack
5461: ANS Forth permits and supports using control structures in a non-nested
5462: way. Information about incomplete control structures is stored on the
5463: control-flow stack. This stack may be implemented on the Forth data
5464: stack, and this is what we have done in Gforth.
5465:
5466: @cindex @code{orig}, control-flow stack item
5467: @cindex @code{dest}, control-flow stack item
5468: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5469: entry represents a backward branch target. A few words are the basis for
5470: building any control structure possible (except control structures that
5471: need storage, like calls, coroutines, and backtracking).
5472:
1.44 crook 5473:
1.1 anton 5474: doc-if
5475: doc-ahead
5476: doc-then
5477: doc-begin
5478: doc-until
5479: doc-again
5480: doc-cs-pick
5481: doc-cs-roll
5482:
1.44 crook 5483:
1.21 crook 5484: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5485: manipulate the control-flow stack in a portable way. Without them, you
5486: would need to know how many stack items are occupied by a control-flow
5487: entry (many systems use one cell. In Gforth they currently take three,
5488: but this may change in the future).
5489:
1.1 anton 5490: Some standard control structure words are built from these words:
5491:
1.44 crook 5492:
1.1 anton 5493: doc-else
5494: doc-while
5495: doc-repeat
5496:
1.44 crook 5497:
5498: @noindent
1.1 anton 5499: Gforth adds some more control-structure words:
5500:
1.44 crook 5501:
1.1 anton 5502: doc-endif
5503: doc-?dup-if
5504: doc-?dup-0=-if
5505:
1.44 crook 5506:
5507: @noindent
1.1 anton 5508: Counted loop words constitute a separate group of words:
5509:
1.44 crook 5510:
1.1 anton 5511: doc-?do
5512: doc-+do
5513: doc-u+do
5514: doc--do
5515: doc-u-do
5516: doc-do
5517: doc-for
5518: doc-loop
5519: doc-+loop
5520: doc--loop
5521: doc-next
5522: doc-leave
5523: doc-?leave
5524: doc-unloop
5525: doc-done
5526:
1.44 crook 5527:
1.21 crook 5528: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5529: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5530: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5531: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5532: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5533: resolved (by using one of the loop-ending words or @code{DONE}).
5534:
1.44 crook 5535: @noindent
1.26 crook 5536: Another group of control structure words are:
1.1 anton 5537:
1.44 crook 5538:
1.1 anton 5539: doc-case
5540: doc-endcase
5541: doc-of
5542: doc-endof
5543:
1.44 crook 5544:
1.21 crook 5545: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5546: @code{CS-ROLL}.
1.1 anton 5547:
5548: @subsubsection Programming Style
1.47 crook 5549: @cindex control structures programming style
5550: @cindex programming style, arbitrary control structures
1.1 anton 5551:
5552: In order to ensure readability we recommend that you do not create
5553: arbitrary control structures directly, but define new control structure
5554: words for the control structure you want and use these words in your
1.26 crook 5555: program. For example, instead of writing:
1.1 anton 5556:
5557: @example
1.26 crook 5558: BEGIN
1.1 anton 5559: ...
1.26 crook 5560: IF [ 1 CS-ROLL ]
1.1 anton 5561: ...
1.26 crook 5562: AGAIN THEN
1.1 anton 5563: @end example
5564:
1.21 crook 5565: @noindent
1.1 anton 5566: we recommend defining control structure words, e.g.,
5567:
5568: @example
1.26 crook 5569: : WHILE ( DEST -- ORIG DEST )
5570: POSTPONE IF
5571: 1 CS-ROLL ; immediate
5572:
5573: : REPEAT ( orig dest -- )
5574: POSTPONE AGAIN
5575: POSTPONE THEN ; immediate
1.1 anton 5576: @end example
5577:
1.21 crook 5578: @noindent
1.1 anton 5579: and then using these to create the control structure:
5580:
5581: @example
1.26 crook 5582: BEGIN
1.1 anton 5583: ...
1.26 crook 5584: WHILE
1.1 anton 5585: ...
1.26 crook 5586: REPEAT
1.1 anton 5587: @end example
5588:
5589: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5590: @code{WHILE} are predefined, so in this example it would not be
5591: necessary to define them.
5592:
5593: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5594: @subsection Calls and returns
5595: @cindex calling a definition
5596: @cindex returning from a definition
5597:
1.3 anton 5598: @cindex recursive definitions
5599: A definition can be called simply be writing the name of the definition
1.26 crook 5600: to be called. Normally a definition is invisible during its own
1.3 anton 5601: definition. If you want to write a directly recursive definition, you
1.26 crook 5602: can use @code{recursive} to make the current definition visible, or
5603: @code{recurse} to call the current definition directly.
1.3 anton 5604:
1.44 crook 5605:
1.3 anton 5606: doc-recursive
5607: doc-recurse
5608:
1.44 crook 5609:
1.21 crook 5610: @comment TODO add example of the two recursion methods
1.12 anton 5611: @quotation
5612: @progstyle
5613: I prefer using @code{recursive} to @code{recurse}, because calling the
5614: definition by name is more descriptive (if the name is well-chosen) than
5615: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5616: implementation, it is much better to read (and think) ``now sort the
5617: partitions'' than to read ``now do a recursive call''.
5618: @end quotation
1.3 anton 5619:
1.29 crook 5620: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5621:
5622: @example
1.28 crook 5623: Defer foo
1.3 anton 5624:
5625: : bar ( ... -- ... )
5626: ... foo ... ;
5627:
5628: :noname ( ... -- ... )
5629: ... bar ... ;
5630: IS foo
5631: @end example
5632:
1.170 pazsan 5633: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5634:
1.26 crook 5635: The current definition returns control to the calling definition when
1.33 anton 5636: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5637:
5638: doc-exit
5639: doc-;s
5640:
1.44 crook 5641:
1.1 anton 5642: @node Exception Handling, , Calls and returns, Control Structures
5643: @subsection Exception Handling
1.26 crook 5644: @cindex exceptions
1.1 anton 5645:
1.68 anton 5646: @c quit is a very bad idea for error handling,
5647: @c because it does not translate into a THROW
5648: @c it also does not belong into this chapter
5649:
5650: If a word detects an error condition that it cannot handle, it can
5651: @code{throw} an exception. In the simplest case, this will terminate
5652: your program, and report an appropriate error.
1.21 crook 5653:
1.68 anton 5654: doc-throw
1.1 anton 5655:
1.69 anton 5656: @code{Throw} consumes a cell-sized error number on the stack. There are
5657: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5658: Gforth (and most other systems) you can use the iors produced by various
5659: words as error numbers (e.g., a typical use of @code{allocate} is
5660: @code{allocate throw}). Gforth also provides the word @code{exception}
5661: to define your own error numbers (with decent error reporting); an ANS
5662: Forth version of this word (but without the error messages) is available
5663: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5664: numbers (anything outside the range -4095..0), but won't get nice error
5665: messages, only numbers. For example, try:
5666:
5667: @example
1.69 anton 5668: -10 throw \ ANS defined
5669: -267 throw \ system defined
5670: s" my error" exception throw \ user defined
5671: 7 throw \ arbitrary number
1.68 anton 5672: @end example
5673:
5674: doc---exception-exception
1.1 anton 5675:
1.69 anton 5676: A common idiom to @code{THROW} a specific error if a flag is true is
5677: this:
5678:
5679: @example
5680: @code{( flag ) 0<> @i{errno} and throw}
5681: @end example
5682:
5683: Your program can provide exception handlers to catch exceptions. An
5684: exception handler can be used to correct the problem, or to clean up
5685: some data structures and just throw the exception to the next exception
5686: handler. Note that @code{throw} jumps to the dynamically innermost
5687: exception handler. The system's exception handler is outermost, and just
5688: prints an error and restarts command-line interpretation (or, in batch
5689: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5690:
1.68 anton 5691: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5692:
1.68 anton 5693: doc-catch
1.160 anton 5694: doc-nothrow
1.68 anton 5695:
5696: The most common use of exception handlers is to clean up the state when
5697: an error happens. E.g.,
1.1 anton 5698:
1.26 crook 5699: @example
1.68 anton 5700: base @ >r hex \ actually the hex should be inside foo, or we h
5701: ['] foo catch ( nerror|0 )
5702: r> base !
1.69 anton 5703: ( nerror|0 ) throw \ pass it on
1.26 crook 5704: @end example
1.1 anton 5705:
1.69 anton 5706: A use of @code{catch} for handling the error @code{myerror} might look
5707: like this:
1.44 crook 5708:
1.68 anton 5709: @example
1.69 anton 5710: ['] foo catch
5711: CASE
1.160 anton 5712: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5713: dup throw \ default: pass other errors on, do nothing on non-errors
5714: ENDCASE
1.68 anton 5715: @end example
1.44 crook 5716:
1.68 anton 5717: Having to wrap the code into a separate word is often cumbersome,
5718: therefore Gforth provides an alternative syntax:
1.1 anton 5719:
5720: @example
1.69 anton 5721: TRY
1.68 anton 5722: @i{code1}
1.172 anton 5723: IFERROR
5724: @i{code2}
5725: THEN
5726: @i{code3}
1.69 anton 5727: ENDTRY
1.1 anton 5728: @end example
5729:
1.172 anton 5730: This performs @i{code1}. If @i{code1} completes normally, execution
5731: continues with @i{code3}. If @i{code1} or there is an exception
5732: before @code{endtry}, the stacks are reset to the state during
5733: @code{try}, the throw value is pushed on the data stack, and execution
5734: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26 crook 5735:
1.68 anton 5736: doc-try
5737: doc-endtry
1.172 anton 5738: doc-iferror
5739:
5740: If you don't need @i{code2}, you can write @code{restore} instead of
5741: @code{iferror then}:
5742:
5743: @example
5744: TRY
5745: @i{code1}
5746: RESTORE
5747: @i{code3}
5748: ENDTRY
5749: @end example
1.26 crook 5750:
1.172 anton 5751: @cindex unwind-protect
1.69 anton 5752: The cleanup example from above in this syntax:
1.26 crook 5753:
1.68 anton 5754: @example
1.174 anton 5755: base @@ @{ oldbase @}
1.172 anton 5756: TRY
1.68 anton 5757: hex foo \ now the hex is placed correctly
1.69 anton 5758: 0 \ value for throw
1.172 anton 5759: RESTORE
5760: oldbase base !
5761: ENDTRY
5762: throw
1.1 anton 5763: @end example
5764:
1.172 anton 5765: An additional advantage of this variant is that an exception between
5766: @code{restore} and @code{endtry} (e.g., from the user pressing
5767: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5768: so the base will be restored under all circumstances.
5769:
5770: However, you have to ensure that this code does not cause an exception
5771: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5772: Moreover, you should also make sure that the stack contents needed by
5773: the @code{iferror}/@code{restore} code exist everywhere between
5774: @code{try} and @code{endtry}; in our example this is achived by
5775: putting the data in a local before the @code{try} (you cannot use the
5776: return stack because the exception frame (@i{sys1}) is in the way
5777: there).
5778:
5779: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5780:
5781: @cindex @code{recover} (old Gforth versions)
5782: If you do not want this exception-restarting behaviour, you achieve
5783: this as follows:
5784:
5785: @example
5786: TRY
5787: @i{code1}
5788: ENDTRY-IFERROR
5789: @i{code2}
5790: THEN
5791: @end example
5792:
5793: If there is an exception in @i{code1}, then @i{code2} is executed,
5794: otherwise execution continues behind the @code{then} (or in a possible
5795: @code{else} branch). This corresponds to the construct
5796:
5797: @example
5798: TRY
5799: @i{code1}
5800: RECOVER
5801: @i{code2}
5802: ENDTRY
5803: @end example
5804:
5805: in Gforth before version 0.7. So you can directly replace
5806: @code{recover}-using code; however, we recommend that you check if it
5807: would not be better to use one of the other @code{try} variants while
5808: you are at it.
5809:
1.173 anton 5810: To ease the transition, Gforth provides two compatibility files:
5811: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5812: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5813: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5814: ... endtry} syntax on new systems, so you can use that file as a
5815: stopgap to run old programs. Both files work on any system (they just
5816: do nothing if the system already has the syntax it implements), so you
5817: can unconditionally @code{require} one of these files, even if you use
5818: a mix old and new systems.
5819:
1.172 anton 5820: doc-restore
5821: doc-endtry-iferror
5822:
5823: Here's the error handling example:
1.1 anton 5824:
1.68 anton 5825: @example
1.69 anton 5826: TRY
1.68 anton 5827: foo
1.172 anton 5828: ENDTRY-IFERROR
1.69 anton 5829: CASE
1.160 anton 5830: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5831: throw \ pass other errors on
5832: ENDCASE
1.172 anton 5833: THEN
1.68 anton 5834: @end example
1.1 anton 5835:
1.69 anton 5836: @progstyle
5837: As usual, you should ensure that the stack depth is statically known at
5838: the end: either after the @code{throw} for passing on errors, or after
5839: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5840: selection construct for handling the error).
5841:
1.68 anton 5842: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5843: and you can provide an error message. @code{Abort} just produces an
5844: ``Aborted'' error.
1.1 anton 5845:
1.68 anton 5846: The problem with these words is that exception handlers cannot
5847: differentiate between different @code{abort"}s; they just look like
5848: @code{-2 throw} to them (the error message cannot be accessed by
5849: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5850: exception handlers.
1.44 crook 5851:
1.68 anton 5852: doc-abort"
1.26 crook 5853: doc-abort
1.29 crook 5854:
5855:
1.44 crook 5856:
1.29 crook 5857: @c -------------------------------------------------------------
1.47 crook 5858: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5859: @section Defining Words
5860: @cindex defining words
5861:
1.47 crook 5862: Defining words are used to extend Forth by creating new entries in the dictionary.
5863:
1.29 crook 5864: @menu
1.67 anton 5865: * CREATE::
1.44 crook 5866: * Variables:: Variables and user variables
1.67 anton 5867: * Constants::
1.44 crook 5868: * Values:: Initialised variables
1.67 anton 5869: * Colon Definitions::
1.44 crook 5870: * Anonymous Definitions:: Definitions without names
1.69 anton 5871: * Supplying names:: Passing definition names as strings
1.67 anton 5872: * User-defined Defining Words::
1.170 pazsan 5873: * Deferred Words:: Allow forward references
1.67 anton 5874: * Aliases::
1.29 crook 5875: @end menu
5876:
1.44 crook 5877: @node CREATE, Variables, Defining Words, Defining Words
5878: @subsection @code{CREATE}
1.29 crook 5879: @cindex simple defining words
5880: @cindex defining words, simple
5881:
5882: Defining words are used to create new entries in the dictionary. The
5883: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5884: this:
5885:
5886: @example
5887: CREATE new-word1
5888: @end example
5889:
1.69 anton 5890: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5891: input stream (@code{new-word1} in our example). It generates a
5892: dictionary entry for @code{new-word1}. When @code{new-word1} is
5893: executed, all that it does is leave an address on the stack. The address
5894: represents the value of the data space pointer (@code{HERE}) at the time
5895: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5896: associating a name with the address of a region of memory.
1.29 crook 5897:
1.34 anton 5898: doc-create
5899:
1.69 anton 5900: Note that in ANS Forth guarantees only for @code{create} that its body
5901: is in dictionary data space (i.e., where @code{here}, @code{allot}
5902: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5903: @code{create}d words can be modified with @code{does>}
5904: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5905: can only be applied to @code{create}d words.
5906:
1.29 crook 5907: By extending this example to reserve some memory in data space, we end
1.69 anton 5908: up with something like a @i{variable}. Here are two different ways to do
5909: it:
1.29 crook 5910:
5911: @example
5912: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5913: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5914: @end example
5915:
5916: The variable can be examined and modified using @code{@@} (``fetch'') and
5917: @code{!} (``store'') like this:
5918:
5919: @example
5920: new-word2 @@ . \ get address, fetch from it and display
5921: 1234 new-word2 ! \ new value, get address, store to it
5922: @end example
5923:
1.44 crook 5924: @cindex arrays
5925: A similar mechanism can be used to create arrays. For example, an
5926: 80-character text input buffer:
1.29 crook 5927:
5928: @example
1.44 crook 5929: CREATE text-buf 80 chars allot
5930:
1.168 anton 5931: text-buf 0 chars + c@@ \ the 1st character (offset 0)
5932: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 5933: @end example
1.29 crook 5934:
1.44 crook 5935: You can build arbitrarily complex data structures by allocating
1.49 anton 5936: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5937: learn about some Gforth tools that make it easier,
1.49 anton 5938: @xref{Structures}.
1.44 crook 5939:
5940:
5941: @node Variables, Constants, CREATE, Defining Words
5942: @subsection Variables
5943: @cindex variables
5944:
5945: The previous section showed how a sequence of commands could be used to
5946: generate a variable. As a final refinement, the whole code sequence can
5947: be wrapped up in a defining word (pre-empting the subject of the next
5948: section), making it easier to create new variables:
5949:
5950: @example
5951: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5952: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5953:
5954: myvariableX foo \ variable foo starts off with an unknown value
5955: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5956:
5957: 45 3 * foo ! \ set foo to 135
5958: 1234 joe ! \ set joe to 1234
5959: 3 joe +! \ increment joe by 3.. to 1237
5960: @end example
5961:
5962: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5963: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5964: guarantee that a @code{Variable} is initialised when it is created
5965: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5966: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5967: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5968: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5969: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5970: store a boolean, you can use @code{on} and @code{off} to toggle its
5971: state.
1.29 crook 5972:
1.34 anton 5973: doc-variable
5974: doc-2variable
5975: doc-fvariable
5976:
1.29 crook 5977: @cindex user variables
5978: @cindex user space
5979: The defining word @code{User} behaves in the same way as @code{Variable}.
5980: The difference is that it reserves space in @i{user (data) space} rather
5981: than normal data space. In a Forth system that has a multi-tasker, each
5982: task has its own set of user variables.
5983:
1.34 anton 5984: doc-user
1.67 anton 5985: @c doc-udp
5986: @c doc-uallot
1.34 anton 5987:
1.29 crook 5988: @comment TODO is that stuff about user variables strictly correct? Is it
5989: @comment just terminal tasks that have user variables?
5990: @comment should document tasker.fs (with some examples) elsewhere
5991: @comment in this manual, then expand on user space and user variables.
5992:
1.44 crook 5993: @node Constants, Values, Variables, Defining Words
5994: @subsection Constants
5995: @cindex constants
5996:
5997: @code{Constant} allows you to declare a fixed value and refer to it by
5998: name. For example:
1.29 crook 5999:
6000: @example
6001: 12 Constant INCHES-PER-FOOT
6002: 3E+08 fconstant SPEED-O-LIGHT
6003: @end example
6004:
6005: A @code{Variable} can be both read and written, so its run-time
6006: behaviour is to supply an address through which its current value can be
6007: manipulated. In contrast, the value of a @code{Constant} cannot be
6008: changed once it has been declared@footnote{Well, often it can be -- but
6009: not in a Standard, portable way. It's safer to use a @code{Value} (read
6010: on).} so it's not necessary to supply the address -- it is more
6011: efficient to return the value of the constant directly. That's exactly
6012: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6013: the top of the stack (You can find one
6014: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6015:
1.69 anton 6016: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6017: double and floating-point constants, respectively.
6018:
1.34 anton 6019: doc-constant
6020: doc-2constant
6021: doc-fconstant
6022:
6023: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6024: @c nac-> How could that not be true in an ANS Forth? You can't define a
6025: @c constant, use it and then delete the definition of the constant..
1.69 anton 6026:
6027: @c anton->An ANS Forth system can compile a constant to a literal; On
6028: @c decompilation you would see only the number, just as if it had been used
6029: @c in the first place. The word will stay, of course, but it will only be
6030: @c used by the text interpreter (no run-time duties, except when it is
6031: @c POSTPONEd or somesuch).
6032:
6033: @c nac:
1.44 crook 6034: @c I agree that it's rather deep, but IMO it is an important difference
6035: @c relative to other programming languages.. often it's annoying: it
6036: @c certainly changes my programming style relative to C.
6037:
1.69 anton 6038: @c anton: In what way?
6039:
1.29 crook 6040: Constants in Forth behave differently from their equivalents in other
6041: programming languages. In other languages, a constant (such as an EQU in
6042: assembler or a #define in C) only exists at compile-time; in the
6043: executable program the constant has been translated into an absolute
6044: number and, unless you are using a symbolic debugger, it's impossible to
6045: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6046: an entry in the header space and remains there after the code that uses
6047: it has been defined. In fact, it must remain in the dictionary since it
6048: has run-time duties to perform. For example:
1.29 crook 6049:
6050: @example
6051: 12 Constant INCHES-PER-FOOT
6052: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6053: @end example
6054:
6055: @cindex in-lining of constants
6056: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6057: associated with the constant @code{INCHES-PER-FOOT}. If you use
6058: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6059: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6060: attempt to optimise constants by in-lining them where they are used. You
6061: can force Gforth to in-line a constant like this:
6062:
6063: @example
6064: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6065: @end example
6066:
6067: If you use @code{see} to decompile @i{this} version of
6068: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6069: longer present. To understand how this works, read
6070: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6071:
6072: In-lining constants in this way might improve execution time
6073: fractionally, and can ensure that a constant is now only referenced at
6074: compile-time. However, the definition of the constant still remains in
6075: the dictionary. Some Forth compilers provide a mechanism for controlling
6076: a second dictionary for holding transient words such that this second
6077: dictionary can be deleted later in order to recover memory
6078: space. However, there is no standard way of doing this.
6079:
6080:
1.44 crook 6081: @node Values, Colon Definitions, Constants, Defining Words
6082: @subsection Values
6083: @cindex values
1.34 anton 6084:
1.69 anton 6085: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6086: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6087: (not in ANS Forth) you can access (and change) a @code{value} also with
6088: @code{>body}.
6089:
6090: Here are some
6091: examples:
1.29 crook 6092:
6093: @example
1.69 anton 6094: 12 Value APPLES \ Define APPLES with an initial value of 12
6095: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6096: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6097: APPLES \ puts 35 on the top of the stack.
1.29 crook 6098: @end example
6099:
1.44 crook 6100: doc-value
6101: doc-to
1.29 crook 6102:
1.35 anton 6103:
1.69 anton 6104:
1.44 crook 6105: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6106: @subsection Colon Definitions
6107: @cindex colon definitions
1.35 anton 6108:
6109: @example
1.44 crook 6110: : name ( ... -- ... )
6111: word1 word2 word3 ;
1.29 crook 6112: @end example
6113:
1.44 crook 6114: @noindent
6115: Creates a word called @code{name} that, upon execution, executes
6116: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6117:
1.49 anton 6118: The explanation above is somewhat superficial. For simple examples of
6119: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6120: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6121: Compilation Semantics}.
1.29 crook 6122:
1.44 crook 6123: doc-:
6124: doc-;
1.1 anton 6125:
1.34 anton 6126:
1.69 anton 6127: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6128: @subsection Anonymous Definitions
6129: @cindex colon definitions
6130: @cindex defining words without name
1.34 anton 6131:
1.44 crook 6132: Sometimes you want to define an @dfn{anonymous word}; a word without a
6133: name. You can do this with:
1.1 anton 6134:
1.44 crook 6135: doc-:noname
1.1 anton 6136:
1.44 crook 6137: This leaves the execution token for the word on the stack after the
6138: closing @code{;}. Here's an example in which a deferred word is
6139: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6140:
1.29 crook 6141: @example
1.44 crook 6142: Defer deferred
6143: :noname ( ... -- ... )
6144: ... ;
6145: IS deferred
1.29 crook 6146: @end example
1.26 crook 6147:
1.44 crook 6148: @noindent
6149: Gforth provides an alternative way of doing this, using two separate
6150: words:
1.27 crook 6151:
1.44 crook 6152: doc-noname
6153: @cindex execution token of last defined word
1.116 anton 6154: doc-latestxt
1.1 anton 6155:
1.44 crook 6156: @noindent
6157: The previous example can be rewritten using @code{noname} and
1.116 anton 6158: @code{latestxt}:
1.1 anton 6159:
1.26 crook 6160: @example
1.44 crook 6161: Defer deferred
6162: noname : ( ... -- ... )
6163: ... ;
1.116 anton 6164: latestxt IS deferred
1.26 crook 6165: @end example
1.1 anton 6166:
1.29 crook 6167: @noindent
1.44 crook 6168: @code{noname} works with any defining word, not just @code{:}.
6169:
1.116 anton 6170: @code{latestxt} also works when the last word was not defined as
1.71 anton 6171: @code{noname}. It does not work for combined words, though. It also has
6172: the useful property that is is valid as soon as the header for a
6173: definition has been built. Thus:
1.44 crook 6174:
6175: @example
1.116 anton 6176: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6177: @end example
1.1 anton 6178:
1.44 crook 6179: @noindent
6180: prints 3 numbers; the last two are the same.
1.26 crook 6181:
1.69 anton 6182: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6183: @subsection Supplying the name of a defined word
6184: @cindex names for defined words
6185: @cindex defining words, name given in a string
6186:
6187: By default, a defining word takes the name for the defined word from the
6188: input stream. Sometimes you want to supply the name from a string. You
6189: can do this with:
6190:
6191: doc-nextname
6192:
6193: For example:
6194:
6195: @example
6196: s" foo" nextname create
6197: @end example
6198:
6199: @noindent
6200: is equivalent to:
6201:
6202: @example
6203: create foo
6204: @end example
6205:
6206: @noindent
6207: @code{nextname} works with any defining word.
6208:
1.1 anton 6209:
1.170 pazsan 6210: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6211: @subsection User-defined Defining Words
6212: @cindex user-defined defining words
6213: @cindex defining words, user-defined
1.1 anton 6214:
1.29 crook 6215: You can create a new defining word by wrapping defining-time code around
6216: an existing defining word and putting the sequence in a colon
1.69 anton 6217: definition.
6218:
6219: @c anton: This example is very complex and leads in a quite different
6220: @c direction from the CREATE-DOES> stuff that follows. It should probably
6221: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6222: @c subsection of Defining Words)
6223:
6224: For example, suppose that you have a word @code{stats} that
1.29 crook 6225: gathers statistics about colon definitions given the @i{xt} of the
6226: definition, and you want every colon definition in your application to
6227: make a call to @code{stats}. You can define and use a new version of
6228: @code{:} like this:
6229:
6230: @example
6231: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6232: ... ; \ other code
6233:
1.116 anton 6234: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6235:
6236: my: foo + - ;
6237: @end example
6238:
6239: When @code{foo} is defined using @code{my:} these steps occur:
6240:
6241: @itemize @bullet
6242: @item
6243: @code{my:} is executed.
6244: @item
6245: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6246: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6247: the input stream for a name, builds a dictionary header for the name
6248: @code{foo} and switches @code{state} from interpret to compile.
6249: @item
1.116 anton 6250: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6251: being defined -- @code{foo} -- onto the stack.
6252: @item
6253: The code that was produced by @code{postpone literal} is executed; this
6254: causes the value on the stack to be compiled as a literal in the code
6255: area of @code{foo}.
6256: @item
6257: The code @code{['] stats} compiles a literal into the definition of
6258: @code{my:}. When @code{compile,} is executed, that literal -- the
6259: execution token for @code{stats} -- is layed down in the code area of
6260: @code{foo} , following the literal@footnote{Strictly speaking, the
6261: mechanism that @code{compile,} uses to convert an @i{xt} into something
6262: in the code area is implementation-dependent. A threaded implementation
6263: might spit out the execution token directly whilst another
6264: implementation might spit out a native code sequence.}.
6265: @item
6266: At this point, the execution of @code{my:} is complete, and control
6267: returns to the text interpreter. The text interpreter is in compile
6268: state, so subsequent text @code{+ -} is compiled into the definition of
6269: @code{foo} and the @code{;} terminates the definition as always.
6270: @end itemize
6271:
6272: You can use @code{see} to decompile a word that was defined using
6273: @code{my:} and see how it is different from a normal @code{:}
6274: definition. For example:
6275:
6276: @example
6277: : bar + - ; \ like foo but using : rather than my:
6278: see bar
6279: : bar
6280: + - ;
6281: see foo
6282: : foo
6283: 107645672 stats + - ;
6284:
1.140 anton 6285: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6286: @end example
6287:
6288: You can use techniques like this to make new defining words in terms of
6289: @i{any} existing defining word.
1.1 anton 6290:
6291:
1.29 crook 6292: @cindex defining defining words
1.26 crook 6293: @cindex @code{CREATE} ... @code{DOES>}
6294: If you want the words defined with your defining words to behave
6295: differently from words defined with standard defining words, you can
6296: write your defining word like this:
1.1 anton 6297:
6298: @example
1.26 crook 6299: : def-word ( "name" -- )
1.29 crook 6300: CREATE @i{code1}
1.26 crook 6301: DOES> ( ... -- ... )
1.29 crook 6302: @i{code2} ;
1.26 crook 6303:
6304: def-word name
1.1 anton 6305: @end example
6306:
1.29 crook 6307: @cindex child words
6308: This fragment defines a @dfn{defining word} @code{def-word} and then
6309: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6310: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6311: is not executed at this time. The word @code{name} is sometimes called a
6312: @dfn{child} of @code{def-word}.
6313:
6314: When you execute @code{name}, the address of the body of @code{name} is
6315: put on the data stack and @i{code2} is executed (the address of the body
6316: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6317: @code{CREATE}, i.e., the address a @code{create}d word returns by
6318: default).
6319:
6320: @c anton:
6321: @c www.dictionary.com says:
6322: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6323: @c several generations of absence, usually caused by the chance
6324: @c recombination of genes. 2.An individual or a part that exhibits
6325: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6326: @c of previous behavior after a period of absence.
6327: @c
6328: @c Doesn't seem to fit.
1.29 crook 6329:
1.69 anton 6330: @c @cindex atavism in child words
1.33 anton 6331: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6332: similarly; they all have a common run-time behaviour determined by
6333: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6334: body of the child word. The structure of the data is common to all
6335: children of @code{def-word}, but the data values are specific -- and
6336: private -- to each child word. When a child word is executed, the
6337: address of its private data area is passed as a parameter on TOS to be
6338: used and manipulated@footnote{It is legitimate both to read and write to
6339: this data area.} by @i{code2}.
1.29 crook 6340:
6341: The two fragments of code that make up the defining words act (are
6342: executed) at two completely separate times:
1.1 anton 6343:
1.29 crook 6344: @itemize @bullet
6345: @item
6346: At @i{define time}, the defining word executes @i{code1} to generate a
6347: child word
6348: @item
6349: At @i{child execution time}, when a child word is invoked, @i{code2}
6350: is executed, using parameters (data) that are private and specific to
6351: the child word.
6352: @end itemize
6353:
1.44 crook 6354: Another way of understanding the behaviour of @code{def-word} and
6355: @code{name} is to say that, if you make the following definitions:
1.33 anton 6356: @example
6357: : def-word1 ( "name" -- )
6358: CREATE @i{code1} ;
6359:
6360: : action1 ( ... -- ... )
6361: @i{code2} ;
6362:
6363: def-word1 name1
6364: @end example
6365:
1.44 crook 6366: @noindent
6367: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6368:
1.29 crook 6369: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6370:
1.1 anton 6371: @example
1.29 crook 6372: : CONSTANT ( w "name" -- )
6373: CREATE ,
1.26 crook 6374: DOES> ( -- w )
6375: @@ ;
1.1 anton 6376: @end example
6377:
1.29 crook 6378: @comment There is a beautiful description of how this works and what
6379: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6380: @comment commentary on the Counting Fruits problem.
6381:
6382: When you create a constant with @code{5 CONSTANT five}, a set of
6383: define-time actions take place; first a new word @code{five} is created,
6384: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6385: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6386: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6387: no code of its own; it simply contains a data field and a pointer to the
6388: code that follows @code{DOES>} in its defining word. That makes words
6389: created in this way very compact.
6390:
6391: The final example in this section is intended to remind you that space
6392: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6393: both read and written by a Standard program@footnote{Exercise: use this
6394: example as a starting point for your own implementation of @code{Value}
6395: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6396: @code{[']}.}:
6397:
6398: @example
6399: : foo ( "name" -- )
6400: CREATE -1 ,
6401: DOES> ( -- )
1.33 anton 6402: @@ . ;
1.29 crook 6403:
6404: foo first-word
6405: foo second-word
6406:
6407: 123 ' first-word >BODY !
6408: @end example
6409:
6410: If @code{first-word} had been a @code{CREATE}d word, we could simply
6411: have executed it to get the address of its data field. However, since it
6412: was defined to have @code{DOES>} actions, its execution semantics are to
6413: perform those @code{DOES>} actions. To get the address of its data field
6414: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6415: translate the xt into the address of the data field. When you execute
6416: @code{first-word}, it will display @code{123}. When you execute
6417: @code{second-word} it will display @code{-1}.
1.26 crook 6418:
6419: @cindex stack effect of @code{DOES>}-parts
6420: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6421: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6422: the stack effect of the defined words, not the stack effect of the
6423: following code (the following code expects the address of the body on
6424: the top of stack, which is not reflected in the stack comment). This is
6425: the convention that I use and recommend (it clashes a bit with using
6426: locals declarations for stack effect specification, though).
1.1 anton 6427:
1.53 anton 6428: @menu
6429: * CREATE..DOES> applications::
6430: * CREATE..DOES> details::
1.63 anton 6431: * Advanced does> usage example::
1.155 anton 6432: * Const-does>::
1.53 anton 6433: @end menu
6434:
6435: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6436: @subsubsection Applications of @code{CREATE..DOES>}
6437: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6438:
1.26 crook 6439: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6440:
1.26 crook 6441: @cindex factoring similar colon definitions
6442: When you see a sequence of code occurring several times, and you can
6443: identify a meaning, you will factor it out as a colon definition. When
6444: you see similar colon definitions, you can factor them using
6445: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6446: that look very similar:
1.1 anton 6447: @example
1.26 crook 6448: : ori, ( reg-target reg-source n -- )
6449: 0 asm-reg-reg-imm ;
6450: : andi, ( reg-target reg-source n -- )
6451: 1 asm-reg-reg-imm ;
1.1 anton 6452: @end example
6453:
1.26 crook 6454: @noindent
6455: This could be factored with:
6456: @example
6457: : reg-reg-imm ( op-code -- )
6458: CREATE ,
6459: DOES> ( reg-target reg-source n -- )
6460: @@ asm-reg-reg-imm ;
6461:
6462: 0 reg-reg-imm ori,
6463: 1 reg-reg-imm andi,
6464: @end example
1.1 anton 6465:
1.26 crook 6466: @cindex currying
6467: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6468: supply a part of the parameters for a word (known as @dfn{currying} in
6469: the functional language community). E.g., @code{+} needs two
6470: parameters. Creating versions of @code{+} with one parameter fixed can
6471: be done like this:
1.82 anton 6472:
1.1 anton 6473: @example
1.82 anton 6474: : curry+ ( n1 "name" -- )
1.26 crook 6475: CREATE ,
6476: DOES> ( n2 -- n1+n2 )
6477: @@ + ;
6478:
6479: 3 curry+ 3+
6480: -2 curry+ 2-
1.1 anton 6481: @end example
6482:
1.91 anton 6483:
1.63 anton 6484: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6485: @subsubsection The gory details of @code{CREATE..DOES>}
6486: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6487:
1.26 crook 6488: doc-does>
1.1 anton 6489:
1.26 crook 6490: @cindex @code{DOES>} in a separate definition
6491: This means that you need not use @code{CREATE} and @code{DOES>} in the
6492: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6493: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6494: @example
6495: : does1
6496: DOES> ( ... -- ... )
1.44 crook 6497: ... ;
6498:
6499: : does2
6500: DOES> ( ... -- ... )
6501: ... ;
6502:
6503: : def-word ( ... -- ... )
6504: create ...
6505: IF
6506: does1
6507: ELSE
6508: does2
6509: ENDIF ;
6510: @end example
6511:
6512: In this example, the selection of whether to use @code{does1} or
1.69 anton 6513: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6514: @code{CREATE}d.
6515:
6516: @cindex @code{DOES>} in interpretation state
6517: In a standard program you can apply a @code{DOES>}-part only if the last
6518: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6519: will override the behaviour of the last word defined in any case. In a
6520: standard program, you can use @code{DOES>} only in a colon
6521: definition. In Gforth, you can also use it in interpretation state, in a
6522: kind of one-shot mode; for example:
6523: @example
6524: CREATE name ( ... -- ... )
6525: @i{initialization}
6526: DOES>
6527: @i{code} ;
6528: @end example
6529:
6530: @noindent
6531: is equivalent to the standard:
6532: @example
6533: :noname
6534: DOES>
6535: @i{code} ;
6536: CREATE name EXECUTE ( ... -- ... )
6537: @i{initialization}
6538: @end example
6539:
1.53 anton 6540: doc->body
6541:
1.152 pazsan 6542: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6543: @subsubsection Advanced does> usage example
6544:
6545: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6546: for disassembling instructions, that follow a very repetetive scheme:
6547:
6548: @example
6549: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6550: @var{entry-num} cells @var{table} + !
6551: @end example
6552:
6553: Of course, this inspires the idea to factor out the commonalities to
6554: allow a definition like
6555:
6556: @example
6557: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6558: @end example
6559:
6560: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6561: correlated. Moreover, before I wrote the disassembler, there already
6562: existed code that defines instructions like this:
1.63 anton 6563:
6564: @example
6565: @var{entry-num} @var{inst-format} @var{inst-name}
6566: @end example
6567:
6568: This code comes from the assembler and resides in
6569: @file{arch/mips/insts.fs}.
6570:
6571: So I had to define the @var{inst-format} words that performed the scheme
6572: above when executed. At first I chose to use run-time code-generation:
6573:
6574: @example
6575: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6576: :noname Postpone @var{disasm-operands}
6577: name Postpone sliteral Postpone type Postpone ;
6578: swap cells @var{table} + ! ;
6579: @end example
6580:
6581: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6582:
1.63 anton 6583: An alternative would have been to write this using
6584: @code{create}/@code{does>}:
6585:
6586: @example
6587: : @var{inst-format} ( entry-num "name" -- )
6588: here name string, ( entry-num c-addr ) \ parse and save "name"
6589: noname create , ( entry-num )
1.116 anton 6590: latestxt swap cells @var{table} + !
1.63 anton 6591: does> ( addr w -- )
6592: \ disassemble instruction w at addr
6593: @@ >r
6594: @var{disasm-operands}
6595: r> count type ;
6596: @end example
6597:
6598: Somehow the first solution is simpler, mainly because it's simpler to
6599: shift a string from definition-time to use-time with @code{sliteral}
6600: than with @code{string,} and friends.
6601:
6602: I wrote a lot of words following this scheme and soon thought about
6603: factoring out the commonalities among them. Note that this uses a
6604: two-level defining word, i.e., a word that defines ordinary defining
6605: words.
6606:
6607: This time a solution involving @code{postpone} and friends seemed more
6608: difficult (try it as an exercise), so I decided to use a
6609: @code{create}/@code{does>} word; since I was already at it, I also used
6610: @code{create}/@code{does>} for the lower level (try using
6611: @code{postpone} etc. as an exercise), resulting in the following
6612: definition:
6613:
6614: @example
6615: : define-format ( disasm-xt table-xt -- )
6616: \ define an instruction format that uses disasm-xt for
6617: \ disassembling and enters the defined instructions into table
6618: \ table-xt
6619: create 2,
6620: does> ( u "inst" -- )
6621: \ defines an anonymous word for disassembling instruction inst,
6622: \ and enters it as u-th entry into table-xt
6623: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6624: noname create 2, \ define anonymous word
1.116 anton 6625: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6626: does> ( addr w -- )
6627: \ disassemble instruction w at addr
6628: 2@@ >r ( addr w disasm-xt R: c-addr )
6629: execute ( R: c-addr ) \ disassemble operands
6630: r> count type ; \ print name
6631: @end example
6632:
6633: Note that the tables here (in contrast to above) do the @code{cells +}
6634: by themselves (that's why you have to pass an xt). This word is used in
6635: the following way:
6636:
6637: @example
6638: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6639: @end example
6640:
1.71 anton 6641: As shown above, the defined instruction format is then used like this:
6642:
6643: @example
6644: @var{entry-num} @var{inst-format} @var{inst-name}
6645: @end example
6646:
1.63 anton 6647: In terms of currying, this kind of two-level defining word provides the
6648: parameters in three stages: first @var{disasm-operands} and @var{table},
6649: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6650: the instruction to be disassembled.
6651:
6652: Of course this did not quite fit all the instruction format names used
6653: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6654: the parameters into the right form.
6655:
6656: If you have trouble following this section, don't worry. First, this is
6657: involved and takes time (and probably some playing around) to
6658: understand; second, this is the first two-level
6659: @code{create}/@code{does>} word I have written in seventeen years of
6660: Forth; and if I did not have @file{insts.fs} to start with, I may well
6661: have elected to use just a one-level defining word (with some repeating
6662: of parameters when using the defining word). So it is not necessary to
6663: understand this, but it may improve your understanding of Forth.
1.44 crook 6664:
6665:
1.152 pazsan 6666: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6667: @subsubsection @code{Const-does>}
6668:
6669: A frequent use of @code{create}...@code{does>} is for transferring some
6670: values from definition-time to run-time. Gforth supports this use with
6671:
6672: doc-const-does>
6673:
6674: A typical use of this word is:
6675:
6676: @example
6677: : curry+ ( n1 "name" -- )
6678: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6679: + ;
6680:
6681: 3 curry+ 3+
6682: @end example
6683:
6684: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6685: definition to run-time.
6686:
6687: The advantages of using @code{const-does>} are:
6688:
6689: @itemize
6690:
6691: @item
6692: You don't have to deal with storing and retrieving the values, i.e.,
6693: your program becomes more writable and readable.
6694:
6695: @item
6696: When using @code{does>}, you have to introduce a @code{@@} that cannot
6697: be optimized away (because you could change the data using
6698: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6699:
6700: @end itemize
6701:
6702: An ANS Forth implementation of @code{const-does>} is available in
6703: @file{compat/const-does.fs}.
6704:
6705:
1.170 pazsan 6706: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6707: @subsection Deferred Words
1.44 crook 6708: @cindex deferred words
6709:
6710: The defining word @code{Defer} allows you to define a word by name
6711: without defining its behaviour; the definition of its behaviour is
6712: deferred. Here are two situation where this can be useful:
6713:
6714: @itemize @bullet
6715: @item
6716: Where you want to allow the behaviour of a word to be altered later, and
6717: for all precompiled references to the word to change when its behaviour
6718: is changed.
6719: @item
6720: For mutual recursion; @xref{Calls and returns}.
6721: @end itemize
6722:
6723: In the following example, @code{foo} always invokes the version of
6724: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6725: always invokes the version that prints ``@code{Hello}''. There is no way
6726: of getting @code{foo} to use the later version without re-ordering the
6727: source code and recompiling it.
6728:
6729: @example
6730: : greet ." Good morning" ;
6731: : foo ... greet ... ;
6732: : greet ." Hello" ;
6733: : bar ... greet ... ;
6734: @end example
6735:
6736: This problem can be solved by defining @code{greet} as a @code{Defer}red
6737: word. The behaviour of a @code{Defer}red word can be defined and
6738: redefined at any time by using @code{IS} to associate the xt of a
6739: previously-defined word with it. The previous example becomes:
6740:
6741: @example
1.69 anton 6742: Defer greet ( -- )
1.44 crook 6743: : foo ... greet ... ;
6744: : bar ... greet ... ;
1.69 anton 6745: : greet1 ( -- ) ." Good morning" ;
6746: : greet2 ( -- ) ." Hello" ;
1.132 anton 6747: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6748: @end example
6749:
1.69 anton 6750: @progstyle
6751: You should write a stack comment for every deferred word, and put only
6752: XTs into deferred words that conform to this stack effect. Otherwise
6753: it's too difficult to use the deferred word.
6754:
1.44 crook 6755: A deferred word can be used to improve the statistics-gathering example
6756: from @ref{User-defined Defining Words}; rather than edit the
6757: application's source code to change every @code{:} to a @code{my:}, do
6758: this:
6759:
6760: @example
6761: : real: : ; \ retain access to the original
6762: defer : \ redefine as a deferred word
1.132 anton 6763: ' my: IS : \ use special version of :
1.44 crook 6764: \
6765: \ load application here
6766: \
1.132 anton 6767: ' real: IS : \ go back to the original
1.44 crook 6768: @end example
6769:
6770:
1.132 anton 6771: One thing to note is that @code{IS} has special compilation semantics,
6772: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6773:
6774: @example
6775: : set-greet ( xt -- )
1.132 anton 6776: IS greet ;
1.44 crook 6777:
6778: ' greet1 set-greet
6779: @end example
6780:
1.132 anton 6781: In situations where @code{IS} does not fit, use @code{defer!} instead.
6782:
1.69 anton 6783: A deferred word can only inherit execution semantics from the xt
6784: (because that is all that an xt can represent -- for more discussion of
6785: this @pxref{Tokens for Words}); by default it will have default
6786: interpretation and compilation semantics deriving from this execution
6787: semantics. However, you can change the interpretation and compilation
6788: semantics of the deferred word in the usual ways:
1.44 crook 6789:
6790: @example
1.132 anton 6791: : bar .... ; immediate
1.44 crook 6792: Defer fred immediate
6793: Defer jim
6794:
1.132 anton 6795: ' bar IS jim \ jim has default semantics
6796: ' bar IS fred \ fred is immediate
1.44 crook 6797: @end example
6798:
6799: doc-defer
1.132 anton 6800: doc-defer!
1.44 crook 6801: doc-is
1.132 anton 6802: doc-defer@
6803: doc-action-of
1.44 crook 6804: @comment TODO document these: what's defers [is]
6805: doc-defers
6806:
6807: @c Use @code{words-deferred} to see a list of deferred words.
6808:
1.132 anton 6809: Definitions of these words (except @code{defers}) in ANS Forth are
6810: provided in @file{compat/defer.fs}.
1.44 crook 6811:
6812:
1.170 pazsan 6813: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6814: @subsection Aliases
6815: @cindex aliases
1.1 anton 6816:
1.44 crook 6817: The defining word @code{Alias} allows you to define a word by name that
6818: has the same behaviour as some other word. Here are two situation where
6819: this can be useful:
1.1 anton 6820:
1.44 crook 6821: @itemize @bullet
6822: @item
6823: When you want access to a word's definition from a different word list
6824: (for an example of this, see the definition of the @code{Root} word list
6825: in the Gforth source).
6826: @item
6827: When you want to create a synonym; a definition that can be known by
6828: either of two names (for example, @code{THEN} and @code{ENDIF} are
6829: aliases).
6830: @end itemize
1.1 anton 6831:
1.69 anton 6832: Like deferred words, an alias has default compilation and interpretation
6833: semantics at the beginning (not the modifications of the other word),
6834: but you can change them in the usual ways (@code{immediate},
6835: @code{compile-only}). For example:
1.1 anton 6836:
6837: @example
1.44 crook 6838: : foo ... ; immediate
6839:
6840: ' foo Alias bar \ bar is not an immediate word
6841: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6842: @end example
6843:
1.44 crook 6844: Words that are aliases have the same xt, different headers in the
6845: dictionary, and consequently different name tokens (@pxref{Tokens for
6846: Words}) and possibly different immediate flags. An alias can only have
6847: default or immediate compilation semantics; you can define aliases for
6848: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6849:
1.44 crook 6850: doc-alias
1.1 anton 6851:
6852:
1.47 crook 6853: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6854: @section Interpretation and Compilation Semantics
1.26 crook 6855: @cindex semantics, interpretation and compilation
1.1 anton 6856:
1.71 anton 6857: @c !! state and ' are used without explanation
6858: @c example for immediate/compile-only? or is the tutorial enough
6859:
1.26 crook 6860: @cindex interpretation semantics
1.71 anton 6861: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6862: interpreter does when it encounters the word in interpret state. It also
6863: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6864: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6865: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6866: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6867:
1.26 crook 6868: @cindex compilation semantics
1.71 anton 6869: The @dfn{compilation semantics} of a (named) word are what the text
6870: interpreter does when it encounters the word in compile state. It also
6871: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6872: compiles@footnote{In standard terminology, ``appends to the current
6873: definition''.} the compilation semantics of @i{word}.
1.1 anton 6874:
1.26 crook 6875: @cindex execution semantics
6876: The standard also talks about @dfn{execution semantics}. They are used
6877: only for defining the interpretation and compilation semantics of many
6878: words. By default, the interpretation semantics of a word are to
6879: @code{execute} its execution semantics, and the compilation semantics of
6880: a word are to @code{compile,} its execution semantics.@footnote{In
6881: standard terminology: The default interpretation semantics are its
6882: execution semantics; the default compilation semantics are to append its
6883: execution semantics to the execution semantics of the current
6884: definition.}
6885:
1.71 anton 6886: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6887: the text interpreter, ticked, or @code{postpone}d, so they have no
6888: interpretation or compilation semantics. Their behaviour is represented
6889: by their XT (@pxref{Tokens for Words}), and we call it execution
6890: semantics, too.
6891:
1.26 crook 6892: @comment TODO expand, make it co-operate with new sections on text interpreter.
6893:
6894: @cindex immediate words
6895: @cindex compile-only words
6896: You can change the semantics of the most-recently defined word:
6897:
1.44 crook 6898:
1.26 crook 6899: doc-immediate
6900: doc-compile-only
6901: doc-restrict
6902:
1.82 anton 6903: By convention, words with non-default compilation semantics (e.g.,
6904: immediate words) often have names surrounded with brackets (e.g.,
6905: @code{[']}, @pxref{Execution token}).
1.44 crook 6906:
1.26 crook 6907: Note that ticking (@code{'}) a compile-only word gives an error
6908: (``Interpreting a compile-only word'').
1.1 anton 6909:
1.47 crook 6910: @menu
1.67 anton 6911: * Combined words::
1.47 crook 6912: @end menu
1.44 crook 6913:
1.71 anton 6914:
1.48 anton 6915: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6916: @subsection Combined Words
6917: @cindex combined words
6918:
6919: Gforth allows you to define @dfn{combined words} -- words that have an
6920: arbitrary combination of interpretation and compilation semantics.
6921:
1.26 crook 6922: doc-interpret/compile:
1.1 anton 6923:
1.26 crook 6924: This feature was introduced for implementing @code{TO} and @code{S"}. I
6925: recommend that you do not define such words, as cute as they may be:
6926: they make it hard to get at both parts of the word in some contexts.
6927: E.g., assume you want to get an execution token for the compilation
6928: part. Instead, define two words, one that embodies the interpretation
6929: part, and one that embodies the compilation part. Once you have done
6930: that, you can define a combined word with @code{interpret/compile:} for
6931: the convenience of your users.
1.1 anton 6932:
1.26 crook 6933: You might try to use this feature to provide an optimizing
6934: implementation of the default compilation semantics of a word. For
6935: example, by defining:
1.1 anton 6936: @example
1.26 crook 6937: :noname
6938: foo bar ;
6939: :noname
6940: POSTPONE foo POSTPONE bar ;
1.29 crook 6941: interpret/compile: opti-foobar
1.1 anton 6942: @end example
1.26 crook 6943:
1.23 crook 6944: @noindent
1.26 crook 6945: as an optimizing version of:
6946:
1.1 anton 6947: @example
1.26 crook 6948: : foobar
6949: foo bar ;
1.1 anton 6950: @end example
6951:
1.26 crook 6952: Unfortunately, this does not work correctly with @code{[compile]},
6953: because @code{[compile]} assumes that the compilation semantics of all
6954: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6955: opti-foobar} would compile compilation semantics, whereas
6956: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6957:
1.26 crook 6958: @cindex state-smart words (are a bad idea)
1.82 anton 6959: @anchor{state-smartness}
1.29 crook 6960: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6961: by @code{interpret/compile:} (words are state-smart if they check
6962: @code{STATE} during execution). E.g., they would try to code
6963: @code{foobar} like this:
1.1 anton 6964:
1.26 crook 6965: @example
6966: : foobar
6967: STATE @@
6968: IF ( compilation state )
6969: POSTPONE foo POSTPONE bar
6970: ELSE
6971: foo bar
6972: ENDIF ; immediate
6973: @end example
1.1 anton 6974:
1.26 crook 6975: Although this works if @code{foobar} is only processed by the text
6976: interpreter, it does not work in other contexts (like @code{'} or
6977: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6978: for a state-smart word, not for the interpretation semantics of the
6979: original @code{foobar}; when you execute this execution token (directly
6980: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6981: state, the result will not be what you expected (i.e., it will not
6982: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6983: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6984: M. Anton Ertl,
6985: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6986: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6987:
1.26 crook 6988: @cindex defining words with arbitrary semantics combinations
6989: It is also possible to write defining words that define words with
6990: arbitrary combinations of interpretation and compilation semantics. In
6991: general, they look like this:
1.1 anton 6992:
1.26 crook 6993: @example
6994: : def-word
6995: create-interpret/compile
1.29 crook 6996: @i{code1}
1.26 crook 6997: interpretation>
1.29 crook 6998: @i{code2}
1.26 crook 6999: <interpretation
7000: compilation>
1.29 crook 7001: @i{code3}
1.26 crook 7002: <compilation ;
7003: @end example
1.1 anton 7004:
1.29 crook 7005: For a @i{word} defined with @code{def-word}, the interpretation
7006: semantics are to push the address of the body of @i{word} and perform
7007: @i{code2}, and the compilation semantics are to push the address of
7008: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7009: can also be defined like this (except that the defined constants don't
7010: behave correctly when @code{[compile]}d):
1.1 anton 7011:
1.26 crook 7012: @example
7013: : constant ( n "name" -- )
7014: create-interpret/compile
7015: ,
7016: interpretation> ( -- n )
7017: @@
7018: <interpretation
7019: compilation> ( compilation. -- ; run-time. -- n )
7020: @@ postpone literal
7021: <compilation ;
7022: @end example
1.1 anton 7023:
1.44 crook 7024:
1.26 crook 7025: doc-create-interpret/compile
7026: doc-interpretation>
7027: doc-<interpretation
7028: doc-compilation>
7029: doc-<compilation
1.1 anton 7030:
1.44 crook 7031:
1.29 crook 7032: Words defined with @code{interpret/compile:} and
1.26 crook 7033: @code{create-interpret/compile} have an extended header structure that
7034: differs from other words; however, unless you try to access them with
7035: plain address arithmetic, you should not notice this. Words for
7036: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7037: @code{'} @i{word} @code{>body} also gives you the body of a word created
7038: with @code{create-interpret/compile}.
1.1 anton 7039:
1.44 crook 7040:
1.47 crook 7041: @c -------------------------------------------------------------
1.81 anton 7042: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7043: @section Tokens for Words
7044: @cindex tokens for words
7045:
7046: This section describes the creation and use of tokens that represent
7047: words.
7048:
1.71 anton 7049: @menu
7050: * Execution token:: represents execution/interpretation semantics
7051: * Compilation token:: represents compilation semantics
7052: * Name token:: represents named words
7053: @end menu
1.47 crook 7054:
1.71 anton 7055: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7056: @subsection Execution token
1.47 crook 7057:
7058: @cindex xt
7059: @cindex execution token
1.71 anton 7060: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7061: You can use @code{execute} to invoke this behaviour.
1.47 crook 7062:
1.71 anton 7063: @cindex tick (')
7064: You can use @code{'} to get an execution token that represents the
7065: interpretation semantics of a named word:
1.47 crook 7066:
7067: @example
1.97 anton 7068: 5 ' . ( n xt )
7069: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7070: @end example
1.47 crook 7071:
1.71 anton 7072: doc-'
7073:
7074: @code{'} parses at run-time; there is also a word @code{[']} that parses
7075: when it is compiled, and compiles the resulting XT:
7076:
7077: @example
7078: : foo ['] . execute ;
7079: 5 foo
7080: : bar ' execute ; \ by contrast,
7081: 5 bar . \ ' parses "." when bar executes
7082: @end example
7083:
7084: doc-[']
7085:
7086: If you want the execution token of @i{word}, write @code{['] @i{word}}
7087: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7088: @code{'} and @code{[']} behave somewhat unusually by complaining about
7089: compile-only words (because these words have no interpretation
7090: semantics). You might get what you want by using @code{COMP' @i{word}
7091: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7092: token}).
7093:
1.116 anton 7094: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7095: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7096: for the only behaviour the word has (the execution semantics). For
1.116 anton 7097: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7098: would produce if the word was defined anonymously.
7099:
7100: @example
7101: :noname ." hello" ;
7102: execute
1.47 crook 7103: @end example
7104:
1.71 anton 7105: An XT occupies one cell and can be manipulated like any other cell.
7106:
1.47 crook 7107: @cindex code field address
7108: @cindex CFA
1.71 anton 7109: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7110: operations that produce or consume it). For old hands: In Gforth, the
7111: XT is implemented as a code field address (CFA).
7112:
7113: doc-execute
7114: doc-perform
7115:
7116: @node Compilation token, Name token, Execution token, Tokens for Words
7117: @subsection Compilation token
1.47 crook 7118:
7119: @cindex compilation token
1.71 anton 7120: @cindex CT (compilation token)
7121: Gforth represents the compilation semantics of a named word by a
1.47 crook 7122: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7123: @i{xt} is an execution token. The compilation semantics represented by
7124: the compilation token can be performed with @code{execute}, which
7125: consumes the whole compilation token, with an additional stack effect
7126: determined by the represented compilation semantics.
7127:
7128: At present, the @i{w} part of a compilation token is an execution token,
7129: and the @i{xt} part represents either @code{execute} or
7130: @code{compile,}@footnote{Depending upon the compilation semantics of the
7131: word. If the word has default compilation semantics, the @i{xt} will
7132: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7133: @i{xt} will represent @code{execute}.}. However, don't rely on that
7134: knowledge, unless necessary; future versions of Gforth may introduce
7135: unusual compilation tokens (e.g., a compilation token that represents
7136: the compilation semantics of a literal).
7137:
1.71 anton 7138: You can perform the compilation semantics represented by the compilation
7139: token with @code{execute}. You can compile the compilation semantics
7140: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7141: equivalent to @code{postpone @i{word}}.
7142:
7143: doc-[comp']
7144: doc-comp'
7145: doc-postpone,
7146:
7147: @node Name token, , Compilation token, Tokens for Words
7148: @subsection Name token
1.47 crook 7149:
7150: @cindex name token
1.116 anton 7151: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7152: token is an abstract data type that occurs as argument or result of the
7153: words below.
7154:
7155: @c !! put this elswhere?
1.47 crook 7156: @cindex name field address
7157: @cindex NFA
1.116 anton 7158: The closest thing to the nt in older Forth systems is the name field
7159: address (NFA), but there are significant differences: in older Forth
7160: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7161: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7162: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7163: is a link field in the structure identified by the name token, but
7164: searching usually uses a hash table external to these structures; the
7165: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7166: implemented as the address of that count field.
1.47 crook 7167:
7168: doc-find-name
1.116 anton 7169: doc-latest
7170: doc->name
1.47 crook 7171: doc-name>int
7172: doc-name?int
7173: doc-name>comp
7174: doc-name>string
1.109 anton 7175: doc-id.
7176: doc-.name
7177: doc-.id
1.47 crook 7178:
1.81 anton 7179: @c ----------------------------------------------------------
7180: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7181: @section Compiling words
7182: @cindex compiling words
7183: @cindex macros
7184:
7185: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7186: between compilation and run-time. E.g., you can run arbitrary code
7187: between defining words (or for computing data used by defining words
7188: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7189: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7190: running arbitrary code while compiling a colon definition (exception:
7191: you must not allot dictionary space).
7192:
7193: @menu
7194: * Literals:: Compiling data values
7195: * Macros:: Compiling words
7196: @end menu
7197:
7198: @node Literals, Macros, Compiling words, Compiling words
7199: @subsection Literals
7200: @cindex Literals
7201:
7202: The simplest and most frequent example is to compute a literal during
7203: compilation. E.g., the following definition prints an array of strings,
7204: one string per line:
7205:
7206: @example
7207: : .strings ( addr u -- ) \ gforth
7208: 2* cells bounds U+DO
7209: cr i 2@@ type
7210: 2 cells +LOOP ;
7211: @end example
1.81 anton 7212:
1.82 anton 7213: With a simple-minded compiler like Gforth's, this computes @code{2
7214: cells} on every loop iteration. You can compute this value once and for
7215: all at compile time and compile it into the definition like this:
7216:
7217: @example
7218: : .strings ( addr u -- ) \ gforth
7219: 2* cells bounds U+DO
7220: cr i 2@@ type
7221: [ 2 cells ] literal +LOOP ;
7222: @end example
7223:
7224: @code{[} switches the text interpreter to interpret state (you will get
7225: an @code{ok} prompt if you type this example interactively and insert a
7226: newline between @code{[} and @code{]}), so it performs the
7227: interpretation semantics of @code{2 cells}; this computes a number.
7228: @code{]} switches the text interpreter back into compile state. It then
7229: performs @code{Literal}'s compilation semantics, which are to compile
7230: this number into the current word. You can decompile the word with
7231: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7232:
1.82 anton 7233: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7234: *} in this way.
1.81 anton 7235:
1.82 anton 7236: doc-[
7237: doc-]
1.81 anton 7238: doc-literal
7239: doc-]L
1.82 anton 7240:
7241: There are also words for compiling other data types than single cells as
7242: literals:
7243:
1.81 anton 7244: doc-2literal
7245: doc-fliteral
1.82 anton 7246: doc-sliteral
7247:
7248: @cindex colon-sys, passing data across @code{:}
7249: @cindex @code{:}, passing data across
7250: You might be tempted to pass data from outside a colon definition to the
7251: inside on the data stack. This does not work, because @code{:} puhes a
7252: colon-sys, making stuff below unaccessible. E.g., this does not work:
7253:
7254: @example
7255: 5 : foo literal ; \ error: "unstructured"
7256: @end example
7257:
7258: Instead, you have to pass the value in some other way, e.g., through a
7259: variable:
7260:
7261: @example
7262: variable temp
7263: 5 temp !
7264: : foo [ temp @@ ] literal ;
7265: @end example
7266:
7267:
7268: @node Macros, , Literals, Compiling words
7269: @subsection Macros
7270: @cindex Macros
7271: @cindex compiling compilation semantics
7272:
7273: @code{Literal} and friends compile data values into the current
7274: definition. You can also write words that compile other words into the
7275: current definition. E.g.,
7276:
7277: @example
7278: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7279: POSTPONE + ;
7280:
7281: : foo ( n1 n2 -- n )
7282: [ compile-+ ] ;
7283: 1 2 foo .
7284: @end example
7285:
7286: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7287: What happens in this example? @code{Postpone} compiles the compilation
7288: semantics of @code{+} into @code{compile-+}; later the text interpreter
7289: executes @code{compile-+} and thus the compilation semantics of +, which
7290: compile (the execution semantics of) @code{+} into
7291: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7292: should only be executed in compile state, so this example is not
7293: guaranteed to work on all standard systems, but on any decent system it
7294: will work.}
7295:
7296: doc-postpone
7297: doc-[compile]
7298:
7299: Compiling words like @code{compile-+} are usually immediate (or similar)
7300: so you do not have to switch to interpret state to execute them;
7301: mopifying the last example accordingly produces:
7302:
7303: @example
7304: : [compile-+] ( compilation: --; interpretation: -- )
7305: \ compiled code: ( n1 n2 -- n )
7306: POSTPONE + ; immediate
7307:
7308: : foo ( n1 n2 -- n )
7309: [compile-+] ;
7310: 1 2 foo .
7311: @end example
7312:
7313: Immediate compiling words are similar to macros in other languages (in
7314: particular, Lisp). The important differences to macros in, e.g., C are:
7315:
7316: @itemize @bullet
7317:
7318: @item
7319: You use the same language for defining and processing macros, not a
7320: separate preprocessing language and processor.
7321:
7322: @item
7323: Consequently, the full power of Forth is available in macro definitions.
7324: E.g., you can perform arbitrarily complex computations, or generate
7325: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7326: Tutorial}). This power is very useful when writing a parser generators
7327: or other code-generating software.
7328:
7329: @item
7330: Macros defined using @code{postpone} etc. deal with the language at a
7331: higher level than strings; name binding happens at macro definition
7332: time, so you can avoid the pitfalls of name collisions that can happen
7333: in C macros. Of course, Forth is a liberal language and also allows to
7334: shoot yourself in the foot with text-interpreted macros like
7335:
7336: @example
7337: : [compile-+] s" +" evaluate ; immediate
7338: @end example
7339:
7340: Apart from binding the name at macro use time, using @code{evaluate}
7341: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7342: @end itemize
7343:
7344: You may want the macro to compile a number into a word. The word to do
7345: it is @code{literal}, but you have to @code{postpone} it, so its
7346: compilation semantics take effect when the macro is executed, not when
7347: it is compiled:
7348:
7349: @example
7350: : [compile-5] ( -- ) \ compiled code: ( -- n )
7351: 5 POSTPONE literal ; immediate
7352:
7353: : foo [compile-5] ;
7354: foo .
7355: @end example
7356:
7357: You may want to pass parameters to a macro, that the macro should
7358: compile into the current definition. If the parameter is a number, then
7359: you can use @code{postpone literal} (similar for other values).
7360:
7361: If you want to pass a word that is to be compiled, the usual way is to
7362: pass an execution token and @code{compile,} it:
7363:
7364: @example
7365: : twice1 ( xt -- ) \ compiled code: ... -- ...
7366: dup compile, compile, ;
7367:
7368: : 2+ ( n1 -- n2 )
7369: [ ' 1+ twice1 ] ;
7370: @end example
7371:
7372: doc-compile,
7373:
7374: An alternative available in Gforth, that allows you to pass compile-only
7375: words as parameters is to use the compilation token (@pxref{Compilation
7376: token}). The same example in this technique:
7377:
7378: @example
7379: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7380: 2dup 2>r execute 2r> execute ;
7381:
7382: : 2+ ( n1 -- n2 )
7383: [ comp' 1+ twice ] ;
7384: @end example
7385:
7386: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7387: works even if the executed compilation semantics has an effect on the
7388: data stack.
7389:
7390: You can also define complete definitions with these words; this provides
7391: an alternative to using @code{does>} (@pxref{User-defined Defining
7392: Words}). E.g., instead of
7393:
7394: @example
7395: : curry+ ( n1 "name" -- )
7396: CREATE ,
7397: DOES> ( n2 -- n1+n2 )
7398: @@ + ;
7399: @end example
7400:
7401: you could define
7402:
7403: @example
7404: : curry+ ( n1 "name" -- )
7405: \ name execution: ( n2 -- n1+n2 )
7406: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7407:
1.82 anton 7408: -3 curry+ 3-
7409: see 3-
7410: @end example
1.81 anton 7411:
1.82 anton 7412: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7413: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7414:
1.82 anton 7415: This way of writing defining words is sometimes more, sometimes less
7416: convenient than using @code{does>} (@pxref{Advanced does> usage
7417: example}). One advantage of this method is that it can be optimized
7418: better, because the compiler knows that the value compiled with
7419: @code{literal} is fixed, whereas the data associated with a
7420: @code{create}d word can be changed.
1.47 crook 7421:
1.26 crook 7422: @c ----------------------------------------------------------
1.111 anton 7423: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7424: @section The Text Interpreter
7425: @cindex interpreter - outer
7426: @cindex text interpreter
7427: @cindex outer interpreter
1.1 anton 7428:
1.34 anton 7429: @c Should we really describe all these ugly details? IMO the text
7430: @c interpreter should be much cleaner, but that may not be possible within
7431: @c ANS Forth. - anton
1.44 crook 7432: @c nac-> I wanted to explain how it works to show how you can exploit
7433: @c it in your own programs. When I was writing a cross-compiler, figuring out
7434: @c some of these gory details was very helpful to me. None of the textbooks
7435: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7436: @c seems to positively avoid going into too much detail for some of
7437: @c the internals.
1.34 anton 7438:
1.71 anton 7439: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7440: @c it is; for the ugly details, I would prefer another place. I wonder
7441: @c whether we should have a chapter before "Words" that describes some
7442: @c basic concepts referred to in words, and a chapter after "Words" that
7443: @c describes implementation details.
7444:
1.29 crook 7445: The text interpreter@footnote{This is an expanded version of the
7446: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7447: that processes input from the current input device. It is also called
7448: the outer interpreter, in contrast to the inner interpreter
7449: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7450: implementations.
1.27 crook 7451:
1.29 crook 7452: @cindex interpret state
7453: @cindex compile state
7454: The text interpreter operates in one of two states: @dfn{interpret
7455: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7456: aptly-named variable @code{state}.
1.29 crook 7457:
7458: This section starts by describing how the text interpreter behaves when
7459: it is in interpret state, processing input from the user input device --
7460: the keyboard. This is the mode that a Forth system is in after it starts
7461: up.
7462:
7463: @cindex input buffer
7464: @cindex terminal input buffer
7465: The text interpreter works from an area of memory called the @dfn{input
7466: buffer}@footnote{When the text interpreter is processing input from the
7467: keyboard, this area of memory is called the @dfn{terminal input buffer}
7468: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7469: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7470: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7471: leading spaces (called @dfn{delimiters}) then parses a string (a
7472: sequence of non-space characters) until it reaches either a space
7473: character or the end of the buffer. Having parsed a string, it makes two
7474: attempts to process it:
1.27 crook 7475:
1.29 crook 7476: @cindex dictionary
1.27 crook 7477: @itemize @bullet
7478: @item
1.29 crook 7479: It looks for the string in a @dfn{dictionary} of definitions. If the
7480: string is found, the string names a @dfn{definition} (also known as a
7481: @dfn{word}) and the dictionary search returns information that allows
7482: the text interpreter to perform the word's @dfn{interpretation
7483: semantics}. In most cases, this simply means that the word will be
7484: executed.
1.27 crook 7485: @item
7486: If the string is not found in the dictionary, the text interpreter
1.29 crook 7487: attempts to treat it as a number, using the rules described in
7488: @ref{Number Conversion}. If the string represents a legal number in the
7489: current radix, the number is pushed onto a parameter stack (the data
7490: stack for integers, the floating-point stack for floating-point
7491: numbers).
7492: @end itemize
7493:
7494: If both attempts fail, or if the word is found in the dictionary but has
7495: no interpretation semantics@footnote{This happens if the word was
7496: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7497: remainder of the input buffer, issues an error message and waits for
7498: more input. If one of the attempts succeeds, the text interpreter
7499: repeats the parsing process until the whole of the input buffer has been
7500: processed, at which point it prints the status message ``@code{ ok}''
7501: and waits for more input.
7502:
1.71 anton 7503: @c anton: this should be in the input stream subsection (or below it)
7504:
1.29 crook 7505: @cindex parse area
7506: The text interpreter keeps track of its position in the input buffer by
7507: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7508: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7509: of the input buffer. The region from offset @code{>IN @@} to the end of
7510: the input buffer is called the @dfn{parse area}@footnote{In other words,
7511: the text interpreter processes the contents of the input buffer by
7512: parsing strings from the parse area until the parse area is empty.}.
7513: This example shows how @code{>IN} changes as the text interpreter parses
7514: the input buffer:
7515:
7516: @example
7517: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7518: CR ." ->" TYPE ." <-" ; IMMEDIATE
7519:
7520: 1 2 3 remaining + remaining .
7521:
7522: : foo 1 2 3 remaining SWAP remaining ;
7523: @end example
7524:
7525: @noindent
7526: The result is:
7527:
7528: @example
7529: ->+ remaining .<-
7530: ->.<-5 ok
7531:
7532: ->SWAP remaining ;-<
7533: ->;<- ok
7534: @end example
7535:
7536: @cindex parsing words
7537: The value of @code{>IN} can also be modified by a word in the input
7538: buffer that is executed by the text interpreter. This means that a word
7539: can ``trick'' the text interpreter into either skipping a section of the
7540: input buffer@footnote{This is how parsing words work.} or into parsing a
7541: section twice. For example:
1.27 crook 7542:
1.29 crook 7543: @example
1.71 anton 7544: : lat ." <<foo>>" ;
7545: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7546: @end example
7547:
7548: @noindent
7549: When @code{flat} is executed, this output is produced@footnote{Exercise
7550: for the reader: what would happen if the @code{3} were replaced with
7551: @code{4}?}:
7552:
7553: @example
1.71 anton 7554: <<bar>><<foo>>
1.29 crook 7555: @end example
7556:
1.71 anton 7557: This technique can be used to work around some of the interoperability
7558: problems of parsing words. Of course, it's better to avoid parsing
7559: words where possible.
7560:
1.29 crook 7561: @noindent
7562: Two important notes about the behaviour of the text interpreter:
1.27 crook 7563:
7564: @itemize @bullet
7565: @item
7566: It processes each input string to completion before parsing additional
1.29 crook 7567: characters from the input buffer.
7568: @item
7569: It treats the input buffer as a read-only region (and so must your code).
7570: @end itemize
7571:
7572: @noindent
7573: When the text interpreter is in compile state, its behaviour changes in
7574: these ways:
7575:
7576: @itemize @bullet
7577: @item
7578: If a parsed string is found in the dictionary, the text interpreter will
7579: perform the word's @dfn{compilation semantics}. In most cases, this
7580: simply means that the execution semantics of the word will be appended
7581: to the current definition.
1.27 crook 7582: @item
1.29 crook 7583: When a number is encountered, it is compiled into the current definition
7584: (as a literal) rather than being pushed onto a parameter stack.
7585: @item
7586: If an error occurs, @code{state} is modified to put the text interpreter
7587: back into interpret state.
7588: @item
7589: Each time a line is entered from the keyboard, Gforth prints
7590: ``@code{ compiled}'' rather than `` @code{ok}''.
7591: @end itemize
7592:
7593: @cindex text interpreter - input sources
7594: When the text interpreter is using an input device other than the
7595: keyboard, its behaviour changes in these ways:
7596:
7597: @itemize @bullet
7598: @item
7599: When the parse area is empty, the text interpreter attempts to refill
7600: the input buffer from the input source. When the input source is
1.71 anton 7601: exhausted, the input source is set back to the previous input source.
1.29 crook 7602: @item
7603: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7604: time the parse area is emptied.
7605: @item
7606: If an error occurs, the input source is set back to the user input
7607: device.
1.27 crook 7608: @end itemize
1.21 crook 7609:
1.49 anton 7610: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7611:
1.26 crook 7612: doc->in
1.27 crook 7613: doc-source
7614:
1.26 crook 7615: doc-tib
7616: doc-#tib
1.1 anton 7617:
1.44 crook 7618:
1.26 crook 7619: @menu
1.67 anton 7620: * Input Sources::
7621: * Number Conversion::
7622: * Interpret/Compile states::
7623: * Interpreter Directives::
1.26 crook 7624: @end menu
1.1 anton 7625:
1.29 crook 7626: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7627: @subsection Input Sources
7628: @cindex input sources
7629: @cindex text interpreter - input sources
7630:
1.44 crook 7631: By default, the text interpreter processes input from the user input
1.29 crook 7632: device (the keyboard) when Forth starts up. The text interpreter can
7633: process input from any of these sources:
7634:
7635: @itemize @bullet
7636: @item
7637: The user input device -- the keyboard.
7638: @item
7639: A file, using the words described in @ref{Forth source files}.
7640: @item
7641: A block, using the words described in @ref{Blocks}.
7642: @item
7643: A text string, using @code{evaluate}.
7644: @end itemize
7645:
7646: A program can identify the current input device from the values of
7647: @code{source-id} and @code{blk}.
7648:
1.44 crook 7649:
1.29 crook 7650: doc-source-id
7651: doc-blk
7652:
7653: doc-save-input
7654: doc-restore-input
7655:
7656: doc-evaluate
1.111 anton 7657: doc-query
1.1 anton 7658:
1.29 crook 7659:
1.44 crook 7660:
1.29 crook 7661: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7662: @subsection Number Conversion
7663: @cindex number conversion
7664: @cindex double-cell numbers, input format
7665: @cindex input format for double-cell numbers
7666: @cindex single-cell numbers, input format
7667: @cindex input format for single-cell numbers
7668: @cindex floating-point numbers, input format
7669: @cindex input format for floating-point numbers
1.1 anton 7670:
1.29 crook 7671: This section describes the rules that the text interpreter uses when it
7672: tries to convert a string into a number.
1.1 anton 7673:
1.26 crook 7674: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7675: number base@footnote{For example, 0-9 when the number base is decimal or
7676: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7677:
1.26 crook 7678: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7679:
1.29 crook 7680: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7681: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7682:
1.26 crook 7683: Let * represent any number of instances of the previous character
7684: (including none).
1.1 anton 7685:
1.26 crook 7686: Let any other character represent itself.
1.1 anton 7687:
1.29 crook 7688: @noindent
1.26 crook 7689: Now, the conversion rules are:
1.21 crook 7690:
1.26 crook 7691: @itemize @bullet
7692: @item
7693: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7694: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7695: @item
7696: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7697: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7698: arithmetic. Examples are -45 -5681 -0
7699: @item
7700: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7701: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7702: (all three of these represent the same number).
1.26 crook 7703: @item
7704: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7705: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7706: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7707: -34.65 (all three of these represent the same number).
1.26 crook 7708: @item
1.29 crook 7709: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7710: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7711: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7712: number) +12.E-4
1.26 crook 7713: @end itemize
1.1 anton 7714:
1.174 anton 7715: By default, the number base used for integer number conversion is
7716: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7717: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7718: change @code{base} anywhere, make sure to save the old value and
7719: restore it afterwards; better yet, use @code{base-execute}, which does
7720: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7721: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7722:
1.29 crook 7723: doc-dpl
1.174 anton 7724: doc-base-execute
1.26 crook 7725: doc-base
7726: doc-hex
7727: doc-decimal
1.1 anton 7728:
1.26 crook 7729: @cindex '-prefix for character strings
7730: @cindex &-prefix for decimal numbers
1.133 anton 7731: @cindex #-prefix for decimal numbers
1.26 crook 7732: @cindex %-prefix for binary numbers
7733: @cindex $-prefix for hexadecimal numbers
1.133 anton 7734: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7735: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7736: prefix@footnote{Some Forth implementations provide a similar scheme by
7737: implementing @code{$} etc. as parsing words that process the subsequent
7738: number in the input stream and push it onto the stack. For example, see
7739: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7740: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7741: is required between the prefix and the number.} before the first digit
1.133 anton 7742: of an (integer) number. The following prefixes are supported:
1.1 anton 7743:
1.26 crook 7744: @itemize @bullet
7745: @item
1.35 anton 7746: @code{&} -- decimal
1.26 crook 7747: @item
1.133 anton 7748: @code{#} -- decimal
7749: @item
1.35 anton 7750: @code{%} -- binary
1.26 crook 7751: @item
1.35 anton 7752: @code{$} -- hexadecimal
1.26 crook 7753: @item
1.133 anton 7754: @code{0x} -- hexadecimal, if base<33.
7755: @item
7756: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7757: optional @code{'} may be present after the character.
1.26 crook 7758: @end itemize
1.1 anton 7759:
1.26 crook 7760: Here are some examples, with the equivalent decimal number shown after
7761: in braces:
1.1 anton 7762:
1.26 crook 7763: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7764: 'A (65),
7765: -'a' (-97),
1.26 crook 7766: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7767:
1.26 crook 7768: @cindex number conversion - traps for the unwary
1.29 crook 7769: @noindent
1.26 crook 7770: Number conversion has a number of traps for the unwary:
1.1 anton 7771:
1.26 crook 7772: @itemize @bullet
7773: @item
7774: You cannot determine the current number base using the code sequence
1.35 anton 7775: @code{base @@ .} -- the number base is always 10 in the current number
7776: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7777: @item
7778: If the number base is set to a value greater than 14 (for example,
7779: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7780: it to be intepreted as either a single-precision integer or a
7781: floating-point number (Gforth treats it as an integer). The ambiguity
7782: can be resolved by explicitly stating the sign of the mantissa and/or
7783: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7784: ambiguity arises; either representation will be treated as a
7785: floating-point number.
7786: @item
1.29 crook 7787: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7788: It is used to specify file types.
7789: @item
1.72 anton 7790: ANS Forth requires the @code{.} of a double-precision number to be the
7791: final character in the string. Gforth allows the @code{.} to be
7792: anywhere after the first digit.
1.26 crook 7793: @item
7794: The number conversion process does not check for overflow.
7795: @item
1.72 anton 7796: In an ANS Forth program @code{base} is required to be decimal when
7797: converting floating-point numbers. In Gforth, number conversion to
7798: floating-point numbers always uses base &10, irrespective of the value
7799: of @code{base}.
1.26 crook 7800: @end itemize
1.1 anton 7801:
1.49 anton 7802: You can read numbers into your programs with the words described in
1.181 anton 7803: @ref{Line input and conversion}.
1.1 anton 7804:
1.82 anton 7805: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7806: @subsection Interpret/Compile states
7807: @cindex Interpret/Compile states
1.1 anton 7808:
1.29 crook 7809: A standard program is not permitted to change @code{state}
7810: explicitly. However, it can change @code{state} implicitly, using the
7811: words @code{[} and @code{]}. When @code{[} is executed it switches
7812: @code{state} to interpret state, and therefore the text interpreter
7813: starts interpreting. When @code{]} is executed it switches @code{state}
7814: to compile state and therefore the text interpreter starts
1.44 crook 7815: compiling. The most common usage for these words is for switching into
7816: interpret state and back from within a colon definition; this technique
1.49 anton 7817: can be used to compile a literal (for an example, @pxref{Literals}) or
7818: for conditional compilation (for an example, @pxref{Interpreter
7819: Directives}).
1.44 crook 7820:
1.35 anton 7821:
7822: @c This is a bad example: It's non-standard, and it's not necessary.
7823: @c However, I can't think of a good example for switching into compile
7824: @c state when there is no current word (@code{state}-smart words are not a
7825: @c good reason). So maybe we should use an example for switching into
7826: @c interpret @code{state} in a colon def. - anton
1.44 crook 7827: @c nac-> I agree. I started out by putting in the example, then realised
7828: @c that it was non-ANS, so wrote more words around it. I hope this
7829: @c re-written version is acceptable to you. I do want to keep the example
7830: @c as it is helpful for showing what is and what is not portable, particularly
7831: @c where it outlaws a style in common use.
7832:
1.72 anton 7833: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7834: @c that, we can also show what's not. In any case, I have written a
7835: @c section Compiling Words which also deals with [ ].
1.35 anton 7836:
1.95 anton 7837: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7838:
1.95 anton 7839: @c @code{[} and @code{]} also give you the ability to switch into compile
7840: @c state and back, but we cannot think of any useful Standard application
7841: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7842:
7843: @c @example
7844: @c : AA ." this is A" ;
7845: @c : BB ." this is B" ;
7846: @c : CC ." this is C" ;
7847:
7848: @c create table ] aa bb cc [
7849:
7850: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7851: @c cells table + @@ execute ;
7852: @c @end example
7853:
7854: @c This example builds a jump table; @code{0 go} will display ``@code{this
7855: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7856: @c defining @code{table} like this:
7857:
7858: @c @example
7859: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7860: @c @end example
7861:
7862: @c The problem with this code is that the definition of @code{table} is not
7863: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7864: @c @i{may} work on systems where code space and data space co-incide, the
7865: @c Standard only allows data space to be assigned for a @code{CREATE}d
7866: @c word. In addition, the Standard only allows @code{@@} to access data
7867: @c space, whilst this example is using it to access code space. The only
7868: @c portable, Standard way to build this table is to build it in data space,
7869: @c like this:
7870:
7871: @c @example
7872: @c create table ' aa , ' bb , ' cc ,
7873: @c @end example
1.29 crook 7874:
1.95 anton 7875: @c doc-state
1.44 crook 7876:
1.29 crook 7877:
1.82 anton 7878: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7879: @subsection Interpreter Directives
7880: @cindex interpreter directives
1.72 anton 7881: @cindex conditional compilation
1.1 anton 7882:
1.29 crook 7883: These words are usually used in interpret state; typically to control
7884: which parts of a source file are processed by the text
1.26 crook 7885: interpreter. There are only a few ANS Forth Standard words, but Gforth
7886: supplements these with a rich set of immediate control structure words
7887: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7888: used in compile state (@pxref{Control Structures}). Typical usages:
7889:
7890: @example
1.72 anton 7891: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7892: .
7893: .
1.72 anton 7894: HAVE-ASSEMBLER [IF]
1.29 crook 7895: : ASSEMBLER-FEATURE
7896: ...
7897: ;
7898: [ENDIF]
7899: .
7900: .
7901: : SEE
7902: ... \ general-purpose SEE code
1.72 anton 7903: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7904: ... \ assembler-specific SEE code
7905: [ [ENDIF] ]
7906: ;
7907: @end example
1.1 anton 7908:
1.44 crook 7909:
1.26 crook 7910: doc-[IF]
7911: doc-[ELSE]
7912: doc-[THEN]
7913: doc-[ENDIF]
1.1 anton 7914:
1.26 crook 7915: doc-[IFDEF]
7916: doc-[IFUNDEF]
1.1 anton 7917:
1.26 crook 7918: doc-[?DO]
7919: doc-[DO]
7920: doc-[FOR]
7921: doc-[LOOP]
7922: doc-[+LOOP]
7923: doc-[NEXT]
1.1 anton 7924:
1.26 crook 7925: doc-[BEGIN]
7926: doc-[UNTIL]
7927: doc-[AGAIN]
7928: doc-[WHILE]
7929: doc-[REPEAT]
1.1 anton 7930:
1.27 crook 7931:
1.26 crook 7932: @c -------------------------------------------------------------
1.111 anton 7933: @node The Input Stream, Word Lists, The Text Interpreter, Words
7934: @section The Input Stream
7935: @cindex input stream
7936:
7937: @c !! integrate this better with the "Text Interpreter" section
7938: The text interpreter reads from the input stream, which can come from
7939: several sources (@pxref{Input Sources}). Some words, in particular
7940: defining words, but also words like @code{'}, read parameters from the
7941: input stream instead of from the stack.
7942:
7943: Such words are called parsing words, because they parse the input
7944: stream. Parsing words are hard to use in other words, because it is
7945: hard to pass program-generated parameters through the input stream.
7946: They also usually have an unintuitive combination of interpretation and
7947: compilation semantics when implemented naively, leading to various
7948: approaches that try to produce a more intuitive behaviour
7949: (@pxref{Combined words}).
7950:
7951: It should be obvious by now that parsing words are a bad idea. If you
7952: want to implement a parsing word for convenience, also provide a factor
7953: of the word that does not parse, but takes the parameters on the stack.
7954: To implement the parsing word on top if it, you can use the following
7955: words:
7956:
7957: @c anton: these belong in the input stream section
7958: doc-parse
1.138 anton 7959: doc-parse-name
1.111 anton 7960: doc-parse-word
7961: doc-name
7962: doc-word
7963: doc-refill
7964:
7965: Conversely, if you have the bad luck (or lack of foresight) to have to
7966: deal with parsing words without having such factors, how do you pass a
7967: string that is not in the input stream to it?
7968:
7969: doc-execute-parsing
7970:
1.146 anton 7971: A definition of this word in ANS Forth is provided in
7972: @file{compat/execute-parsing.fs}.
7973:
1.111 anton 7974: If you want to run a parsing word on a file, the following word should
7975: help:
7976:
7977: doc-execute-parsing-file
7978:
7979: @c -------------------------------------------------------------
7980: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7981: @section Word Lists
7982: @cindex word lists
1.32 anton 7983: @cindex header space
1.1 anton 7984:
1.36 anton 7985: A wordlist is a list of named words; you can add new words and look up
7986: words by name (and you can remove words in a restricted way with
7987: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7988:
7989: @cindex search order stack
7990: The text interpreter searches the wordlists present in the search order
7991: (a stack of wordlists), from the top to the bottom. Within each
7992: wordlist, the search starts conceptually at the newest word; i.e., if
7993: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7994:
1.26 crook 7995: @cindex compilation word list
1.36 anton 7996: New words are added to the @dfn{compilation wordlist} (aka current
7997: wordlist).
1.1 anton 7998:
1.36 anton 7999: @cindex wid
8000: A word list is identified by a cell-sized word list identifier (@i{wid})
8001: in much the same way as a file is identified by a file handle. The
8002: numerical value of the wid has no (portable) meaning, and might change
8003: from session to session.
1.1 anton 8004:
1.29 crook 8005: The ANS Forth ``Search order'' word set is intended to provide a set of
8006: low-level tools that allow various different schemes to be
1.74 anton 8007: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8008: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8009: Forth.
1.1 anton 8010:
1.27 crook 8011: @comment TODO: locals section refers to here, saying that every word list (aka
8012: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8013: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8014:
1.45 crook 8015: @comment TODO: document markers, reveal, tables, mappedwordlist
8016:
8017: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8018: @comment word from the source files, rather than some alias.
1.44 crook 8019:
1.26 crook 8020: doc-forth-wordlist
8021: doc-definitions
8022: doc-get-current
8023: doc-set-current
8024: doc-get-order
1.185 anton 8025: doc-set-order
1.26 crook 8026: doc-wordlist
1.30 anton 8027: doc-table
1.79 anton 8028: doc->order
1.36 anton 8029: doc-previous
1.26 crook 8030: doc-also
1.185 anton 8031: doc-forth
1.26 crook 8032: doc-only
1.185 anton 8033: doc-order
1.15 anton 8034:
1.26 crook 8035: doc-find
8036: doc-search-wordlist
1.15 anton 8037:
1.26 crook 8038: doc-words
8039: doc-vlist
1.44 crook 8040: @c doc-words-deferred
1.1 anton 8041:
1.74 anton 8042: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8043: doc-root
8044: doc-vocabulary
8045: doc-seal
8046: doc-vocs
8047: doc-current
8048: doc-context
1.1 anton 8049:
1.44 crook 8050:
1.26 crook 8051: @menu
1.75 anton 8052: * Vocabularies::
1.67 anton 8053: * Why use word lists?::
1.75 anton 8054: * Word list example::
1.26 crook 8055: @end menu
8056:
1.75 anton 8057: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8058: @subsection Vocabularies
8059: @cindex Vocabularies, detailed explanation
8060:
8061: Here is an example of creating and using a new wordlist using ANS
8062: Forth words:
8063:
8064: @example
8065: wordlist constant my-new-words-wordlist
8066: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8067:
8068: \ add it to the search order
8069: also my-new-words
8070:
8071: \ alternatively, add it to the search order and make it
8072: \ the compilation word list
8073: also my-new-words definitions
8074: \ type "order" to see the problem
8075: @end example
8076:
8077: The problem with this example is that @code{order} has no way to
8078: associate the name @code{my-new-words} with the wid of the word list (in
8079: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8080: that has no associated name). There is no Standard way of associating a
8081: name with a wid.
8082:
8083: In Gforth, this example can be re-coded using @code{vocabulary}, which
8084: associates a name with a wid:
8085:
8086: @example
8087: vocabulary my-new-words
8088:
8089: \ add it to the search order
8090: also my-new-words
8091:
8092: \ alternatively, add it to the search order and make it
8093: \ the compilation word list
8094: my-new-words definitions
8095: \ type "order" to see that the problem is solved
8096: @end example
8097:
8098:
8099: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8100: @subsection Why use word lists?
8101: @cindex word lists - why use them?
8102:
1.74 anton 8103: Here are some reasons why people use wordlists:
1.26 crook 8104:
8105: @itemize @bullet
1.74 anton 8106:
8107: @c anton: Gforth's hashing implementation makes the search speed
8108: @c independent from the number of words. But it is linear with the number
8109: @c of wordlists that have to be searched, so in effect using more wordlists
8110: @c actually slows down compilation.
8111:
8112: @c @item
8113: @c To improve compilation speed by reducing the number of header space
8114: @c entries that must be searched. This is achieved by creating a new
8115: @c word list that contains all of the definitions that are used in the
8116: @c definition of a Forth system but which would not usually be used by
8117: @c programs running on that system. That word list would be on the search
8118: @c list when the Forth system was compiled but would be removed from the
8119: @c search list for normal operation. This can be a useful technique for
8120: @c low-performance systems (for example, 8-bit processors in embedded
8121: @c systems) but is unlikely to be necessary in high-performance desktop
8122: @c systems.
8123:
1.26 crook 8124: @item
8125: To prevent a set of words from being used outside the context in which
8126: they are valid. Two classic examples of this are an integrated editor
8127: (all of the edit commands are defined in a separate word list; the
8128: search order is set to the editor word list when the editor is invoked;
8129: the old search order is restored when the editor is terminated) and an
8130: integrated assembler (the op-codes for the machine are defined in a
8131: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8132:
8133: @item
8134: To organize the words of an application or library into a user-visible
8135: set (in @code{forth-wordlist} or some other common wordlist) and a set
8136: of helper words used just for the implementation (hidden in a separate
1.75 anton 8137: wordlist). This keeps @code{words}' output smaller, separates
8138: implementation and interface, and reduces the chance of name conflicts
8139: within the common wordlist.
1.74 anton 8140:
1.26 crook 8141: @item
8142: To prevent a name-space clash between multiple definitions with the same
8143: name. For example, when building a cross-compiler you might have a word
8144: @code{IF} that generates conditional code for your target system. By
8145: placing this definition in a different word list you can control whether
8146: the host system's @code{IF} or the target system's @code{IF} get used in
8147: any particular context by controlling the order of the word lists on the
8148: search order stack.
1.74 anton 8149:
1.26 crook 8150: @end itemize
1.1 anton 8151:
1.74 anton 8152: The downsides of using wordlists are:
8153:
8154: @itemize
8155:
8156: @item
8157: Debugging becomes more cumbersome.
8158:
8159: @item
8160: Name conflicts worked around with wordlists are still there, and you
8161: have to arrange the search order carefully to get the desired results;
8162: if you forget to do that, you get hard-to-find errors (as in any case
8163: where you read the code differently from the compiler; @code{see} can
1.75 anton 8164: help seeing which of several possible words the name resolves to in such
8165: cases). @code{See} displays just the name of the words, not what
8166: wordlist they belong to, so it might be misleading. Using unique names
8167: is a better approach to avoid name conflicts.
1.74 anton 8168:
8169: @item
8170: You have to explicitly undo any changes to the search order. In many
8171: cases it would be more convenient if this happened implicitly. Gforth
8172: currently does not provide such a feature, but it may do so in the
8173: future.
8174: @end itemize
8175:
8176:
1.75 anton 8177: @node Word list example, , Why use word lists?, Word Lists
8178: @subsection Word list example
8179: @cindex word lists - example
1.1 anton 8180:
1.74 anton 8181: The following example is from the
8182: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8183: garbage collector} and uses wordlists to separate public words from
8184: helper words:
8185:
8186: @example
8187: get-current ( wid )
8188: vocabulary garbage-collector also garbage-collector definitions
8189: ... \ define helper words
8190: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8191: ... \ define the public (i.e., API) words
8192: \ they can refer to the helper words
8193: previous \ restore original search order (helper words become invisible)
8194: @end example
8195:
1.26 crook 8196: @c -------------------------------------------------------------
8197: @node Environmental Queries, Files, Word Lists, Words
8198: @section Environmental Queries
8199: @cindex environmental queries
1.21 crook 8200:
1.26 crook 8201: ANS Forth introduced the idea of ``environmental queries'' as a way
8202: for a program running on a system to determine certain characteristics of the system.
8203: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8204:
1.32 anton 8205: The Standard requires that the header space used for environmental queries
8206: be distinct from the header space used for definitions.
1.21 crook 8207:
1.26 crook 8208: Typically, environmental queries are supported by creating a set of
1.29 crook 8209: definitions in a word list that is @i{only} used during environmental
1.26 crook 8210: queries; that is what Gforth does. There is no Standard way of adding
8211: definitions to the set of recognised environmental queries, but any
8212: implementation that supports the loading of optional word sets must have
8213: some mechanism for doing this (after loading the word set, the
8214: associated environmental query string must return @code{true}). In
8215: Gforth, the word list used to honour environmental queries can be
8216: manipulated just like any other word list.
1.21 crook 8217:
1.44 crook 8218:
1.26 crook 8219: doc-environment?
8220: doc-environment-wordlist
1.21 crook 8221:
1.26 crook 8222: doc-gforth
8223: doc-os-class
1.21 crook 8224:
1.44 crook 8225:
1.26 crook 8226: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8227: returning two items on the stack, querying it using @code{environment?}
8228: will return an additional item; the @code{true} flag that shows that the
8229: string was recognised.
1.21 crook 8230:
1.26 crook 8231: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8232:
1.26 crook 8233: Here are some examples of using environmental queries:
1.21 crook 8234:
1.26 crook 8235: @example
8236: s" address-unit-bits" environment? 0=
8237: [IF]
8238: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8239: [ELSE]
8240: drop \ ensure balanced stack effect
1.26 crook 8241: [THEN]
1.21 crook 8242:
1.75 anton 8243: \ this might occur in the prelude of a standard program that uses THROW
8244: s" exception" environment? [IF]
8245: 0= [IF]
8246: : throw abort" exception thrown" ;
8247: [THEN]
8248: [ELSE] \ we don't know, so make sure
8249: : throw abort" exception thrown" ;
8250: [THEN]
1.21 crook 8251:
1.26 crook 8252: s" gforth" environment? [IF] .( Gforth version ) TYPE
8253: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8254:
8255: \ a program using v*
8256: s" gforth" environment? [IF]
8257: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8258: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8259: >r swap 2swap swap 0e r> 0 ?DO
8260: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8261: LOOP
8262: 2drop 2drop ;
8263: [THEN]
8264: [ELSE] \
8265: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8266: ...
8267: [THEN]
1.26 crook 8268: @end example
1.21 crook 8269:
1.26 crook 8270: Here is an example of adding a definition to the environment word list:
1.21 crook 8271:
1.26 crook 8272: @example
8273: get-current environment-wordlist set-current
8274: true constant block
8275: true constant block-ext
8276: set-current
8277: @end example
1.21 crook 8278:
1.26 crook 8279: You can see what definitions are in the environment word list like this:
1.21 crook 8280:
1.26 crook 8281: @example
1.79 anton 8282: environment-wordlist >order words previous
1.26 crook 8283: @end example
1.21 crook 8284:
8285:
1.26 crook 8286: @c -------------------------------------------------------------
8287: @node Files, Blocks, Environmental Queries, Words
8288: @section Files
1.28 crook 8289: @cindex files
8290: @cindex I/O - file-handling
1.21 crook 8291:
1.26 crook 8292: Gforth provides facilities for accessing files that are stored in the
8293: host operating system's file-system. Files that are processed by Gforth
8294: can be divided into two categories:
1.21 crook 8295:
1.23 crook 8296: @itemize @bullet
8297: @item
1.29 crook 8298: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8299: @item
1.29 crook 8300: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8301: @end itemize
8302:
8303: @menu
1.48 anton 8304: * Forth source files::
8305: * General files::
1.167 anton 8306: * Redirection::
1.48 anton 8307: * Search Paths::
1.26 crook 8308: @end menu
8309:
8310: @c -------------------------------------------------------------
8311: @node Forth source files, General files, Files, Files
8312: @subsection Forth source files
8313: @cindex including files
8314: @cindex Forth source files
1.21 crook 8315:
1.26 crook 8316: The simplest way to interpret the contents of a file is to use one of
8317: these two formats:
1.21 crook 8318:
1.26 crook 8319: @example
8320: include mysource.fs
8321: s" mysource.fs" included
8322: @end example
1.21 crook 8323:
1.75 anton 8324: You usually want to include a file only if it is not included already
1.26 crook 8325: (by, say, another source file). In that case, you can use one of these
1.45 crook 8326: three formats:
1.21 crook 8327:
1.26 crook 8328: @example
8329: require mysource.fs
8330: needs mysource.fs
8331: s" mysource.fs" required
8332: @end example
1.21 crook 8333:
1.26 crook 8334: @cindex stack effect of included files
8335: @cindex including files, stack effect
1.45 crook 8336: It is good practice to write your source files such that interpreting them
8337: does not change the stack. Source files designed in this way can be used with
1.26 crook 8338: @code{required} and friends without complications. For example:
1.21 crook 8339:
1.26 crook 8340: @example
1.75 anton 8341: 1024 require foo.fs drop
1.26 crook 8342: @end example
1.21 crook 8343:
1.75 anton 8344: Here you want to pass the argument 1024 (e.g., a buffer size) to
8345: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8346: ), which allows its use with @code{require}. Of course with such
8347: parameters to required files, you have to ensure that the first
8348: @code{require} fits for all uses (i.e., @code{require} it early in the
8349: master load file).
1.44 crook 8350:
1.26 crook 8351: doc-include-file
8352: doc-included
1.28 crook 8353: doc-included?
1.26 crook 8354: doc-include
8355: doc-required
8356: doc-require
8357: doc-needs
1.75 anton 8358: @c doc-init-included-files @c internal
8359: doc-sourcefilename
8360: doc-sourceline#
1.44 crook 8361:
1.26 crook 8362: A definition in ANS Forth for @code{required} is provided in
8363: @file{compat/required.fs}.
1.21 crook 8364:
1.26 crook 8365: @c -------------------------------------------------------------
1.167 anton 8366: @node General files, Redirection, Forth source files, Files
1.26 crook 8367: @subsection General files
8368: @cindex general files
8369: @cindex file-handling
1.21 crook 8370:
1.75 anton 8371: Files are opened/created by name and type. The following file access
8372: methods (FAMs) are recognised:
1.44 crook 8373:
1.75 anton 8374: @cindex fam (file access method)
1.26 crook 8375: doc-r/o
8376: doc-r/w
8377: doc-w/o
8378: doc-bin
1.1 anton 8379:
1.44 crook 8380:
1.26 crook 8381: When a file is opened/created, it returns a file identifier,
1.29 crook 8382: @i{wfileid} that is used for all other file commands. All file
8383: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8384: successful operation and an implementation-defined non-zero value in the
8385: case of an error.
1.21 crook 8386:
1.44 crook 8387:
1.26 crook 8388: doc-open-file
8389: doc-create-file
1.21 crook 8390:
1.26 crook 8391: doc-close-file
8392: doc-delete-file
8393: doc-rename-file
8394: doc-read-file
8395: doc-read-line
1.154 anton 8396: doc-key-file
8397: doc-key?-file
1.26 crook 8398: doc-write-file
8399: doc-write-line
8400: doc-emit-file
8401: doc-flush-file
1.21 crook 8402:
1.26 crook 8403: doc-file-status
8404: doc-file-position
8405: doc-reposition-file
8406: doc-file-size
8407: doc-resize-file
1.21 crook 8408:
1.93 anton 8409: doc-slurp-file
8410: doc-slurp-fid
1.112 anton 8411: doc-stdin
8412: doc-stdout
8413: doc-stderr
1.44 crook 8414:
1.26 crook 8415: @c ---------------------------------------------------------
1.167 anton 8416: @node Redirection, Search Paths, General files, Files
8417: @subsection Redirection
8418: @cindex Redirection
8419: @cindex Input Redirection
8420: @cindex Output Redirection
8421:
8422: You can redirect the output of @code{type} and @code{emit} and all the
8423: words that use them (all output words that don't have an explicit
1.174 anton 8424: target file) to an arbitrary file with the @code{outfile-execute},
8425: used like this:
1.167 anton 8426:
8427: @example
1.174 anton 8428: : some-warning ( n -- )
8429: cr ." warning# " . ;
8430:
1.167 anton 8431: : print-some-warning ( n -- )
1.174 anton 8432: ['] some-warning stderr outfile-execute ;
1.167 anton 8433: @end example
8434:
1.174 anton 8435: After @code{some-warning} is executed, the original output direction
8436: is restored; this construct is safe against exceptions. Similarly,
8437: there is @code{infile-execute} for redirecting the input of @code{key}
8438: and its users (any input word that does not take a file explicitly).
8439:
8440: doc-outfile-execute
8441: doc-infile-execute
1.167 anton 8442:
8443: If you do not want to redirect the input or output to a file, you can
8444: also make use of the fact that @code{key}, @code{emit} and @code{type}
8445: are deferred words (@pxref{Deferred Words}). However, in that case
8446: you have to worry about the restoration and the protection against
8447: exceptions yourself; also, note that for redirecting the output in
8448: this way, you have to redirect both @code{emit} and @code{type}.
8449:
8450: @c ---------------------------------------------------------
8451: @node Search Paths, , Redirection, Files
1.26 crook 8452: @subsection Search Paths
8453: @cindex path for @code{included}
8454: @cindex file search path
8455: @cindex @code{include} search path
8456: @cindex search path for files
1.21 crook 8457:
1.26 crook 8458: If you specify an absolute filename (i.e., a filename starting with
8459: @file{/} or @file{~}, or with @file{:} in the second position (as in
8460: @samp{C:...})) for @code{included} and friends, that file is included
8461: just as you would expect.
1.21 crook 8462:
1.75 anton 8463: If the filename starts with @file{./}, this refers to the directory that
8464: the present file was @code{included} from. This allows files to include
8465: other files relative to their own position (irrespective of the current
8466: working directory or the absolute position). This feature is essential
8467: for libraries consisting of several files, where a file may include
8468: other files from the library. It corresponds to @code{#include "..."}
8469: in C. If the current input source is not a file, @file{.} refers to the
8470: directory of the innermost file being included, or, if there is no file
8471: being included, to the current working directory.
8472:
8473: For relative filenames (not starting with @file{./}), Gforth uses a
8474: search path similar to Forth's search order (@pxref{Word Lists}). It
8475: tries to find the given filename in the directories present in the path,
8476: and includes the first one it finds. There are separate search paths for
8477: Forth source files and general files. If the search path contains the
8478: directory @file{.}, this refers to the directory of the current file, or
8479: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8480:
1.26 crook 8481: Use @file{~+} to refer to the current working directory (as in the
8482: @code{bash}).
1.1 anton 8483:
1.75 anton 8484: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8485:
1.48 anton 8486: @menu
1.75 anton 8487: * Source Search Paths::
1.48 anton 8488: * General Search Paths::
8489: @end menu
8490:
1.26 crook 8491: @c ---------------------------------------------------------
1.75 anton 8492: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8493: @subsubsection Source Search Paths
8494: @cindex search path control, source files
1.5 anton 8495:
1.26 crook 8496: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8497: Gforth}). You can display it and change it using @code{fpath} in
8498: combination with the general path handling words.
1.5 anton 8499:
1.75 anton 8500: doc-fpath
8501: @c the functionality of the following words is easily available through
8502: @c fpath and the general path words. The may go away.
8503: @c doc-.fpath
8504: @c doc-fpath+
8505: @c doc-fpath=
8506: @c doc-open-fpath-file
1.44 crook 8507:
8508: @noindent
1.26 crook 8509: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8510:
1.26 crook 8511: @example
1.75 anton 8512: fpath path= /usr/lib/forth/|./
1.26 crook 8513: require timer.fs
8514: @end example
1.5 anton 8515:
1.75 anton 8516:
1.26 crook 8517: @c ---------------------------------------------------------
1.75 anton 8518: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8519: @subsubsection General Search Paths
1.75 anton 8520: @cindex search path control, source files
1.5 anton 8521:
1.26 crook 8522: Your application may need to search files in several directories, like
8523: @code{included} does. To facilitate this, Gforth allows you to define
8524: and use your own search paths, by providing generic equivalents of the
8525: Forth search path words:
1.5 anton 8526:
1.75 anton 8527: doc-open-path-file
8528: doc-path-allot
8529: doc-clear-path
8530: doc-also-path
1.26 crook 8531: doc-.path
8532: doc-path+
8533: doc-path=
1.5 anton 8534:
1.75 anton 8535: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8536:
1.75 anton 8537: Here's an example of creating an empty search path:
8538: @c
1.26 crook 8539: @example
1.75 anton 8540: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8541: @end example
1.5 anton 8542:
1.26 crook 8543: @c -------------------------------------------------------------
8544: @node Blocks, Other I/O, Files, Words
8545: @section Blocks
1.28 crook 8546: @cindex I/O - blocks
8547: @cindex blocks
8548:
8549: When you run Gforth on a modern desk-top computer, it runs under the
8550: control of an operating system which provides certain services. One of
8551: these services is @var{file services}, which allows Forth source code
8552: and data to be stored in files and read into Gforth (@pxref{Files}).
8553:
8554: Traditionally, Forth has been an important programming language on
8555: systems where it has interfaced directly to the underlying hardware with
8556: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8557: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8558:
8559: A block is a 1024-byte data area, which can be used to hold data or
8560: Forth source code. No structure is imposed on the contents of the
8561: block. A block is identified by its number; blocks are numbered
8562: contiguously from 1 to an implementation-defined maximum.
8563:
8564: A typical system that used blocks but no operating system might use a
8565: single floppy-disk drive for mass storage, with the disks formatted to
8566: provide 256-byte sectors. Blocks would be implemented by assigning the
8567: first four sectors of the disk to block 1, the second four sectors to
8568: block 2 and so on, up to the limit of the capacity of the disk. The disk
8569: would not contain any file system information, just the set of blocks.
8570:
1.29 crook 8571: @cindex blocks file
1.28 crook 8572: On systems that do provide file services, blocks are typically
1.29 crook 8573: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8574: file}. The size of the blocks file will be an exact multiple of 1024
8575: bytes, corresponding to the number of blocks it contains. This is the
8576: mechanism that Gforth uses.
8577:
1.29 crook 8578: @cindex @file{blocks.fb}
1.75 anton 8579: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8580: having specified a blocks file, Gforth defaults to the blocks file
8581: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8582: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8583:
1.29 crook 8584: @cindex block buffers
1.28 crook 8585: When you read and write blocks under program control, Gforth uses a
1.29 crook 8586: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8587: not used when you use @code{load} to interpret the contents of a block.
8588:
1.75 anton 8589: The behaviour of the block buffers is analagous to that of a cache.
8590: Each block buffer has three states:
1.28 crook 8591:
8592: @itemize @bullet
8593: @item
8594: Unassigned
8595: @item
8596: Assigned-clean
8597: @item
8598: Assigned-dirty
8599: @end itemize
8600:
1.29 crook 8601: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8602: block, the block (specified by its block number) must be assigned to a
8603: block buffer.
8604:
8605: The assignment of a block to a block buffer is performed by @code{block}
8606: or @code{buffer}. Use @code{block} when you wish to modify the existing
8607: contents of a block. Use @code{buffer} when you don't care about the
8608: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8609: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8610: with the particular block is already stored in a block buffer due to an
8611: earlier @code{block} command, @code{buffer} will return that block
8612: buffer and the existing contents of the block will be
8613: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8614: block buffer for the block.}.
1.28 crook 8615:
1.47 crook 8616: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8617: @code{buffer}, that block buffer becomes the @i{current block
8618: buffer}. Data may only be manipulated (read or written) within the
8619: current block buffer.
1.47 crook 8620:
8621: When the contents of the current block buffer has been modified it is
1.48 anton 8622: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8623: either abandon the changes (by doing nothing) or mark the block as
8624: changed (assigned-dirty), using @code{update}. Using @code{update} does
8625: not change the blocks file; it simply changes a block buffer's state to
8626: @i{assigned-dirty}. The block will be written implicitly when it's
8627: buffer is needed for another block, or explicitly by @code{flush} or
8628: @code{save-buffers}.
8629:
8630: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8631: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8632: @code{flush}.
1.28 crook 8633:
1.29 crook 8634: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8635: algorithm to assign a block buffer to a block. That means that any
8636: particular block can only be assigned to one specific block buffer,
1.29 crook 8637: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8638: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8639: the new block immediately. If it is @i{assigned-dirty} its current
8640: contents are written back to the blocks file on disk before it is
1.28 crook 8641: allocated to the new block.
8642:
8643: Although no structure is imposed on the contents of a block, it is
8644: traditional to display the contents as 16 lines each of 64 characters. A
8645: block provides a single, continuous stream of input (for example, it
8646: acts as a single parse area) -- there are no end-of-line characters
8647: within a block, and no end-of-file character at the end of a
8648: block. There are two consequences of this:
1.26 crook 8649:
1.28 crook 8650: @itemize @bullet
8651: @item
8652: The last character of one line wraps straight into the first character
8653: of the following line
8654: @item
8655: The word @code{\} -- comment to end of line -- requires special
8656: treatment; in the context of a block it causes all characters until the
8657: end of the current 64-character ``line'' to be ignored.
8658: @end itemize
8659:
8660: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8661: the current blocks file will be extended to the appropriate size and the
1.28 crook 8662: block buffer will be initialised with spaces.
8663:
1.47 crook 8664: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8665: for details) but doesn't encourage the use of blocks; the mechanism is
8666: only provided for backward compatibility -- ANS Forth requires blocks to
8667: be available when files are.
1.28 crook 8668:
8669: Common techniques that are used when working with blocks include:
8670:
8671: @itemize @bullet
8672: @item
8673: A screen editor that allows you to edit blocks without leaving the Forth
8674: environment.
8675: @item
8676: Shadow screens; where every code block has an associated block
8677: containing comments (for example: code in odd block numbers, comments in
8678: even block numbers). Typically, the block editor provides a convenient
8679: mechanism to toggle between code and comments.
8680: @item
8681: Load blocks; a single block (typically block 1) contains a number of
8682: @code{thru} commands which @code{load} the whole of the application.
8683: @end itemize
1.26 crook 8684:
1.29 crook 8685: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8686: integrated into a Forth programming environment.
1.26 crook 8687:
8688: @comment TODO what about errors on open-blocks?
1.44 crook 8689:
1.26 crook 8690: doc-open-blocks
8691: doc-use
1.75 anton 8692: doc-block-offset
1.26 crook 8693: doc-get-block-fid
8694: doc-block-position
1.28 crook 8695:
1.75 anton 8696: doc-list
1.28 crook 8697: doc-scr
8698:
1.184 anton 8699: doc-block
1.28 crook 8700: doc-buffer
8701:
1.75 anton 8702: doc-empty-buffers
8703: doc-empty-buffer
1.26 crook 8704: doc-update
1.28 crook 8705: doc-updated?
1.26 crook 8706: doc-save-buffers
1.75 anton 8707: doc-save-buffer
1.26 crook 8708: doc-flush
1.28 crook 8709:
1.26 crook 8710: doc-load
8711: doc-thru
8712: doc-+load
8713: doc-+thru
1.45 crook 8714: doc---gforthman--->
1.26 crook 8715: doc-block-included
8716:
1.44 crook 8717:
1.26 crook 8718: @c -------------------------------------------------------------
1.126 pazsan 8719: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8720: @section Other I/O
1.28 crook 8721: @cindex I/O - keyboard and display
1.26 crook 8722:
8723: @menu
8724: * Simple numeric output:: Predefined formats
8725: * Formatted numeric output:: Formatted (pictured) output
8726: * String Formats:: How Forth stores strings in memory
1.67 anton 8727: * Displaying characters and strings:: Other stuff
1.175 anton 8728: * Terminal output:: Cursor positioning etc.
1.181 anton 8729: * Single-key input::
8730: * Line input and conversion::
1.112 anton 8731: * Pipes:: How to create your own pipes
1.149 pazsan 8732: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8733: @end menu
8734:
8735: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8736: @subsection Simple numeric output
1.28 crook 8737: @cindex numeric output - simple/free-format
1.5 anton 8738:
1.26 crook 8739: The simplest output functions are those that display numbers from the
8740: data or floating-point stacks. Floating-point output is always displayed
8741: using base 10. Numbers displayed from the data stack use the value stored
8742: in @code{base}.
1.5 anton 8743:
1.44 crook 8744:
1.26 crook 8745: doc-.
8746: doc-dec.
8747: doc-hex.
8748: doc-u.
8749: doc-.r
8750: doc-u.r
8751: doc-d.
8752: doc-ud.
8753: doc-d.r
8754: doc-ud.r
8755: doc-f.
8756: doc-fe.
8757: doc-fs.
1.111 anton 8758: doc-f.rdp
1.44 crook 8759:
1.26 crook 8760: Examples of printing the number 1234.5678E23 in the different floating-point output
8761: formats are shown below:
1.5 anton 8762:
8763: @example
1.26 crook 8764: f. 123456779999999000000000000.
8765: fe. 123.456779999999E24
8766: fs. 1.23456779999999E26
1.5 anton 8767: @end example
8768:
8769:
1.26 crook 8770: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8771: @subsection Formatted numeric output
1.28 crook 8772: @cindex formatted numeric output
1.26 crook 8773: @cindex pictured numeric output
1.28 crook 8774: @cindex numeric output - formatted
1.26 crook 8775:
1.29 crook 8776: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8777: output} for formatted printing of integers. In this technique, digits
8778: are extracted from the number (using the current output radix defined by
8779: @code{base}), converted to ASCII codes and appended to a string that is
8780: built in a scratch-pad area of memory (@pxref{core-idef,
8781: Implementation-defined options, Implementation-defined
8782: options}). Arbitrary characters can be appended to the string during the
8783: extraction process. The completed string is specified by an address
8784: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8785: under program control.
1.5 anton 8786:
1.75 anton 8787: All of the integer output words described in the previous section
8788: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8789: numeric output.
1.5 anton 8790:
1.47 crook 8791: Three important things to remember about pictured numeric output:
1.5 anton 8792:
1.26 crook 8793: @itemize @bullet
8794: @item
1.28 crook 8795: It always operates on double-precision numbers; to display a
1.49 anton 8796: single-precision number, convert it first (for ways of doing this
8797: @pxref{Double precision}).
1.26 crook 8798: @item
1.28 crook 8799: It always treats the double-precision number as though it were
8800: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8801: @item
8802: The string is built up from right to left; least significant digit first.
8803: @end itemize
1.5 anton 8804:
1.44 crook 8805:
1.26 crook 8806: doc-<#
1.47 crook 8807: doc-<<#
1.26 crook 8808: doc-#
8809: doc-#s
8810: doc-hold
8811: doc-sign
8812: doc-#>
1.47 crook 8813: doc-#>>
1.5 anton 8814:
1.26 crook 8815: doc-represent
1.111 anton 8816: doc-f>str-rdp
8817: doc-f>buf-rdp
1.5 anton 8818:
1.44 crook 8819:
8820: @noindent
1.26 crook 8821: Here are some examples of using pictured numeric output:
1.5 anton 8822:
8823: @example
1.26 crook 8824: : my-u. ( u -- )
8825: \ Simplest use of pns.. behaves like Standard u.
8826: 0 \ convert to unsigned double
1.75 anton 8827: <<# \ start conversion
1.26 crook 8828: #s \ convert all digits
8829: #> \ complete conversion
1.75 anton 8830: TYPE SPACE \ display, with trailing space
8831: #>> ; \ release hold area
1.5 anton 8832:
1.26 crook 8833: : cents-only ( u -- )
8834: 0 \ convert to unsigned double
1.75 anton 8835: <<# \ start conversion
1.26 crook 8836: # # \ convert two least-significant digits
8837: #> \ complete conversion, discard other digits
1.75 anton 8838: TYPE SPACE \ display, with trailing space
8839: #>> ; \ release hold area
1.5 anton 8840:
1.26 crook 8841: : dollars-and-cents ( u -- )
8842: 0 \ convert to unsigned double
1.75 anton 8843: <<# \ start conversion
1.26 crook 8844: # # \ convert two least-significant digits
8845: [char] . hold \ insert decimal point
8846: #s \ convert remaining digits
8847: [char] $ hold \ append currency symbol
8848: #> \ complete conversion
1.75 anton 8849: TYPE SPACE \ display, with trailing space
8850: #>> ; \ release hold area
1.5 anton 8851:
1.26 crook 8852: : my-. ( n -- )
8853: \ handling negatives.. behaves like Standard .
8854: s>d \ convert to signed double
8855: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8856: <<# \ start conversion
1.26 crook 8857: #s \ convert all digits
8858: rot sign \ get at sign byte, append "-" if needed
8859: #> \ complete conversion
1.75 anton 8860: TYPE SPACE \ display, with trailing space
8861: #>> ; \ release hold area
1.5 anton 8862:
1.26 crook 8863: : account. ( n -- )
1.75 anton 8864: \ accountants don't like minus signs, they use parentheses
1.26 crook 8865: \ for negative numbers
8866: s>d \ convert to signed double
8867: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8868: <<# \ start conversion
1.26 crook 8869: 2 pick \ get copy of sign byte
8870: 0< IF [char] ) hold THEN \ right-most character of output
8871: #s \ convert all digits
8872: rot \ get at sign byte
8873: 0< IF [char] ( hold THEN
8874: #> \ complete conversion
1.75 anton 8875: TYPE SPACE \ display, with trailing space
8876: #>> ; \ release hold area
8877:
1.5 anton 8878: @end example
8879:
1.26 crook 8880: Here are some examples of using these words:
1.5 anton 8881:
8882: @example
1.26 crook 8883: 1 my-u. 1
8884: hex -1 my-u. decimal FFFFFFFF
8885: 1 cents-only 01
8886: 1234 cents-only 34
8887: 2 dollars-and-cents $0.02
8888: 1234 dollars-and-cents $12.34
8889: 123 my-. 123
8890: -123 my. -123
8891: 123 account. 123
8892: -456 account. (456)
1.5 anton 8893: @end example
8894:
8895:
1.26 crook 8896: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8897: @subsection String Formats
1.27 crook 8898: @cindex strings - see character strings
8899: @cindex character strings - formats
1.28 crook 8900: @cindex I/O - see character strings
1.75 anton 8901: @cindex counted strings
8902:
8903: @c anton: this does not really belong here; maybe the memory section,
8904: @c or the principles chapter
1.26 crook 8905:
1.27 crook 8906: Forth commonly uses two different methods for representing character
8907: strings:
1.26 crook 8908:
8909: @itemize @bullet
8910: @item
8911: @cindex address of counted string
1.45 crook 8912: @cindex counted string
1.29 crook 8913: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8914: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8915: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8916: memory.
8917: @item
1.29 crook 8918: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8919: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8920: first byte of the string.
8921: @end itemize
8922:
8923: ANS Forth encourages the use of the second format when representing
1.75 anton 8924: strings.
1.26 crook 8925:
1.44 crook 8926:
1.26 crook 8927: doc-count
8928:
1.44 crook 8929:
1.49 anton 8930: For words that move, copy and search for strings see @ref{Memory
8931: Blocks}. For words that display characters and strings see
8932: @ref{Displaying characters and strings}.
1.26 crook 8933:
1.175 anton 8934: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 8935: @subsection Displaying characters and strings
1.27 crook 8936: @cindex characters - compiling and displaying
8937: @cindex character strings - compiling and displaying
1.26 crook 8938:
8939: This section starts with a glossary of Forth words and ends with a set
8940: of examples.
8941:
8942: doc-bl
8943: doc-space
8944: doc-spaces
8945: doc-emit
8946: doc-toupper
8947: doc-."
8948: doc-.(
1.98 anton 8949: doc-.\"
1.26 crook 8950: doc-type
1.44 crook 8951: doc-typewhite
1.26 crook 8952: doc-cr
1.27 crook 8953: @cindex cursor control
1.26 crook 8954: doc-s"
1.98 anton 8955: doc-s\"
1.26 crook 8956: doc-c"
8957: doc-char
8958: doc-[char]
8959:
1.44 crook 8960:
8961: @noindent
1.26 crook 8962: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8963:
8964: @example
1.26 crook 8965: .( text-1)
8966: : my-word
8967: ." text-2" cr
8968: .( text-3)
8969: ;
8970:
8971: ." text-4"
8972:
8973: : my-char
8974: [char] ALPHABET emit
8975: char emit
8976: ;
1.5 anton 8977: @end example
8978:
1.26 crook 8979: When you load this code into Gforth, the following output is generated:
1.5 anton 8980:
1.26 crook 8981: @example
1.30 anton 8982: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8983: @end example
1.5 anton 8984:
1.26 crook 8985: @itemize @bullet
8986: @item
8987: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8988: is an immediate word; it behaves in the same way whether it is used inside
8989: or outside a colon definition.
8990: @item
8991: Message @code{text-4} is displayed because of Gforth's added interpretation
8992: semantics for @code{."}.
8993: @item
1.29 crook 8994: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8995: performs the compilation semantics for @code{."} within the definition of
8996: @code{my-word}.
8997: @end itemize
1.5 anton 8998:
1.26 crook 8999: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9000:
1.26 crook 9001: @example
1.30 anton 9002: @kbd{my-word @key{RET}} text-2
1.26 crook 9003: ok
1.30 anton 9004: @kbd{my-char fred @key{RET}} Af ok
9005: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9006: @end example
1.5 anton 9007:
9008: @itemize @bullet
9009: @item
1.26 crook 9010: Message @code{text-2} is displayed because of the run-time behaviour of
9011: @code{."}.
9012: @item
9013: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9014: on the stack at run-time. @code{emit} always displays the character
9015: when @code{my-char} is executed.
9016: @item
9017: @code{char} parses a string at run-time and the second @code{emit} displays
9018: the first character of the string.
1.5 anton 9019: @item
1.26 crook 9020: If you type @code{see my-char} you can see that @code{[char]} discarded
9021: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9022: definition of @code{my-char}.
1.5 anton 9023: @end itemize
9024:
9025:
1.181 anton 9026: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9027: @subsection Terminal output
9028: @cindex output to terminal
9029: @cindex terminal output
9030:
9031: If you are outputting to a terminal, you may want to control the
9032: positioning of the cursor:
9033: @cindex cursor positioning
9034:
9035: doc-at-xy
9036:
9037: In order to know where to position the cursor, it is often helpful to
9038: know the size of the screen:
9039: @cindex terminal size
9040:
9041: doc-form
9042:
9043: And sometimes you want to use:
9044: @cindex clear screen
9045:
9046: doc-page
9047:
9048: Note that on non-terminals you should use @code{12 emit}, not
9049: @code{page}, to get a form feed.
9050:
1.5 anton 9051:
1.181 anton 9052: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9053: @subsection Single-key input
9054: @cindex single-key input
9055: @cindex input, single-key
9056:
9057: If you want to get a single printable character, you can use
9058: @code{key}; to check whether a character is available for @code{key},
9059: you can use @code{key?}.
1.5 anton 9060:
1.181 anton 9061: doc-key
9062: doc-key?
1.27 crook 9063:
1.181 anton 9064: If you want to process a mix of printable and non-printable
9065: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9066: produces a keyboard event that you have to convert into a character
9067: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9068:
9069: Typical code for using EKEY looks like this:
9070:
9071: @example
9072: ekey ekey>char if ( c )
9073: ... \ do something with the character
9074: else ekey>fkey if ( key-id )
9075: case
9076: k-up of ... endof
9077: k-f1 of ... endof
9078: k-left k-shift-mask or k-ctrl-mask or of ... endof
9079: ...
9080: endcase
9081: else ( keyboard-event )
9082: drop \ just ignore an unknown keyboard event type
9083: then then
9084: @end example
1.44 crook 9085:
1.45 crook 9086: doc-ekey
1.141 anton 9087: doc-ekey>char
1.181 anton 9088: doc-ekey>fkey
1.45 crook 9089: doc-ekey?
1.141 anton 9090:
1.181 anton 9091: The key identifiers for cursor keys are:
1.141 anton 9092:
9093: doc-k-left
9094: doc-k-right
1.185 anton 9095: doc-k-up
9096: doc-k-down
9097: doc-k-home
9098: doc-k-end
1.141 anton 9099: doc-k-prior
9100: doc-k-next
9101: doc-k-insert
9102: doc-k-delete
9103:
1.181 anton 9104: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9105:
1.181 anton 9106: doc-k-f1
9107: doc-k-f2
9108: doc-k-f3
9109: doc-k-f4
9110: doc-k-f5
9111: doc-k-f6
9112: doc-k-f7
9113: doc-k-f8
9114: doc-k-f9
9115: doc-k-f10
9116: doc-k-f11
9117: doc-k-f12
9118:
9119: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9120:
9121: You can combine these key identifiers with masks for various shift keys:
9122:
9123: doc-k-shift-mask
9124: doc-k-ctrl-mask
9125: doc-k-alt-mask
9126:
9127: Note that, even if a Forth system has @code{ekey>fkey} and the key
9128: identifier words, the keys are not necessarily available or it may not
9129: necessarily be able to report all the keys and all the possible
9130: combinations with shift masks. Therefore, write your programs in such
9131: a way that they are still useful even if the keys and key combinations
9132: cannot be pressed or are not recognized.
9133:
9134: Examples: Older keyboards often do not have an F11 and F12 key. If
9135: you run Gforth in an xterm, the xterm catches a number of combinations
9136: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9137: Gforth currently does not recognize and report combinations with
9138: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9139: above would never be entered).
9140:
9141: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9142: you need the ANSI.SYS driver to get that behaviour); it works by
9143: recognizing the escape sequences that ANSI terminals send when such a
9144: key is pressed. If you have a terminal that sends other escape
9145: sequences, you will not get useful results on Gforth. Other Forth
9146: systems may work in a different way.
9147:
9148:
9149: @node Line input and conversion, Pipes, Single-key input, Other I/O
9150: @subsection Line input and conversion
9151: @cindex line input from terminal
9152: @cindex input, linewise from terminal
9153: @cindex convertin strings to numbers
9154: @cindex I/O - see input
9155:
9156: For ways of storing character strings in memory see @ref{String Formats}.
9157:
9158: @comment TODO examples for >number >float accept key key? pad parse word refill
9159: @comment then index them
1.141 anton 9160:
9161: Words for inputting one line from the keyboard:
9162:
9163: doc-accept
9164: doc-edit-line
9165:
9166: Conversion words:
9167:
1.143 anton 9168: doc-s>number?
9169: doc-s>unumber?
1.26 crook 9170: doc->number
9171: doc->float
1.143 anton 9172:
1.141 anton 9173:
1.27 crook 9174: @comment obsolescent words..
1.141 anton 9175: Obsolescent input and conversion words:
9176:
1.27 crook 9177: doc-convert
1.26 crook 9178: doc-expect
1.27 crook 9179: doc-span
1.5 anton 9180:
9181:
1.181 anton 9182: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9183: @subsection Pipes
9184: @cindex pipes, creating your own
9185:
9186: In addition to using Gforth in pipes created by other processes
9187: (@pxref{Gforth in pipes}), you can create your own pipe with
9188: @code{open-pipe}, and read from or write to it.
9189:
9190: doc-open-pipe
9191: doc-close-pipe
9192:
9193: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9194: you don't catch this exception, Gforth will catch it and exit, usually
9195: silently (@pxref{Gforth in pipes}). Since you probably do not want
9196: this, you should wrap a @code{catch} or @code{try} block around the code
9197: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9198: problem yourself, and then return to regular processing.
9199:
9200: doc-broken-pipe-error
9201:
1.155 anton 9202: @node Xchars and Unicode, , Pipes, Other I/O
9203: @subsection Xchars and Unicode
1.149 pazsan 9204:
1.188 ! pazsan 9205: ASCII is only appropriate for the English language. Most western
! 9206: languages however fit somewhat into the Forth frame, since a byte is
! 9207: sufficient to encode the few special characters in each (though not
! 9208: always the same encoding can be used; latin-1 is most widely used,
! 9209: though). For other languages, different char-sets have to be used,
! 9210: several of them variable-width. Most prominent representant is
! 9211: UTF-8. Let's call these extended characters xchars. The primitive
! 9212: fixed-size characters stored as bytes are called pchars in this
! 9213: section.
! 9214:
! 9215: The xchar words add a few data types:
! 9216:
! 9217: @itemize
! 9218:
! 9219: @item
! 9220: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
! 9221: and is a subset of unsigned cell. Note: UTF-8 can not store more that
! 9222: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
! 9223: character set can be used.
! 9224:
! 9225: @item
! 9226: @var{xc-addr} is the address of an xchar in memory. Alignment
! 9227: requirements are the same as @var{c-addr}. The memory representation of an
! 9228: xchar differs from the stack representation, and depends on the
! 9229: encoding used. An xchar may use a variable number of pchars in memory.
! 9230:
! 9231: @item
! 9232: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
! 9233: @var{xc-addr}, @var{u} pchars long.
! 9234:
! 9235: @end itemize
! 9236:
! 9237: doc-xc-size
! 9238: doc-x-size
! 9239: doc-xc@+
! 9240: doc-xc!+
! 9241: doc-xc!+?
! 9242: doc-xchar+
! 9243: doc-xchar-
! 9244: doc-+x/string
! 9245: doc-x\string-
! 9246: doc--trailing-garbage
! 9247: doc-x-width
! 9248: doc-xkey
! 9249: doc-xemit
! 9250:
! 9251: There's a new environment query
! 9252:
! 9253: doc-xchar-encoding
1.112 anton 9254:
1.121 anton 9255: @node OS command line arguments, Locals, Other I/O, Words
9256: @section OS command line arguments
9257: @cindex OS command line arguments
9258: @cindex command line arguments, OS
9259: @cindex arguments, OS command line
9260:
9261: The usual way to pass arguments to Gforth programs on the command line
9262: is via the @option{-e} option, e.g.
9263:
9264: @example
9265: gforth -e "123 456" foo.fs -e bye
9266: @end example
9267:
9268: However, you may want to interpret the command-line arguments directly.
9269: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9270: through @code{next-arg}:
1.121 anton 9271:
1.123 anton 9272: doc-next-arg
1.121 anton 9273:
1.123 anton 9274: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9275:
9276: @example
9277: : echo ( -- )
1.122 anton 9278: begin
1.123 anton 9279: next-arg 2dup 0 0 d<> while
9280: type space
9281: repeat
9282: 2drop ;
1.121 anton 9283:
9284: echo cr bye
9285: @end example
9286:
9287: This can be invoked with
9288:
9289: @example
9290: gforth echo.fs hello world
9291: @end example
1.123 anton 9292:
9293: and it will print
9294:
9295: @example
9296: hello world
9297: @end example
9298:
9299: The next lower level of dealing with the OS command line are the
9300: following words:
9301:
9302: doc-arg
9303: doc-shift-args
9304:
9305: Finally, at the lowest level Gforth provides the following words:
9306:
9307: doc-argc
9308: doc-argv
1.121 anton 9309:
1.78 anton 9310: @c -------------------------------------------------------------
1.126 pazsan 9311: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9312: @section Locals
9313: @cindex locals
9314:
9315: Local variables can make Forth programming more enjoyable and Forth
9316: programs easier to read. Unfortunately, the locals of ANS Forth are
9317: laden with restrictions. Therefore, we provide not only the ANS Forth
9318: locals wordset, but also our own, more powerful locals wordset (we
9319: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9320:
1.78 anton 9321: The ideas in this section have also been published in M. Anton Ertl,
9322: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9323: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9324:
9325: @menu
1.78 anton 9326: * Gforth locals::
9327: * ANS Forth locals::
1.5 anton 9328: @end menu
9329:
1.78 anton 9330: @node Gforth locals, ANS Forth locals, Locals, Locals
9331: @subsection Gforth locals
9332: @cindex Gforth locals
9333: @cindex locals, Gforth style
1.5 anton 9334:
1.78 anton 9335: Locals can be defined with
1.44 crook 9336:
1.78 anton 9337: @example
9338: @{ local1 local2 ... -- comment @}
9339: @end example
9340: or
9341: @example
9342: @{ local1 local2 ... @}
9343: @end example
1.5 anton 9344:
1.78 anton 9345: E.g.,
9346: @example
9347: : max @{ n1 n2 -- n3 @}
9348: n1 n2 > if
9349: n1
9350: else
9351: n2
9352: endif ;
9353: @end example
1.44 crook 9354:
1.78 anton 9355: The similarity of locals definitions with stack comments is intended. A
9356: locals definition often replaces the stack comment of a word. The order
9357: of the locals corresponds to the order in a stack comment and everything
9358: after the @code{--} is really a comment.
1.77 anton 9359:
1.78 anton 9360: This similarity has one disadvantage: It is too easy to confuse locals
9361: declarations with stack comments, causing bugs and making them hard to
9362: find. However, this problem can be avoided by appropriate coding
9363: conventions: Do not use both notations in the same program. If you do,
9364: they should be distinguished using additional means, e.g. by position.
1.77 anton 9365:
1.78 anton 9366: @cindex types of locals
9367: @cindex locals types
9368: The name of the local may be preceded by a type specifier, e.g.,
9369: @code{F:} for a floating point value:
1.5 anton 9370:
1.78 anton 9371: @example
9372: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9373: \ complex multiplication
9374: Ar Br f* Ai Bi f* f-
9375: Ar Bi f* Ai Br f* f+ ;
9376: @end example
1.44 crook 9377:
1.78 anton 9378: @cindex flavours of locals
9379: @cindex locals flavours
9380: @cindex value-flavoured locals
9381: @cindex variable-flavoured locals
9382: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9383: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9384: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9385: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9386: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9387: produces its address (which becomes invalid when the variable's scope is
9388: left). E.g., the standard word @code{emit} can be defined in terms of
9389: @code{type} like this:
1.5 anton 9390:
1.78 anton 9391: @example
9392: : emit @{ C^ char* -- @}
9393: char* 1 type ;
9394: @end example
1.5 anton 9395:
1.78 anton 9396: @cindex default type of locals
9397: @cindex locals, default type
9398: A local without type specifier is a @code{W:} local. Both flavours of
9399: locals are initialized with values from the data or FP stack.
1.44 crook 9400:
1.78 anton 9401: Currently there is no way to define locals with user-defined data
9402: structures, but we are working on it.
1.5 anton 9403:
1.78 anton 9404: Gforth allows defining locals everywhere in a colon definition. This
9405: poses the following questions:
1.5 anton 9406:
1.78 anton 9407: @menu
9408: * Where are locals visible by name?::
9409: * How long do locals live?::
9410: * Locals programming style::
9411: * Locals implementation::
9412: @end menu
1.44 crook 9413:
1.78 anton 9414: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9415: @subsubsection Where are locals visible by name?
9416: @cindex locals visibility
9417: @cindex visibility of locals
9418: @cindex scope of locals
1.5 anton 9419:
1.78 anton 9420: Basically, the answer is that locals are visible where you would expect
9421: it in block-structured languages, and sometimes a little longer. If you
9422: want to restrict the scope of a local, enclose its definition in
9423: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9424:
9425:
1.78 anton 9426: doc-scope
9427: doc-endscope
1.5 anton 9428:
9429:
1.78 anton 9430: These words behave like control structure words, so you can use them
9431: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9432: arbitrary ways.
1.77 anton 9433:
1.78 anton 9434: If you want a more exact answer to the visibility question, here's the
9435: basic principle: A local is visible in all places that can only be
9436: reached through the definition of the local@footnote{In compiler
9437: construction terminology, all places dominated by the definition of the
9438: local.}. In other words, it is not visible in places that can be reached
9439: without going through the definition of the local. E.g., locals defined
9440: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9441: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9442: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9443:
1.78 anton 9444: The reasoning behind this solution is: We want to have the locals
9445: visible as long as it is meaningful. The user can always make the
9446: visibility shorter by using explicit scoping. In a place that can
9447: only be reached through the definition of a local, the meaning of a
9448: local name is clear. In other places it is not: How is the local
9449: initialized at the control flow path that does not contain the
9450: definition? Which local is meant, if the same name is defined twice in
9451: two independent control flow paths?
1.77 anton 9452:
1.78 anton 9453: This should be enough detail for nearly all users, so you can skip the
9454: rest of this section. If you really must know all the gory details and
9455: options, read on.
1.77 anton 9456:
1.78 anton 9457: In order to implement this rule, the compiler has to know which places
9458: are unreachable. It knows this automatically after @code{AHEAD},
9459: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9460: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9461: compiler that the control flow never reaches that place. If
9462: @code{UNREACHABLE} is not used where it could, the only consequence is
9463: that the visibility of some locals is more limited than the rule above
9464: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9465: lie to the compiler), buggy code will be produced.
1.77 anton 9466:
1.5 anton 9467:
1.78 anton 9468: doc-unreachable
1.5 anton 9469:
1.23 crook 9470:
1.78 anton 9471: Another problem with this rule is that at @code{BEGIN}, the compiler
9472: does not know which locals will be visible on the incoming
9473: back-edge. All problems discussed in the following are due to this
9474: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9475: loops as examples; the discussion also applies to @code{?DO} and other
9476: loops). Perhaps the most insidious example is:
1.26 crook 9477: @example
1.78 anton 9478: AHEAD
9479: BEGIN
9480: x
9481: [ 1 CS-ROLL ] THEN
9482: @{ x @}
9483: ...
9484: UNTIL
1.26 crook 9485: @end example
1.23 crook 9486:
1.78 anton 9487: This should be legal according to the visibility rule. The use of
9488: @code{x} can only be reached through the definition; but that appears
9489: textually below the use.
9490:
9491: From this example it is clear that the visibility rules cannot be fully
9492: implemented without major headaches. Our implementation treats common
9493: cases as advertised and the exceptions are treated in a safe way: The
9494: compiler makes a reasonable guess about the locals visible after a
9495: @code{BEGIN}; if it is too pessimistic, the
9496: user will get a spurious error about the local not being defined; if the
9497: compiler is too optimistic, it will notice this later and issue a
9498: warning. In the case above the compiler would complain about @code{x}
9499: being undefined at its use. You can see from the obscure examples in
9500: this section that it takes quite unusual control structures to get the
9501: compiler into trouble, and even then it will often do fine.
1.23 crook 9502:
1.78 anton 9503: If the @code{BEGIN} is reachable from above, the most optimistic guess
9504: is that all locals visible before the @code{BEGIN} will also be
9505: visible after the @code{BEGIN}. This guess is valid for all loops that
9506: are entered only through the @code{BEGIN}, in particular, for normal
9507: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9508: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9509: compiler. When the branch to the @code{BEGIN} is finally generated by
9510: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9511: warns the user if it was too optimistic:
1.26 crook 9512: @example
1.78 anton 9513: IF
9514: @{ x @}
9515: BEGIN
9516: \ x ?
9517: [ 1 cs-roll ] THEN
9518: ...
9519: UNTIL
1.26 crook 9520: @end example
1.23 crook 9521:
1.78 anton 9522: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9523: optimistically assumes that it lives until the @code{THEN}. It notices
9524: this difference when it compiles the @code{UNTIL} and issues a
9525: warning. The user can avoid the warning, and make sure that @code{x}
9526: is not used in the wrong area by using explicit scoping:
9527: @example
9528: IF
9529: SCOPE
9530: @{ x @}
9531: ENDSCOPE
9532: BEGIN
9533: [ 1 cs-roll ] THEN
9534: ...
9535: UNTIL
9536: @end example
1.23 crook 9537:
1.78 anton 9538: Since the guess is optimistic, there will be no spurious error messages
9539: about undefined locals.
1.44 crook 9540:
1.78 anton 9541: If the @code{BEGIN} is not reachable from above (e.g., after
9542: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9543: optimistic guess, as the locals visible after the @code{BEGIN} may be
9544: defined later. Therefore, the compiler assumes that no locals are
9545: visible after the @code{BEGIN}. However, the user can use
9546: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9547: visible at the BEGIN as at the point where the top control-flow stack
9548: item was created.
1.23 crook 9549:
1.44 crook 9550:
1.78 anton 9551: doc-assume-live
1.26 crook 9552:
1.23 crook 9553:
1.78 anton 9554: @noindent
9555: E.g.,
9556: @example
9557: @{ x @}
9558: AHEAD
9559: ASSUME-LIVE
9560: BEGIN
9561: x
9562: [ 1 CS-ROLL ] THEN
9563: ...
9564: UNTIL
9565: @end example
1.44 crook 9566:
1.78 anton 9567: Other cases where the locals are defined before the @code{BEGIN} can be
9568: handled by inserting an appropriate @code{CS-ROLL} before the
9569: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9570: behind the @code{ASSUME-LIVE}).
1.23 crook 9571:
1.78 anton 9572: Cases where locals are defined after the @code{BEGIN} (but should be
9573: visible immediately after the @code{BEGIN}) can only be handled by
9574: rearranging the loop. E.g., the ``most insidious'' example above can be
9575: arranged into:
9576: @example
9577: BEGIN
9578: @{ x @}
9579: ... 0=
9580: WHILE
9581: x
9582: REPEAT
9583: @end example
1.44 crook 9584:
1.78 anton 9585: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9586: @subsubsection How long do locals live?
9587: @cindex locals lifetime
9588: @cindex lifetime of locals
1.23 crook 9589:
1.78 anton 9590: The right answer for the lifetime question would be: A local lives at
9591: least as long as it can be accessed. For a value-flavoured local this
9592: means: until the end of its visibility. However, a variable-flavoured
9593: local could be accessed through its address far beyond its visibility
9594: scope. Ultimately, this would mean that such locals would have to be
9595: garbage collected. Since this entails un-Forth-like implementation
9596: complexities, I adopted the same cowardly solution as some other
9597: languages (e.g., C): The local lives only as long as it is visible;
9598: afterwards its address is invalid (and programs that access it
9599: afterwards are erroneous).
1.23 crook 9600:
1.78 anton 9601: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9602: @subsubsection Locals programming style
9603: @cindex locals programming style
9604: @cindex programming style, locals
1.23 crook 9605:
1.78 anton 9606: The freedom to define locals anywhere has the potential to change
9607: programming styles dramatically. In particular, the need to use the
9608: return stack for intermediate storage vanishes. Moreover, all stack
9609: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9610: determined arguments) can be eliminated: If the stack items are in the
9611: wrong order, just write a locals definition for all of them; then
9612: write the items in the order you want.
1.23 crook 9613:
1.78 anton 9614: This seems a little far-fetched and eliminating stack manipulations is
9615: unlikely to become a conscious programming objective. Still, the number
9616: of stack manipulations will be reduced dramatically if local variables
9617: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9618: a traditional implementation of @code{max}).
1.23 crook 9619:
1.78 anton 9620: This shows one potential benefit of locals: making Forth programs more
9621: readable. Of course, this benefit will only be realized if the
9622: programmers continue to honour the principle of factoring instead of
9623: using the added latitude to make the words longer.
1.23 crook 9624:
1.78 anton 9625: @cindex single-assignment style for locals
9626: Using @code{TO} can and should be avoided. Without @code{TO},
9627: every value-flavoured local has only a single assignment and many
9628: advantages of functional languages apply to Forth. I.e., programs are
9629: easier to analyse, to optimize and to read: It is clear from the
9630: definition what the local stands for, it does not turn into something
9631: different later.
1.23 crook 9632:
1.78 anton 9633: E.g., a definition using @code{TO} might look like this:
9634: @example
9635: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9636: u1 u2 min 0
9637: ?do
9638: addr1 c@@ addr2 c@@ -
9639: ?dup-if
9640: unloop exit
9641: then
9642: addr1 char+ TO addr1
9643: addr2 char+ TO addr2
9644: loop
9645: u1 u2 - ;
1.26 crook 9646: @end example
1.78 anton 9647: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9648: every loop iteration. @code{strcmp} is a typical example of the
9649: readability problems of using @code{TO}. When you start reading
9650: @code{strcmp}, you think that @code{addr1} refers to the start of the
9651: string. Only near the end of the loop you realize that it is something
9652: else.
1.23 crook 9653:
1.78 anton 9654: This can be avoided by defining two locals at the start of the loop that
9655: are initialized with the right value for the current iteration.
9656: @example
9657: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9658: addr1 addr2
9659: u1 u2 min 0
9660: ?do @{ s1 s2 @}
9661: s1 c@@ s2 c@@ -
9662: ?dup-if
9663: unloop exit
9664: then
9665: s1 char+ s2 char+
9666: loop
9667: 2drop
9668: u1 u2 - ;
9669: @end example
9670: Here it is clear from the start that @code{s1} has a different value
9671: in every loop iteration.
1.23 crook 9672:
1.78 anton 9673: @node Locals implementation, , Locals programming style, Gforth locals
9674: @subsubsection Locals implementation
9675: @cindex locals implementation
9676: @cindex implementation of locals
1.23 crook 9677:
1.78 anton 9678: @cindex locals stack
9679: Gforth uses an extra locals stack. The most compelling reason for
9680: this is that the return stack is not float-aligned; using an extra stack
9681: also eliminates the problems and restrictions of using the return stack
9682: as locals stack. Like the other stacks, the locals stack grows toward
9683: lower addresses. A few primitives allow an efficient implementation:
9684:
9685:
9686: doc-@local#
9687: doc-f@local#
9688: doc-laddr#
9689: doc-lp+!#
9690: doc-lp!
9691: doc->l
9692: doc-f>l
9693:
9694:
9695: In addition to these primitives, some specializations of these
9696: primitives for commonly occurring inline arguments are provided for
9697: efficiency reasons, e.g., @code{@@local0} as specialization of
9698: @code{@@local#} for the inline argument 0. The following compiling words
9699: compile the right specialized version, or the general version, as
9700: appropriate:
1.23 crook 9701:
1.5 anton 9702:
1.107 dvdkhlng 9703: @c doc-compile-@local
9704: @c doc-compile-f@local
1.78 anton 9705: doc-compile-lp+!
1.5 anton 9706:
9707:
1.78 anton 9708: Combinations of conditional branches and @code{lp+!#} like
9709: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9710: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9711:
1.78 anton 9712: A special area in the dictionary space is reserved for keeping the
9713: local variable names. @code{@{} switches the dictionary pointer to this
9714: area and @code{@}} switches it back and generates the locals
9715: initializing code. @code{W:} etc.@ are normal defining words. This
9716: special area is cleared at the start of every colon definition.
1.5 anton 9717:
1.78 anton 9718: @cindex word list for defining locals
9719: A special feature of Gforth's dictionary is used to implement the
9720: definition of locals without type specifiers: every word list (aka
9721: vocabulary) has its own methods for searching
9722: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9723: with a special search method: When it is searched for a word, it
9724: actually creates that word using @code{W:}. @code{@{} changes the search
9725: order to first search the word list containing @code{@}}, @code{W:} etc.,
9726: and then the word list for defining locals without type specifiers.
1.5 anton 9727:
1.78 anton 9728: The lifetime rules support a stack discipline within a colon
9729: definition: The lifetime of a local is either nested with other locals
9730: lifetimes or it does not overlap them.
1.23 crook 9731:
1.78 anton 9732: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9733: pointer manipulation is generated. Between control structure words
9734: locals definitions can push locals onto the locals stack. @code{AGAIN}
9735: is the simplest of the other three control flow words. It has to
9736: restore the locals stack depth of the corresponding @code{BEGIN}
9737: before branching. The code looks like this:
9738: @format
9739: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9740: @code{branch} <begin>
9741: @end format
1.26 crook 9742:
1.78 anton 9743: @code{UNTIL} is a little more complicated: If it branches back, it
9744: must adjust the stack just like @code{AGAIN}. But if it falls through,
9745: the locals stack must not be changed. The compiler generates the
9746: following code:
9747: @format
9748: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9749: @end format
9750: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9751:
1.78 anton 9752: @code{THEN} can produce somewhat inefficient code:
9753: @format
9754: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9755: <orig target>:
9756: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9757: @end format
9758: The second @code{lp+!#} adjusts the locals stack pointer from the
9759: level at the @i{orig} point to the level after the @code{THEN}. The
9760: first @code{lp+!#} adjusts the locals stack pointer from the current
9761: level to the level at the orig point, so the complete effect is an
9762: adjustment from the current level to the right level after the
9763: @code{THEN}.
1.26 crook 9764:
1.78 anton 9765: @cindex locals information on the control-flow stack
9766: @cindex control-flow stack items, locals information
9767: In a conventional Forth implementation a dest control-flow stack entry
9768: is just the target address and an orig entry is just the address to be
9769: patched. Our locals implementation adds a word list to every orig or dest
9770: item. It is the list of locals visible (or assumed visible) at the point
9771: described by the entry. Our implementation also adds a tag to identify
9772: the kind of entry, in particular to differentiate between live and dead
9773: (reachable and unreachable) orig entries.
1.26 crook 9774:
1.78 anton 9775: A few unusual operations have to be performed on locals word lists:
1.44 crook 9776:
1.5 anton 9777:
1.78 anton 9778: doc-common-list
9779: doc-sub-list?
9780: doc-list-size
1.52 anton 9781:
9782:
1.78 anton 9783: Several features of our locals word list implementation make these
9784: operations easy to implement: The locals word lists are organised as
9785: linked lists; the tails of these lists are shared, if the lists
9786: contain some of the same locals; and the address of a name is greater
9787: than the address of the names behind it in the list.
1.5 anton 9788:
1.78 anton 9789: Another important implementation detail is the variable
9790: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9791: determine if they can be reached directly or only through the branch
9792: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9793: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9794: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9795:
1.78 anton 9796: Counted loops are similar to other loops in most respects, but
9797: @code{LEAVE} requires special attention: It performs basically the same
9798: service as @code{AHEAD}, but it does not create a control-flow stack
9799: entry. Therefore the information has to be stored elsewhere;
9800: traditionally, the information was stored in the target fields of the
9801: branches created by the @code{LEAVE}s, by organizing these fields into a
9802: linked list. Unfortunately, this clever trick does not provide enough
9803: space for storing our extended control flow information. Therefore, we
9804: introduce another stack, the leave stack. It contains the control-flow
9805: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9806:
1.78 anton 9807: Local names are kept until the end of the colon definition, even if
9808: they are no longer visible in any control-flow path. In a few cases
9809: this may lead to increased space needs for the locals name area, but
9810: usually less than reclaiming this space would cost in code size.
1.5 anton 9811:
1.44 crook 9812:
1.78 anton 9813: @node ANS Forth locals, , Gforth locals, Locals
9814: @subsection ANS Forth locals
9815: @cindex locals, ANS Forth style
1.5 anton 9816:
1.78 anton 9817: The ANS Forth locals wordset does not define a syntax for locals, but
9818: words that make it possible to define various syntaxes. One of the
9819: possible syntaxes is a subset of the syntax we used in the Gforth locals
9820: wordset, i.e.:
1.29 crook 9821:
9822: @example
1.78 anton 9823: @{ local1 local2 ... -- comment @}
9824: @end example
9825: @noindent
9826: or
9827: @example
9828: @{ local1 local2 ... @}
1.29 crook 9829: @end example
9830:
1.78 anton 9831: The order of the locals corresponds to the order in a stack comment. The
9832: restrictions are:
1.5 anton 9833:
1.78 anton 9834: @itemize @bullet
9835: @item
9836: Locals can only be cell-sized values (no type specifiers are allowed).
9837: @item
9838: Locals can be defined only outside control structures.
9839: @item
9840: Locals can interfere with explicit usage of the return stack. For the
9841: exact (and long) rules, see the standard. If you don't use return stack
9842: accessing words in a definition using locals, you will be all right. The
9843: purpose of this rule is to make locals implementation on the return
9844: stack easier.
9845: @item
9846: The whole definition must be in one line.
9847: @end itemize
1.5 anton 9848:
1.78 anton 9849: Locals defined in ANS Forth behave like @code{VALUE}s
9850: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9851: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9852:
1.78 anton 9853: Since the syntax above is supported by Gforth directly, you need not do
9854: anything to use it. If you want to port a program using this syntax to
9855: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9856: syntax on the other system.
1.5 anton 9857:
1.78 anton 9858: Note that a syntax shown in the standard, section A.13 looks
9859: similar, but is quite different in having the order of locals
9860: reversed. Beware!
1.5 anton 9861:
1.78 anton 9862: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9863:
1.78 anton 9864: doc-(local)
1.5 anton 9865:
1.78 anton 9866: The ANS Forth locals extension wordset defines a syntax using
9867: @code{locals|}, but it is so awful that we strongly recommend not to use
9868: it. We have implemented this syntax to make porting to Gforth easy, but
9869: do not document it here. The problem with this syntax is that the locals
9870: are defined in an order reversed with respect to the standard stack
9871: comment notation, making programs harder to read, and easier to misread
9872: and miswrite. The only merit of this syntax is that it is easy to
9873: implement using the ANS Forth locals wordset.
1.53 anton 9874:
9875:
1.78 anton 9876: @c ----------------------------------------------------------
9877: @node Structures, Object-oriented Forth, Locals, Words
9878: @section Structures
9879: @cindex structures
9880: @cindex records
1.53 anton 9881:
1.78 anton 9882: This section presents the structure package that comes with Gforth. A
9883: version of the package implemented in ANS Forth is available in
9884: @file{compat/struct.fs}. This package was inspired by a posting on
9885: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9886: possibly John Hayes). A version of this section has been published in
9887: M. Anton Ertl,
9888: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9889: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9890: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9891:
1.78 anton 9892: @menu
9893: * Why explicit structure support?::
9894: * Structure Usage::
9895: * Structure Naming Convention::
9896: * Structure Implementation::
9897: * Structure Glossary::
1.183 anton 9898: * Forth200x Structures::
1.78 anton 9899: @end menu
1.55 anton 9900:
1.78 anton 9901: @node Why explicit structure support?, Structure Usage, Structures, Structures
9902: @subsection Why explicit structure support?
1.53 anton 9903:
1.78 anton 9904: @cindex address arithmetic for structures
9905: @cindex structures using address arithmetic
9906: If we want to use a structure containing several fields, we could simply
9907: reserve memory for it, and access the fields using address arithmetic
9908: (@pxref{Address arithmetic}). As an example, consider a structure with
9909: the following fields
1.57 anton 9910:
1.78 anton 9911: @table @code
9912: @item a
9913: is a float
9914: @item b
9915: is a cell
9916: @item c
9917: is a float
9918: @end table
1.57 anton 9919:
1.78 anton 9920: Given the (float-aligned) base address of the structure we get the
9921: address of the field
1.52 anton 9922:
1.78 anton 9923: @table @code
9924: @item a
9925: without doing anything further.
9926: @item b
9927: with @code{float+}
9928: @item c
9929: with @code{float+ cell+ faligned}
9930: @end table
1.52 anton 9931:
1.78 anton 9932: It is easy to see that this can become quite tiring.
1.52 anton 9933:
1.78 anton 9934: Moreover, it is not very readable, because seeing a
9935: @code{cell+} tells us neither which kind of structure is
9936: accessed nor what field is accessed; we have to somehow infer the kind
9937: of structure, and then look up in the documentation, which field of
9938: that structure corresponds to that offset.
1.53 anton 9939:
1.78 anton 9940: Finally, this kind of address arithmetic also causes maintenance
9941: troubles: If you add or delete a field somewhere in the middle of the
9942: structure, you have to find and change all computations for the fields
9943: afterwards.
1.52 anton 9944:
1.78 anton 9945: So, instead of using @code{cell+} and friends directly, how
9946: about storing the offsets in constants:
1.52 anton 9947:
1.78 anton 9948: @example
9949: 0 constant a-offset
9950: 0 float+ constant b-offset
9951: 0 float+ cell+ faligned c-offset
9952: @end example
1.64 pazsan 9953:
1.78 anton 9954: Now we can get the address of field @code{x} with @code{x-offset
9955: +}. This is much better in all respects. Of course, you still
9956: have to change all later offset definitions if you add a field. You can
9957: fix this by declaring the offsets in the following way:
1.57 anton 9958:
1.78 anton 9959: @example
9960: 0 constant a-offset
9961: a-offset float+ constant b-offset
9962: b-offset cell+ faligned constant c-offset
9963: @end example
1.57 anton 9964:
1.78 anton 9965: Since we always use the offsets with @code{+}, we could use a defining
9966: word @code{cfield} that includes the @code{+} in the action of the
9967: defined word:
1.64 pazsan 9968:
1.78 anton 9969: @example
9970: : cfield ( n "name" -- )
9971: create ,
9972: does> ( name execution: addr1 -- addr2 )
9973: @@ + ;
1.64 pazsan 9974:
1.78 anton 9975: 0 cfield a
9976: 0 a float+ cfield b
9977: 0 b cell+ faligned cfield c
9978: @end example
1.64 pazsan 9979:
1.78 anton 9980: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9981:
1.78 anton 9982: The structure field words now can be used quite nicely. However,
9983: their definition is still a bit cumbersome: We have to repeat the
9984: name, the information about size and alignment is distributed before
9985: and after the field definitions etc. The structure package presented
9986: here addresses these problems.
1.64 pazsan 9987:
1.78 anton 9988: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9989: @subsection Structure Usage
9990: @cindex structure usage
1.57 anton 9991:
1.78 anton 9992: @cindex @code{field} usage
9993: @cindex @code{struct} usage
9994: @cindex @code{end-struct} usage
9995: You can define a structure for a (data-less) linked list with:
1.57 anton 9996: @example
1.78 anton 9997: struct
9998: cell% field list-next
9999: end-struct list%
1.57 anton 10000: @end example
10001:
1.78 anton 10002: With the address of the list node on the stack, you can compute the
10003: address of the field that contains the address of the next node with
10004: @code{list-next}. E.g., you can determine the length of a list
10005: with:
1.57 anton 10006:
10007: @example
1.78 anton 10008: : list-length ( list -- n )
10009: \ "list" is a pointer to the first element of a linked list
10010: \ "n" is the length of the list
10011: 0 BEGIN ( list1 n1 )
10012: over
10013: WHILE ( list1 n1 )
10014: 1+ swap list-next @@ swap
10015: REPEAT
10016: nip ;
1.57 anton 10017: @end example
10018:
1.78 anton 10019: You can reserve memory for a list node in the dictionary with
10020: @code{list% %allot}, which leaves the address of the list node on the
10021: stack. For the equivalent allocation on the heap you can use @code{list%
10022: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10023: use @code{list% %allocate}). You can get the the size of a list
10024: node with @code{list% %size} and its alignment with @code{list%
10025: %alignment}.
10026:
10027: Note that in ANS Forth the body of a @code{create}d word is
10028: @code{aligned} but not necessarily @code{faligned};
10029: therefore, if you do a:
1.57 anton 10030:
10031: @example
1.78 anton 10032: create @emph{name} foo% %allot drop
1.57 anton 10033: @end example
10034:
1.78 anton 10035: @noindent
10036: then the memory alloted for @code{foo%} is guaranteed to start at the
10037: body of @code{@emph{name}} only if @code{foo%} contains only character,
10038: cell and double fields. Therefore, if your structure contains floats,
10039: better use
1.57 anton 10040:
10041: @example
1.78 anton 10042: foo% %allot constant @emph{name}
1.57 anton 10043: @end example
10044:
1.78 anton 10045: @cindex structures containing structures
10046: You can include a structure @code{foo%} as a field of
10047: another structure, like this:
1.65 anton 10048: @example
1.78 anton 10049: struct
10050: ...
10051: foo% field ...
10052: ...
10053: end-struct ...
1.65 anton 10054: @end example
1.52 anton 10055:
1.78 anton 10056: @cindex structure extension
10057: @cindex extended records
10058: Instead of starting with an empty structure, you can extend an
10059: existing structure. E.g., a plain linked list without data, as defined
10060: above, is hardly useful; You can extend it to a linked list of integers,
10061: like this:@footnote{This feature is also known as @emph{extended
10062: records}. It is the main innovation in the Oberon language; in other
10063: words, adding this feature to Modula-2 led Wirth to create a new
10064: language, write a new compiler etc. Adding this feature to Forth just
10065: required a few lines of code.}
1.52 anton 10066:
1.78 anton 10067: @example
10068: list%
10069: cell% field intlist-int
10070: end-struct intlist%
10071: @end example
1.55 anton 10072:
1.78 anton 10073: @code{intlist%} is a structure with two fields:
10074: @code{list-next} and @code{intlist-int}.
1.55 anton 10075:
1.78 anton 10076: @cindex structures containing arrays
10077: You can specify an array type containing @emph{n} elements of
10078: type @code{foo%} like this:
1.55 anton 10079:
10080: @example
1.78 anton 10081: foo% @emph{n} *
1.56 anton 10082: @end example
1.55 anton 10083:
1.78 anton 10084: You can use this array type in any place where you can use a normal
10085: type, e.g., when defining a @code{field}, or with
10086: @code{%allot}.
10087:
10088: @cindex first field optimization
10089: The first field is at the base address of a structure and the word for
10090: this field (e.g., @code{list-next}) actually does not change the address
10091: on the stack. You may be tempted to leave it away in the interest of
10092: run-time and space efficiency. This is not necessary, because the
10093: structure package optimizes this case: If you compile a first-field
10094: words, no code is generated. So, in the interest of readability and
10095: maintainability you should include the word for the field when accessing
10096: the field.
1.52 anton 10097:
10098:
1.78 anton 10099: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10100: @subsection Structure Naming Convention
10101: @cindex structure naming convention
1.52 anton 10102:
1.78 anton 10103: The field names that come to (my) mind are often quite generic, and,
10104: if used, would cause frequent name clashes. E.g., many structures
10105: probably contain a @code{counter} field. The structure names
10106: that come to (my) mind are often also the logical choice for the names
10107: of words that create such a structure.
1.52 anton 10108:
1.78 anton 10109: Therefore, I have adopted the following naming conventions:
1.52 anton 10110:
1.78 anton 10111: @itemize @bullet
10112: @cindex field naming convention
10113: @item
10114: The names of fields are of the form
10115: @code{@emph{struct}-@emph{field}}, where
10116: @code{@emph{struct}} is the basic name of the structure, and
10117: @code{@emph{field}} is the basic name of the field. You can
10118: think of field words as converting the (address of the)
10119: structure into the (address of the) field.
1.52 anton 10120:
1.78 anton 10121: @cindex structure naming convention
10122: @item
10123: The names of structures are of the form
10124: @code{@emph{struct}%}, where
10125: @code{@emph{struct}} is the basic name of the structure.
10126: @end itemize
1.52 anton 10127:
1.78 anton 10128: This naming convention does not work that well for fields of extended
10129: structures; e.g., the integer list structure has a field
10130: @code{intlist-int}, but has @code{list-next}, not
10131: @code{intlist-next}.
1.53 anton 10132:
1.78 anton 10133: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10134: @subsection Structure Implementation
10135: @cindex structure implementation
10136: @cindex implementation of structures
1.52 anton 10137:
1.78 anton 10138: The central idea in the implementation is to pass the data about the
10139: structure being built on the stack, not in some global
10140: variable. Everything else falls into place naturally once this design
10141: decision is made.
1.53 anton 10142:
1.78 anton 10143: The type description on the stack is of the form @emph{align
10144: size}. Keeping the size on the top-of-stack makes dealing with arrays
10145: very simple.
1.53 anton 10146:
1.78 anton 10147: @code{field} is a defining word that uses @code{Create}
10148: and @code{DOES>}. The body of the field contains the offset
10149: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10150:
10151: @example
1.78 anton 10152: @@ +
1.53 anton 10153: @end example
10154:
1.78 anton 10155: @noindent
10156: i.e., add the offset to the address, giving the stack effect
10157: @i{addr1 -- addr2} for a field.
10158:
10159: @cindex first field optimization, implementation
10160: This simple structure is slightly complicated by the optimization
10161: for fields with offset 0, which requires a different
10162: @code{DOES>}-part (because we cannot rely on there being
10163: something on the stack if such a field is invoked during
10164: compilation). Therefore, we put the different @code{DOES>}-parts
10165: in separate words, and decide which one to invoke based on the
10166: offset. For a zero offset, the field is basically a noop; it is
10167: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10168:
1.183 anton 10169: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10170: @subsection Structure Glossary
10171: @cindex structure glossary
1.53 anton 10172:
1.5 anton 10173:
1.78 anton 10174: doc-%align
10175: doc-%alignment
10176: doc-%alloc
10177: doc-%allocate
10178: doc-%allot
10179: doc-cell%
10180: doc-char%
10181: doc-dfloat%
10182: doc-double%
10183: doc-end-struct
10184: doc-field
10185: doc-float%
10186: doc-naligned
10187: doc-sfloat%
10188: doc-%size
10189: doc-struct
1.54 anton 10190:
10191:
1.183 anton 10192: @node Forth200x Structures, , Structure Glossary, Structures
10193: @subsection Forth200x Structures
10194: @cindex Structures in Forth200x
10195:
10196: The Forth 200x standard defines a slightly less convenient form of
10197: structures. In general (when using @code{field+}, you have to perform
10198: the alignment yourself, but there are a number of convenience words
10199: (e.g., @code{field:} that perform the alignment for you.
10200:
10201: A typical usage example is:
10202:
10203: @example
10204: 0
10205: field: s-a
10206: faligned 2 floats +field s-b
10207: constant s-struct
10208: @end example
10209:
10210: An alternative way of writing this structure is:
10211:
10212: @example
10213: begin-structure s-struct
10214: field: s-a
10215: faligned 2 floats +field s-b
10216: end-structure
10217: @end example
10218:
10219: doc-begin-structure
10220: doc-end-structure
10221: doc-+field
10222: doc-cfield:
10223: doc-field:
10224: doc-2field:
10225: doc-ffield:
10226: doc-sffield:
10227: doc-dffield:
10228:
1.26 crook 10229: @c -------------------------------------------------------------
1.78 anton 10230: @node Object-oriented Forth, Programming Tools, Structures, Words
10231: @section Object-oriented Forth
10232:
10233: Gforth comes with three packages for object-oriented programming:
10234: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10235: is preloaded, so you have to @code{include} them before use. The most
10236: important differences between these packages (and others) are discussed
10237: in @ref{Comparison with other object models}. All packages are written
10238: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10239:
1.78 anton 10240: @menu
10241: * Why object-oriented programming?::
10242: * Object-Oriented Terminology::
10243: * Objects::
10244: * OOF::
10245: * Mini-OOF::
10246: * Comparison with other object models::
10247: @end menu
1.5 anton 10248:
1.78 anton 10249: @c ----------------------------------------------------------------
10250: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10251: @subsection Why object-oriented programming?
10252: @cindex object-oriented programming motivation
10253: @cindex motivation for object-oriented programming
1.44 crook 10254:
1.78 anton 10255: Often we have to deal with several data structures (@emph{objects}),
10256: that have to be treated similarly in some respects, but differently in
10257: others. Graphical objects are the textbook example: circles, triangles,
10258: dinosaurs, icons, and others, and we may want to add more during program
10259: development. We want to apply some operations to any graphical object,
10260: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10261: has to do something different for every kind of object.
10262: @comment TODO add some other operations eg perimeter, area
10263: @comment and tie in to concrete examples later..
1.5 anton 10264:
1.78 anton 10265: We could implement @code{draw} as a big @code{CASE}
10266: control structure that executes the appropriate code depending on the
10267: kind of object to be drawn. This would be not be very elegant, and,
10268: moreover, we would have to change @code{draw} every time we add
10269: a new kind of graphical object (say, a spaceship).
1.44 crook 10270:
1.78 anton 10271: What we would rather do is: When defining spaceships, we would tell
10272: the system: ``Here's how you @code{draw} a spaceship; you figure
10273: out the rest''.
1.5 anton 10274:
1.78 anton 10275: This is the problem that all systems solve that (rightfully) call
10276: themselves object-oriented; the object-oriented packages presented here
10277: solve this problem (and not much else).
10278: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10279:
1.78 anton 10280: @c ------------------------------------------------------------------------
10281: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10282: @subsection Object-Oriented Terminology
10283: @cindex object-oriented terminology
10284: @cindex terminology for object-oriented programming
1.5 anton 10285:
1.78 anton 10286: This section is mainly for reference, so you don't have to understand
10287: all of it right away. The terminology is mainly Smalltalk-inspired. In
10288: short:
1.44 crook 10289:
1.78 anton 10290: @table @emph
10291: @cindex class
10292: @item class
10293: a data structure definition with some extras.
1.5 anton 10294:
1.78 anton 10295: @cindex object
10296: @item object
10297: an instance of the data structure described by the class definition.
1.5 anton 10298:
1.78 anton 10299: @cindex instance variables
10300: @item instance variables
10301: fields of the data structure.
1.5 anton 10302:
1.78 anton 10303: @cindex selector
10304: @cindex method selector
10305: @cindex virtual function
10306: @item selector
10307: (or @emph{method selector}) a word (e.g.,
10308: @code{draw}) that performs an operation on a variety of data
10309: structures (classes). A selector describes @emph{what} operation to
10310: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10311:
1.78 anton 10312: @cindex method
10313: @item method
10314: the concrete definition that performs the operation
10315: described by the selector for a specific class. A method specifies
10316: @emph{how} the operation is performed for a specific class.
1.5 anton 10317:
1.78 anton 10318: @cindex selector invocation
10319: @cindex message send
10320: @cindex invoking a selector
10321: @item selector invocation
10322: a call of a selector. One argument of the call (the TOS (top-of-stack))
10323: is used for determining which method is used. In Smalltalk terminology:
10324: a message (consisting of the selector and the other arguments) is sent
10325: to the object.
1.5 anton 10326:
1.78 anton 10327: @cindex receiving object
10328: @item receiving object
10329: the object used for determining the method executed by a selector
10330: invocation. In the @file{objects.fs} model, it is the object that is on
10331: the TOS when the selector is invoked. (@emph{Receiving} comes from
10332: the Smalltalk @emph{message} terminology.)
1.5 anton 10333:
1.78 anton 10334: @cindex child class
10335: @cindex parent class
10336: @cindex inheritance
10337: @item child class
10338: a class that has (@emph{inherits}) all properties (instance variables,
10339: selectors, methods) from a @emph{parent class}. In Smalltalk
10340: terminology: The subclass inherits from the superclass. In C++
10341: terminology: The derived class inherits from the base class.
1.5 anton 10342:
1.78 anton 10343: @end table
1.5 anton 10344:
1.78 anton 10345: @c If you wonder about the message sending terminology, it comes from
10346: @c a time when each object had it's own task and objects communicated via
10347: @c message passing; eventually the Smalltalk developers realized that
10348: @c they can do most things through simple (indirect) calls. They kept the
10349: @c terminology.
1.5 anton 10350:
1.78 anton 10351: @c --------------------------------------------------------------
10352: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10353: @subsection The @file{objects.fs} model
10354: @cindex objects
10355: @cindex object-oriented programming
1.26 crook 10356:
1.78 anton 10357: @cindex @file{objects.fs}
10358: @cindex @file{oof.fs}
1.26 crook 10359:
1.78 anton 10360: This section describes the @file{objects.fs} package. This material also
10361: has been published in M. Anton Ertl,
10362: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10363: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10364: 37--43.
10365: @c McKewan's and Zsoter's packages
1.26 crook 10366:
1.78 anton 10367: This section assumes that you have read @ref{Structures}.
1.5 anton 10368:
1.78 anton 10369: The techniques on which this model is based have been used to implement
10370: the parser generator, Gray, and have also been used in Gforth for
10371: implementing the various flavours of word lists (hashed or not,
10372: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10373:
10374:
1.26 crook 10375: @menu
1.78 anton 10376: * Properties of the Objects model::
10377: * Basic Objects Usage::
10378: * The Objects base class::
10379: * Creating objects::
10380: * Object-Oriented Programming Style::
10381: * Class Binding::
10382: * Method conveniences::
10383: * Classes and Scoping::
10384: * Dividing classes::
10385: * Object Interfaces::
10386: * Objects Implementation::
10387: * Objects Glossary::
1.26 crook 10388: @end menu
1.5 anton 10389:
1.78 anton 10390: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10391:
1.78 anton 10392: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10393: @subsubsection Properties of the @file{objects.fs} model
10394: @cindex @file{objects.fs} properties
1.5 anton 10395:
1.78 anton 10396: @itemize @bullet
10397: @item
10398: It is straightforward to pass objects on the stack. Passing
10399: selectors on the stack is a little less convenient, but possible.
1.44 crook 10400:
1.78 anton 10401: @item
10402: Objects are just data structures in memory, and are referenced by their
10403: address. You can create words for objects with normal defining words
10404: like @code{constant}. Likewise, there is no difference between instance
10405: variables that contain objects and those that contain other data.
1.5 anton 10406:
1.78 anton 10407: @item
10408: Late binding is efficient and easy to use.
1.44 crook 10409:
1.78 anton 10410: @item
10411: It avoids parsing, and thus avoids problems with state-smartness
10412: and reduced extensibility; for convenience there are a few parsing
10413: words, but they have non-parsing counterparts. There are also a few
10414: defining words that parse. This is hard to avoid, because all standard
10415: defining words parse (except @code{:noname}); however, such
10416: words are not as bad as many other parsing words, because they are not
10417: state-smart.
1.5 anton 10418:
1.78 anton 10419: @item
10420: It does not try to incorporate everything. It does a few things and does
10421: them well (IMO). In particular, this model was not designed to support
10422: information hiding (although it has features that may help); you can use
10423: a separate package for achieving this.
1.5 anton 10424:
1.78 anton 10425: @item
10426: It is layered; you don't have to learn and use all features to use this
10427: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10428: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10429: are optional and independent of each other.
1.5 anton 10430:
1.78 anton 10431: @item
10432: An implementation in ANS Forth is available.
1.5 anton 10433:
1.78 anton 10434: @end itemize
1.5 anton 10435:
1.44 crook 10436:
1.78 anton 10437: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10438: @subsubsection Basic @file{objects.fs} Usage
10439: @cindex basic objects usage
10440: @cindex objects, basic usage
1.5 anton 10441:
1.78 anton 10442: You can define a class for graphical objects like this:
1.44 crook 10443:
1.78 anton 10444: @cindex @code{class} usage
10445: @cindex @code{end-class} usage
10446: @cindex @code{selector} usage
1.5 anton 10447: @example
1.78 anton 10448: object class \ "object" is the parent class
10449: selector draw ( x y graphical -- )
10450: end-class graphical
10451: @end example
10452:
10453: This code defines a class @code{graphical} with an
10454: operation @code{draw}. We can perform the operation
10455: @code{draw} on any @code{graphical} object, e.g.:
10456:
10457: @example
10458: 100 100 t-rex draw
1.26 crook 10459: @end example
1.5 anton 10460:
1.78 anton 10461: @noindent
10462: where @code{t-rex} is a word (say, a constant) that produces a
10463: graphical object.
10464:
10465: @comment TODO add a 2nd operation eg perimeter.. and use for
10466: @comment a concrete example
1.5 anton 10467:
1.78 anton 10468: @cindex abstract class
10469: How do we create a graphical object? With the present definitions,
10470: we cannot create a useful graphical object. The class
10471: @code{graphical} describes graphical objects in general, but not
10472: any concrete graphical object type (C++ users would call it an
10473: @emph{abstract class}); e.g., there is no method for the selector
10474: @code{draw} in the class @code{graphical}.
1.5 anton 10475:
1.78 anton 10476: For concrete graphical objects, we define child classes of the
10477: class @code{graphical}, e.g.:
1.5 anton 10478:
1.78 anton 10479: @cindex @code{overrides} usage
10480: @cindex @code{field} usage in class definition
1.26 crook 10481: @example
1.78 anton 10482: graphical class \ "graphical" is the parent class
10483: cell% field circle-radius
1.5 anton 10484:
1.78 anton 10485: :noname ( x y circle -- )
10486: circle-radius @@ draw-circle ;
10487: overrides draw
1.5 anton 10488:
1.78 anton 10489: :noname ( n-radius circle -- )
10490: circle-radius ! ;
10491: overrides construct
1.5 anton 10492:
1.78 anton 10493: end-class circle
10494: @end example
1.44 crook 10495:
1.78 anton 10496: Here we define a class @code{circle} as a child of @code{graphical},
10497: with field @code{circle-radius} (which behaves just like a field
10498: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10499: for the selectors @code{draw} and @code{construct} (@code{construct} is
10500: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10501:
1.78 anton 10502: Now we can create a circle on the heap (i.e.,
10503: @code{allocate}d memory) with:
1.44 crook 10504:
1.78 anton 10505: @cindex @code{heap-new} usage
1.5 anton 10506: @example
1.78 anton 10507: 50 circle heap-new constant my-circle
1.5 anton 10508: @end example
10509:
1.78 anton 10510: @noindent
10511: @code{heap-new} invokes @code{construct}, thus
10512: initializing the field @code{circle-radius} with 50. We can draw
10513: this new circle at (100,100) with:
1.5 anton 10514:
10515: @example
1.78 anton 10516: 100 100 my-circle draw
1.5 anton 10517: @end example
10518:
1.78 anton 10519: @cindex selector invocation, restrictions
10520: @cindex class definition, restrictions
10521: Note: You can only invoke a selector if the object on the TOS
10522: (the receiving object) belongs to the class where the selector was
10523: defined or one of its descendents; e.g., you can invoke
10524: @code{draw} only for objects belonging to @code{graphical}
10525: or its descendents (e.g., @code{circle}). Immediately before
10526: @code{end-class}, the search order has to be the same as
10527: immediately after @code{class}.
10528:
10529: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10530: @subsubsection The @file{object.fs} base class
10531: @cindex @code{object} class
10532:
10533: When you define a class, you have to specify a parent class. So how do
10534: you start defining classes? There is one class available from the start:
10535: @code{object}. It is ancestor for all classes and so is the
10536: only class that has no parent. It has two selectors: @code{construct}
10537: and @code{print}.
10538:
10539: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10540: @subsubsection Creating objects
10541: @cindex creating objects
10542: @cindex object creation
10543: @cindex object allocation options
10544:
10545: @cindex @code{heap-new} discussion
10546: @cindex @code{dict-new} discussion
10547: @cindex @code{construct} discussion
10548: You can create and initialize an object of a class on the heap with
10549: @code{heap-new} ( ... class -- object ) and in the dictionary
10550: (allocation with @code{allot}) with @code{dict-new} (
10551: ... class -- object ). Both words invoke @code{construct}, which
10552: consumes the stack items indicated by "..." above.
10553:
10554: @cindex @code{init-object} discussion
10555: @cindex @code{class-inst-size} discussion
10556: If you want to allocate memory for an object yourself, you can get its
10557: alignment and size with @code{class-inst-size 2@@} ( class --
10558: align size ). Once you have memory for an object, you can initialize
10559: it with @code{init-object} ( ... class object -- );
10560: @code{construct} does only a part of the necessary work.
10561:
10562: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10563: @subsubsection Object-Oriented Programming Style
10564: @cindex object-oriented programming style
10565: @cindex programming style, object-oriented
1.5 anton 10566:
1.78 anton 10567: This section is not exhaustive.
1.5 anton 10568:
1.78 anton 10569: @cindex stack effects of selectors
10570: @cindex selectors and stack effects
10571: In general, it is a good idea to ensure that all methods for the
10572: same selector have the same stack effect: when you invoke a selector,
10573: you often have no idea which method will be invoked, so, unless all
10574: methods have the same stack effect, you will not know the stack effect
10575: of the selector invocation.
1.5 anton 10576:
1.78 anton 10577: One exception to this rule is methods for the selector
10578: @code{construct}. We know which method is invoked, because we
10579: specify the class to be constructed at the same place. Actually, I
10580: defined @code{construct} as a selector only to give the users a
10581: convenient way to specify initialization. The way it is used, a
10582: mechanism different from selector invocation would be more natural
10583: (but probably would take more code and more space to explain).
1.5 anton 10584:
1.78 anton 10585: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10586: @subsubsection Class Binding
10587: @cindex class binding
10588: @cindex early binding
1.5 anton 10589:
1.78 anton 10590: @cindex late binding
10591: Normal selector invocations determine the method at run-time depending
10592: on the class of the receiving object. This run-time selection is called
10593: @i{late binding}.
1.5 anton 10594:
1.78 anton 10595: Sometimes it's preferable to invoke a different method. For example,
10596: you might want to use the simple method for @code{print}ing
10597: @code{object}s instead of the possibly long-winded @code{print} method
10598: of the receiver class. You can achieve this by replacing the invocation
10599: of @code{print} with:
1.5 anton 10600:
1.78 anton 10601: @cindex @code{[bind]} usage
1.5 anton 10602: @example
1.78 anton 10603: [bind] object print
1.5 anton 10604: @end example
10605:
1.78 anton 10606: @noindent
10607: in compiled code or:
10608:
10609: @cindex @code{bind} usage
1.5 anton 10610: @example
1.78 anton 10611: bind object print
1.5 anton 10612: @end example
10613:
1.78 anton 10614: @cindex class binding, alternative to
10615: @noindent
10616: in interpreted code. Alternatively, you can define the method with a
10617: name (e.g., @code{print-object}), and then invoke it through the
10618: name. Class binding is just a (often more convenient) way to achieve
10619: the same effect; it avoids name clutter and allows you to invoke
10620: methods directly without naming them first.
1.5 anton 10621:
1.78 anton 10622: @cindex superclass binding
10623: @cindex parent class binding
10624: A frequent use of class binding is this: When we define a method
10625: for a selector, we often want the method to do what the selector does
10626: in the parent class, and a little more. There is a special word for
10627: this purpose: @code{[parent]}; @code{[parent]
10628: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10629: selector}}, where @code{@emph{parent}} is the parent
10630: class of the current class. E.g., a method definition might look like:
1.44 crook 10631:
1.78 anton 10632: @cindex @code{[parent]} usage
10633: @example
10634: :noname
10635: dup [parent] foo \ do parent's foo on the receiving object
10636: ... \ do some more
10637: ; overrides foo
10638: @end example
1.6 pazsan 10639:
1.78 anton 10640: @cindex class binding as optimization
10641: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10642: March 1997), Andrew McKewan presents class binding as an optimization
10643: technique. I recommend not using it for this purpose unless you are in
10644: an emergency. Late binding is pretty fast with this model anyway, so the
10645: benefit of using class binding is small; the cost of using class binding
10646: where it is not appropriate is reduced maintainability.
1.44 crook 10647:
1.78 anton 10648: While we are at programming style questions: You should bind
10649: selectors only to ancestor classes of the receiving object. E.g., say,
10650: you know that the receiving object is of class @code{foo} or its
10651: descendents; then you should bind only to @code{foo} and its
10652: ancestors.
1.12 anton 10653:
1.78 anton 10654: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10655: @subsubsection Method conveniences
10656: @cindex method conveniences
1.44 crook 10657:
1.78 anton 10658: In a method you usually access the receiving object pretty often. If
10659: you define the method as a plain colon definition (e.g., with
10660: @code{:noname}), you may have to do a lot of stack
10661: gymnastics. To avoid this, you can define the method with @code{m:
10662: ... ;m}. E.g., you could define the method for
10663: @code{draw}ing a @code{circle} with
1.6 pazsan 10664:
1.78 anton 10665: @cindex @code{this} usage
10666: @cindex @code{m:} usage
10667: @cindex @code{;m} usage
10668: @example
10669: m: ( x y circle -- )
10670: ( x y ) this circle-radius @@ draw-circle ;m
10671: @end example
1.6 pazsan 10672:
1.78 anton 10673: @cindex @code{exit} in @code{m: ... ;m}
10674: @cindex @code{exitm} discussion
10675: @cindex @code{catch} in @code{m: ... ;m}
10676: When this method is executed, the receiver object is removed from the
10677: stack; you can access it with @code{this} (admittedly, in this
10678: example the use of @code{m: ... ;m} offers no advantage). Note
10679: that I specify the stack effect for the whole method (i.e. including
10680: the receiver object), not just for the code between @code{m:}
10681: and @code{;m}. You cannot use @code{exit} in
10682: @code{m:...;m}; instead, use
10683: @code{exitm}.@footnote{Moreover, for any word that calls
10684: @code{catch} and was defined before loading
10685: @code{objects.fs}, you have to redefine it like I redefined
10686: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10687:
1.78 anton 10688: @cindex @code{inst-var} usage
10689: You will frequently use sequences of the form @code{this
10690: @emph{field}} (in the example above: @code{this
10691: circle-radius}). If you use the field only in this way, you can
10692: define it with @code{inst-var} and eliminate the
10693: @code{this} before the field name. E.g., the @code{circle}
10694: class above could also be defined with:
1.6 pazsan 10695:
1.78 anton 10696: @example
10697: graphical class
10698: cell% inst-var radius
1.6 pazsan 10699:
1.78 anton 10700: m: ( x y circle -- )
10701: radius @@ draw-circle ;m
10702: overrides draw
1.6 pazsan 10703:
1.78 anton 10704: m: ( n-radius circle -- )
10705: radius ! ;m
10706: overrides construct
1.6 pazsan 10707:
1.78 anton 10708: end-class circle
10709: @end example
1.6 pazsan 10710:
1.78 anton 10711: @code{radius} can only be used in @code{circle} and its
10712: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10713:
1.78 anton 10714: @cindex @code{inst-value} usage
10715: You can also define fields with @code{inst-value}, which is
10716: to @code{inst-var} what @code{value} is to
10717: @code{variable}. You can change the value of such a field with
10718: @code{[to-inst]}. E.g., we could also define the class
10719: @code{circle} like this:
1.44 crook 10720:
1.78 anton 10721: @example
10722: graphical class
10723: inst-value radius
1.6 pazsan 10724:
1.78 anton 10725: m: ( x y circle -- )
10726: radius draw-circle ;m
10727: overrides draw
1.44 crook 10728:
1.78 anton 10729: m: ( n-radius circle -- )
10730: [to-inst] radius ;m
10731: overrides construct
1.6 pazsan 10732:
1.78 anton 10733: end-class circle
10734: @end example
1.6 pazsan 10735:
1.78 anton 10736: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10737:
1.78 anton 10738: @c Finally, you can define named methods with @code{:m}. One use of this
10739: @c feature is the definition of words that occur only in one class and are
10740: @c not intended to be overridden, but which still need method context
10741: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10742: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10743:
10744:
1.78 anton 10745: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10746: @subsubsection Classes and Scoping
10747: @cindex classes and scoping
10748: @cindex scoping and classes
1.6 pazsan 10749:
1.78 anton 10750: Inheritance is frequent, unlike structure extension. This exacerbates
10751: the problem with the field name convention (@pxref{Structure Naming
10752: Convention}): One always has to remember in which class the field was
10753: originally defined; changing a part of the class structure would require
10754: changes for renaming in otherwise unaffected code.
1.6 pazsan 10755:
1.78 anton 10756: @cindex @code{inst-var} visibility
10757: @cindex @code{inst-value} visibility
10758: To solve this problem, I added a scoping mechanism (which was not in my
10759: original charter): A field defined with @code{inst-var} (or
10760: @code{inst-value}) is visible only in the class where it is defined and in
10761: the descendent classes of this class. Using such fields only makes
10762: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10763:
1.78 anton 10764: This scoping mechanism allows us to use the unadorned field name,
10765: because name clashes with unrelated words become much less likely.
1.6 pazsan 10766:
1.78 anton 10767: @cindex @code{protected} discussion
10768: @cindex @code{private} discussion
10769: Once we have this mechanism, we can also use it for controlling the
10770: visibility of other words: All words defined after
10771: @code{protected} are visible only in the current class and its
10772: descendents. @code{public} restores the compilation
10773: (i.e. @code{current}) word list that was in effect before. If you
10774: have several @code{protected}s without an intervening
10775: @code{public} or @code{set-current}, @code{public}
10776: will restore the compilation word list in effect before the first of
10777: these @code{protected}s.
1.6 pazsan 10778:
1.78 anton 10779: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10780: @subsubsection Dividing classes
10781: @cindex Dividing classes
10782: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10783:
1.78 anton 10784: You may want to do the definition of methods separate from the
10785: definition of the class, its selectors, fields, and instance variables,
10786: i.e., separate the implementation from the definition. You can do this
10787: in the following way:
1.6 pazsan 10788:
1.78 anton 10789: @example
10790: graphical class
10791: inst-value radius
10792: end-class circle
1.6 pazsan 10793:
1.78 anton 10794: ... \ do some other stuff
1.6 pazsan 10795:
1.78 anton 10796: circle methods \ now we are ready
1.44 crook 10797:
1.78 anton 10798: m: ( x y circle -- )
10799: radius draw-circle ;m
10800: overrides draw
1.6 pazsan 10801:
1.78 anton 10802: m: ( n-radius circle -- )
10803: [to-inst] radius ;m
10804: overrides construct
1.44 crook 10805:
1.78 anton 10806: end-methods
10807: @end example
1.7 pazsan 10808:
1.78 anton 10809: You can use several @code{methods}...@code{end-methods} sections. The
10810: only things you can do to the class in these sections are: defining
10811: methods, and overriding the class's selectors. You must not define new
10812: selectors or fields.
1.7 pazsan 10813:
1.78 anton 10814: Note that you often have to override a selector before using it. In
10815: particular, you usually have to override @code{construct} with a new
10816: method before you can invoke @code{heap-new} and friends. E.g., you
10817: must not create a circle before the @code{overrides construct} sequence
10818: in the example above.
1.7 pazsan 10819:
1.78 anton 10820: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10821: @subsubsection Object Interfaces
10822: @cindex object interfaces
10823: @cindex interfaces for objects
1.7 pazsan 10824:
1.78 anton 10825: In this model you can only call selectors defined in the class of the
10826: receiving objects or in one of its ancestors. If you call a selector
10827: with a receiving object that is not in one of these classes, the
10828: result is undefined; if you are lucky, the program crashes
10829: immediately.
1.7 pazsan 10830:
1.78 anton 10831: @cindex selectors common to hardly-related classes
10832: Now consider the case when you want to have a selector (or several)
10833: available in two classes: You would have to add the selector to a
10834: common ancestor class, in the worst case to @code{object}. You
10835: may not want to do this, e.g., because someone else is responsible for
10836: this ancestor class.
1.7 pazsan 10837:
1.78 anton 10838: The solution for this problem is interfaces. An interface is a
10839: collection of selectors. If a class implements an interface, the
10840: selectors become available to the class and its descendents. A class
10841: can implement an unlimited number of interfaces. For the problem
10842: discussed above, we would define an interface for the selector(s), and
10843: both classes would implement the interface.
1.7 pazsan 10844:
1.78 anton 10845: As an example, consider an interface @code{storage} for
10846: writing objects to disk and getting them back, and a class
10847: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10848:
1.78 anton 10849: @cindex @code{interface} usage
10850: @cindex @code{end-interface} usage
10851: @cindex @code{implementation} usage
10852: @example
10853: interface
10854: selector write ( file object -- )
10855: selector read1 ( file object -- )
10856: end-interface storage
1.13 pazsan 10857:
1.78 anton 10858: bar class
10859: storage implementation
1.13 pazsan 10860:
1.78 anton 10861: ... overrides write
10862: ... overrides read1
10863: ...
10864: end-class foo
10865: @end example
1.13 pazsan 10866:
1.78 anton 10867: @noindent
10868: (I would add a word @code{read} @i{( file -- object )} that uses
10869: @code{read1} internally, but that's beyond the point illustrated
10870: here.)
1.13 pazsan 10871:
1.78 anton 10872: Note that you cannot use @code{protected} in an interface; and
10873: of course you cannot define fields.
1.13 pazsan 10874:
1.78 anton 10875: In the Neon model, all selectors are available for all classes;
10876: therefore it does not need interfaces. The price you pay in this model
10877: is slower late binding, and therefore, added complexity to avoid late
10878: binding.
1.13 pazsan 10879:
1.78 anton 10880: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10881: @subsubsection @file{objects.fs} Implementation
10882: @cindex @file{objects.fs} implementation
1.13 pazsan 10883:
1.78 anton 10884: @cindex @code{object-map} discussion
10885: An object is a piece of memory, like one of the data structures
10886: described with @code{struct...end-struct}. It has a field
10887: @code{object-map} that points to the method map for the object's
10888: class.
1.13 pazsan 10889:
1.78 anton 10890: @cindex method map
10891: @cindex virtual function table
10892: The @emph{method map}@footnote{This is Self terminology; in C++
10893: terminology: virtual function table.} is an array that contains the
10894: execution tokens (@i{xt}s) of the methods for the object's class. Each
10895: selector contains an offset into a method map.
1.13 pazsan 10896:
1.78 anton 10897: @cindex @code{selector} implementation, class
10898: @code{selector} is a defining word that uses
10899: @code{CREATE} and @code{DOES>}. The body of the
10900: selector contains the offset; the @code{DOES>} action for a
10901: class selector is, basically:
1.8 pazsan 10902:
10903: @example
1.78 anton 10904: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10905: @end example
10906:
1.78 anton 10907: Since @code{object-map} is the first field of the object, it
10908: does not generate any code. As you can see, calling a selector has a
10909: small, constant cost.
1.26 crook 10910:
1.78 anton 10911: @cindex @code{current-interface} discussion
10912: @cindex class implementation and representation
10913: A class is basically a @code{struct} combined with a method
10914: map. During the class definition the alignment and size of the class
10915: are passed on the stack, just as with @code{struct}s, so
10916: @code{field} can also be used for defining class
10917: fields. However, passing more items on the stack would be
10918: inconvenient, so @code{class} builds a data structure in memory,
10919: which is accessed through the variable
10920: @code{current-interface}. After its definition is complete, the
10921: class is represented on the stack by a pointer (e.g., as parameter for
10922: a child class definition).
1.26 crook 10923:
1.78 anton 10924: A new class starts off with the alignment and size of its parent,
10925: and a copy of the parent's method map. Defining new fields extends the
10926: size and alignment; likewise, defining new selectors extends the
10927: method map. @code{overrides} just stores a new @i{xt} in the method
10928: map at the offset given by the selector.
1.13 pazsan 10929:
1.78 anton 10930: @cindex class binding, implementation
10931: Class binding just gets the @i{xt} at the offset given by the selector
10932: from the class's method map and @code{compile,}s (in the case of
10933: @code{[bind]}) it.
1.13 pazsan 10934:
1.78 anton 10935: @cindex @code{this} implementation
10936: @cindex @code{catch} and @code{this}
10937: @cindex @code{this} and @code{catch}
10938: I implemented @code{this} as a @code{value}. At the
10939: start of an @code{m:...;m} method the old @code{this} is
10940: stored to the return stack and restored at the end; and the object on
10941: the TOS is stored @code{TO this}. This technique has one
10942: disadvantage: If the user does not leave the method via
10943: @code{;m}, but via @code{throw} or @code{exit},
10944: @code{this} is not restored (and @code{exit} may
10945: crash). To deal with the @code{throw} problem, I have redefined
10946: @code{catch} to save and restore @code{this}; the same
10947: should be done with any word that can catch an exception. As for
10948: @code{exit}, I simply forbid it (as a replacement, there is
10949: @code{exitm}).
1.13 pazsan 10950:
1.78 anton 10951: @cindex @code{inst-var} implementation
10952: @code{inst-var} is just the same as @code{field}, with
10953: a different @code{DOES>} action:
1.13 pazsan 10954: @example
1.78 anton 10955: @@ this +
1.8 pazsan 10956: @end example
1.78 anton 10957: Similar for @code{inst-value}.
1.8 pazsan 10958:
1.78 anton 10959: @cindex class scoping implementation
10960: Each class also has a word list that contains the words defined with
10961: @code{inst-var} and @code{inst-value}, and its protected
10962: words. It also has a pointer to its parent. @code{class} pushes
10963: the word lists of the class and all its ancestors onto the search order stack,
10964: and @code{end-class} drops them.
1.20 pazsan 10965:
1.78 anton 10966: @cindex interface implementation
10967: An interface is like a class without fields, parent and protected
10968: words; i.e., it just has a method map. If a class implements an
10969: interface, its method map contains a pointer to the method map of the
10970: interface. The positive offsets in the map are reserved for class
10971: methods, therefore interface map pointers have negative
10972: offsets. Interfaces have offsets that are unique throughout the
10973: system, unlike class selectors, whose offsets are only unique for the
10974: classes where the selector is available (invokable).
1.20 pazsan 10975:
1.78 anton 10976: This structure means that interface selectors have to perform one
10977: indirection more than class selectors to find their method. Their body
10978: contains the interface map pointer offset in the class method map, and
10979: the method offset in the interface method map. The
10980: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10981:
10982: @example
1.78 anton 10983: ( object selector-body )
10984: 2dup selector-interface @@ ( object selector-body object interface-offset )
10985: swap object-map @@ + @@ ( object selector-body map )
10986: swap selector-offset @@ + @@ execute
1.20 pazsan 10987: @end example
10988:
1.78 anton 10989: where @code{object-map} and @code{selector-offset} are
10990: first fields and generate no code.
1.20 pazsan 10991:
1.78 anton 10992: As a concrete example, consider the following code:
1.20 pazsan 10993:
10994: @example
1.78 anton 10995: interface
10996: selector if1sel1
10997: selector if1sel2
10998: end-interface if1
1.20 pazsan 10999:
1.78 anton 11000: object class
11001: if1 implementation
11002: selector cl1sel1
11003: cell% inst-var cl1iv1
1.20 pazsan 11004:
1.78 anton 11005: ' m1 overrides construct
11006: ' m2 overrides if1sel1
11007: ' m3 overrides if1sel2
11008: ' m4 overrides cl1sel2
11009: end-class cl1
1.20 pazsan 11010:
1.78 anton 11011: create obj1 object dict-new drop
11012: create obj2 cl1 dict-new drop
11013: @end example
1.20 pazsan 11014:
1.78 anton 11015: The data structure created by this code (including the data structure
11016: for @code{object}) is shown in the
11017: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11018: @comment TODO add this diagram..
1.20 pazsan 11019:
1.78 anton 11020: @node Objects Glossary, , Objects Implementation, Objects
11021: @subsubsection @file{objects.fs} Glossary
11022: @cindex @file{objects.fs} Glossary
1.20 pazsan 11023:
11024:
1.78 anton 11025: doc---objects-bind
11026: doc---objects-<bind>
11027: doc---objects-bind'
11028: doc---objects-[bind]
11029: doc---objects-class
11030: doc---objects-class->map
11031: doc---objects-class-inst-size
11032: doc---objects-class-override!
1.79 anton 11033: doc---objects-class-previous
11034: doc---objects-class>order
1.78 anton 11035: doc---objects-construct
11036: doc---objects-current'
11037: doc---objects-[current]
11038: doc---objects-current-interface
11039: doc---objects-dict-new
11040: doc---objects-end-class
11041: doc---objects-end-class-noname
11042: doc---objects-end-interface
11043: doc---objects-end-interface-noname
11044: doc---objects-end-methods
11045: doc---objects-exitm
11046: doc---objects-heap-new
11047: doc---objects-implementation
11048: doc---objects-init-object
11049: doc---objects-inst-value
11050: doc---objects-inst-var
11051: doc---objects-interface
11052: doc---objects-m:
11053: doc---objects-:m
11054: doc---objects-;m
11055: doc---objects-method
11056: doc---objects-methods
11057: doc---objects-object
11058: doc---objects-overrides
11059: doc---objects-[parent]
11060: doc---objects-print
11061: doc---objects-protected
11062: doc---objects-public
11063: doc---objects-selector
11064: doc---objects-this
11065: doc---objects-<to-inst>
11066: doc---objects-[to-inst]
11067: doc---objects-to-this
11068: doc---objects-xt-new
1.20 pazsan 11069:
11070:
1.78 anton 11071: @c -------------------------------------------------------------
11072: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11073: @subsection The @file{oof.fs} model
11074: @cindex oof
11075: @cindex object-oriented programming
1.20 pazsan 11076:
1.78 anton 11077: @cindex @file{objects.fs}
11078: @cindex @file{oof.fs}
1.20 pazsan 11079:
1.78 anton 11080: This section describes the @file{oof.fs} package.
1.20 pazsan 11081:
1.78 anton 11082: The package described in this section has been used in bigFORTH since 1991, and
11083: used for two large applications: a chromatographic system used to
11084: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11085:
1.78 anton 11086: You can find a description (in German) of @file{oof.fs} in @cite{Object
11087: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11088: 10(2), 1994.
1.20 pazsan 11089:
1.78 anton 11090: @menu
11091: * Properties of the OOF model::
11092: * Basic OOF Usage::
11093: * The OOF base class::
11094: * Class Declaration::
11095: * Class Implementation::
11096: @end menu
1.20 pazsan 11097:
1.78 anton 11098: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11099: @subsubsection Properties of the @file{oof.fs} model
11100: @cindex @file{oof.fs} properties
1.20 pazsan 11101:
1.78 anton 11102: @itemize @bullet
11103: @item
11104: This model combines object oriented programming with information
11105: hiding. It helps you writing large application, where scoping is
11106: necessary, because it provides class-oriented scoping.
1.20 pazsan 11107:
1.78 anton 11108: @item
11109: Named objects, object pointers, and object arrays can be created,
11110: selector invocation uses the ``object selector'' syntax. Selector invocation
11111: to objects and/or selectors on the stack is a bit less convenient, but
11112: possible.
1.44 crook 11113:
1.78 anton 11114: @item
11115: Selector invocation and instance variable usage of the active object is
11116: straightforward, since both make use of the active object.
1.44 crook 11117:
1.78 anton 11118: @item
11119: Late binding is efficient and easy to use.
1.20 pazsan 11120:
1.78 anton 11121: @item
11122: State-smart objects parse selectors. However, extensibility is provided
11123: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11124:
1.78 anton 11125: @item
11126: An implementation in ANS Forth is available.
1.20 pazsan 11127:
1.78 anton 11128: @end itemize
1.23 crook 11129:
11130:
1.78 anton 11131: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11132: @subsubsection Basic @file{oof.fs} Usage
11133: @cindex @file{oof.fs} usage
1.23 crook 11134:
1.78 anton 11135: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11136:
1.78 anton 11137: You can define a class for graphical objects like this:
1.23 crook 11138:
1.78 anton 11139: @cindex @code{class} usage
11140: @cindex @code{class;} usage
11141: @cindex @code{method} usage
11142: @example
11143: object class graphical \ "object" is the parent class
1.139 pazsan 11144: method draw ( x y -- )
1.78 anton 11145: class;
11146: @end example
1.23 crook 11147:
1.78 anton 11148: This code defines a class @code{graphical} with an
11149: operation @code{draw}. We can perform the operation
11150: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11151:
1.78 anton 11152: @example
11153: 100 100 t-rex draw
11154: @end example
1.23 crook 11155:
1.78 anton 11156: @noindent
11157: where @code{t-rex} is an object or object pointer, created with e.g.
11158: @code{graphical : t-rex}.
1.23 crook 11159:
1.78 anton 11160: @cindex abstract class
11161: How do we create a graphical object? With the present definitions,
11162: we cannot create a useful graphical object. The class
11163: @code{graphical} describes graphical objects in general, but not
11164: any concrete graphical object type (C++ users would call it an
11165: @emph{abstract class}); e.g., there is no method for the selector
11166: @code{draw} in the class @code{graphical}.
1.23 crook 11167:
1.78 anton 11168: For concrete graphical objects, we define child classes of the
11169: class @code{graphical}, e.g.:
1.23 crook 11170:
1.78 anton 11171: @example
11172: graphical class circle \ "graphical" is the parent class
11173: cell var circle-radius
11174: how:
11175: : draw ( x y -- )
11176: circle-radius @@ draw-circle ;
1.23 crook 11177:
1.139 pazsan 11178: : init ( n-radius -- )
1.78 anton 11179: circle-radius ! ;
11180: class;
11181: @end example
1.1 anton 11182:
1.78 anton 11183: Here we define a class @code{circle} as a child of @code{graphical},
11184: with a field @code{circle-radius}; it defines new methods for the
11185: selectors @code{draw} and @code{init} (@code{init} is defined in
11186: @code{object}, the parent class of @code{graphical}).
1.1 anton 11187:
1.78 anton 11188: Now we can create a circle in the dictionary with:
1.1 anton 11189:
1.78 anton 11190: @example
11191: 50 circle : my-circle
11192: @end example
1.21 crook 11193:
1.78 anton 11194: @noindent
11195: @code{:} invokes @code{init}, thus initializing the field
11196: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11197: with:
1.1 anton 11198:
1.78 anton 11199: @example
11200: 100 100 my-circle draw
11201: @end example
1.1 anton 11202:
1.78 anton 11203: @cindex selector invocation, restrictions
11204: @cindex class definition, restrictions
11205: Note: You can only invoke a selector if the receiving object belongs to
11206: the class where the selector was defined or one of its descendents;
11207: e.g., you can invoke @code{draw} only for objects belonging to
11208: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11209: mechanism will check if you try to invoke a selector that is not
11210: defined in this class hierarchy, so you'll get an error at compilation
11211: time.
1.1 anton 11212:
11213:
1.78 anton 11214: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11215: @subsubsection The @file{oof.fs} base class
11216: @cindex @file{oof.fs} base class
1.1 anton 11217:
1.78 anton 11218: When you define a class, you have to specify a parent class. So how do
11219: you start defining classes? There is one class available from the start:
11220: @code{object}. You have to use it as ancestor for all classes. It is the
11221: only class that has no parent. Classes are also objects, except that
11222: they don't have instance variables; class manipulation such as
11223: inheritance or changing definitions of a class is handled through
11224: selectors of the class @code{object}.
1.1 anton 11225:
1.78 anton 11226: @code{object} provides a number of selectors:
1.1 anton 11227:
1.78 anton 11228: @itemize @bullet
11229: @item
11230: @code{class} for subclassing, @code{definitions} to add definitions
11231: later on, and @code{class?} to get type informations (is the class a
11232: subclass of the class passed on the stack?).
1.1 anton 11233:
1.78 anton 11234: doc---object-class
11235: doc---object-definitions
11236: doc---object-class?
1.1 anton 11237:
11238:
1.26 crook 11239: @item
1.78 anton 11240: @code{init} and @code{dispose} as constructor and destructor of the
11241: object. @code{init} is invocated after the object's memory is allocated,
11242: while @code{dispose} also handles deallocation. Thus if you redefine
11243: @code{dispose}, you have to call the parent's dispose with @code{super
11244: dispose}, too.
11245:
11246: doc---object-init
11247: doc---object-dispose
11248:
1.1 anton 11249:
1.26 crook 11250: @item
1.78 anton 11251: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11252: @code{[]} to create named and unnamed objects and object arrays or
11253: object pointers.
11254:
11255: doc---object-new
11256: doc---object-new[]
11257: doc---object-:
11258: doc---object-ptr
11259: doc---object-asptr
11260: doc---object-[]
11261:
1.1 anton 11262:
1.26 crook 11263: @item
1.78 anton 11264: @code{::} and @code{super} for explicit scoping. You should use explicit
11265: scoping only for super classes or classes with the same set of instance
11266: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11267:
1.78 anton 11268: doc---object-::
11269: doc---object-super
1.21 crook 11270:
11271:
1.26 crook 11272: @item
1.78 anton 11273: @code{self} to get the address of the object
1.21 crook 11274:
1.78 anton 11275: doc---object-self
1.21 crook 11276:
11277:
1.78 anton 11278: @item
11279: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11280: pointers and instance defers.
1.21 crook 11281:
1.78 anton 11282: doc---object-bind
11283: doc---object-bound
11284: doc---object-link
11285: doc---object-is
1.21 crook 11286:
11287:
1.78 anton 11288: @item
11289: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11290: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11291:
1.78 anton 11292: doc---object-'
11293: doc---object-postpone
1.21 crook 11294:
11295:
1.78 anton 11296: @item
11297: @code{with} and @code{endwith} to select the active object from the
11298: stack, and enable its scope. Using @code{with} and @code{endwith}
11299: also allows you to create code using selector @code{postpone} without being
11300: trapped by the state-smart objects.
1.21 crook 11301:
1.78 anton 11302: doc---object-with
11303: doc---object-endwith
1.21 crook 11304:
11305:
1.78 anton 11306: @end itemize
1.21 crook 11307:
1.78 anton 11308: @node Class Declaration, Class Implementation, The OOF base class, OOF
11309: @subsubsection Class Declaration
11310: @cindex class declaration
1.21 crook 11311:
1.78 anton 11312: @itemize @bullet
11313: @item
11314: Instance variables
1.21 crook 11315:
1.78 anton 11316: doc---oof-var
1.21 crook 11317:
11318:
1.78 anton 11319: @item
11320: Object pointers
1.21 crook 11321:
1.78 anton 11322: doc---oof-ptr
11323: doc---oof-asptr
1.21 crook 11324:
11325:
1.78 anton 11326: @item
11327: Instance defers
1.21 crook 11328:
1.78 anton 11329: doc---oof-defer
1.21 crook 11330:
11331:
1.78 anton 11332: @item
11333: Method selectors
1.21 crook 11334:
1.78 anton 11335: doc---oof-early
11336: doc---oof-method
1.21 crook 11337:
11338:
1.78 anton 11339: @item
11340: Class-wide variables
1.21 crook 11341:
1.78 anton 11342: doc---oof-static
1.21 crook 11343:
11344:
1.78 anton 11345: @item
11346: End declaration
1.1 anton 11347:
1.78 anton 11348: doc---oof-how:
11349: doc---oof-class;
1.21 crook 11350:
11351:
1.78 anton 11352: @end itemize
1.21 crook 11353:
1.78 anton 11354: @c -------------------------------------------------------------
11355: @node Class Implementation, , Class Declaration, OOF
11356: @subsubsection Class Implementation
11357: @cindex class implementation
1.21 crook 11358:
1.78 anton 11359: @c -------------------------------------------------------------
11360: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11361: @subsection The @file{mini-oof.fs} model
11362: @cindex mini-oof
1.21 crook 11363:
1.78 anton 11364: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11365: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11366: and reduces to the bare minimum of features. This is based on a posting
11367: of Bernd Paysan in comp.lang.forth.
1.21 crook 11368:
1.78 anton 11369: @menu
11370: * Basic Mini-OOF Usage::
11371: * Mini-OOF Example::
11372: * Mini-OOF Implementation::
11373: @end menu
1.21 crook 11374:
1.78 anton 11375: @c -------------------------------------------------------------
11376: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11377: @subsubsection Basic @file{mini-oof.fs} Usage
11378: @cindex mini-oof usage
1.21 crook 11379:
1.78 anton 11380: There is a base class (@code{class}, which allocates one cell for the
11381: object pointer) plus seven other words: to define a method, a variable,
11382: a class; to end a class, to resolve binding, to allocate an object and
11383: to compile a class method.
11384: @comment TODO better description of the last one
1.26 crook 11385:
1.21 crook 11386:
1.78 anton 11387: doc-object
11388: doc-method
11389: doc-var
11390: doc-class
11391: doc-end-class
11392: doc-defines
11393: doc-new
11394: doc-::
1.21 crook 11395:
11396:
11397:
1.78 anton 11398: @c -------------------------------------------------------------
11399: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11400: @subsubsection Mini-OOF Example
11401: @cindex mini-oof example
1.1 anton 11402:
1.78 anton 11403: A short example shows how to use this package. This example, in slightly
11404: extended form, is supplied as @file{moof-exm.fs}
11405: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11406:
1.26 crook 11407: @example
1.78 anton 11408: object class
11409: method init
11410: method draw
11411: end-class graphical
1.26 crook 11412: @end example
1.20 pazsan 11413:
1.78 anton 11414: This code defines a class @code{graphical} with an
11415: operation @code{draw}. We can perform the operation
11416: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11417:
1.26 crook 11418: @example
1.78 anton 11419: 100 100 t-rex draw
1.26 crook 11420: @end example
1.12 anton 11421:
1.78 anton 11422: where @code{t-rex} is an object or object pointer, created with e.g.
11423: @code{graphical new Constant t-rex}.
1.12 anton 11424:
1.78 anton 11425: For concrete graphical objects, we define child classes of the
11426: class @code{graphical}, e.g.:
1.12 anton 11427:
1.26 crook 11428: @example
11429: graphical class
1.78 anton 11430: cell var circle-radius
11431: end-class circle \ "graphical" is the parent class
1.12 anton 11432:
1.78 anton 11433: :noname ( x y -- )
11434: circle-radius @@ draw-circle ; circle defines draw
11435: :noname ( r -- )
11436: circle-radius ! ; circle defines init
11437: @end example
1.12 anton 11438:
1.78 anton 11439: There is no implicit init method, so we have to define one. The creation
11440: code of the object now has to call init explicitely.
1.21 crook 11441:
1.78 anton 11442: @example
11443: circle new Constant my-circle
11444: 50 my-circle init
1.12 anton 11445: @end example
11446:
1.78 anton 11447: It is also possible to add a function to create named objects with
11448: automatic call of @code{init}, given that all objects have @code{init}
11449: on the same place:
1.38 anton 11450:
1.78 anton 11451: @example
11452: : new: ( .. o "name" -- )
11453: new dup Constant init ;
11454: 80 circle new: large-circle
11455: @end example
1.12 anton 11456:
1.78 anton 11457: We can draw this new circle at (100,100) with:
1.12 anton 11458:
1.78 anton 11459: @example
11460: 100 100 my-circle draw
11461: @end example
1.12 anton 11462:
1.78 anton 11463: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11464: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11465:
1.78 anton 11466: Object-oriented systems with late binding typically use a
11467: ``vtable''-approach: the first variable in each object is a pointer to a
11468: table, which contains the methods as function pointers. The vtable
11469: may also contain other information.
1.12 anton 11470:
1.79 anton 11471: So first, let's declare selectors:
1.37 anton 11472:
11473: @example
1.79 anton 11474: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11475: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11476: @end example
1.37 anton 11477:
1.79 anton 11478: During selector declaration, the number of selectors and instance
11479: variables is on the stack (in address units). @code{method} creates one
11480: selector and increments the selector number. To execute a selector, it
1.78 anton 11481: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11482: executes the method @i{xt} stored there. Each selector takes the object
11483: it is invoked with as top of stack parameter; it passes the parameters
11484: (including the object) unchanged to the appropriate method which should
1.78 anton 11485: consume that object.
1.37 anton 11486:
1.78 anton 11487: Now, we also have to declare instance variables
1.37 anton 11488:
1.78 anton 11489: @example
1.79 anton 11490: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11491: DOES> ( o -- addr ) @@ + ;
1.37 anton 11492: @end example
11493:
1.78 anton 11494: As before, a word is created with the current offset. Instance
11495: variables can have different sizes (cells, floats, doubles, chars), so
11496: all we do is take the size and add it to the offset. If your machine
11497: has alignment restrictions, put the proper @code{aligned} or
11498: @code{faligned} before the variable, to adjust the variable
11499: offset. That's why it is on the top of stack.
1.37 anton 11500:
1.78 anton 11501: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11502:
1.78 anton 11503: @example
11504: Create object 1 cells , 2 cells ,
1.79 anton 11505: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11506: @end example
1.12 anton 11507:
1.78 anton 11508: For inheritance, the vtable of the parent object has to be
11509: copied when a new, derived class is declared. This gives all the
11510: methods of the parent class, which can be overridden, though.
1.12 anton 11511:
1.78 anton 11512: @example
1.79 anton 11513: : end-class ( class selectors vars "name" -- )
1.78 anton 11514: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11515: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11516: @end example
1.12 anton 11517:
1.78 anton 11518: The first line creates the vtable, initialized with
11519: @code{noop}s. The second line is the inheritance mechanism, it
11520: copies the xts from the parent vtable.
1.12 anton 11521:
1.78 anton 11522: We still have no way to define new methods, let's do that now:
1.12 anton 11523:
1.26 crook 11524: @example
1.79 anton 11525: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11526: @end example
1.12 anton 11527:
1.78 anton 11528: To allocate a new object, we need a word, too:
1.12 anton 11529:
1.78 anton 11530: @example
11531: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11532: @end example
11533:
1.78 anton 11534: Sometimes derived classes want to access the method of the
11535: parent object. There are two ways to achieve this with Mini-OOF:
11536: first, you could use named words, and second, you could look up the
11537: vtable of the parent object.
1.12 anton 11538:
1.78 anton 11539: @example
11540: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11541: @end example
1.12 anton 11542:
11543:
1.78 anton 11544: Nothing can be more confusing than a good example, so here is
11545: one. First let's declare a text object (called
11546: @code{button}), that stores text and position:
1.12 anton 11547:
1.78 anton 11548: @example
11549: object class
11550: cell var text
11551: cell var len
11552: cell var x
11553: cell var y
11554: method init
11555: method draw
11556: end-class button
11557: @end example
1.12 anton 11558:
1.78 anton 11559: @noindent
11560: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11561:
1.26 crook 11562: @example
1.78 anton 11563: :noname ( o -- )
11564: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11565: button defines draw
11566: :noname ( addr u o -- )
11567: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11568: button defines init
1.26 crook 11569: @end example
1.12 anton 11570:
1.78 anton 11571: @noindent
11572: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11573: new data and no new selectors:
1.78 anton 11574:
11575: @example
11576: button class
11577: end-class bold-button
1.12 anton 11578:
1.78 anton 11579: : bold 27 emit ." [1m" ;
11580: : normal 27 emit ." [0m" ;
11581: @end example
1.1 anton 11582:
1.78 anton 11583: @noindent
11584: The class @code{bold-button} has a different draw method to
11585: @code{button}, but the new method is defined in terms of the draw method
11586: for @code{button}:
1.20 pazsan 11587:
1.78 anton 11588: @example
11589: :noname bold [ button :: draw ] normal ; bold-button defines draw
11590: @end example
1.21 crook 11591:
1.78 anton 11592: @noindent
1.79 anton 11593: Finally, create two objects and apply selectors:
1.21 crook 11594:
1.26 crook 11595: @example
1.78 anton 11596: button new Constant foo
11597: s" thin foo" foo init
11598: page
11599: foo draw
11600: bold-button new Constant bar
11601: s" fat bar" bar init
11602: 1 bar y !
11603: bar draw
1.26 crook 11604: @end example
1.21 crook 11605:
11606:
1.78 anton 11607: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11608: @subsection Comparison with other object models
11609: @cindex comparison of object models
11610: @cindex object models, comparison
11611:
11612: Many object-oriented Forth extensions have been proposed (@cite{A survey
11613: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11614: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11615: relation of the object models described here to two well-known and two
11616: closely-related (by the use of method maps) models. Andras Zsoter
11617: helped us with this section.
11618:
11619: @cindex Neon model
11620: The most popular model currently seems to be the Neon model (see
11621: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11622: 1997) by Andrew McKewan) but this model has a number of limitations
11623: @footnote{A longer version of this critique can be
11624: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11625: Dimensions, May 1997) by Anton Ertl.}:
11626:
11627: @itemize @bullet
11628: @item
11629: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11630: to pass objects on the stack.
1.21 crook 11631:
1.78 anton 11632: @item
11633: It requires that the selector parses the input stream (at
1.79 anton 11634: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11635: hard to find.
1.21 crook 11636:
1.78 anton 11637: @item
1.79 anton 11638: It allows using every selector on every object; this eliminates the
11639: need for interfaces, but makes it harder to create efficient
11640: implementations.
1.78 anton 11641: @end itemize
1.21 crook 11642:
1.78 anton 11643: @cindex Pountain's object-oriented model
11644: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11645: Press, London, 1987) by Dick Pountain. However, it is not really about
11646: object-oriented programming, because it hardly deals with late
11647: binding. Instead, it focuses on features like information hiding and
11648: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11649:
1.78 anton 11650: @cindex Zsoter's object-oriented model
1.79 anton 11651: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11652: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11653: describes a model that makes heavy use of an active object (like
11654: @code{this} in @file{objects.fs}): The active object is not only used
11655: for accessing all fields, but also specifies the receiving object of
11656: every selector invocation; you have to change the active object
11657: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11658: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11659: the method entry point is unnecessary with Zsoter's model, because the
11660: receiving object is the active object already. On the other hand, the
11661: explicit change is absolutely necessary in that model, because otherwise
11662: no one could ever change the active object. An ANS Forth implementation
11663: of this model is available through
11664: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11665:
1.78 anton 11666: @cindex @file{oof.fs}, differences to other models
11667: The @file{oof.fs} model combines information hiding and overloading
11668: resolution (by keeping names in various word lists) with object-oriented
11669: programming. It sets the active object implicitly on method entry, but
11670: also allows explicit changing (with @code{>o...o>} or with
11671: @code{with...endwith}). It uses parsing and state-smart objects and
11672: classes for resolving overloading and for early binding: the object or
11673: class parses the selector and determines the method from this. If the
11674: selector is not parsed by an object or class, it performs a call to the
11675: selector for the active object (late binding), like Zsoter's model.
11676: Fields are always accessed through the active object. The big
11677: disadvantage of this model is the parsing and the state-smartness, which
11678: reduces extensibility and increases the opportunities for subtle bugs;
11679: essentially, you are only safe if you never tick or @code{postpone} an
11680: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11681:
1.78 anton 11682: @cindex @file{mini-oof.fs}, differences to other models
11683: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11684: version of the @file{objects.fs} model, but syntactically it is a
11685: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11686:
11687:
1.78 anton 11688: @c -------------------------------------------------------------
1.150 anton 11689: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11690: @section Programming Tools
11691: @cindex programming tools
1.21 crook 11692:
1.78 anton 11693: @c !! move this and assembler down below OO stuff.
1.21 crook 11694:
1.78 anton 11695: @menu
1.150 anton 11696: * Examining:: Data and Code.
11697: * Forgetting words:: Usually before reloading.
1.78 anton 11698: * Debugging:: Simple and quick.
11699: * Assertions:: Making your programs self-checking.
11700: * Singlestep Debugger:: Executing your program word by word.
11701: @end menu
1.21 crook 11702:
1.78 anton 11703: @node Examining, Forgetting words, Programming Tools, Programming Tools
11704: @subsection Examining data and code
11705: @cindex examining data and code
11706: @cindex data examination
11707: @cindex code examination
1.44 crook 11708:
1.78 anton 11709: The following words inspect the stack non-destructively:
1.21 crook 11710:
1.78 anton 11711: doc-.s
11712: doc-f.s
1.158 anton 11713: doc-maxdepth-.s
1.44 crook 11714:
1.78 anton 11715: There is a word @code{.r} but it does @i{not} display the return stack!
11716: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11717:
1.78 anton 11718: doc-depth
11719: doc-fdepth
11720: doc-clearstack
1.124 anton 11721: doc-clearstacks
1.21 crook 11722:
1.78 anton 11723: The following words inspect memory.
1.21 crook 11724:
1.78 anton 11725: doc-?
11726: doc-dump
1.21 crook 11727:
1.78 anton 11728: And finally, @code{see} allows to inspect code:
1.21 crook 11729:
1.78 anton 11730: doc-see
11731: doc-xt-see
1.111 anton 11732: doc-simple-see
11733: doc-simple-see-range
1.182 anton 11734: doc-see-code
11735: doc-see-code-range
1.21 crook 11736:
1.78 anton 11737: @node Forgetting words, Debugging, Examining, Programming Tools
11738: @subsection Forgetting words
11739: @cindex words, forgetting
11740: @cindex forgeting words
1.21 crook 11741:
1.78 anton 11742: @c anton: other, maybe better places for this subsection: Defining Words;
11743: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11744:
1.78 anton 11745: Forth allows you to forget words (and everything that was alloted in the
11746: dictonary after them) in a LIFO manner.
1.21 crook 11747:
1.78 anton 11748: doc-marker
1.21 crook 11749:
1.78 anton 11750: The most common use of this feature is during progam development: when
11751: you change a source file, forget all the words it defined and load it
11752: again (since you also forget everything defined after the source file
11753: was loaded, you have to reload that, too). Note that effects like
11754: storing to variables and destroyed system words are not undone when you
11755: forget words. With a system like Gforth, that is fast enough at
11756: starting up and compiling, I find it more convenient to exit and restart
11757: Gforth, as this gives me a clean slate.
1.21 crook 11758:
1.78 anton 11759: Here's an example of using @code{marker} at the start of a source file
11760: that you are debugging; it ensures that you only ever have one copy of
11761: the file's definitions compiled at any time:
1.21 crook 11762:
1.78 anton 11763: @example
11764: [IFDEF] my-code
11765: my-code
11766: [ENDIF]
1.26 crook 11767:
1.78 anton 11768: marker my-code
11769: init-included-files
1.21 crook 11770:
1.78 anton 11771: \ .. definitions start here
11772: \ .
11773: \ .
11774: \ end
11775: @end example
1.21 crook 11776:
1.26 crook 11777:
1.78 anton 11778: @node Debugging, Assertions, Forgetting words, Programming Tools
11779: @subsection Debugging
11780: @cindex debugging
1.21 crook 11781:
1.78 anton 11782: Languages with a slow edit/compile/link/test development loop tend to
11783: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11784:
1.78 anton 11785: A much better (faster) way in fast-compiling languages is to add
11786: printing code at well-selected places, let the program run, look at
11787: the output, see where things went wrong, add more printing code, etc.,
11788: until the bug is found.
1.21 crook 11789:
1.78 anton 11790: The simple debugging aids provided in @file{debugs.fs}
11791: are meant to support this style of debugging.
1.21 crook 11792:
1.78 anton 11793: The word @code{~~} prints debugging information (by default the source
11794: location and the stack contents). It is easy to insert. If you use Emacs
11795: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11796: query-replace them with nothing). The deferred words
1.101 anton 11797: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11798: @code{~~}. The default source location output format works well with
11799: Emacs' compilation mode, so you can step through the program at the
11800: source level using @kbd{C-x `} (the advantage over a stepping debugger
11801: is that you can step in any direction and you know where the crash has
11802: happened or where the strange data has occurred).
1.21 crook 11803:
1.78 anton 11804: doc-~~
11805: doc-printdebugdata
1.101 anton 11806: doc-.debugline
1.21 crook 11807:
1.106 anton 11808: @cindex filenames in @code{~~} output
11809: @code{~~} (and assertions) will usually print the wrong file name if a
11810: marker is executed in the same file after their occurance. They will
11811: print @samp{*somewhere*} as file name if a marker is executed in the
11812: same file before their occurance.
11813:
11814:
1.78 anton 11815: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11816: @subsection Assertions
11817: @cindex assertions
1.21 crook 11818:
1.78 anton 11819: It is a good idea to make your programs self-checking, especially if you
11820: make an assumption that may become invalid during maintenance (for
11821: example, that a certain field of a data structure is never zero). Gforth
11822: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11823:
11824: @example
1.78 anton 11825: assert( @i{flag} )
1.26 crook 11826: @end example
11827:
1.78 anton 11828: The code between @code{assert(} and @code{)} should compute a flag, that
11829: should be true if everything is alright and false otherwise. It should
11830: not change anything else on the stack. The overall stack effect of the
11831: assertion is @code{( -- )}. E.g.
1.21 crook 11832:
1.26 crook 11833: @example
1.78 anton 11834: assert( 1 1 + 2 = ) \ what we learn in school
11835: assert( dup 0<> ) \ assert that the top of stack is not zero
11836: assert( false ) \ this code should not be reached
1.21 crook 11837: @end example
11838:
1.78 anton 11839: The need for assertions is different at different times. During
11840: debugging, we want more checking, in production we sometimes care more
11841: for speed. Therefore, assertions can be turned off, i.e., the assertion
11842: becomes a comment. Depending on the importance of an assertion and the
11843: time it takes to check it, you may want to turn off some assertions and
11844: keep others turned on. Gforth provides several levels of assertions for
11845: this purpose:
11846:
11847:
11848: doc-assert0(
11849: doc-assert1(
11850: doc-assert2(
11851: doc-assert3(
11852: doc-assert(
11853: doc-)
1.21 crook 11854:
11855:
1.78 anton 11856: The variable @code{assert-level} specifies the highest assertions that
11857: are turned on. I.e., at the default @code{assert-level} of one,
11858: @code{assert0(} and @code{assert1(} assertions perform checking, while
11859: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11860:
1.78 anton 11861: The value of @code{assert-level} is evaluated at compile-time, not at
11862: run-time. Therefore you cannot turn assertions on or off at run-time;
11863: you have to set the @code{assert-level} appropriately before compiling a
11864: piece of code. You can compile different pieces of code at different
11865: @code{assert-level}s (e.g., a trusted library at level 1 and
11866: newly-written code at level 3).
1.26 crook 11867:
11868:
1.78 anton 11869: doc-assert-level
1.26 crook 11870:
11871:
1.78 anton 11872: If an assertion fails, a message compatible with Emacs' compilation mode
11873: is produced and the execution is aborted (currently with @code{ABORT"}.
11874: If there is interest, we will introduce a special throw code. But if you
11875: intend to @code{catch} a specific condition, using @code{throw} is
11876: probably more appropriate than an assertion).
1.106 anton 11877:
11878: @cindex filenames in assertion output
11879: Assertions (and @code{~~}) will usually print the wrong file name if a
11880: marker is executed in the same file after their occurance. They will
11881: print @samp{*somewhere*} as file name if a marker is executed in the
11882: same file before their occurance.
1.44 crook 11883:
1.78 anton 11884: Definitions in ANS Forth for these assertion words are provided
11885: in @file{compat/assert.fs}.
1.26 crook 11886:
1.44 crook 11887:
1.78 anton 11888: @node Singlestep Debugger, , Assertions, Programming Tools
11889: @subsection Singlestep Debugger
11890: @cindex singlestep Debugger
11891: @cindex debugging Singlestep
1.44 crook 11892:
1.159 anton 11893: The singlestep debugger works only with the engine @code{gforth-ditc}.
1.112 anton 11894:
1.78 anton 11895: When you create a new word there's often the need to check whether it
11896: behaves correctly or not. You can do this by typing @code{dbg
11897: badword}. A debug session might look like this:
1.26 crook 11898:
1.78 anton 11899: @example
11900: : badword 0 DO i . LOOP ; ok
11901: 2 dbg badword
11902: : badword
11903: Scanning code...
1.44 crook 11904:
1.78 anton 11905: Nesting debugger ready!
1.44 crook 11906:
1.78 anton 11907: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11908: 400D4740 8049F68 DO -> [ 0 ]
11909: 400D4744 804A0C8 i -> [ 1 ] 00000
11910: 400D4748 400C5E60 . -> 0 [ 0 ]
11911: 400D474C 8049D0C LOOP -> [ 0 ]
11912: 400D4744 804A0C8 i -> [ 1 ] 00001
11913: 400D4748 400C5E60 . -> 1 [ 0 ]
11914: 400D474C 8049D0C LOOP -> [ 0 ]
11915: 400D4758 804B384 ; -> ok
11916: @end example
1.21 crook 11917:
1.78 anton 11918: Each line displayed is one step. You always have to hit return to
11919: execute the next word that is displayed. If you don't want to execute
11920: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11921: an overview what keys are available:
1.44 crook 11922:
1.78 anton 11923: @table @i
1.44 crook 11924:
1.78 anton 11925: @item @key{RET}
11926: Next; Execute the next word.
1.21 crook 11927:
1.78 anton 11928: @item n
11929: Nest; Single step through next word.
1.44 crook 11930:
1.78 anton 11931: @item u
11932: Unnest; Stop debugging and execute rest of word. If we got to this word
11933: with nest, continue debugging with the calling word.
1.44 crook 11934:
1.78 anton 11935: @item d
11936: Done; Stop debugging and execute rest.
1.21 crook 11937:
1.78 anton 11938: @item s
11939: Stop; Abort immediately.
1.44 crook 11940:
1.78 anton 11941: @end table
1.44 crook 11942:
1.78 anton 11943: Debugging large application with this mechanism is very difficult, because
11944: you have to nest very deeply into the program before the interesting part
11945: begins. This takes a lot of time.
1.26 crook 11946:
1.78 anton 11947: To do it more directly put a @code{BREAK:} command into your source code.
11948: When program execution reaches @code{BREAK:} the single step debugger is
11949: invoked and you have all the features described above.
1.44 crook 11950:
1.78 anton 11951: If you have more than one part to debug it is useful to know where the
11952: program has stopped at the moment. You can do this by the
11953: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11954: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11955:
1.26 crook 11956:
1.78 anton 11957: doc-dbg
11958: doc-break:
11959: doc-break"
1.44 crook 11960:
1.150 anton 11961: @c ------------------------------------------------------------
11962: @node C Interface, Assembler and Code Words, Programming Tools, Words
11963: @section C Interface
11964: @cindex C interface
11965: @cindex foreign language interface
11966: @cindex interface to C functions
11967:
1.178 anton 11968: Note that the C interface is not yet complete; callbacks are missing,
11969: as well as a way of declaring structs, unions, and their fields.
1.150 anton 11970:
11971: @menu
11972: * Calling C Functions::
11973: * Declaring C Functions::
1.180 anton 11974: * Calling C function pointers::
1.150 anton 11975: * Callbacks::
1.178 anton 11976: * C interface internals::
1.155 anton 11977: * Low-Level C Interface Words::
1.150 anton 11978: @end menu
11979:
1.151 pazsan 11980: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 11981: @subsection Calling C functions
1.155 anton 11982: @cindex C functions, calls to
11983: @cindex calling C functions
1.150 anton 11984:
1.151 pazsan 11985: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 11986: can call it as follows: You push the arguments on the stack(s), and
11987: then call the word for the C function. The arguments have to be
11988: pushed in the same order as the arguments appear in the C
11989: documentation (i.e., the first argument is deepest on the stack).
11990: Integer and pointer arguments have to be pushed on the data stack,
11991: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 11992: by the called C function.
1.150 anton 11993:
1.155 anton 11994: On returning from the C function, the return value, if any, resides on
11995: the appropriate stack: an integer return value is pushed on the data
11996: stack, an FP return value on the FP stack, and a void return value
11997: results in not pushing anything. Note that most C functions have a
11998: return value, even if that is often not used in C; in Forth, you have
11999: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12000:
1.177 anton 12001: The C interface automatically converts between the C type and the
12002: Forth type as necessary, on a best-effort basis (in some cases, there
12003: may be some loss).
1.150 anton 12004:
12005: As an example, consider the POSIX function @code{lseek()}:
12006:
12007: @example
12008: off_t lseek(int fd, off_t offset, int whence);
12009: @end example
12010:
12011: This function takes three integer arguments, and returns an integer
12012: argument, so a Forth call for setting the current file offset to the
12013: start of the file could look like this:
12014:
12015: @example
12016: fd @@ 0 SEEK_SET lseek -1 = if
12017: ... \ error handling
12018: then
12019: @end example
12020:
12021: You might be worried that an @code{off_t} does not fit into a cell, so
12022: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12023: of the return values. In that case, in your declaration of the
12024: function (@pxref{Declaring C Functions}) you should declare it to use
12025: double-cells for the off_t argument and return value, and maybe give
12026: the resulting Forth word a different name, like @code{dlseek}; the
12027: result could be called like this:
1.150 anton 12028:
12029: @example
12030: fd @@ 0. SEEK_SET dlseek -1. d= if
12031: ... \ error handling
12032: then
12033: @end example
12034:
12035: Passing and returning structs or unions is currently not supported by
12036: our interface@footnote{If you know the calling convention of your C
12037: compiler, you usually can call such functions in some way, but that
12038: way is usually not portable between platforms, and sometimes not even
12039: between C compilers.}.
12040:
1.177 anton 12041: Calling functions with a variable number of arguments (@emph{variadic}
12042: functions, e.g., @code{printf()}) is only supported by having you
12043: declare one function-calling word for each argument pattern, and
12044: calling the appropriate word for the desired pattern.
12045:
1.150 anton 12046:
1.155 anton 12047:
1.180 anton 12048: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12049: @subsection Declaring C Functions
1.155 anton 12050: @cindex C functions, declarations
12051: @cindex declaring C functions
1.150 anton 12052:
12053: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12054: it. The declaration consists of two parts:
12055:
12056: @table @b
12057:
12058: @item The C part
1.179 anton 12059: is the C declaration of the function, or more typically and portably,
12060: a C-style @code{#include} of a file that contains the declaration of
12061: the C function.
1.177 anton 12062:
12063: @item The Forth part
12064: declares the Forth types of the parameters and the Forth word name
12065: corresponding to the C function.
12066:
12067: @end table
12068:
12069: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12070: declarations are:
12071:
12072: @example
12073: \c #define _FILE_OFFSET_BITS 64
12074: \c #include <sys/types.h>
12075: \c #include <unistd.h>
12076: c-function lseek lseek n n n -- n
12077: c-function dlseek lseek n d n -- d
12078: @end example
12079:
1.178 anton 12080: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12081: of the line is ordinary C code. You can use as many lines of C
12082: declarations as you like, and they are visible for all further
12083: function declarations.
12084:
12085: The Forth part declares each interface word with @code{c-function},
12086: followed by the Forth name of the word, the C name of the called
12087: function, and the stack effect of the word. The stack effect contains
1.178 anton 12088: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12089: exactly one type for the return value. The possible types are:
12090:
12091: @table @code
12092:
12093: @item n
12094: single-cell integer
12095:
12096: @item a
12097: address (single-cell)
12098:
12099: @item d
12100: double-cell integer
12101:
12102: @item r
12103: floating-point value
12104:
12105: @item func
12106: C function pointer
12107:
12108: @item void
12109: no value (used as return type for void functions)
12110:
12111: @end table
12112:
12113: @cindex variadic C functions
12114:
12115: To deal with variadic C functions, you can declare one Forth word for
12116: every pattern you want to use, e.g.:
12117:
12118: @example
12119: \c #include <stdio.h>
12120: c-function printf-nr printf a n r -- n
12121: c-function printf-rn printf a r n -- n
12122: @end example
12123:
12124: Note that with C functions declared as variadic (or if you don't
12125: provide a prototype), the C interface has no C type to convert to, so
12126: no automatic conversion happens, which may lead to portability
12127: problems in some cases. In such cases you can perform the conversion
12128: explicitly on the C level, e.g., as follows:
12129:
12130: @example
1.178 anton 12131: \c #define printfll(s,ll) printf(s,(long long)ll)
12132: c-function printfll printfll a n -- n
1.177 anton 12133: @end example
12134:
12135: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12136: that casts (converts) the Forth single-cell integer into a
12137: C @code{long long} before calling @code{printf()}.
1.177 anton 12138:
12139: doc-\c
12140: doc-c-function
12141:
12142: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12143: dynamic linking. If these features are not available, there are
12144: other, less convenient and less portable C interfaces in @file{lib.fs}
12145: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12146: mostly incompatible with each other and with the documented C
12147: interface; you can find some examples for the @file{lib.fs} interface
12148: in @file{lib.fs}.
1.177 anton 12149:
12150:
1.180 anton 12151: @node Calling C function pointers, Callbacks, Declaring C Functions, C Interface
12152: @subsection Calling C function pointers from Forth
12153: @cindex C function pointers, calling from Forth
1.177 anton 12154:
1.180 anton 12155: If you come across a C function pointer (e.g., in some C-constructed
12156: structure) and want to call it from your Forth program, you can also
12157: use the features explained until now to achieve that, as follows:
1.150 anton 12158:
1.180 anton 12159: Let us assume that there is a C function pointer type @code{func1}
12160: defined in some header file @file{func1.h}, and you know that these
12161: functions take one integer argument and return an integer result; and
12162: you want to call functions through such pointers. Just define
1.155 anton 12163:
1.180 anton 12164: @example
12165: \c #include <func1.h>
12166: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12167: c-function call-func1 call_func1 n func -- n
12168: @end example
12169:
12170: and then you can call a function pointed to by, say @code{func1a} as
12171: follows:
12172:
12173: @example
12174: -5 func1a call-func1 .
12175: @end example
12176:
12177: In the C part, @code{call_func} is defined as a macro to avoid having
12178: to declare the exact parameter and return types, so the C compiler
12179: knows them from the declaration of @code{func1}.
12180:
12181: The Forth word @code{call-func1} is similar to @code{execute}, except
12182: that it takes a C @code{func1} pointer instead of a Forth execution
12183: token, and it is specific to @code{func1} pointers. For each type of
12184: function pointer you want to call from Forth, you have to define
12185: a separate calling word.
12186:
12187:
12188: @node Callbacks, C interface internals, Calling C function pointers, C Interface
1.150 anton 12189: @subsection Callbacks
1.155 anton 12190: @cindex Callback functions written in Forth
12191: @cindex C function pointers to Forth words
12192:
1.177 anton 12193: Callbacks are not yet supported by the documented C interface. You
12194: can use the undocumented @file{lib.fs} interface for callbacks.
12195:
1.155 anton 12196: In some cases you have to pass a function pointer to a C function,
12197: i.e., the library wants to call back to your application (and the
12198: pointed-to function is called a callback function). You can pass the
12199: address of an existing C function (that you get with @code{lib-sym},
12200: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12201: function, you probably want to define the function as a Forth word.
12202:
12203: @c I don't understand the existing callback interface from the example - anton
12204:
1.165 anton 12205:
12206: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12207: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12208: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12209: @c > > C-Funktionsadresse auf dem TOS).
12210: @c >
12211: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12212: @c > gesehen habe, wozu das gut ist.
12213: @c
12214: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12215: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12216: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12217: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12218: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12219: @c demselben Prototyp.
12220:
12221:
1.178 anton 12222: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12223: @subsection How the C interface works
12224:
12225: The documented C interface works by generating a C code out of the
12226: declarations.
12227:
12228: In particular, for every Forth word declared with @code{c-function},
12229: it generates a wrapper function in C that takes the Forth data from
12230: the Forth stacks, and calls the target C function with these data as
12231: arguments. The C compiler then performs an implicit conversion
12232: between the Forth type from the stack, and the C type for the
12233: parameter, which is given by the C function prototype. After the C
12234: function returns, the return value is likewise implicitly converted to
12235: a Forth type and written back on the stack.
12236:
12237: The @code{\c} lines are literally included in the C code (but without
12238: the @code{\c}), and provide the necessary declarations so that the C
12239: compiler knows the C types and has enough information to perform the
12240: conversion.
12241:
12242: These wrapper functions are eventually compiled and dynamically linked
12243: into Gforth, and then they can be called.
12244:
12245:
1.178 anton 12246: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12247: @subsection Low-Level C Interface Words
1.44 crook 12248:
1.155 anton 12249: doc-open-lib
12250: doc-lib-sym
1.177 anton 12251: doc-call-c
1.26 crook 12252:
1.78 anton 12253: @c -------------------------------------------------------------
1.150 anton 12254: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12255: @section Assembler and Code Words
12256: @cindex assembler
12257: @cindex code words
1.44 crook 12258:
1.78 anton 12259: @menu
12260: * Code and ;code::
12261: * Common Assembler:: Assembler Syntax
12262: * Common Disassembler::
12263: * 386 Assembler:: Deviations and special cases
12264: * Alpha Assembler:: Deviations and special cases
12265: * MIPS assembler:: Deviations and special cases
1.161 anton 12266: * PowerPC assembler:: Deviations and special cases
1.78 anton 12267: * Other assemblers:: How to write them
12268: @end menu
1.21 crook 12269:
1.78 anton 12270: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12271: @subsection @code{Code} and @code{;code}
1.26 crook 12272:
1.78 anton 12273: Gforth provides some words for defining primitives (words written in
12274: machine code), and for defining the machine-code equivalent of
12275: @code{DOES>}-based defining words. However, the machine-independent
12276: nature of Gforth poses a few problems: First of all, Gforth runs on
12277: several architectures, so it can provide no standard assembler. What's
12278: worse is that the register allocation not only depends on the processor,
12279: but also on the @code{gcc} version and options used.
1.44 crook 12280:
1.78 anton 12281: The words that Gforth offers encapsulate some system dependences (e.g.,
12282: the header structure), so a system-independent assembler may be used in
12283: Gforth. If you do not have an assembler, you can compile machine code
12284: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12285: because these words emit stuff in @i{data} space; it works because
12286: Gforth has unified code/data spaces. Assembler isn't likely to be
12287: portable anyway.}.
1.21 crook 12288:
1.44 crook 12289:
1.78 anton 12290: doc-assembler
12291: doc-init-asm
12292: doc-code
12293: doc-end-code
12294: doc-;code
12295: doc-flush-icache
1.44 crook 12296:
1.21 crook 12297:
1.78 anton 12298: If @code{flush-icache} does not work correctly, @code{code} words
12299: etc. will not work (reliably), either.
1.44 crook 12300:
1.78 anton 12301: The typical usage of these @code{code} words can be shown most easily by
12302: analogy to the equivalent high-level defining words:
1.44 crook 12303:
1.78 anton 12304: @example
12305: : foo code foo
12306: <high-level Forth words> <assembler>
12307: ; end-code
12308:
12309: : bar : bar
12310: <high-level Forth words> <high-level Forth words>
12311: CREATE CREATE
12312: <high-level Forth words> <high-level Forth words>
12313: DOES> ;code
12314: <high-level Forth words> <assembler>
12315: ; end-code
12316: @end example
1.21 crook 12317:
1.78 anton 12318: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12319:
1.78 anton 12320: @cindex registers of the inner interpreter
12321: In the assembly code you will want to refer to the inner interpreter's
12322: registers (e.g., the data stack pointer) and you may want to use other
12323: registers for temporary storage. Unfortunately, the register allocation
12324: is installation-dependent.
1.44 crook 12325:
1.78 anton 12326: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12327: (return stack pointer) may be in different places in @code{gforth} and
12328: @code{gforth-fast}, or different installations. This means that you
12329: cannot write a @code{NEXT} routine that works reliably on both versions
12330: or different installations; so for doing @code{NEXT}, I recommend
12331: jumping to @code{' noop >code-address}, which contains nothing but a
12332: @code{NEXT}.
1.21 crook 12333:
1.78 anton 12334: For general accesses to the inner interpreter's registers, the easiest
12335: solution is to use explicit register declarations (@pxref{Explicit Reg
12336: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12337: all of the inner interpreter's registers: You have to compile Gforth
12338: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12339: the appropriate declarations must be present in the @code{machine.h}
12340: file (see @code{mips.h} for an example; you can find a full list of all
12341: declarable register symbols with @code{grep register engine.c}). If you
12342: give explicit registers to all variables that are declared at the
12343: beginning of @code{engine()}, you should be able to use the other
12344: caller-saved registers for temporary storage. Alternatively, you can use
12345: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12346: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12347: reserve a register (however, this restriction on register allocation may
12348: slow Gforth significantly).
1.44 crook 12349:
1.78 anton 12350: If this solution is not viable (e.g., because @code{gcc} does not allow
12351: you to explicitly declare all the registers you need), you have to find
12352: out by looking at the code where the inner interpreter's registers
12353: reside and which registers can be used for temporary storage. You can
12354: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12355:
1.78 anton 12356: In any case, it is good practice to abstract your assembly code from the
12357: actual register allocation. E.g., if the data stack pointer resides in
12358: register @code{$17}, create an alias for this register called @code{sp},
12359: and use that in your assembly code.
1.21 crook 12360:
1.78 anton 12361: @cindex code words, portable
12362: Another option for implementing normal and defining words efficiently
12363: is to add the desired functionality to the source of Gforth. For normal
12364: words you just have to edit @file{primitives} (@pxref{Automatic
12365: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12366: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12367: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12368:
1.78 anton 12369: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12370: @subsection Common Assembler
1.44 crook 12371:
1.78 anton 12372: The assemblers in Gforth generally use a postfix syntax, i.e., the
12373: instruction name follows the operands.
1.21 crook 12374:
1.78 anton 12375: The operands are passed in the usual order (the same that is used in the
12376: manual of the architecture). Since they all are Forth words, they have
12377: to be separated by spaces; you can also use Forth words to compute the
12378: operands.
1.44 crook 12379:
1.78 anton 12380: The instruction names usually end with a @code{,}. This makes it easier
12381: to visually separate instructions if you put several of them on one
12382: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12383:
1.78 anton 12384: Registers are usually specified by number; e.g., (decimal) @code{11}
12385: specifies registers R11 and F11 on the Alpha architecture (which one,
12386: depends on the instruction). The usual names are also available, e.g.,
12387: @code{s2} for R11 on Alpha.
1.21 crook 12388:
1.78 anton 12389: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12390: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12391: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12392: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12393: conditions are specified in a way specific to each assembler.
1.1 anton 12394:
1.78 anton 12395: Note that the register assignments of the Gforth engine can change
12396: between Gforth versions, or even between different compilations of the
12397: same Gforth version (e.g., if you use a different GCC version). So if
12398: you want to refer to Gforth's registers (e.g., the stack pointer or
12399: TOS), I recommend defining your own words for refering to these
12400: registers, and using them later on; then you can easily adapt to a
12401: changed register assignment. The stability of the register assignment
12402: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12403:
1.100 anton 12404: The most common use of these registers is to dispatch to the next word
12405: (the @code{next} routine). A portable way to do this is to jump to
12406: @code{' noop >code-address} (of course, this is less efficient than
12407: integrating the @code{next} code and scheduling it well).
1.1 anton 12408:
1.96 anton 12409: Another difference between Gforth version is that the top of stack is
12410: kept in memory in @code{gforth} and, on most platforms, in a register in
12411: @code{gforth-fast}.
12412:
1.78 anton 12413: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12414: @subsection Common Disassembler
1.127 anton 12415: @cindex disassembler, general
12416: @cindex gdb disassembler
1.1 anton 12417:
1.78 anton 12418: You can disassemble a @code{code} word with @code{see}
12419: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12420:
1.127 anton 12421: doc-discode
1.44 crook 12422:
1.127 anton 12423: There are two kinds of disassembler for Gforth: The Forth disassembler
12424: (available on some CPUs) and the gdb disassembler (available on
12425: platforms with @command{gdb} and @command{mktemp}). If both are
12426: available, the Forth disassembler is used by default. If you prefer
12427: the gdb disassembler, say
12428:
12429: @example
12430: ' disasm-gdb is discode
12431: @end example
12432:
12433: If neither is available, @code{discode} performs @code{dump}.
12434:
12435: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12436: assembler (i.e., same syntax, etc.). It also includes additional
12437: information in comments. In particular, the address of the instruction
12438: is given in a comment before the instruction.
1.1 anton 12439:
1.127 anton 12440: The gdb disassembler produces output in the same format as the gdb
12441: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12442: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12443: the 386 and AMD64 architectures).
12444:
1.78 anton 12445: @code{See} may display more or less than the actual code of the word,
12446: because the recognition of the end of the code is unreliable. You can
1.127 anton 12447: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12448: the code word is not immediately followed by a named word. If you have
1.116 anton 12449: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12450: to ensure that the end is recognized.
1.21 crook 12451:
1.78 anton 12452: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12453: @subsection 386 Assembler
1.44 crook 12454:
1.78 anton 12455: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12456: available under GPL, and originally part of bigFORTH.
1.21 crook 12457:
1.78 anton 12458: The 386 disassembler included in Gforth was written by Andrew McKewan
12459: and is in the public domain.
1.21 crook 12460:
1.91 anton 12461: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12462:
1.78 anton 12463: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12464:
1.78 anton 12465: The assembler includes all instruction of the Athlon, i.e. 486 core
12466: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12467: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12468: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12469:
1.78 anton 12470: There are several prefixes to switch between different operation sizes,
12471: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12472: double-word accesses. Addressing modes can be switched with @code{.wa}
12473: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12474: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12475:
1.78 anton 12476: For floating point operations, the prefixes are @code{.fs} (IEEE
12477: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12478: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12479:
1.78 anton 12480: The MMX opcodes don't have size prefixes, they are spelled out like in
12481: the Intel assembler. Instead of move from and to memory, there are
12482: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12483:
1.78 anton 12484: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12485: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12486: e.g., @code{3 #}. Here are some examples of addressing modes in various
12487: syntaxes:
1.21 crook 12488:
1.26 crook 12489: @example
1.91 anton 12490: Gforth Intel (NASM) AT&T (gas) Name
12491: .w ax ax %ax register (16 bit)
12492: ax eax %eax register (32 bit)
12493: 3 # offset 3 $3 immediate
12494: 1000 #) byte ptr 1000 1000 displacement
12495: bx ) [ebx] (%ebx) base
12496: 100 di d) 100[edi] 100(%edi) base+displacement
12497: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12498: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12499: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12500: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12501: @end example
12502:
12503: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12504: @code{DI)} to enforce 32-bit displacement fields (useful for
12505: later patching).
1.21 crook 12506:
1.78 anton 12507: Some example of instructions are:
1.1 anton 12508:
12509: @example
1.78 anton 12510: ax bx mov \ move ebx,eax
12511: 3 # ax mov \ mov eax,3
1.137 pazsan 12512: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12513: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12514: .w ax bx mov \ mov bx,ax
1.1 anton 12515: @end example
12516:
1.78 anton 12517: The following forms are supported for binary instructions:
1.1 anton 12518:
12519: @example
1.78 anton 12520: <reg> <reg> <inst>
12521: <n> # <reg> <inst>
12522: <mem> <reg> <inst>
12523: <reg> <mem> <inst>
1.136 pazsan 12524: <n> # <mem> <inst>
1.1 anton 12525: @end example
12526:
1.136 pazsan 12527: The shift/rotate syntax is:
1.1 anton 12528:
1.26 crook 12529: @example
1.78 anton 12530: <reg/mem> 1 # shl \ shortens to shift without immediate
12531: <reg/mem> 4 # shl
12532: <reg/mem> cl shl
1.26 crook 12533: @end example
1.1 anton 12534:
1.78 anton 12535: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12536: the byte version.
1.1 anton 12537:
1.78 anton 12538: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12539: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12540: pc < >= <= >}. (Note that most of these words shadow some Forth words
12541: when @code{assembler} is in front of @code{forth} in the search path,
12542: e.g., in @code{code} words). Currently the control structure words use
12543: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12544: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12545:
1.78 anton 12546: Here is an example of a @code{code} word (assumes that the stack pointer
12547: is in esi and the TOS is in ebx):
1.21 crook 12548:
1.26 crook 12549: @example
1.78 anton 12550: code my+ ( n1 n2 -- n )
12551: 4 si D) bx add
12552: 4 # si add
12553: Next
12554: end-code
1.26 crook 12555: @end example
1.21 crook 12556:
1.161 anton 12557:
1.78 anton 12558: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12559: @subsection Alpha Assembler
1.21 crook 12560:
1.78 anton 12561: The Alpha assembler and disassembler were originally written by Bernd
12562: Thallner.
1.26 crook 12563:
1.78 anton 12564: The register names @code{a0}--@code{a5} are not available to avoid
12565: shadowing hex numbers.
1.2 jwilke 12566:
1.78 anton 12567: Immediate forms of arithmetic instructions are distinguished by a
12568: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12569: does not count as arithmetic instruction).
1.2 jwilke 12570:
1.78 anton 12571: You have to specify all operands to an instruction, even those that
12572: other assemblers consider optional, e.g., the destination register for
12573: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12574:
1.78 anton 12575: You can specify conditions for @code{if,} by removing the first @code{b}
12576: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12577:
1.26 crook 12578: @example
1.78 anton 12579: 11 fgt if, \ if F11>0e
12580: ...
12581: endif,
1.26 crook 12582: @end example
1.2 jwilke 12583:
1.78 anton 12584: @code{fbgt,} gives @code{fgt}.
12585:
1.161 anton 12586: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12587: @subsection MIPS assembler
1.2 jwilke 12588:
1.78 anton 12589: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12590:
1.78 anton 12591: Currently the assembler and disassembler only cover the MIPS-I
12592: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12593:
1.78 anton 12594: The register names @code{$a0}--@code{$a3} are not available to avoid
12595: shadowing hex numbers.
1.2 jwilke 12596:
1.78 anton 12597: Because there is no way to distinguish registers from immediate values,
12598: you have to explicitly use the immediate forms of instructions, i.e.,
12599: @code{addiu,}, not just @code{addu,} (@command{as} does this
12600: implicitly).
1.2 jwilke 12601:
1.78 anton 12602: If the architecture manual specifies several formats for the instruction
12603: (e.g., for @code{jalr,}), you usually have to use the one with more
12604: arguments (i.e., two for @code{jalr,}). When in doubt, see
12605: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12606:
1.78 anton 12607: Branches and jumps in the MIPS architecture have a delay slot. You have
12608: to fill it yourself (the simplest way is to use @code{nop,}), the
12609: assembler does not do it for you (unlike @command{as}). Even
12610: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12611: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12612: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12613:
1.78 anton 12614: Note that you must not put branches, jumps, or @code{li,} into the delay
12615: slot: @code{li,} may expand to several instructions, and control flow
12616: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12617:
1.78 anton 12618: For branches the argument specifying the target is a relative address;
12619: You have to add the address of the delay slot to get the absolute
12620: address.
1.1 anton 12621:
1.78 anton 12622: The MIPS architecture also has load delay slots and restrictions on
12623: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12624: yourself to satisfy these restrictions, the assembler does not do it for
12625: you.
1.1 anton 12626:
1.78 anton 12627: You can specify the conditions for @code{if,} etc. by taking a
12628: conditional branch and leaving away the @code{b} at the start and the
12629: @code{,} at the end. E.g.,
1.1 anton 12630:
1.26 crook 12631: @example
1.78 anton 12632: 4 5 eq if,
12633: ... \ do something if $4 equals $5
12634: then,
1.26 crook 12635: @end example
1.1 anton 12636:
1.161 anton 12637:
12638: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
12639: @subsection PowerPC assembler
12640:
1.162 anton 12641: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12642: Revucky.
12643:
1.162 anton 12644: This assembler does not follow the convention of ending mnemonic names
12645: with a ``,'', so some mnemonic names shadow regular Forth words (in
12646: particular: @code{and or xor fabs}); so if you want to use the Forth
12647: words, you have to make them visible first, e.g., with @code{also
12648: forth}.
12649:
1.161 anton 12650: Registers are referred to by their number, e.g., @code{9} means the
12651: integer register 9 or the FP register 9 (depending on the
12652: instruction).
12653:
12654: Because there is no way to distinguish registers from immediate values,
12655: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12656: @code{addi,}, not just @code{add,}.
1.161 anton 12657:
1.162 anton 12658: The assembler and disassembler usually support the most general form
1.161 anton 12659: of an instruction, but usually not the shorter forms (especially for
12660: branches).
12661:
12662:
12663:
12664: @node Other assemblers, , PowerPC assembler, Assembler and Code Words
1.78 anton 12665: @subsection Other assemblers
12666:
12667: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12668: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12669: an assembler already. If you are writing them from scratch, please use
12670: a similar syntax style as the one we use (i.e., postfix, commas at the
12671: end of the instruction names, @pxref{Common Assembler}); make the output
12672: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12673: similar to the style we used.
12674:
12675: Hints on implementation: The most important part is to have a good test
12676: suite that contains all instructions. Once you have that, the rest is
12677: easy. For actual coding you can take a look at
12678: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12679: the assembler and disassembler, avoiding redundancy and some potential
12680: bugs. You can also look at that file (and @pxref{Advanced does> usage
12681: example}) to get ideas how to factor a disassembler.
12682:
12683: Start with the disassembler, because it's easier to reuse data from the
12684: disassembler for the assembler than the other way round.
1.1 anton 12685:
1.78 anton 12686: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12687: how simple it can be.
1.1 anton 12688:
1.161 anton 12689:
12690:
12691:
1.78 anton 12692: @c -------------------------------------------------------------
12693: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12694: @section Threading Words
12695: @cindex threading words
1.1 anton 12696:
1.78 anton 12697: @cindex code address
12698: These words provide access to code addresses and other threading stuff
12699: in Gforth (and, possibly, other interpretive Forths). It more or less
12700: abstracts away the differences between direct and indirect threading
12701: (and, for direct threading, the machine dependences). However, at
12702: present this wordset is still incomplete. It is also pretty low-level;
12703: some day it will hopefully be made unnecessary by an internals wordset
12704: that abstracts implementation details away completely.
1.1 anton 12705:
1.78 anton 12706: The terminology used here stems from indirect threaded Forth systems; in
12707: such a system, the XT of a word is represented by the CFA (code field
12708: address) of a word; the CFA points to a cell that contains the code
12709: address. The code address is the address of some machine code that
12710: performs the run-time action of invoking the word (e.g., the
12711: @code{dovar:} routine pushes the address of the body of the word (a
12712: variable) on the stack
12713: ).
1.1 anton 12714:
1.78 anton 12715: @cindex code address
12716: @cindex code field address
12717: In an indirect threaded Forth, you can get the code address of @i{name}
12718: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12719: >code-address}, independent of the threading method.
1.1 anton 12720:
1.78 anton 12721: doc-threading-method
12722: doc->code-address
12723: doc-code-address!
1.1 anton 12724:
1.78 anton 12725: @cindex @code{does>}-handler
12726: @cindex @code{does>}-code
12727: For a word defined with @code{DOES>}, the code address usually points to
12728: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12729: routine (in Gforth on some platforms, it can also point to the dodoes
12730: routine itself). What you are typically interested in, though, is
12731: whether a word is a @code{DOES>}-defined word, and what Forth code it
12732: executes; @code{>does-code} tells you that.
1.1 anton 12733:
1.78 anton 12734: doc->does-code
1.1 anton 12735:
1.78 anton 12736: To create a @code{DOES>}-defined word with the following basic words,
12737: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12738: @code{/does-handler} aus behind you have to place your executable Forth
12739: code. Finally you have to create a word and modify its behaviour with
12740: @code{does-handler!}.
1.1 anton 12741:
1.78 anton 12742: doc-does-code!
12743: doc-does-handler!
12744: doc-/does-handler
1.1 anton 12745:
1.78 anton 12746: The code addresses produced by various defining words are produced by
12747: the following words:
1.1 anton 12748:
1.78 anton 12749: doc-docol:
12750: doc-docon:
12751: doc-dovar:
12752: doc-douser:
12753: doc-dodefer:
12754: doc-dofield:
1.1 anton 12755:
1.99 anton 12756: @cindex definer
12757: The following two words generalize @code{>code-address},
12758: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12759:
12760: doc->definer
12761: doc-definer!
12762:
1.26 crook 12763: @c -------------------------------------------------------------
1.78 anton 12764: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12765: @section Passing Commands to the Operating System
12766: @cindex operating system - passing commands
12767: @cindex shell commands
12768:
12769: Gforth allows you to pass an arbitrary string to the host operating
12770: system shell (if such a thing exists) for execution.
12771:
12772: doc-sh
12773: doc-system
12774: doc-$?
1.23 crook 12775: doc-getenv
1.44 crook 12776:
1.26 crook 12777: @c -------------------------------------------------------------
1.47 crook 12778: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12779: @section Keeping track of Time
12780: @cindex time-related words
12781:
12782: doc-ms
12783: doc-time&date
1.79 anton 12784: doc-utime
12785: doc-cputime
1.47 crook 12786:
12787:
12788: @c -------------------------------------------------------------
12789: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12790: @section Miscellaneous Words
12791: @cindex miscellaneous words
12792:
1.29 crook 12793: @comment TODO find homes for these
12794:
1.26 crook 12795: These section lists the ANS Forth words that are not documented
1.21 crook 12796: elsewhere in this manual. Ultimately, they all need proper homes.
12797:
1.68 anton 12798: doc-quit
1.44 crook 12799:
1.26 crook 12800: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12801: (@pxref{ANS conformance}):
1.21 crook 12802:
12803: @code{EDITOR}
12804: @code{EMIT?}
12805: @code{FORGET}
12806:
1.24 anton 12807: @c ******************************************************************
12808: @node Error messages, Tools, Words, Top
12809: @chapter Error messages
12810: @cindex error messages
12811: @cindex backtrace
12812:
12813: A typical Gforth error message looks like this:
12814:
12815: @example
1.86 anton 12816: in file included from \evaluated string/:-1
1.24 anton 12817: in file included from ./yyy.fs:1
12818: ./xxx.fs:4: Invalid memory address
1.134 anton 12819: >>>bar<<<
1.79 anton 12820: Backtrace:
1.25 anton 12821: $400E664C @@
12822: $400E6664 foo
1.24 anton 12823: @end example
12824:
12825: The message identifying the error is @code{Invalid memory address}. The
12826: error happened when text-interpreting line 4 of the file
12827: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12828: word on the line where the error happened, is pointed out (with
1.134 anton 12829: @code{>>>} and @code{<<<}).
1.24 anton 12830:
12831: The file containing the error was included in line 1 of @file{./yyy.fs},
12832: and @file{yyy.fs} was included from a non-file (in this case, by giving
12833: @file{yyy.fs} as command-line parameter to Gforth).
12834:
12835: At the end of the error message you find a return stack dump that can be
12836: interpreted as a backtrace (possibly empty). On top you find the top of
12837: the return stack when the @code{throw} happened, and at the bottom you
12838: find the return stack entry just above the return stack of the topmost
12839: text interpreter.
12840:
12841: To the right of most return stack entries you see a guess for the word
12842: that pushed that return stack entry as its return address. This gives a
12843: backtrace. In our case we see that @code{bar} called @code{foo}, and
12844: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12845: address} exception).
12846:
12847: Note that the backtrace is not perfect: We don't know which return stack
12848: entries are return addresses (so we may get false positives); and in
12849: some cases (e.g., for @code{abort"}) we cannot determine from the return
12850: address the word that pushed the return address, so for some return
12851: addresses you see no names in the return stack dump.
1.25 anton 12852:
12853: @cindex @code{catch} and backtraces
12854: The return stack dump represents the return stack at the time when a
12855: specific @code{throw} was executed. In programs that make use of
12856: @code{catch}, it is not necessarily clear which @code{throw} should be
12857: used for the return stack dump (e.g., consider one @code{throw} that
12858: indicates an error, which is caught, and during recovery another error
1.160 anton 12859: happens; which @code{throw} should be used for the stack dump?).
12860: Gforth presents the return stack dump for the first @code{throw} after
12861: the last executed (not returned-to) @code{catch} or @code{nothrow};
12862: this works well in the usual case. To get the right backtrace, you
12863: usually want to insert @code{nothrow} or @code{['] false catch drop}
12864: after a @code{catch} if the error is not rethrown.
1.25 anton 12865:
12866: @cindex @code{gforth-fast} and backtraces
12867: @cindex @code{gforth-fast}, difference from @code{gforth}
12868: @cindex backtraces with @code{gforth-fast}
12869: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12870: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12871: from primitives (e.g., invalid memory address, stack empty etc.);
12872: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12873: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12874: exception caused by a primitive in @code{gforth-fast}, you will
12875: typically see no return stack dump at all; however, if the exception is
12876: caught by @code{catch} (e.g., for restoring some state), and then
12877: @code{throw}n again, the return stack dump will be for the first such
12878: @code{throw}.
1.2 jwilke 12879:
1.5 anton 12880: @c ******************************************************************
1.24 anton 12881: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12882: @chapter Tools
12883:
12884: @menu
12885: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12886: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12887: @end menu
12888:
12889: See also @ref{Emacs and Gforth}.
12890:
1.126 pazsan 12891: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12892: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12893: @cindex @file{ans-report.fs}
12894: @cindex report the words used in your program
12895: @cindex words used in your program
12896:
12897: If you want to label a Forth program as ANS Forth Program, you must
12898: document which wordsets the program uses; for extension wordsets, it is
12899: helpful to list the words the program requires from these wordsets
12900: (because Forth systems are allowed to provide only some words of them).
12901:
12902: The @file{ans-report.fs} tool makes it easy for you to determine which
12903: words from which wordset and which non-ANS words your application
12904: uses. You simply have to include @file{ans-report.fs} before loading the
12905: program you want to check. After loading your program, you can get the
12906: report with @code{print-ans-report}. A typical use is to run this as
12907: batch job like this:
12908: @example
12909: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12910: @end example
12911:
12912: The output looks like this (for @file{compat/control.fs}):
12913: @example
12914: The program uses the following words
12915: from CORE :
12916: : POSTPONE THEN ; immediate ?dup IF 0=
12917: from BLOCK-EXT :
12918: \
12919: from FILE :
12920: (
12921: @end example
12922:
12923: @subsection Caveats
12924:
12925: Note that @file{ans-report.fs} just checks which words are used, not whether
12926: they are used in an ANS Forth conforming way!
12927:
12928: Some words are defined in several wordsets in the
12929: standard. @file{ans-report.fs} reports them for only one of the
12930: wordsets, and not necessarily the one you expect. It depends on usage
12931: which wordset is the right one to specify. E.g., if you only use the
12932: compilation semantics of @code{S"}, it is a Core word; if you also use
12933: its interpretation semantics, it is a File word.
1.124 anton 12934:
12935:
1.127 anton 12936: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12937: @section Stack depth changes during interpretation
12938: @cindex @file{depth-changes.fs}
12939: @cindex depth changes during interpretation
12940: @cindex stack depth changes during interpretation
12941: @cindex items on the stack after interpretation
12942:
12943: Sometimes you notice that, after loading a file, there are items left
12944: on the stack. The tool @file{depth-changes.fs} helps you find out
12945: quickly where in the file these stack items are coming from.
12946:
12947: The simplest way of using @file{depth-changes.fs} is to include it
12948: before the file(s) you want to check, e.g.:
12949:
12950: @example
12951: gforth depth-changes.fs my-file.fs
12952: @end example
12953:
12954: This will compare the stack depths of the data and FP stack at every
12955: empty line (in interpretation state) against these depths at the last
12956: empty line (in interpretation state). If the depths are not equal,
12957: the position in the file and the stack contents are printed with
12958: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12959: change has occured in the paragraph of non-empty lines before the
12960: indicated line. It is a good idea to leave an empty line at the end
12961: of the file, so the last paragraph is checked, too.
12962:
12963: Checking only at empty lines usually works well, but sometimes you
12964: have big blocks of non-empty lines (e.g., when building a big table),
12965: and you want to know where in this block the stack depth changed. You
12966: can check all interpreted lines with
12967:
12968: @example
12969: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12970: @end example
12971:
12972: This checks the stack depth at every end-of-line. So the depth change
12973: occured in the line reported by the @code{~~} (not in the line
12974: before).
12975:
12976: Note that, while this offers better accuracy in indicating where the
12977: stack depth changes, it will often report many intentional stack depth
12978: changes (e.g., when an interpreted computation stretches across
12979: several lines). You can suppress the checking of some lines by
12980: putting backslashes at the end of these lines (not followed by white
12981: space), and using
12982:
12983: @example
12984: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12985: @end example
1.1 anton 12986:
12987: @c ******************************************************************
1.65 anton 12988: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12989: @chapter ANS conformance
12990: @cindex ANS conformance of Gforth
12991:
12992: To the best of our knowledge, Gforth is an
12993:
12994: ANS Forth System
12995: @itemize @bullet
12996: @item providing the Core Extensions word set
12997: @item providing the Block word set
12998: @item providing the Block Extensions word set
12999: @item providing the Double-Number word set
13000: @item providing the Double-Number Extensions word set
13001: @item providing the Exception word set
13002: @item providing the Exception Extensions word set
13003: @item providing the Facility word set
1.40 anton 13004: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13005: @item providing the File Access word set
13006: @item providing the File Access Extensions word set
13007: @item providing the Floating-Point word set
13008: @item providing the Floating-Point Extensions word set
13009: @item providing the Locals word set
13010: @item providing the Locals Extensions word set
13011: @item providing the Memory-Allocation word set
13012: @item providing the Memory-Allocation Extensions word set (that one's easy)
13013: @item providing the Programming-Tools word set
13014: @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
13015: @item providing the Search-Order word set
13016: @item providing the Search-Order Extensions word set
13017: @item providing the String word set
13018: @item providing the String Extensions word set (another easy one)
13019: @end itemize
13020:
1.118 anton 13021: Gforth has the following environmental restrictions:
13022:
13023: @cindex environmental restrictions
13024: @itemize @bullet
13025: @item
13026: While processing the OS command line, if an exception is not caught,
13027: Gforth exits with a non-zero exit code instyead of performing QUIT.
13028:
13029: @item
13030: When an @code{throw} is performed after a @code{query}, Gforth does not
13031: allways restore the input source specification in effect at the
13032: corresponding catch.
13033:
13034: @end itemize
13035:
13036:
1.1 anton 13037: @cindex system documentation
13038: In addition, ANS Forth systems are required to document certain
13039: implementation choices. This chapter tries to meet these
13040: requirements. In many cases it gives a way to ask the system for the
13041: information instead of providing the information directly, in
13042: particular, if the information depends on the processor, the operating
13043: system or the installation options chosen, or if they are likely to
13044: change during the maintenance of Gforth.
13045:
13046: @comment The framework for the rest has been taken from pfe.
13047:
13048: @menu
13049: * The Core Words::
13050: * The optional Block word set::
13051: * The optional Double Number word set::
13052: * The optional Exception word set::
13053: * The optional Facility word set::
13054: * The optional File-Access word set::
13055: * The optional Floating-Point word set::
13056: * The optional Locals word set::
13057: * The optional Memory-Allocation word set::
13058: * The optional Programming-Tools word set::
13059: * The optional Search-Order word set::
13060: @end menu
13061:
13062:
13063: @c =====================================================================
13064: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13065: @comment node-name, next, previous, up
13066: @section The Core Words
13067: @c =====================================================================
13068: @cindex core words, system documentation
13069: @cindex system documentation, core words
13070:
13071: @menu
13072: * core-idef:: Implementation Defined Options
13073: * core-ambcond:: Ambiguous Conditions
13074: * core-other:: Other System Documentation
13075: @end menu
13076:
13077: @c ---------------------------------------------------------------------
13078: @node core-idef, core-ambcond, The Core Words, The Core Words
13079: @subsection Implementation Defined Options
13080: @c ---------------------------------------------------------------------
13081: @cindex core words, implementation-defined options
13082: @cindex implementation-defined options, core words
13083:
13084:
13085: @table @i
13086: @item (Cell) aligned addresses:
13087: @cindex cell-aligned addresses
13088: @cindex aligned addresses
13089: processor-dependent. Gforth's alignment words perform natural alignment
13090: (e.g., an address aligned for a datum of size 8 is divisible by
13091: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13092:
13093: @item @code{EMIT} and non-graphic characters:
13094: @cindex @code{EMIT} and non-graphic characters
13095: @cindex non-graphic characters and @code{EMIT}
13096: The character is output using the C library function (actually, macro)
13097: @code{putc}.
13098:
13099: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13100: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13101: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13102: @cindex @code{ACCEPT}, editing
13103: @cindex @code{EXPECT}, editing
13104: This is modeled on the GNU readline library (@pxref{Readline
13105: Interaction, , Command Line Editing, readline, The GNU Readline
13106: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13107: producing a full word completion every time you type it (instead of
1.28 crook 13108: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13109:
13110: @item character set:
13111: @cindex character set
13112: The character set of your computer and display device. Gforth is
13113: 8-bit-clean (but some other component in your system may make trouble).
13114:
13115: @item Character-aligned address requirements:
13116: @cindex character-aligned address requirements
13117: installation-dependent. Currently a character is represented by a C
13118: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13119: (Comments on that requested).
13120:
13121: @item character-set extensions and matching of names:
13122: @cindex character-set extensions and matching of names
1.26 crook 13123: @cindex case-sensitivity for name lookup
13124: @cindex name lookup, case-sensitivity
13125: @cindex locale and case-sensitivity
1.21 crook 13126: Any character except the ASCII NUL character can be used in a
1.1 anton 13127: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13128: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13129: function is probably influenced by the locale. E.g., the @code{C} locale
13130: does not know about accents and umlauts, so they are matched
13131: case-sensitively in that locale. For portability reasons it is best to
13132: write programs such that they work in the @code{C} locale. Then one can
13133: use libraries written by a Polish programmer (who might use words
13134: containing ISO Latin-2 encoded characters) and by a French programmer
13135: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13136: funny results for some of the words (which ones, depends on the font you
13137: are using)). Also, the locale you prefer may not be available in other
13138: operating systems. Hopefully, Unicode will solve these problems one day.
13139:
13140: @item conditions under which control characters match a space delimiter:
13141: @cindex space delimiters
13142: @cindex control characters as delimiters
1.117 anton 13143: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13144: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13145: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13146: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13147: interpreter (aka text interpreter) by default, treats all white-space
13148: characters as delimiters.
13149:
1.26 crook 13150: @item format of the control-flow stack:
13151: @cindex control-flow stack, format
13152: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13153: stack item in cells is given by the constant @code{cs-item-size}. At the
13154: time of this writing, an item consists of a (pointer to a) locals list
13155: (third), an address in the code (second), and a tag for identifying the
13156: item (TOS). The following tags are used: @code{defstart},
13157: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13158: @code{scopestart}.
13159:
13160: @item conversion of digits > 35
13161: @cindex digits > 35
13162: The characters @code{[\]^_'} are the digits with the decimal value
13163: 36@minus{}41. There is no way to input many of the larger digits.
13164:
13165: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13166: @cindex @code{EXPECT}, display after end of input
13167: @cindex @code{ACCEPT}, display after end of input
13168: The cursor is moved to the end of the entered string. If the input is
13169: terminated using the @kbd{Return} key, a space is typed.
13170:
13171: @item exception abort sequence of @code{ABORT"}:
13172: @cindex exception abort sequence of @code{ABORT"}
13173: @cindex @code{ABORT"}, exception abort sequence
13174: The error string is stored into the variable @code{"error} and a
13175: @code{-2 throw} is performed.
13176:
13177: @item input line terminator:
13178: @cindex input line terminator
13179: @cindex line terminator on input
1.26 crook 13180: @cindex newline character on input
1.1 anton 13181: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13182: lines. One of these characters is typically produced when you type the
13183: @kbd{Enter} or @kbd{Return} key.
13184:
13185: @item maximum size of a counted string:
13186: @cindex maximum size of a counted string
13187: @cindex counted string, maximum size
13188: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13189: on all platforms, but this may change.
1.1 anton 13190:
13191: @item maximum size of a parsed string:
13192: @cindex maximum size of a parsed string
13193: @cindex parsed string, maximum size
13194: Given by the constant @code{/line}. Currently 255 characters.
13195:
13196: @item maximum size of a definition name, in characters:
13197: @cindex maximum size of a definition name, in characters
13198: @cindex name, maximum length
1.113 anton 13199: MAXU/8
1.1 anton 13200:
13201: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13202: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13203: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13204: MAXU/8
1.1 anton 13205:
13206: @item method of selecting the user input device:
13207: @cindex user input device, method of selecting
13208: The user input device is the standard input. There is currently no way to
13209: change it from within Gforth. However, the input can typically be
13210: redirected in the command line that starts Gforth.
13211:
13212: @item method of selecting the user output device:
13213: @cindex user output device, method of selecting
13214: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13215: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13216: output when the user output device is a terminal, otherwise the output
13217: is buffered.
1.1 anton 13218:
13219: @item methods of dictionary compilation:
13220: What are we expected to document here?
13221:
13222: @item number of bits in one address unit:
13223: @cindex number of bits in one address unit
13224: @cindex address unit, size in bits
13225: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13226: platforms.
1.1 anton 13227:
13228: @item number representation and arithmetic:
13229: @cindex number representation and arithmetic
1.79 anton 13230: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13231:
13232: @item ranges for integer types:
13233: @cindex ranges for integer types
13234: @cindex integer types, ranges
13235: Installation-dependent. Make environmental queries for @code{MAX-N},
13236: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13237: unsigned (and positive) types is 0. The lower bound for signed types on
13238: two's complement and one's complement machines machines can be computed
13239: by adding 1 to the upper bound.
13240:
13241: @item read-only data space regions:
13242: @cindex read-only data space regions
13243: @cindex data-space, read-only regions
13244: The whole Forth data space is writable.
13245:
13246: @item size of buffer at @code{WORD}:
13247: @cindex size of buffer at @code{WORD}
13248: @cindex @code{WORD} buffer size
13249: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13250: shared with the pictured numeric output string. If overwriting
13251: @code{PAD} is acceptable, it is as large as the remaining dictionary
13252: space, although only as much can be sensibly used as fits in a counted
13253: string.
13254:
13255: @item size of one cell in address units:
13256: @cindex cell size
13257: @code{1 cells .}.
13258:
13259: @item size of one character in address units:
13260: @cindex char size
1.79 anton 13261: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13262:
13263: @item size of the keyboard terminal buffer:
13264: @cindex size of the keyboard terminal buffer
13265: @cindex terminal buffer, size
13266: Varies. You can determine the size at a specific time using @code{lp@@
13267: tib - .}. It is shared with the locals stack and TIBs of files that
13268: include the current file. You can change the amount of space for TIBs
13269: and locals stack at Gforth startup with the command line option
13270: @code{-l}.
13271:
13272: @item size of the pictured numeric output buffer:
13273: @cindex size of the pictured numeric output buffer
13274: @cindex pictured numeric output buffer, size
13275: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13276: shared with @code{WORD}.
13277:
13278: @item size of the scratch area returned by @code{PAD}:
13279: @cindex size of the scratch area returned by @code{PAD}
13280: @cindex @code{PAD} size
13281: The remainder of dictionary space. @code{unused pad here - - .}.
13282:
13283: @item system case-sensitivity characteristics:
13284: @cindex case-sensitivity characteristics
1.26 crook 13285: Dictionary searches are case-insensitive (except in
1.1 anton 13286: @code{TABLE}s). However, as explained above under @i{character-set
13287: extensions}, the matching for non-ASCII characters is determined by the
13288: locale you are using. In the default @code{C} locale all non-ASCII
13289: characters are matched case-sensitively.
13290:
13291: @item system prompt:
13292: @cindex system prompt
13293: @cindex prompt
13294: @code{ ok} in interpret state, @code{ compiled} in compile state.
13295:
13296: @item division rounding:
13297: @cindex division rounding
1.166 anton 13298: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13299: division (with the default installation of Gforth). You can check
13300: this with @code{s" floored" environment? drop .}. If you write
13301: programs that need a specific division rounding, best use
13302: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13303:
13304: @item values of @code{STATE} when true:
13305: @cindex @code{STATE} values
13306: -1.
13307:
13308: @item values returned after arithmetic overflow:
13309: On two's complement machines, arithmetic is performed modulo
13310: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13311: arithmetic (with appropriate mapping for signed types). Division by
13312: zero typically results in a @code{-55 throw} (Floating-point
13313: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13314: division overflow can result in these throws, or in @code{-11 throw};
13315: in @code{gforth-fast} division overflow and divide by zero may also
13316: result in returning bogus results without producing an exception.
1.1 anton 13317:
13318: @item whether the current definition can be found after @t{DOES>}:
13319: @cindex @t{DOES>}, visibility of current definition
13320: No.
13321:
13322: @end table
13323:
13324: @c ---------------------------------------------------------------------
13325: @node core-ambcond, core-other, core-idef, The Core Words
13326: @subsection Ambiguous conditions
13327: @c ---------------------------------------------------------------------
13328: @cindex core words, ambiguous conditions
13329: @cindex ambiguous conditions, core words
13330:
13331: @table @i
13332:
13333: @item a name is neither a word nor a number:
13334: @cindex name not found
1.26 crook 13335: @cindex undefined word
1.80 anton 13336: @code{-13 throw} (Undefined word).
1.1 anton 13337:
13338: @item a definition name exceeds the maximum length allowed:
1.26 crook 13339: @cindex word name too long
1.1 anton 13340: @code{-19 throw} (Word name too long)
13341:
13342: @item addressing a region not inside the various data spaces of the forth system:
13343: @cindex Invalid memory address
1.32 anton 13344: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13345: typically readable. Accessing other addresses gives results dependent on
13346: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13347: address).
13348:
13349: @item argument type incompatible with parameter:
1.26 crook 13350: @cindex argument type mismatch
1.1 anton 13351: This is usually not caught. Some words perform checks, e.g., the control
13352: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13353: mismatch).
13354:
13355: @item attempting to obtain the execution token of a word with undefined execution semantics:
13356: @cindex Interpreting a compile-only word, for @code{'} etc.
13357: @cindex execution token of words with undefined execution semantics
13358: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13359: get an execution token for @code{compile-only-error} (which performs a
13360: @code{-14 throw} when executed).
13361:
13362: @item dividing by zero:
13363: @cindex dividing by zero
13364: @cindex floating point unidentified fault, integer division
1.80 anton 13365: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13366: zero); on other systems, this typically results in a @code{-55 throw}
13367: (Floating-point unidentified fault).
1.1 anton 13368:
13369: @item insufficient data stack or return stack space:
13370: @cindex insufficient data stack or return stack space
13371: @cindex stack overflow
1.26 crook 13372: @cindex address alignment exception, stack overflow
1.1 anton 13373: @cindex Invalid memory address, stack overflow
13374: Depending on the operating system, the installation, and the invocation
13375: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13376: it is not checked. If it is checked, you typically get a @code{-3 throw}
13377: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13378: throw} (Invalid memory address) (depending on the platform and how you
13379: achieved the overflow) as soon as the overflow happens. If it is not
13380: checked, overflows typically result in mysterious illegal memory
13381: accesses, producing @code{-9 throw} (Invalid memory address) or
13382: @code{-23 throw} (Address alignment exception); they might also destroy
13383: the internal data structure of @code{ALLOCATE} and friends, resulting in
13384: various errors in these words.
1.1 anton 13385:
13386: @item insufficient space for loop control parameters:
13387: @cindex insufficient space for loop control parameters
1.80 anton 13388: Like other return stack overflows.
1.1 anton 13389:
13390: @item insufficient space in the dictionary:
13391: @cindex insufficient space in the dictionary
13392: @cindex dictionary overflow
1.12 anton 13393: If you try to allot (either directly with @code{allot}, or indirectly
13394: with @code{,}, @code{create} etc.) more memory than available in the
13395: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13396: to access memory beyond the end of the dictionary, the results are
13397: similar to stack overflows.
1.1 anton 13398:
13399: @item interpreting a word with undefined interpretation semantics:
13400: @cindex interpreting a word with undefined interpretation semantics
13401: @cindex Interpreting a compile-only word
13402: For some words, we have defined interpretation semantics. For the
13403: others: @code{-14 throw} (Interpreting a compile-only word).
13404:
13405: @item modifying the contents of the input buffer or a string literal:
13406: @cindex modifying the contents of the input buffer or a string literal
13407: These are located in writable memory and can be modified.
13408:
13409: @item overflow of the pictured numeric output string:
13410: @cindex overflow of the pictured numeric output string
13411: @cindex pictured numeric output string, overflow
1.24 anton 13412: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13413:
13414: @item parsed string overflow:
13415: @cindex parsed string overflow
13416: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13417:
13418: @item producing a result out of range:
13419: @cindex result out of range
13420: On two's complement machines, arithmetic is performed modulo
13421: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13422: arithmetic (with appropriate mapping for signed types). Division by
13423: zero typically results in a @code{-10 throw} (divide by zero) or
13424: @code{-55 throw} (floating point unidentified fault). Overflow on
13425: division may result in these errors or in @code{-11 throw} (result out
13426: of range). @code{Gforth-fast} may silently produce bogus results on
13427: division overflow or division by zero. @code{Convert} and
1.24 anton 13428: @code{>number} currently overflow silently.
1.1 anton 13429:
13430: @item reading from an empty data or return stack:
13431: @cindex stack empty
13432: @cindex stack underflow
1.24 anton 13433: @cindex return stack underflow
1.1 anton 13434: The data stack is checked by the outer (aka text) interpreter after
13435: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13436: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13437: depending on operating system, installation, and invocation. If they are
13438: caught by a check, they typically result in @code{-4 throw} (Stack
13439: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13440: (Invalid memory address), depending on the platform and which stack
13441: underflows and by how much. Note that even if the system uses checking
13442: (through the MMU), your program may have to underflow by a significant
13443: number of stack items to trigger the reaction (the reason for this is
13444: that the MMU, and therefore the checking, works with a page-size
13445: granularity). If there is no checking, the symptoms resulting from an
13446: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13447: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13448: (Invalid memory address) and Illegal Instruction (typically @code{-260
13449: throw}).
1.1 anton 13450:
13451: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13452: @cindex unexpected end of the input buffer
13453: @cindex zero-length string as a name
13454: @cindex Attempt to use zero-length string as a name
13455: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13456: use zero-length string as a name). Words like @code{'} probably will not
13457: find what they search. Note that it is possible to create zero-length
13458: names with @code{nextname} (should it not?).
13459:
13460: @item @code{>IN} greater than input buffer:
13461: @cindex @code{>IN} greater than input buffer
13462: The next invocation of a parsing word returns a string with length 0.
13463:
13464: @item @code{RECURSE} appears after @code{DOES>}:
13465: @cindex @code{RECURSE} appears after @code{DOES>}
13466: Compiles a recursive call to the defining word, not to the defined word.
13467:
13468: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13469: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13470: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13471: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13472: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13473: the end of the file was reached), its source-id may be
13474: reused. Therefore, restoring an input source specification referencing a
13475: closed file may lead to unpredictable results instead of a @code{-12
13476: THROW}.
13477:
13478: In the future, Gforth may be able to restore input source specifications
13479: from other than the current input source.
13480:
13481: @item data space containing definitions gets de-allocated:
13482: @cindex data space containing definitions gets de-allocated
13483: Deallocation with @code{allot} is not checked. This typically results in
13484: memory access faults or execution of illegal instructions.
13485:
13486: @item data space read/write with incorrect alignment:
13487: @cindex data space read/write with incorrect alignment
13488: @cindex alignment faults
1.26 crook 13489: @cindex address alignment exception
1.1 anton 13490: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13491: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13492: alignment turned on, incorrect alignment results in a @code{-9 throw}
13493: (Invalid memory address). There are reportedly some processors with
1.12 anton 13494: alignment restrictions that do not report violations.
1.1 anton 13495:
13496: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13497: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13498: Like other alignment errors.
13499:
13500: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13501: Like other stack underflows.
13502:
13503: @item loop control parameters not available:
13504: @cindex loop control parameters not available
13505: Not checked. The counted loop words simply assume that the top of return
13506: stack items are loop control parameters and behave accordingly.
13507:
13508: @item most recent definition does not have a name (@code{IMMEDIATE}):
13509: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13510: @cindex last word was headerless
13511: @code{abort" last word was headerless"}.
13512:
13513: @item name not defined by @code{VALUE} used by @code{TO}:
13514: @cindex name not defined by @code{VALUE} used by @code{TO}
13515: @cindex @code{TO} on non-@code{VALUE}s
13516: @cindex Invalid name argument, @code{TO}
13517: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13518: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13519:
13520: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13521: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13522: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13523: @code{-13 throw} (Undefined word)
13524:
13525: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13526: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13527: Gforth behaves as if they were of the same type. I.e., you can predict
13528: the behaviour by interpreting all parameters as, e.g., signed.
13529:
13530: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13531: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13532: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13533: compilation semantics of @code{TO}.
13534:
13535: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13536: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13537: @cindex @code{WORD}, string overflow
13538: Not checked. The string will be ok, but the count will, of course,
13539: contain only the least significant bits of the length.
13540:
13541: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13542: @cindex @code{LSHIFT}, large shift counts
13543: @cindex @code{RSHIFT}, large shift counts
13544: Processor-dependent. Typical behaviours are returning 0 and using only
13545: the low bits of the shift count.
13546:
13547: @item word not defined via @code{CREATE}:
13548: @cindex @code{>BODY} of non-@code{CREATE}d words
13549: @code{>BODY} produces the PFA of the word no matter how it was defined.
13550:
13551: @cindex @code{DOES>} of non-@code{CREATE}d words
13552: @code{DOES>} changes the execution semantics of the last defined word no
13553: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13554: @code{CREATE , DOES>}.
13555:
13556: @item words improperly used outside @code{<#} and @code{#>}:
13557: Not checked. As usual, you can expect memory faults.
13558:
13559: @end table
13560:
13561:
13562: @c ---------------------------------------------------------------------
13563: @node core-other, , core-ambcond, The Core Words
13564: @subsection Other system documentation
13565: @c ---------------------------------------------------------------------
13566: @cindex other system documentation, core words
13567: @cindex core words, other system documentation
13568:
13569: @table @i
13570: @item nonstandard words using @code{PAD}:
13571: @cindex @code{PAD} use by nonstandard words
13572: None.
13573:
13574: @item operator's terminal facilities available:
13575: @cindex operator's terminal facilities available
1.80 anton 13576: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13577: and you can give commands to Gforth interactively. The actual facilities
13578: available depend on how you invoke Gforth.
13579:
13580: @item program data space available:
13581: @cindex program data space available
13582: @cindex data space available
13583: @code{UNUSED .} gives the remaining dictionary space. The total
13584: dictionary space can be specified with the @code{-m} switch
13585: (@pxref{Invoking Gforth}) when Gforth starts up.
13586:
13587: @item return stack space available:
13588: @cindex return stack space available
13589: You can compute the total return stack space in cells with
13590: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13591: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13592:
13593: @item stack space available:
13594: @cindex stack space available
13595: You can compute the total data stack space in cells with
13596: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13597: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13598:
13599: @item system dictionary space required, in address units:
13600: @cindex system dictionary space required, in address units
13601: Type @code{here forthstart - .} after startup. At the time of this
13602: writing, this gives 80080 (bytes) on a 32-bit system.
13603: @end table
13604:
13605:
13606: @c =====================================================================
13607: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13608: @section The optional Block word set
13609: @c =====================================================================
13610: @cindex system documentation, block words
13611: @cindex block words, system documentation
13612:
13613: @menu
13614: * block-idef:: Implementation Defined Options
13615: * block-ambcond:: Ambiguous Conditions
13616: * block-other:: Other System Documentation
13617: @end menu
13618:
13619:
13620: @c ---------------------------------------------------------------------
13621: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13622: @subsection Implementation Defined Options
13623: @c ---------------------------------------------------------------------
13624: @cindex implementation-defined options, block words
13625: @cindex block words, implementation-defined options
13626:
13627: @table @i
13628: @item the format for display by @code{LIST}:
13629: @cindex @code{LIST} display format
13630: First the screen number is displayed, then 16 lines of 64 characters,
13631: each line preceded by the line number.
13632:
13633: @item the length of a line affected by @code{\}:
13634: @cindex length of a line affected by @code{\}
13635: @cindex @code{\}, line length in blocks
13636: 64 characters.
13637: @end table
13638:
13639:
13640: @c ---------------------------------------------------------------------
13641: @node block-ambcond, block-other, block-idef, The optional Block word set
13642: @subsection Ambiguous conditions
13643: @c ---------------------------------------------------------------------
13644: @cindex block words, ambiguous conditions
13645: @cindex ambiguous conditions, block words
13646:
13647: @table @i
13648: @item correct block read was not possible:
13649: @cindex block read not possible
13650: Typically results in a @code{throw} of some OS-derived value (between
13651: -512 and -2048). If the blocks file was just not long enough, blanks are
13652: supplied for the missing portion.
13653:
13654: @item I/O exception in block transfer:
13655: @cindex I/O exception in block transfer
13656: @cindex block transfer, I/O exception
13657: Typically results in a @code{throw} of some OS-derived value (between
13658: -512 and -2048).
13659:
13660: @item invalid block number:
13661: @cindex invalid block number
13662: @cindex block number invalid
13663: @code{-35 throw} (Invalid block number)
13664:
13665: @item a program directly alters the contents of @code{BLK}:
13666: @cindex @code{BLK}, altering @code{BLK}
13667: The input stream is switched to that other block, at the same
13668: position. If the storing to @code{BLK} happens when interpreting
13669: non-block input, the system will get quite confused when the block ends.
13670:
13671: @item no current block buffer for @code{UPDATE}:
13672: @cindex @code{UPDATE}, no current block buffer
13673: @code{UPDATE} has no effect.
13674:
13675: @end table
13676:
13677: @c ---------------------------------------------------------------------
13678: @node block-other, , block-ambcond, The optional Block word set
13679: @subsection Other system documentation
13680: @c ---------------------------------------------------------------------
13681: @cindex other system documentation, block words
13682: @cindex block words, other system documentation
13683:
13684: @table @i
13685: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13686: No restrictions (yet).
13687:
13688: @item the number of blocks available for source and data:
13689: depends on your disk space.
13690:
13691: @end table
13692:
13693:
13694: @c =====================================================================
13695: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13696: @section The optional Double Number word set
13697: @c =====================================================================
13698: @cindex system documentation, double words
13699: @cindex double words, system documentation
13700:
13701: @menu
13702: * double-ambcond:: Ambiguous Conditions
13703: @end menu
13704:
13705:
13706: @c ---------------------------------------------------------------------
13707: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13708: @subsection Ambiguous conditions
13709: @c ---------------------------------------------------------------------
13710: @cindex double words, ambiguous conditions
13711: @cindex ambiguous conditions, double words
13712:
13713: @table @i
1.29 crook 13714: @item @i{d} outside of range of @i{n} in @code{D>S}:
13715: @cindex @code{D>S}, @i{d} out of range of @i{n}
13716: The least significant cell of @i{d} is produced.
1.1 anton 13717:
13718: @end table
13719:
13720:
13721: @c =====================================================================
13722: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13723: @section The optional Exception word set
13724: @c =====================================================================
13725: @cindex system documentation, exception words
13726: @cindex exception words, system documentation
13727:
13728: @menu
13729: * exception-idef:: Implementation Defined Options
13730: @end menu
13731:
13732:
13733: @c ---------------------------------------------------------------------
13734: @node exception-idef, , The optional Exception word set, The optional Exception word set
13735: @subsection Implementation Defined Options
13736: @c ---------------------------------------------------------------------
13737: @cindex implementation-defined options, exception words
13738: @cindex exception words, implementation-defined options
13739:
13740: @table @i
13741: @item @code{THROW}-codes used in the system:
13742: @cindex @code{THROW}-codes used in the system
13743: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13744: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13745: codes -512@minus{}-2047 are used for OS errors (for file and memory
13746: allocation operations). The mapping from OS error numbers to throw codes
13747: is -512@minus{}@code{errno}. One side effect of this mapping is that
13748: undefined OS errors produce a message with a strange number; e.g.,
13749: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13750: @end table
13751:
13752: @c =====================================================================
13753: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13754: @section The optional Facility word set
13755: @c =====================================================================
13756: @cindex system documentation, facility words
13757: @cindex facility words, system documentation
13758:
13759: @menu
13760: * facility-idef:: Implementation Defined Options
13761: * facility-ambcond:: Ambiguous Conditions
13762: @end menu
13763:
13764:
13765: @c ---------------------------------------------------------------------
13766: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13767: @subsection Implementation Defined Options
13768: @c ---------------------------------------------------------------------
13769: @cindex implementation-defined options, facility words
13770: @cindex facility words, implementation-defined options
13771:
13772: @table @i
13773: @item encoding of keyboard events (@code{EKEY}):
13774: @cindex keyboard events, encoding in @code{EKEY}
13775: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13776: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13777: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13778: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13779: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13780: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13781:
1.1 anton 13782:
13783: @item duration of a system clock tick:
13784: @cindex duration of a system clock tick
13785: @cindex clock tick duration
13786: System dependent. With respect to @code{MS}, the time is specified in
13787: microseconds. How well the OS and the hardware implement this, is
13788: another question.
13789:
13790: @item repeatability to be expected from the execution of @code{MS}:
13791: @cindex repeatability to be expected from the execution of @code{MS}
13792: @cindex @code{MS}, repeatability to be expected
13793: System dependent. On Unix, a lot depends on load. If the system is
13794: lightly loaded, and the delay is short enough that Gforth does not get
13795: swapped out, the performance should be acceptable. Under MS-DOS and
13796: other single-tasking systems, it should be good.
13797:
13798: @end table
13799:
13800:
13801: @c ---------------------------------------------------------------------
13802: @node facility-ambcond, , facility-idef, The optional Facility word set
13803: @subsection Ambiguous conditions
13804: @c ---------------------------------------------------------------------
13805: @cindex facility words, ambiguous conditions
13806: @cindex ambiguous conditions, facility words
13807:
13808: @table @i
13809: @item @code{AT-XY} can't be performed on user output device:
13810: @cindex @code{AT-XY} can't be performed on user output device
13811: Largely terminal dependent. No range checks are done on the arguments.
13812: No errors are reported. You may see some garbage appearing, you may see
13813: simply nothing happen.
13814:
13815: @end table
13816:
13817:
13818: @c =====================================================================
13819: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13820: @section The optional File-Access word set
13821: @c =====================================================================
13822: @cindex system documentation, file words
13823: @cindex file words, system documentation
13824:
13825: @menu
13826: * file-idef:: Implementation Defined Options
13827: * file-ambcond:: Ambiguous Conditions
13828: @end menu
13829:
13830: @c ---------------------------------------------------------------------
13831: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13832: @subsection Implementation Defined Options
13833: @c ---------------------------------------------------------------------
13834: @cindex implementation-defined options, file words
13835: @cindex file words, implementation-defined options
13836:
13837: @table @i
13838: @item file access methods used:
13839: @cindex file access methods used
13840: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13841: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13842: @code{wb}): The file is cleared, if it exists, and created, if it does
13843: not (with both @code{open-file} and @code{create-file}). Under Unix
13844: @code{create-file} creates a file with 666 permissions modified by your
13845: umask.
13846:
13847: @item file exceptions:
13848: @cindex file exceptions
13849: The file words do not raise exceptions (except, perhaps, memory access
13850: faults when you pass illegal addresses or file-ids).
13851:
13852: @item file line terminator:
13853: @cindex file line terminator
13854: System-dependent. Gforth uses C's newline character as line
13855: terminator. What the actual character code(s) of this are is
13856: system-dependent.
13857:
13858: @item file name format:
13859: @cindex file name format
13860: System dependent. Gforth just uses the file name format of your OS.
13861:
13862: @item information returned by @code{FILE-STATUS}:
13863: @cindex @code{FILE-STATUS}, returned information
13864: @code{FILE-STATUS} returns the most powerful file access mode allowed
13865: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13866: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13867: along with the returned mode.
13868:
13869: @item input file state after an exception when including source:
13870: @cindex exception when including source
13871: All files that are left via the exception are closed.
13872:
1.29 crook 13873: @item @i{ior} values and meaning:
13874: @cindex @i{ior} values and meaning
1.68 anton 13875: @cindex @i{wior} values and meaning
1.29 crook 13876: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13877: intended as throw codes. They typically are in the range
13878: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13879: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13880:
13881: @item maximum depth of file input nesting:
13882: @cindex maximum depth of file input nesting
13883: @cindex file input nesting, maximum depth
13884: limited by the amount of return stack, locals/TIB stack, and the number
13885: of open files available. This should not give you troubles.
13886:
13887: @item maximum size of input line:
13888: @cindex maximum size of input line
13889: @cindex input line size, maximum
13890: @code{/line}. Currently 255.
13891:
13892: @item methods of mapping block ranges to files:
13893: @cindex mapping block ranges to files
13894: @cindex files containing blocks
13895: @cindex blocks in files
13896: By default, blocks are accessed in the file @file{blocks.fb} in the
13897: current working directory. The file can be switched with @code{USE}.
13898:
13899: @item number of string buffers provided by @code{S"}:
13900: @cindex @code{S"}, number of string buffers
13901: 1
13902:
13903: @item size of string buffer used by @code{S"}:
13904: @cindex @code{S"}, size of string buffer
13905: @code{/line}. currently 255.
13906:
13907: @end table
13908:
13909: @c ---------------------------------------------------------------------
13910: @node file-ambcond, , file-idef, The optional File-Access word set
13911: @subsection Ambiguous conditions
13912: @c ---------------------------------------------------------------------
13913: @cindex file words, ambiguous conditions
13914: @cindex ambiguous conditions, file words
13915:
13916: @table @i
13917: @item attempting to position a file outside its boundaries:
13918: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13919: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13920: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13921:
13922: @item attempting to read from file positions not yet written:
13923: @cindex reading from file positions not yet written
13924: End-of-file, i.e., zero characters are read and no error is reported.
13925:
1.29 crook 13926: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13927: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13928: An appropriate exception may be thrown, but a memory fault or other
13929: problem is more probable.
13930:
1.29 crook 13931: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13932: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13933: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13934: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13935: thrown.
13936:
13937: @item named file cannot be opened (@code{INCLUDED}):
13938: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13939: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13940:
13941: @item requesting an unmapped block number:
13942: @cindex unmapped block numbers
13943: There are no unmapped legal block numbers. On some operating systems,
13944: writing a block with a large number may overflow the file system and
13945: have an error message as consequence.
13946:
13947: @item using @code{source-id} when @code{blk} is non-zero:
13948: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13949: @code{source-id} performs its function. Typically it will give the id of
13950: the source which loaded the block. (Better ideas?)
13951:
13952: @end table
13953:
13954:
13955: @c =====================================================================
13956: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13957: @section The optional Floating-Point word set
13958: @c =====================================================================
13959: @cindex system documentation, floating-point words
13960: @cindex floating-point words, system documentation
13961:
13962: @menu
13963: * floating-idef:: Implementation Defined Options
13964: * floating-ambcond:: Ambiguous Conditions
13965: @end menu
13966:
13967:
13968: @c ---------------------------------------------------------------------
13969: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13970: @subsection Implementation Defined Options
13971: @c ---------------------------------------------------------------------
13972: @cindex implementation-defined options, floating-point words
13973: @cindex floating-point words, implementation-defined options
13974:
13975: @table @i
13976: @item format and range of floating point numbers:
13977: @cindex format and range of floating point numbers
13978: @cindex floating point numbers, format and range
13979: System-dependent; the @code{double} type of C.
13980:
1.29 crook 13981: @item results of @code{REPRESENT} when @i{float} is out of range:
13982: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13983: System dependent; @code{REPRESENT} is implemented using the C library
13984: function @code{ecvt()} and inherits its behaviour in this respect.
13985:
13986: @item rounding or truncation of floating-point numbers:
13987: @cindex rounding of floating-point numbers
13988: @cindex truncation of floating-point numbers
13989: @cindex floating-point numbers, rounding or truncation
13990: System dependent; the rounding behaviour is inherited from the hosting C
13991: compiler. IEEE-FP-based (i.e., most) systems by default round to
13992: nearest, and break ties by rounding to even (i.e., such that the last
13993: bit of the mantissa is 0).
13994:
13995: @item size of floating-point stack:
13996: @cindex floating-point stack size
13997: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13998: the floating-point stack (in floats). You can specify this on startup
13999: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14000:
14001: @item width of floating-point stack:
14002: @cindex floating-point stack width
14003: @code{1 floats}.
14004:
14005: @end table
14006:
14007:
14008: @c ---------------------------------------------------------------------
14009: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14010: @subsection Ambiguous conditions
14011: @c ---------------------------------------------------------------------
14012: @cindex floating-point words, ambiguous conditions
14013: @cindex ambiguous conditions, floating-point words
14014:
14015: @table @i
14016: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14017: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14018: System-dependent. Typically results in a @code{-23 THROW} like other
14019: alignment violations.
14020:
14021: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14022: @cindex @code{f@@} used with an address that is not float aligned
14023: @cindex @code{f!} used with an address that is not float aligned
14024: System-dependent. Typically results in a @code{-23 THROW} like other
14025: alignment violations.
14026:
14027: @item floating-point result out of range:
14028: @cindex floating-point result out of range
1.80 anton 14029: System-dependent. Can result in a @code{-43 throw} (floating point
14030: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14031: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14032: unidentified fault), or can produce a special value representing, e.g.,
14033: Infinity.
14034:
14035: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14036: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14037: System-dependent. Typically results in an alignment fault like other
14038: alignment violations.
14039:
1.35 anton 14040: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14041: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14042: The floating-point number is converted into decimal nonetheless.
14043:
14044: @item Both arguments are equal to zero (@code{FATAN2}):
14045: @cindex @code{FATAN2}, both arguments are equal to zero
14046: System-dependent. @code{FATAN2} is implemented using the C library
14047: function @code{atan2()}.
14048:
1.29 crook 14049: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14050: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14051: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14052: because of small errors and the tan will be a very large (or very small)
14053: but finite number.
14054:
1.29 crook 14055: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14056: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14057: The result is rounded to the nearest float.
14058:
14059: @item dividing by zero:
14060: @cindex dividing by zero, floating-point
14061: @cindex floating-point dividing by zero
14062: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14063: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14064: (floating point divide by zero) or @code{-55 throw} (Floating-point
14065: unidentified fault).
1.1 anton 14066:
14067: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14068: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14069: System dependent. On IEEE-FP based systems the number is converted into
14070: an infinity.
14071:
1.29 crook 14072: @item @i{float}<1 (@code{FACOSH}):
14073: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14074: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14075: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14076:
1.29 crook 14077: @item @i{float}=<-1 (@code{FLNP1}):
14078: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14079: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14080: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14081: negative infinity for @i{float}=-1).
1.1 anton 14082:
1.29 crook 14083: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14084: @cindex @code{FLN}, @i{float}=<0
14085: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14086: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14087: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14088: negative infinity for @i{float}=0).
1.1 anton 14089:
1.29 crook 14090: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14091: @cindex @code{FASINH}, @i{float}<0
14092: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14093: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14094: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14095: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14096: C library?).
1.1 anton 14097:
1.29 crook 14098: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14099: @cindex @code{FACOS}, |@i{float}|>1
14100: @cindex @code{FASIN}, |@i{float}|>1
14101: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14102: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14103: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14104:
1.29 crook 14105: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14106: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14107: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14108: Platform-dependent; typically, some double number is produced and no
14109: error is reported.
1.1 anton 14110:
14111: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14112: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14113: @code{Precision} characters of the numeric output area are used. If
14114: @code{precision} is too high, these words will smash the data or code
14115: close to @code{here}.
1.1 anton 14116: @end table
14117:
14118: @c =====================================================================
14119: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14120: @section The optional Locals word set
14121: @c =====================================================================
14122: @cindex system documentation, locals words
14123: @cindex locals words, system documentation
14124:
14125: @menu
14126: * locals-idef:: Implementation Defined Options
14127: * locals-ambcond:: Ambiguous Conditions
14128: @end menu
14129:
14130:
14131: @c ---------------------------------------------------------------------
14132: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14133: @subsection Implementation Defined Options
14134: @c ---------------------------------------------------------------------
14135: @cindex implementation-defined options, locals words
14136: @cindex locals words, implementation-defined options
14137:
14138: @table @i
14139: @item maximum number of locals in a definition:
14140: @cindex maximum number of locals in a definition
14141: @cindex locals, maximum number in a definition
14142: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14143: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14144: characters. The number of locals in a definition is bounded by the size
14145: of locals-buffer, which contains the names of the locals.
14146:
14147: @end table
14148:
14149:
14150: @c ---------------------------------------------------------------------
14151: @node locals-ambcond, , locals-idef, The optional Locals word set
14152: @subsection Ambiguous conditions
14153: @c ---------------------------------------------------------------------
14154: @cindex locals words, ambiguous conditions
14155: @cindex ambiguous conditions, locals words
14156:
14157: @table @i
14158: @item executing a named local in interpretation state:
14159: @cindex local in interpretation state
14160: @cindex Interpreting a compile-only word, for a local
14161: Locals have no interpretation semantics. If you try to perform the
14162: interpretation semantics, you will get a @code{-14 throw} somewhere
14163: (Interpreting a compile-only word). If you perform the compilation
14164: semantics, the locals access will be compiled (irrespective of state).
14165:
1.29 crook 14166: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14167: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14168: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14169: @cindex Invalid name argument, @code{TO}
14170: @code{-32 throw} (Invalid name argument)
14171:
14172: @end table
14173:
14174:
14175: @c =====================================================================
14176: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14177: @section The optional Memory-Allocation word set
14178: @c =====================================================================
14179: @cindex system documentation, memory-allocation words
14180: @cindex memory-allocation words, system documentation
14181:
14182: @menu
14183: * memory-idef:: Implementation Defined Options
14184: @end menu
14185:
14186:
14187: @c ---------------------------------------------------------------------
14188: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14189: @subsection Implementation Defined Options
14190: @c ---------------------------------------------------------------------
14191: @cindex implementation-defined options, memory-allocation words
14192: @cindex memory-allocation words, implementation-defined options
14193:
14194: @table @i
1.29 crook 14195: @item values and meaning of @i{ior}:
14196: @cindex @i{ior} values and meaning
14197: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14198: intended as throw codes. They typically are in the range
14199: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14200: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14201:
14202: @end table
14203:
14204: @c =====================================================================
14205: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14206: @section The optional Programming-Tools word set
14207: @c =====================================================================
14208: @cindex system documentation, programming-tools words
14209: @cindex programming-tools words, system documentation
14210:
14211: @menu
14212: * programming-idef:: Implementation Defined Options
14213: * programming-ambcond:: Ambiguous Conditions
14214: @end menu
14215:
14216:
14217: @c ---------------------------------------------------------------------
14218: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14219: @subsection Implementation Defined Options
14220: @c ---------------------------------------------------------------------
14221: @cindex implementation-defined options, programming-tools words
14222: @cindex programming-tools words, implementation-defined options
14223:
14224: @table @i
14225: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14226: @cindex @code{;CODE} ending sequence
14227: @cindex @code{CODE} ending sequence
14228: @code{END-CODE}
14229:
14230: @item manner of processing input following @code{;CODE} and @code{CODE}:
14231: @cindex @code{;CODE}, processing input
14232: @cindex @code{CODE}, processing input
14233: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14234: the input is processed by the text interpreter, (starting) in interpret
14235: state.
14236:
14237: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14238: @cindex @code{ASSEMBLER}, search order capability
14239: The ANS Forth search order word set.
14240:
14241: @item source and format of display by @code{SEE}:
14242: @cindex @code{SEE}, source and format of output
1.80 anton 14243: The source for @code{see} is the executable code used by the inner
1.1 anton 14244: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14245: (and on some platforms, assembly code for primitives) as well as
14246: possible.
1.1 anton 14247:
14248: @end table
14249:
14250: @c ---------------------------------------------------------------------
14251: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14252: @subsection Ambiguous conditions
14253: @c ---------------------------------------------------------------------
14254: @cindex programming-tools words, ambiguous conditions
14255: @cindex ambiguous conditions, programming-tools words
14256:
14257: @table @i
14258:
1.21 crook 14259: @item deleting the compilation word list (@code{FORGET}):
14260: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14261: Not implemented (yet).
14262:
1.29 crook 14263: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14264: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14265: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14266: @cindex control-flow stack underflow
14267: This typically results in an @code{abort"} with a descriptive error
14268: message (may change into a @code{-22 throw} (Control structure mismatch)
14269: in the future). You may also get a memory access error. If you are
14270: unlucky, this ambiguous condition is not caught.
14271:
1.29 crook 14272: @item @i{name} can't be found (@code{FORGET}):
14273: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14274: Not implemented (yet).
14275:
1.29 crook 14276: @item @i{name} not defined via @code{CREATE}:
14277: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14278: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14279: the execution semantics of the last defined word no matter how it was
14280: defined.
14281:
14282: @item @code{POSTPONE} applied to @code{[IF]}:
14283: @cindex @code{POSTPONE} applied to @code{[IF]}
14284: @cindex @code{[IF]} and @code{POSTPONE}
14285: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14286: equivalent to @code{[IF]}.
14287:
14288: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14289: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14290: Continue in the same state of conditional compilation in the next outer
14291: input source. Currently there is no warning to the user about this.
14292:
14293: @item removing a needed definition (@code{FORGET}):
14294: @cindex @code{FORGET}, removing a needed definition
14295: Not implemented (yet).
14296:
14297: @end table
14298:
14299:
14300: @c =====================================================================
14301: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14302: @section The optional Search-Order word set
14303: @c =====================================================================
14304: @cindex system documentation, search-order words
14305: @cindex search-order words, system documentation
14306:
14307: @menu
14308: * search-idef:: Implementation Defined Options
14309: * search-ambcond:: Ambiguous Conditions
14310: @end menu
14311:
14312:
14313: @c ---------------------------------------------------------------------
14314: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14315: @subsection Implementation Defined Options
14316: @c ---------------------------------------------------------------------
14317: @cindex implementation-defined options, search-order words
14318: @cindex search-order words, implementation-defined options
14319:
14320: @table @i
14321: @item maximum number of word lists in search order:
14322: @cindex maximum number of word lists in search order
14323: @cindex search order, maximum depth
14324: @code{s" wordlists" environment? drop .}. Currently 16.
14325:
14326: @item minimum search order:
14327: @cindex minimum search order
14328: @cindex search order, minimum
14329: @code{root root}.
14330:
14331: @end table
14332:
14333: @c ---------------------------------------------------------------------
14334: @node search-ambcond, , search-idef, The optional Search-Order word set
14335: @subsection Ambiguous conditions
14336: @c ---------------------------------------------------------------------
14337: @cindex search-order words, ambiguous conditions
14338: @cindex ambiguous conditions, search-order words
14339:
14340: @table @i
1.21 crook 14341: @item changing the compilation word list (during compilation):
14342: @cindex changing the compilation word list (during compilation)
14343: @cindex compilation word list, change before definition ends
14344: The word is entered into the word list that was the compilation word list
1.1 anton 14345: at the start of the definition. Any changes to the name field (e.g.,
14346: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14347: are applied to the latest defined word (as reported by @code{latest} or
14348: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14349:
14350: @item search order empty (@code{previous}):
14351: @cindex @code{previous}, search order empty
1.26 crook 14352: @cindex vocstack empty, @code{previous}
1.1 anton 14353: @code{abort" Vocstack empty"}.
14354:
14355: @item too many word lists in search order (@code{also}):
14356: @cindex @code{also}, too many word lists in search order
1.26 crook 14357: @cindex vocstack full, @code{also}
1.1 anton 14358: @code{abort" Vocstack full"}.
14359:
14360: @end table
14361:
14362: @c ***************************************************************
1.65 anton 14363: @node Standard vs Extensions, Model, ANS conformance, Top
14364: @chapter Should I use Gforth extensions?
14365: @cindex Gforth extensions
14366:
14367: As you read through the rest of this manual, you will see documentation
14368: for @i{Standard} words, and documentation for some appealing Gforth
14369: @i{extensions}. You might ask yourself the question: @i{``Should I
14370: restrict myself to the standard, or should I use the extensions?''}
14371:
14372: The answer depends on the goals you have for the program you are working
14373: on:
14374:
14375: @itemize @bullet
14376:
14377: @item Is it just for yourself or do you want to share it with others?
14378:
14379: @item
14380: If you want to share it, do the others all use Gforth?
14381:
14382: @item
14383: If it is just for yourself, do you want to restrict yourself to Gforth?
14384:
14385: @end itemize
14386:
14387: If restricting the program to Gforth is ok, then there is no reason not
14388: to use extensions. It is still a good idea to keep to the standard
14389: where it is easy, in case you want to reuse these parts in another
14390: program that you want to be portable.
14391:
14392: If you want to be able to port the program to other Forth systems, there
14393: are the following points to consider:
14394:
14395: @itemize @bullet
14396:
14397: @item
14398: Most Forth systems that are being maintained support the ANS Forth
14399: standard. So if your program complies with the standard, it will be
14400: portable among many systems.
14401:
14402: @item
14403: A number of the Gforth extensions can be implemented in ANS Forth using
14404: public-domain files provided in the @file{compat/} directory. These are
14405: mentioned in the text in passing. There is no reason not to use these
14406: extensions, your program will still be ANS Forth compliant; just include
14407: the appropriate compat files with your program.
14408:
14409: @item
14410: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14411: analyse your program and determine what non-Standard words it relies
14412: upon. However, it does not check whether you use standard words in a
14413: non-standard way.
14414:
14415: @item
14416: Some techniques are not standardized by ANS Forth, and are hard or
14417: impossible to implement in a standard way, but can be implemented in
14418: most Forth systems easily, and usually in similar ways (e.g., accessing
14419: word headers). Forth has a rich historical precedent for programmers
14420: taking advantage of implementation-dependent features of their tools
14421: (for example, relying on a knowledge of the dictionary
14422: structure). Sometimes these techniques are necessary to extract every
14423: last bit of performance from the hardware, sometimes they are just a
14424: programming shorthand.
14425:
14426: @item
14427: Does using a Gforth extension save more work than the porting this part
14428: to other Forth systems (if any) will cost?
14429:
14430: @item
14431: Is the additional functionality worth the reduction in portability and
14432: the additional porting problems?
14433:
14434: @end itemize
14435:
14436: In order to perform these consideratios, you need to know what's
14437: standard and what's not. This manual generally states if something is
1.81 anton 14438: non-standard, but the authoritative source is the
14439: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14440: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14441: into the thought processes of the technical committee.
14442:
14443: Note also that portability between Forth systems is not the only
14444: portability issue; there is also the issue of portability between
14445: different platforms (processor/OS combinations).
14446:
14447: @c ***************************************************************
14448: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14449: @chapter Model
14450:
14451: This chapter has yet to be written. It will contain information, on
14452: which internal structures you can rely.
14453:
14454: @c ***************************************************************
14455: @node Integrating Gforth, Emacs and Gforth, Model, Top
14456: @chapter Integrating Gforth into C programs
14457:
14458: This is not yet implemented.
14459:
14460: Several people like to use Forth as scripting language for applications
14461: that are otherwise written in C, C++, or some other language.
14462:
14463: The Forth system ATLAST provides facilities for embedding it into
14464: applications; unfortunately it has several disadvantages: most
14465: importantly, it is not based on ANS Forth, and it is apparently dead
14466: (i.e., not developed further and not supported). The facilities
1.21 crook 14467: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14468: making the switch should not be hard.
14469:
14470: We also tried to design the interface such that it can easily be
14471: implemented by other Forth systems, so that we may one day arrive at a
14472: standardized interface. Such a standard interface would allow you to
14473: replace the Forth system without having to rewrite C code.
14474:
14475: You embed the Gforth interpreter by linking with the library
14476: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14477: global symbols in this library that belong to the interface, have the
14478: prefix @code{forth_}. (Global symbols that are used internally have the
14479: prefix @code{gforth_}).
14480:
14481: You can include the declarations of Forth types and the functions and
14482: variables of the interface with @code{#include <forth.h>}.
14483:
14484: Types.
14485:
14486: Variables.
14487:
14488: Data and FP Stack pointer. Area sizes.
14489:
14490: functions.
14491:
14492: forth_init(imagefile)
14493: forth_evaluate(string) exceptions?
14494: forth_goto(address) (or forth_execute(xt)?)
14495: forth_continue() (a corountining mechanism)
14496:
14497: Adding primitives.
14498:
14499: No checking.
14500:
14501: Signals?
14502:
14503: Accessing the Stacks
14504:
1.26 crook 14505: @c ******************************************************************
1.1 anton 14506: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14507: @chapter Emacs and Gforth
14508: @cindex Emacs and Gforth
14509:
14510: @cindex @file{gforth.el}
14511: @cindex @file{forth.el}
14512: @cindex Rydqvist, Goran
1.107 dvdkhlng 14513: @cindex Kuehling, David
1.1 anton 14514: @cindex comment editing commands
14515: @cindex @code{\}, editing with Emacs
14516: @cindex debug tracer editing commands
14517: @cindex @code{~~}, removal with Emacs
14518: @cindex Forth mode in Emacs
1.107 dvdkhlng 14519:
1.1 anton 14520: Gforth comes with @file{gforth.el}, an improved version of
14521: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14522: improvements are:
14523:
14524: @itemize @bullet
14525: @item
1.107 dvdkhlng 14526: A better handling of indentation.
14527: @item
14528: A custom hilighting engine for Forth-code.
1.26 crook 14529: @item
14530: Comment paragraph filling (@kbd{M-q})
14531: @item
14532: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14533: @item
14534: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14535: @item
14536: Support of the @code{info-lookup} feature for looking up the
14537: documentation of a word.
1.107 dvdkhlng 14538: @item
14539: Support for reading and writing blocks files.
1.26 crook 14540: @end itemize
14541:
1.107 dvdkhlng 14542: To get a basic description of these features, enter Forth mode and
14543: type @kbd{C-h m}.
1.1 anton 14544:
14545: @cindex source location of error or debugging output in Emacs
14546: @cindex error output, finding the source location in Emacs
14547: @cindex debugging output, finding the source location in Emacs
14548: In addition, Gforth supports Emacs quite well: The source code locations
14549: given in error messages, debugging output (from @code{~~}) and failed
14550: assertion messages are in the right format for Emacs' compilation mode
14551: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14552: Manual}) so the source location corresponding to an error or other
14553: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14554: @kbd{C-c C-c} for the error under the cursor).
14555:
1.107 dvdkhlng 14556: @cindex viewing the documentation of a word in Emacs
14557: @cindex context-sensitive help
14558: Moreover, for words documented in this manual, you can look up the
14559: glossary entry quickly by using @kbd{C-h TAB}
14560: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14561: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14562: later and does not work for words containing @code{:}.
14563:
14564: @menu
14565: * Installing gforth.el:: Making Emacs aware of Forth.
14566: * Emacs Tags:: Viewing the source of a word in Emacs.
14567: * Hilighting:: Making Forth code look prettier.
14568: * Auto-Indentation:: Customizing auto-indentation.
14569: * Blocks Files:: Reading and writing blocks files.
14570: @end menu
14571:
14572: @c ----------------------------------
1.109 anton 14573: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14574: @section Installing gforth.el
14575: @cindex @file{.emacs}
14576: @cindex @file{gforth.el}, installation
14577: To make the features from @file{gforth.el} available in Emacs, add
14578: the following lines to your @file{.emacs} file:
14579:
14580: @example
14581: (autoload 'forth-mode "gforth.el")
14582: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14583: auto-mode-alist))
14584: (autoload 'forth-block-mode "gforth.el")
14585: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14586: auto-mode-alist))
14587: (add-hook 'forth-mode-hook (function (lambda ()
14588: ;; customize variables here:
14589: (setq forth-indent-level 4)
14590: (setq forth-minor-indent-level 2)
14591: (setq forth-hilight-level 3)
14592: ;;; ...
14593: )))
14594: @end example
14595:
14596: @c ----------------------------------
14597: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14598: @section Emacs Tags
1.1 anton 14599: @cindex @file{TAGS} file
14600: @cindex @file{etags.fs}
14601: @cindex viewing the source of a word in Emacs
1.43 anton 14602: @cindex @code{require}, placement in files
14603: @cindex @code{include}, placement in files
1.107 dvdkhlng 14604: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14605: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14606: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14607: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14608: several tags files at the same time (e.g., one for the Gforth sources
14609: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14610: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14611: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14612: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14613: with @file{etags.fs}, you should avoid putting definitions both before
14614: and after @code{require} etc., otherwise you will see the same file
14615: visited several times by commands like @code{tags-search}.
1.1 anton 14616:
1.107 dvdkhlng 14617: @c ----------------------------------
14618: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14619: @section Hilighting
14620: @cindex hilighting Forth code in Emacs
14621: @cindex highlighting Forth code in Emacs
14622: @file{gforth.el} comes with a custom source hilighting engine. When
14623: you open a file in @code{forth-mode}, it will be completely parsed,
14624: assigning faces to keywords, comments, strings etc. While you edit
14625: the file, modified regions get parsed and updated on-the-fly.
14626:
14627: Use the variable `forth-hilight-level' to change the level of
14628: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14629: you set the hilighting level to 0, the parser will still work in the
14630: background, collecting information about whether regions of text are
14631: ``compiled'' or ``interpreted''. Those information are required for
14632: auto-indentation to work properly. Set `forth-disable-parser' to
14633: non-nil if your computer is too slow to handle parsing. This will
14634: have an impact on the smartness of the auto-indentation engine,
14635: though.
14636:
14637: Sometimes Forth sources define new features that should be hilighted,
14638: new control structures, defining-words etc. You can use the variable
14639: `forth-custom-words' to make @code{forth-mode} hilight additional
14640: words and constructs. See the docstring of `forth-words' for details
14641: (in Emacs, type @kbd{C-h v forth-words}).
14642:
14643: `forth-custom-words' is meant to be customized in your
14644: @file{.emacs} file. To customize hilighing in a file-specific manner,
14645: set `forth-local-words' in a local-variables section at the end of
14646: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14647:
14648: Example:
14649: @example
14650: 0 [IF]
14651: Local Variables:
14652: forth-local-words:
14653: ((("t:") definition-starter (font-lock-keyword-face . 1)
14654: "[ \t\n]" t name (font-lock-function-name-face . 3))
14655: ((";t") definition-ender (font-lock-keyword-face . 1)))
14656: End:
14657: [THEN]
14658: @end example
14659:
14660: @c ----------------------------------
14661: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14662: @section Auto-Indentation
14663: @cindex auto-indentation of Forth code in Emacs
14664: @cindex indentation of Forth code in Emacs
14665: @code{forth-mode} automatically tries to indent lines in a smart way,
14666: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14667:
14668: Simple customization can be achieved by setting
14669: `forth-indent-level' and `forth-minor-indent-level' in your
14670: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14671: per default by multiples of 4 columns. To use the more traditional
14672: 3-column indentation, add the following lines to your @file{.emacs}:
14673:
14674: @example
14675: (add-hook 'forth-mode-hook (function (lambda ()
14676: ;; customize variables here:
14677: (setq forth-indent-level 3)
14678: (setq forth-minor-indent-level 1)
14679: )))
14680: @end example
14681:
14682: If you want indentation to recognize non-default words, customize it
14683: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14684: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14685: v forth-indent-words}).
14686:
14687: To customize indentation in a file-specific manner, set
14688: `forth-local-indent-words' in a local-variables section at the end of
14689: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14690: Emacs Manual}).
14691:
14692: Example:
14693: @example
14694: 0 [IF]
14695: Local Variables:
14696: forth-local-indent-words:
14697: ((("t:") (0 . 2) (0 . 2))
14698: ((";t") (-2 . 0) (0 . -2)))
14699: End:
14700: [THEN]
14701: @end example
14702:
14703: @c ----------------------------------
1.109 anton 14704: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14705: @section Blocks Files
14706: @cindex blocks files, use with Emacs
14707: @code{forth-mode} Autodetects blocks files by checking whether the
14708: length of the first line exceeds 1023 characters. It then tries to
14709: convert the file into normal text format. When you save the file, it
14710: will be written to disk as normal stream-source file.
14711:
14712: If you want to write blocks files, use @code{forth-blocks-mode}. It
14713: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14714:
1.107 dvdkhlng 14715: @itemize @bullet
14716: @item
14717: Files are written to disk in blocks file format.
14718: @item
14719: Screen numbers are displayed in the mode line (enumerated beginning
14720: with the value of `forth-block-base')
14721: @item
14722: Warnings are displayed when lines exceed 64 characters.
14723: @item
14724: The beginning of the currently edited block is marked with an
14725: overlay-arrow.
14726: @end itemize
1.41 anton 14727:
1.107 dvdkhlng 14728: There are some restrictions you should be aware of. When you open a
14729: blocks file that contains tabulator or newline characters, these
14730: characters will be translated into spaces when the file is written
14731: back to disk. If tabs or newlines are encountered during blocks file
14732: reading, an error is output to the echo area. So have a look at the
14733: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14734:
1.107 dvdkhlng 14735: Please consult the docstring of @code{forth-blocks-mode} for more
14736: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14737:
1.26 crook 14738: @c ******************************************************************
1.1 anton 14739: @node Image Files, Engine, Emacs and Gforth, Top
14740: @chapter Image Files
1.26 crook 14741: @cindex image file
14742: @cindex @file{.fi} files
1.1 anton 14743: @cindex precompiled Forth code
14744: @cindex dictionary in persistent form
14745: @cindex persistent form of dictionary
14746:
14747: An image file is a file containing an image of the Forth dictionary,
14748: i.e., compiled Forth code and data residing in the dictionary. By
14749: convention, we use the extension @code{.fi} for image files.
14750:
14751: @menu
1.18 anton 14752: * Image Licensing Issues:: Distribution terms for images.
14753: * Image File Background:: Why have image files?
1.67 anton 14754: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14755: * Data-Relocatable Image Files:: are better.
1.67 anton 14756: * Fully Relocatable Image Files:: better yet.
1.18 anton 14757: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14758: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14759: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14760: @end menu
14761:
1.18 anton 14762: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14763: @section Image Licensing Issues
14764: @cindex license for images
14765: @cindex image license
14766:
14767: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14768: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14769: original image; i.e., according to copyright law it is a derived work of
14770: the original image.
14771:
14772: Since Gforth is distributed under the GNU GPL, the newly created image
14773: falls under the GNU GPL, too. In particular, this means that if you
14774: distribute the image, you have to make all of the sources for the image
1.113 anton 14775: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14776: GNU General Public License (Section 3)}.
14777:
14778: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14779: contains only code compiled from the sources you gave it; if none of
14780: these sources is under the GPL, the terms discussed above do not apply
14781: to the image. However, if your image needs an engine (a gforth binary)
14782: that is under the GPL, you should make sure that you distribute both in
14783: a way that is at most a @emph{mere aggregation}, if you don't want the
14784: terms of the GPL to apply to the image.
14785:
14786: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14787: @section Image File Background
14788: @cindex image file background
14789:
1.80 anton 14790: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14791: definitions written in Forth. Since the Forth compiler itself belongs to
14792: those definitions, it is not possible to start the system with the
1.80 anton 14793: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14794: code as an image file in nearly executable form. When Gforth starts up,
14795: a C routine loads the image file into memory, optionally relocates the
14796: addresses, then sets up the memory (stacks etc.) according to
14797: information in the image file, and (finally) starts executing Forth
14798: code.
1.1 anton 14799:
14800: The image file variants represent different compromises between the
14801: goals of making it easy to generate image files and making them
14802: portable.
14803:
14804: @cindex relocation at run-time
1.26 crook 14805: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14806: run-time. This avoids many of the complications discussed below (image
14807: files are data relocatable without further ado), but costs performance
14808: (one addition per memory access).
14809:
14810: @cindex relocation at load-time
1.26 crook 14811: By contrast, the Gforth loader performs relocation at image load time. The
14812: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14813: appropriate code-field addresses (or code addresses in the case of
14814: direct threading).
14815:
14816: There are three kinds of image files, with different degrees of
14817: relocatability: non-relocatable, data-relocatable, and fully relocatable
14818: image files.
14819:
14820: @cindex image file loader
14821: @cindex relocating loader
14822: @cindex loader for image files
14823: These image file variants have several restrictions in common; they are
14824: caused by the design of the image file loader:
14825:
14826: @itemize @bullet
14827: @item
14828: There is only one segment; in particular, this means, that an image file
14829: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14830: them). The contents of the stacks are not represented, either.
1.1 anton 14831:
14832: @item
14833: The only kinds of relocation supported are: adding the same offset to
14834: all cells that represent data addresses; and replacing special tokens
14835: with code addresses or with pieces of machine code.
14836:
14837: If any complex computations involving addresses are performed, the
14838: results cannot be represented in the image file. Several applications that
14839: use such computations come to mind:
14840: @itemize @minus
14841: @item
14842: Hashing addresses (or data structures which contain addresses) for table
14843: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14844: purpose, you will have no problem, because the hash tables are
14845: recomputed automatically when the system is started. If you use your own
14846: hash tables, you will have to do something similar.
14847:
14848: @item
14849: There's a cute implementation of doubly-linked lists that uses
14850: @code{XOR}ed addresses. You could represent such lists as singly-linked
14851: in the image file, and restore the doubly-linked representation on
14852: startup.@footnote{In my opinion, though, you should think thrice before
14853: using a doubly-linked list (whatever implementation).}
14854:
14855: @item
14856: The code addresses of run-time routines like @code{docol:} cannot be
14857: represented in the image file (because their tokens would be replaced by
14858: machine code in direct threaded implementations). As a workaround,
14859: compute these addresses at run-time with @code{>code-address} from the
14860: executions tokens of appropriate words (see the definitions of
1.80 anton 14861: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14862:
14863: @item
14864: On many architectures addresses are represented in machine code in some
14865: shifted or mangled form. You cannot put @code{CODE} words that contain
14866: absolute addresses in this form in a relocatable image file. Workarounds
14867: are representing the address in some relative form (e.g., relative to
14868: the CFA, which is present in some register), or loading the address from
14869: a place where it is stored in a non-mangled form.
14870: @end itemize
14871: @end itemize
14872:
14873: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14874: @section Non-Relocatable Image Files
14875: @cindex non-relocatable image files
1.26 crook 14876: @cindex image file, non-relocatable
1.1 anton 14877:
14878: These files are simple memory dumps of the dictionary. They are specific
14879: to the executable (i.e., @file{gforth} file) they were created
14880: with. What's worse, they are specific to the place on which the
14881: dictionary resided when the image was created. Now, there is no
14882: guarantee that the dictionary will reside at the same place the next
14883: time you start Gforth, so there's no guarantee that a non-relocatable
14884: image will work the next time (Gforth will complain instead of crashing,
14885: though).
14886:
14887: You can create a non-relocatable image file with
14888:
1.44 crook 14889:
1.1 anton 14890: doc-savesystem
14891:
1.44 crook 14892:
1.1 anton 14893: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14894: @section Data-Relocatable Image Files
14895: @cindex data-relocatable image files
1.26 crook 14896: @cindex image file, data-relocatable
1.1 anton 14897:
14898: These files contain relocatable data addresses, but fixed code addresses
14899: (instead of tokens). They are specific to the executable (i.e.,
14900: @file{gforth} file) they were created with. For direct threading on some
14901: architectures (e.g., the i386), data-relocatable images do not work. You
14902: get a data-relocatable image, if you use @file{gforthmi} with a
14903: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14904: Relocatable Image Files}).
14905:
14906: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14907: @section Fully Relocatable Image Files
14908: @cindex fully relocatable image files
1.26 crook 14909: @cindex image file, fully relocatable
1.1 anton 14910:
14911: @cindex @file{kern*.fi}, relocatability
14912: @cindex @file{gforth.fi}, relocatability
14913: These image files have relocatable data addresses, and tokens for code
14914: addresses. They can be used with different binaries (e.g., with and
14915: without debugging) on the same machine, and even across machines with
14916: the same data formats (byte order, cell size, floating point
14917: format). However, they are usually specific to the version of Gforth
14918: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14919: are fully relocatable.
14920:
14921: There are two ways to create a fully relocatable image file:
14922:
14923: @menu
1.29 crook 14924: * gforthmi:: The normal way
1.1 anton 14925: * cross.fs:: The hard way
14926: @end menu
14927:
14928: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14929: @subsection @file{gforthmi}
14930: @cindex @file{comp-i.fs}
14931: @cindex @file{gforthmi}
14932:
14933: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14934: image @i{file} that contains everything you would load by invoking
14935: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14936: @example
1.29 crook 14937: gforthmi @i{file} @i{options}
1.1 anton 14938: @end example
14939:
14940: E.g., if you want to create an image @file{asm.fi} that has the file
14941: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14942: like this:
14943:
14944: @example
14945: gforthmi asm.fi asm.fs
14946: @end example
14947:
1.27 crook 14948: @file{gforthmi} is implemented as a sh script and works like this: It
14949: produces two non-relocatable images for different addresses and then
14950: compares them. Its output reflects this: first you see the output (if
1.62 crook 14951: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14952: files, then you see the output of the comparing program: It displays the
14953: offset used for data addresses and the offset used for code addresses;
1.1 anton 14954: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14955: image files, it displays a line like this:
1.1 anton 14956:
14957: @example
14958: 78DC BFFFFA50 BFFFFA40
14959: @end example
14960:
14961: This means that at offset $78dc from @code{forthstart}, one input image
14962: contains $bffffa50, and the other contains $bffffa40. Since these cells
14963: cannot be represented correctly in the output image, you should examine
14964: these places in the dictionary and verify that these cells are dead
14965: (i.e., not read before they are written).
1.39 anton 14966:
14967: @cindex --application, @code{gforthmi} option
14968: If you insert the option @code{--application} in front of the image file
14969: name, you will get an image that uses the @code{--appl-image} option
14970: instead of the @code{--image-file} option (@pxref{Invoking
14971: Gforth}). When you execute such an image on Unix (by typing the image
14972: name as command), the Gforth engine will pass all options to the image
14973: instead of trying to interpret them as engine options.
1.1 anton 14974:
1.27 crook 14975: If you type @file{gforthmi} with no arguments, it prints some usage
14976: instructions.
14977:
1.1 anton 14978: @cindex @code{savesystem} during @file{gforthmi}
14979: @cindex @code{bye} during @file{gforthmi}
14980: @cindex doubly indirect threaded code
1.44 crook 14981: @cindex environment variables
14982: @cindex @code{GFORTHD} -- environment variable
14983: @cindex @code{GFORTH} -- environment variable
1.1 anton 14984: @cindex @code{gforth-ditc}
1.29 crook 14985: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14986: words @code{savesystem} and @code{bye} must be visible. A special doubly
14987: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14988: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14989: this executable through the environment variable @code{GFORTHD}
14990: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14991: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14992: data-relocatable image (because there is no code address offset). The
14993: normal @file{gforth} executable is used for creating the relocatable
14994: image; you can pass the exact filename of this executable through the
14995: environment variable @code{GFORTH}.
1.1 anton 14996:
14997: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14998: @subsection @file{cross.fs}
14999: @cindex @file{cross.fs}
15000: @cindex cross-compiler
15001: @cindex metacompiler
1.47 crook 15002: @cindex target compiler
1.1 anton 15003:
15004: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15005: programming language (@pxref{Cross Compiler}).
1.1 anton 15006:
1.47 crook 15007: @code{cross} allows you to create image files for machines with
1.1 anton 15008: different data sizes and data formats than the one used for generating
15009: the image file. You can also use it to create an application image that
15010: does not contain a Forth compiler. These features are bought with
15011: restrictions and inconveniences in programming. E.g., addresses have to
15012: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15013: order to make the code relocatable.
15014:
15015:
15016: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15017: @section Stack and Dictionary Sizes
15018: @cindex image file, stack and dictionary sizes
15019: @cindex dictionary size default
15020: @cindex stack size default
15021:
15022: If you invoke Gforth with a command line flag for the size
15023: (@pxref{Invoking Gforth}), the size you specify is stored in the
15024: dictionary. If you save the dictionary with @code{savesystem} or create
15025: an image with @file{gforthmi}, this size will become the default
15026: for the resulting image file. E.g., the following will create a
1.21 crook 15027: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15028:
15029: @example
15030: gforthmi gforth.fi -m 1M
15031: @end example
15032:
15033: In other words, if you want to set the default size for the dictionary
15034: and the stacks of an image, just invoke @file{gforthmi} with the
15035: appropriate options when creating the image.
15036:
15037: @cindex stack size, cache-friendly
15038: Note: For cache-friendly behaviour (i.e., good performance), you should
15039: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15040: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15041: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15042:
15043: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15044: @section Running Image Files
15045: @cindex running image files
15046: @cindex invoking image files
15047: @cindex image file invocation
15048:
15049: @cindex -i, invoke image file
15050: @cindex --image file, invoke image file
1.29 crook 15051: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15052: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15053: @example
1.29 crook 15054: gforth -i @i{image}
1.1 anton 15055: @end example
15056:
15057: @cindex executable image file
1.26 crook 15058: @cindex image file, executable
1.1 anton 15059: If your operating system supports starting scripts with a line of the
15060: form @code{#! ...}, you just have to type the image file name to start
15061: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15062: just a convention). I.e., to run Gforth with the image file @i{image},
15063: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15064: This works because every @code{.fi} file starts with a line of this
15065: format:
15066:
15067: @example
15068: #! /usr/local/bin/gforth-0.4.0 -i
15069: @end example
15070:
15071: The file and pathname for the Gforth engine specified on this line is
15072: the specific Gforth executable that it was built against; i.e. the value
15073: of the environment variable @code{GFORTH} at the time that
15074: @file{gforthmi} was executed.
1.1 anton 15075:
1.27 crook 15076: You can make use of the same shell capability to make a Forth source
15077: file into an executable. For example, if you place this text in a file:
1.26 crook 15078:
15079: @example
15080: #! /usr/local/bin/gforth
15081:
15082: ." Hello, world" CR
15083: bye
15084: @end example
15085:
15086: @noindent
1.27 crook 15087: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15088: directly from the command line. The sequence @code{#!} is used in two
15089: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15090: system@footnote{The Unix kernel actually recognises two types of files:
15091: executable files and files of data, where the data is processed by an
15092: interpreter that is specified on the ``interpreter line'' -- the first
15093: line of the file, starting with the sequence #!. There may be a small
15094: limit (e.g., 32) on the number of characters that may be specified on
15095: the interpreter line.} secondly it is treated as a comment character by
15096: Gforth. Because of the second usage, a space is required between
1.80 anton 15097: @code{#!} and the path to the executable (moreover, some Unixes
15098: require the sequence @code{#! /}).
1.27 crook 15099:
15100: The disadvantage of this latter technique, compared with using
1.80 anton 15101: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15102: compiled on-the-fly, each time the program is invoked.
1.26 crook 15103:
1.1 anton 15104: doc-#!
15105:
1.44 crook 15106:
1.1 anton 15107: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15108: @section Modifying the Startup Sequence
15109: @cindex startup sequence for image file
15110: @cindex image file initialization sequence
15111: @cindex initialization sequence of image file
15112:
1.120 anton 15113: You can add your own initialization to the startup sequence of an image
15114: through the deferred word @code{'cold}. @code{'cold} is invoked just
15115: before the image-specific command line processing (i.e., loading files
15116: and evaluating (@code{-e}) strings) starts.
1.1 anton 15117:
15118: A sequence for adding your initialization usually looks like this:
15119:
15120: @example
15121: :noname
15122: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15123: ... \ your stuff
15124: ; IS 'cold
15125: @end example
15126:
1.157 anton 15127: After @code{'cold}, Gforth processes the image options
15128: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15129: another deferred word. This normally prints Gforth's startup message
15130: and does nothing else.
15131:
1.1 anton 15132: @cindex turnkey image files
1.26 crook 15133: @cindex image file, turnkey applications
1.157 anton 15134: So, if you want to make a turnkey image (i.e., an image for an
15135: application instead of an extended Forth system), you can do this in
15136: two ways:
15137:
15138: @itemize @bullet
15139:
15140: @item
15141: If you want to do your interpretation of the OS command-line
15142: arguments, hook into @code{'cold}. In that case you probably also
15143: want to build the image with @code{gforthmi --application}
15144: (@pxref{gforthmi}) to keep the engine from processing OS command line
15145: options. You can then do your own command-line processing with
15146: @code{next-arg}
15147:
15148: @item
15149: If you want to have the normal Gforth processing of OS command-line
15150: arguments, hook into @code{bootmessage}.
15151:
15152: @end itemize
15153:
15154: In either case, you probably do not want the word that you execute in
15155: these hooks to exit normally, but use @code{bye} or @code{throw}.
15156: Otherwise the Gforth startup process would continue and eventually
15157: present the Forth command line to the user.
1.26 crook 15158:
15159: doc-'cold
1.157 anton 15160: doc-bootmessage
1.44 crook 15161:
1.1 anton 15162: @c ******************************************************************
1.113 anton 15163: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15164: @chapter Engine
15165: @cindex engine
15166: @cindex virtual machine
15167:
1.26 crook 15168: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15169: may be helpful for finding your way in the Gforth sources.
15170:
1.109 anton 15171: The ideas in this section have also been published in the following
15172: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15173: Forth-Tagung '93; M. Anton Ertl,
15174: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15175: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15176: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15177: Threaded code variations and optimizations (extended version)}},
15178: Forth-Tagung '02.
1.1 anton 15179:
15180: @menu
15181: * Portability::
15182: * Threading::
15183: * Primitives::
15184: * Performance::
15185: @end menu
15186:
15187: @node Portability, Threading, Engine, Engine
15188: @section Portability
15189: @cindex engine portability
15190:
1.26 crook 15191: An important goal of the Gforth Project is availability across a wide
15192: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15193: achieved this goal by manually coding the engine in assembly language
15194: for several then-popular processors. This approach is very
15195: labor-intensive and the results are short-lived due to progress in
15196: computer architecture.
1.1 anton 15197:
15198: @cindex C, using C for the engine
15199: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15200: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15201: particularly popular for UNIX-based Forths due to the large variety of
15202: architectures of UNIX machines. Unfortunately an implementation in C
15203: does not mix well with the goals of efficiency and with using
15204: traditional techniques: Indirect or direct threading cannot be expressed
15205: in C, and switch threading, the fastest technique available in C, is
15206: significantly slower. Another problem with C is that it is very
15207: cumbersome to express double integer arithmetic.
15208:
15209: @cindex GNU C for the engine
15210: @cindex long long
15211: Fortunately, there is a portable language that does not have these
15212: limitations: GNU C, the version of C processed by the GNU C compiler
15213: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15214: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15215: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15216: threading possible, its @code{long long} type (@pxref{Long Long, ,
15217: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15218: double numbers on many systems. GNU C is freely available on all
1.1 anton 15219: important (and many unimportant) UNIX machines, VMS, 80386s running
15220: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15221: on all these machines.
15222:
15223: Writing in a portable language has the reputation of producing code that
15224: is slower than assembly. For our Forth engine we repeatedly looked at
15225: the code produced by the compiler and eliminated most compiler-induced
15226: inefficiencies by appropriate changes in the source code.
15227:
15228: @cindex explicit register declarations
15229: @cindex --enable-force-reg, configuration flag
15230: @cindex -DFORCE_REG
15231: However, register allocation cannot be portably influenced by the
15232: programmer, leading to some inefficiencies on register-starved
15233: machines. We use explicit register declarations (@pxref{Explicit Reg
15234: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15235: improve the speed on some machines. They are turned on by using the
15236: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15237: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15238: machine, but also on the compiler version: On some machines some
15239: compiler versions produce incorrect code when certain explicit register
15240: declarations are used. So by default @code{-DFORCE_REG} is not used.
15241:
15242: @node Threading, Primitives, Portability, Engine
15243: @section Threading
15244: @cindex inner interpreter implementation
15245: @cindex threaded code implementation
15246:
15247: @cindex labels as values
15248: GNU C's labels as values extension (available since @code{gcc-2.0},
15249: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15250: makes it possible to take the address of @i{label} by writing
15251: @code{&&@i{label}}. This address can then be used in a statement like
15252: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15253: @code{goto x}.
15254:
1.26 crook 15255: @cindex @code{NEXT}, indirect threaded
1.1 anton 15256: @cindex indirect threaded inner interpreter
15257: @cindex inner interpreter, indirect threaded
1.26 crook 15258: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15259: @example
15260: cfa = *ip++;
15261: ca = *cfa;
15262: goto *ca;
15263: @end example
15264: @cindex instruction pointer
15265: For those unfamiliar with the names: @code{ip} is the Forth instruction
15266: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15267: execution token and points to the code field of the next word to be
15268: executed; The @code{ca} (code address) fetched from there points to some
15269: executable code, e.g., a primitive or the colon definition handler
15270: @code{docol}.
15271:
1.26 crook 15272: @cindex @code{NEXT}, direct threaded
1.1 anton 15273: @cindex direct threaded inner interpreter
15274: @cindex inner interpreter, direct threaded
15275: Direct threading is even simpler:
15276: @example
15277: ca = *ip++;
15278: goto *ca;
15279: @end example
15280:
15281: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15282: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15283:
15284: @menu
15285: * Scheduling::
15286: * Direct or Indirect Threaded?::
1.109 anton 15287: * Dynamic Superinstructions::
1.1 anton 15288: * DOES>::
15289: @end menu
15290:
15291: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15292: @subsection Scheduling
15293: @cindex inner interpreter optimization
15294:
15295: There is a little complication: Pipelined and superscalar processors,
15296: i.e., RISC and some modern CISC machines can process independent
15297: instructions while waiting for the results of an instruction. The
15298: compiler usually reorders (schedules) the instructions in a way that
15299: achieves good usage of these delay slots. However, on our first tries
15300: the compiler did not do well on scheduling primitives. E.g., for
15301: @code{+} implemented as
15302: @example
15303: n=sp[0]+sp[1];
15304: sp++;
15305: sp[0]=n;
15306: NEXT;
15307: @end example
1.81 anton 15308: the @code{NEXT} comes strictly after the other code, i.e., there is
15309: nearly no scheduling. After a little thought the problem becomes clear:
15310: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15311: addresses (and the version of @code{gcc} we used would not know it even
15312: if it was possible), so it could not move the load of the cfa above the
15313: store to the TOS. Indeed the pointers could be the same, if code on or
15314: very near the top of stack were executed. In the interest of speed we
15315: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15316: in scheduling: @code{NEXT} is divided into several parts:
15317: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15318: like:
1.1 anton 15319: @example
1.81 anton 15320: NEXT_P0;
1.1 anton 15321: n=sp[0]+sp[1];
15322: sp++;
15323: NEXT_P1;
15324: sp[0]=n;
15325: NEXT_P2;
15326: @end example
15327:
1.81 anton 15328: There are various schemes that distribute the different operations of
15329: NEXT between these parts in several ways; in general, different schemes
15330: perform best on different processors. We use a scheme for most
15331: architectures that performs well for most processors of this
1.109 anton 15332: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15333: the scheme on installation time.
15334:
1.1 anton 15335:
1.109 anton 15336: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15337: @subsection Direct or Indirect Threaded?
15338: @cindex threading, direct or indirect?
15339:
1.109 anton 15340: Threaded forth code consists of references to primitives (simple machine
15341: code routines like @code{+}) and to non-primitives (e.g., colon
15342: definitions, variables, constants); for a specific class of
15343: non-primitives (e.g., variables) there is one code routine (e.g.,
15344: @code{dovar}), but each variable needs a separate reference to its data.
15345:
15346: Traditionally Forth has been implemented as indirect threaded code,
15347: because this allows to use only one cell to reference a non-primitive
15348: (basically you point to the data, and find the code address there).
15349:
15350: @cindex primitive-centric threaded code
15351: However, threaded code in Gforth (since 0.6.0) uses two cells for
15352: non-primitives, one for the code address, and one for the data address;
15353: the data pointer is an immediate argument for the virtual machine
15354: instruction represented by the code address. We call this
15355: @emph{primitive-centric} threaded code, because all code addresses point
15356: to simple primitives. E.g., for a variable, the code address is for
15357: @code{lit} (also used for integer literals like @code{99}).
15358:
15359: Primitive-centric threaded code allows us to use (faster) direct
15360: threading as dispatch method, completely portably (direct threaded code
15361: in Gforth before 0.6.0 required architecture-specific code). It also
15362: eliminates the performance problems related to I-cache consistency that
15363: 386 implementations have with direct threaded code, and allows
15364: additional optimizations.
15365:
15366: @cindex hybrid direct/indirect threaded code
15367: There is a catch, however: the @var{xt} parameter of @code{execute} can
15368: occupy only one cell, so how do we pass non-primitives with their code
15369: @emph{and} data addresses to them? Our answer is to use indirect
15370: threaded dispatch for @code{execute} and other words that use a
15371: single-cell xt. So, normal threaded code in colon definitions uses
15372: direct threading, and @code{execute} and similar words, which dispatch
15373: to xts on the data stack, use indirect threaded code. We call this
15374: @emph{hybrid direct/indirect} threaded code.
15375:
15376: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15377: @cindex gforth engine
15378: @cindex gforth-fast engine
15379: The engines @command{gforth} and @command{gforth-fast} use hybrid
15380: direct/indirect threaded code. This means that with these engines you
15381: cannot use @code{,} to compile an xt. Instead, you have to use
15382: @code{compile,}.
15383:
15384: @cindex gforth-itc engine
1.115 anton 15385: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15386: This engine uses plain old indirect threaded code. It still compiles in
15387: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15388: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15389: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15390: and execute @code{' , is compile,}. Your program can check if it is
15391: running on a hybrid direct/indirect threaded engine or a pure indirect
15392: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15393:
15394:
15395: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15396: @subsection Dynamic Superinstructions
15397: @cindex Dynamic superinstructions with replication
15398: @cindex Superinstructions
15399: @cindex Replication
15400:
15401: The engines @command{gforth} and @command{gforth-fast} use another
15402: optimization: Dynamic superinstructions with replication. As an
15403: example, consider the following colon definition:
15404:
15405: @example
15406: : squared ( n1 -- n2 )
15407: dup * ;
15408: @end example
15409:
15410: Gforth compiles this into the threaded code sequence
15411:
15412: @example
15413: dup
15414: *
15415: ;s
15416: @end example
15417:
15418: In normal direct threaded code there is a code address occupying one
15419: cell for each of these primitives. Each code address points to a
15420: machine code routine, and the interpreter jumps to this machine code in
15421: order to execute the primitive. The routines for these three
15422: primitives are (in @command{gforth-fast} on the 386):
15423:
15424: @example
15425: Code dup
15426: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15427: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15428: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15429: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15430: end-code
15431: Code *
15432: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15433: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15434: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15435: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15436: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15437: end-code
15438: Code ;s
15439: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15440: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15441: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15442: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15443: end-code
15444: @end example
15445:
15446: With dynamic superinstructions and replication the compiler does not
15447: just lay down the threaded code, but also copies the machine code
15448: fragments, usually without the jump at the end.
15449:
15450: @example
15451: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15452: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15453: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15454: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15455: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15456: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15457: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15458: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15459: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15460: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15461: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15462: @end example
15463:
15464: Only when a threaded-code control-flow change happens (e.g., in
15465: @code{;s}), the jump is appended. This optimization eliminates many of
15466: these jumps and makes the rest much more predictable. The speedup
15467: depends on the processor and the application; on the Athlon and Pentium
15468: III this optimization typically produces a speedup by a factor of 2.
15469:
15470: The code addresses in the direct-threaded code are set to point to the
15471: appropriate points in the copied machine code, in this example like
15472: this:
1.1 anton 15473:
1.109 anton 15474: @example
15475: primitive code address
15476: dup $4057D27D
15477: * $4057D286
15478: ;s $4057D292
15479: @end example
15480:
15481: Thus there can be threaded-code jumps to any place in this piece of
15482: code. This also simplifies decompilation quite a bit.
15483:
15484: @cindex --no-dynamic command-line option
15485: @cindex --no-super command-line option
15486: You can disable this optimization with @option{--no-dynamic}. You can
15487: use the copying without eliminating the jumps (i.e., dynamic
15488: replication, but without superinstructions) with @option{--no-super};
15489: this gives the branch prediction benefit alone; the effect on
1.110 anton 15490: performance depends on the CPU; on the Athlon and Pentium III the
15491: speedup is a little less than for dynamic superinstructions with
15492: replication.
15493:
15494: @cindex patching threaded code
15495: One use of these options is if you want to patch the threaded code.
15496: With superinstructions, many of the dispatch jumps are eliminated, so
15497: patching often has no effect. These options preserve all the dispatch
15498: jumps.
1.109 anton 15499:
15500: @cindex --dynamic command-line option
1.110 anton 15501: On some machines dynamic superinstructions are disabled by default,
15502: because it is unsafe on these machines. However, if you feel
15503: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15504:
15505: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15506: @subsection DOES>
15507: @cindex @code{DOES>} implementation
15508:
1.26 crook 15509: @cindex @code{dodoes} routine
15510: @cindex @code{DOES>}-code
1.1 anton 15511: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15512: the chunk of code executed by every word defined by a
1.109 anton 15513: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15514: this is only needed if the xt of the word is @code{execute}d. The main
15515: problem here is: How to find the Forth code to be executed, i.e. the
15516: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15517: solutions:
1.1 anton 15518:
1.21 crook 15519: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15520: @code{DOES>}-code address is stored in the cell after the code address
15521: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15522: illegal in the Forth-79 and all later standards, because in fig-Forth
15523: this address lies in the body (which is illegal in these
15524: standards). However, by making the code field larger for all words this
15525: solution becomes legal again. We use this approach. Leaving a cell
15526: unused in most words is a bit wasteful, but on the machines we are
15527: targeting this is hardly a problem.
15528:
1.1 anton 15529:
15530: @node Primitives, Performance, Threading, Engine
15531: @section Primitives
15532: @cindex primitives, implementation
15533: @cindex virtual machine instructions, implementation
15534:
15535: @menu
15536: * Automatic Generation::
15537: * TOS Optimization::
15538: * Produced code::
15539: @end menu
15540:
15541: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15542: @subsection Automatic Generation
15543: @cindex primitives, automatic generation
15544:
15545: @cindex @file{prims2x.fs}
1.109 anton 15546:
1.1 anton 15547: Since the primitives are implemented in a portable language, there is no
15548: longer any need to minimize the number of primitives. On the contrary,
15549: having many primitives has an advantage: speed. In order to reduce the
15550: number of errors in primitives and to make programming them easier, we
1.109 anton 15551: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15552: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15553: generates most (and sometimes all) of the C code for a primitive from
15554: the stack effect notation. The source for a primitive has the following
15555: form:
1.1 anton 15556:
15557: @cindex primitive source format
15558: @format
1.58 anton 15559: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15560: [@code{""}@i{glossary entry}@code{""}]
15561: @i{C code}
1.1 anton 15562: [@code{:}
1.29 crook 15563: @i{Forth code}]
1.1 anton 15564: @end format
15565:
15566: The items in brackets are optional. The category and glossary fields
15567: are there for generating the documentation, the Forth code is there
15568: for manual implementations on machines without GNU C. E.g., the source
15569: for the primitive @code{+} is:
15570: @example
1.58 anton 15571: + ( n1 n2 -- n ) core plus
1.1 anton 15572: n = n1+n2;
15573: @end example
15574:
15575: This looks like a specification, but in fact @code{n = n1+n2} is C
15576: code. Our primitive generation tool extracts a lot of information from
15577: the stack effect notations@footnote{We use a one-stack notation, even
15578: though we have separate data and floating-point stacks; The separate
15579: notation can be generated easily from the unified notation.}: The number
15580: of items popped from and pushed on the stack, their type, and by what
15581: name they are referred to in the C code. It then generates a C code
15582: prelude and postlude for each primitive. The final C code for @code{+}
15583: looks like this:
15584:
15585: @example
1.46 pazsan 15586: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15587: /* */ /* documentation */
1.81 anton 15588: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15589: @{
15590: DEF_CA /* definition of variable ca (indirect threading) */
15591: Cell n1; /* definitions of variables */
15592: Cell n2;
15593: Cell n;
1.81 anton 15594: NEXT_P0; /* NEXT part 0 */
1.1 anton 15595: n1 = (Cell) sp[1]; /* input */
15596: n2 = (Cell) TOS;
15597: sp += 1; /* stack adjustment */
15598: @{
15599: n = n1+n2; /* C code taken from the source */
15600: @}
15601: NEXT_P1; /* NEXT part 1 */
15602: TOS = (Cell)n; /* output */
15603: NEXT_P2; /* NEXT part 2 */
15604: @}
15605: @end example
15606:
15607: This looks long and inefficient, but the GNU C compiler optimizes quite
15608: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15609: HP RISC machines: Defining the @code{n}s does not produce any code, and
15610: using them as intermediate storage also adds no cost.
15611:
1.26 crook 15612: There are also other optimizations that are not illustrated by this
15613: example: assignments between simple variables are usually for free (copy
1.1 anton 15614: propagation). If one of the stack items is not used by the primitive
15615: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15616: (dead code elimination). On the other hand, there are some things that
15617: the compiler does not do, therefore they are performed by
15618: @file{prims2x.fs}: The compiler does not optimize code away that stores
15619: a stack item to the place where it just came from (e.g., @code{over}).
15620:
15621: While programming a primitive is usually easy, there are a few cases
15622: where the programmer has to take the actions of the generator into
15623: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15624: fall through to @code{NEXT}.
1.109 anton 15625:
15626: For more information
1.1 anton 15627:
15628: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15629: @subsection TOS Optimization
15630: @cindex TOS optimization for primitives
15631: @cindex primitives, keeping the TOS in a register
15632:
15633: An important optimization for stack machine emulators, e.g., Forth
15634: engines, is keeping one or more of the top stack items in
1.29 crook 15635: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15636: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15637: @itemize @bullet
15638: @item
1.29 crook 15639: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15640: due to fewer loads from and stores to the stack.
1.29 crook 15641: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15642: @i{y<n}, due to additional moves between registers.
1.1 anton 15643: @end itemize
15644:
15645: @cindex -DUSE_TOS
15646: @cindex -DUSE_NO_TOS
15647: In particular, keeping one item in a register is never a disadvantage,
15648: if there are enough registers. Keeping two items in registers is a
15649: disadvantage for frequent words like @code{?branch}, constants,
15650: variables, literals and @code{i}. Therefore our generator only produces
15651: code that keeps zero or one items in registers. The generated C code
15652: covers both cases; the selection between these alternatives is made at
15653: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15654: code for @code{+} is just a simple variable name in the one-item case,
15655: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15656: GNU C compiler tries to keep simple variables like @code{TOS} in
15657: registers, and it usually succeeds, if there are enough registers.
15658:
15659: @cindex -DUSE_FTOS
15660: @cindex -DUSE_NO_FTOS
15661: The primitive generator performs the TOS optimization for the
15662: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15663: operations the benefit of this optimization is even larger:
15664: floating-point operations take quite long on most processors, but can be
15665: performed in parallel with other operations as long as their results are
15666: not used. If the FP-TOS is kept in a register, this works. If
15667: it is kept on the stack, i.e., in memory, the store into memory has to
15668: wait for the result of the floating-point operation, lengthening the
15669: execution time of the primitive considerably.
15670:
15671: The TOS optimization makes the automatic generation of primitives a
15672: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15673: @code{TOS} is not sufficient. There are some special cases to
15674: consider:
15675: @itemize @bullet
15676: @item In the case of @code{dup ( w -- w w )} the generator must not
15677: eliminate the store to the original location of the item on the stack,
15678: if the TOS optimization is turned on.
15679: @item Primitives with stack effects of the form @code{--}
1.29 crook 15680: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15681: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15682: must load the TOS from the stack at the end. But for the null stack
15683: effect @code{--} no stores or loads should be generated.
15684: @end itemize
15685:
15686: @node Produced code, , TOS Optimization, Primitives
15687: @subsection Produced code
15688: @cindex primitives, assembly code listing
15689:
15690: @cindex @file{engine.s}
15691: To see what assembly code is produced for the primitives on your machine
15692: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15693: look at the resulting file @file{engine.s}. Alternatively, you can also
15694: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15695:
15696: @node Performance, , Primitives, Engine
15697: @section Performance
15698: @cindex performance of some Forth interpreters
15699: @cindex engine performance
15700: @cindex benchmarking Forth systems
15701: @cindex Gforth performance
15702:
15703: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15704: impossible to write a significantly faster threaded-code engine.
1.1 anton 15705:
15706: On register-starved machines like the 386 architecture processors
15707: improvements are possible, because @code{gcc} does not utilize the
15708: registers as well as a human, even with explicit register declarations;
15709: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15710: and hand-tuned it for the 486; this system is 1.19 times faster on the
15711: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15712: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15713: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15714: registers fit in real registers (and we can even afford to use the TOS
15715: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15716: earlier results. And dynamic superinstructions provide another speedup
15717: (but only around a factor 1.2 on the 486).
1.1 anton 15718:
15719: @cindex Win32Forth performance
15720: @cindex NT Forth performance
15721: @cindex eforth performance
15722: @cindex ThisForth performance
15723: @cindex PFE performance
15724: @cindex TILE performance
1.81 anton 15725: The potential advantage of assembly language implementations is not
1.112 anton 15726: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15727: (direct threaded, compiled with @code{gcc-2.95.1} and
15728: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15729: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15730: (with and without peephole (aka pinhole) optimization of the threaded
15731: code); all these systems were written in assembly language. We also
15732: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15733: with @code{gcc-2.6.3} with the default configuration for Linux:
15734: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15735: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15736: employs peephole optimization of the threaded code) and TILE (compiled
15737: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15738: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15739: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15740: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15741: then extended it to run the benchmarks, added the peephole optimizer,
15742: ran the benchmarks and reported the results.
1.40 anton 15743:
1.1 anton 15744: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15745: matrix multiplication come from the Stanford integer benchmarks and have
15746: been translated into Forth by Martin Fraeman; we used the versions
15747: included in the TILE Forth package, but with bigger data set sizes; and
15748: a recursive Fibonacci number computation for benchmarking calling
15749: performance. The following table shows the time taken for the benchmarks
15750: scaled by the time taken by Gforth (in other words, it shows the speedup
15751: factor that Gforth achieved over the other systems).
15752:
15753: @example
1.112 anton 15754: relative Win32- NT eforth This-
15755: time Gforth Forth Forth eforth +opt PFE Forth TILE
15756: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15757: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15758: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15759: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15760: @end example
15761:
1.26 crook 15762: You may be quite surprised by the good performance of Gforth when
15763: compared with systems written in assembly language. One important reason
15764: for the disappointing performance of these other systems is probably
15765: that they are not written optimally for the 486 (e.g., they use the
15766: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15767: but costly method for relocating the Forth image: like @code{cforth}, it
15768: computes the actual addresses at run time, resulting in two address
15769: computations per @code{NEXT} (@pxref{Image File Background}).
15770:
1.1 anton 15771: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15772: explained with the self-imposed restriction of the latter systems to
15773: standard C, which makes efficient threading impossible (however, the
1.4 anton 15774: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15775: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15776: Moreover, current C compilers have a hard time optimizing other aspects
15777: of the ThisForth and the TILE source.
15778:
1.26 crook 15779: The performance of Gforth on 386 architecture processors varies widely
15780: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15781: allocate any of the virtual machine registers into real machine
15782: registers by itself and would not work correctly with explicit register
1.112 anton 15783: declarations, giving a significantly slower engine (on a 486DX2/66
15784: running the Sieve) than the one measured above.
1.1 anton 15785:
1.26 crook 15786: Note that there have been several releases of Win32Forth since the
15787: release presented here, so the results presented above may have little
1.40 anton 15788: predictive value for the performance of Win32Forth today (results for
15789: the current release on an i486DX2/66 are welcome).
1.1 anton 15790:
15791: @cindex @file{Benchres}
1.66 anton 15792: In
15793: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15794: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15795: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15796: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15797: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15798: than the version used here. You can find a newer version of these
15799: measurements at
1.47 crook 15800: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15801: find numbers for Gforth on various machines in @file{Benchres}.
15802:
1.26 crook 15803: @c ******************************************************************
1.113 anton 15804: @c @node Binding to System Library, Cross Compiler, Engine, Top
15805: @c @chapter Binding to System Library
1.13 pazsan 15806:
1.113 anton 15807: @c ****************************************************************
15808: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15809: @chapter Cross Compiler
1.47 crook 15810: @cindex @file{cross.fs}
15811: @cindex cross-compiler
15812: @cindex metacompiler
15813: @cindex target compiler
1.13 pazsan 15814:
1.46 pazsan 15815: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15816: mostly written in Forth, including crucial parts like the outer
15817: interpreter and compiler, it needs compiled Forth code to get
15818: started. The cross compiler allows to create new images for other
15819: architectures, even running under another Forth system.
1.13 pazsan 15820:
15821: @menu
1.67 anton 15822: * Using the Cross Compiler::
15823: * How the Cross Compiler Works::
1.13 pazsan 15824: @end menu
15825:
1.21 crook 15826: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15827: @section Using the Cross Compiler
1.46 pazsan 15828:
15829: The cross compiler uses a language that resembles Forth, but isn't. The
15830: main difference is that you can execute Forth code after definition,
15831: while you usually can't execute the code compiled by cross, because the
15832: code you are compiling is typically for a different computer than the
15833: one you are compiling on.
15834:
1.81 anton 15835: @c anton: This chapter is somewhat different from waht I would expect: I
15836: @c would expect an explanation of the cross language and how to create an
15837: @c application image with it. The section explains some aspects of
15838: @c creating a Gforth kernel.
15839:
1.46 pazsan 15840: The Makefile is already set up to allow you to create kernels for new
15841: architectures with a simple make command. The generic kernels using the
15842: GCC compiled virtual machine are created in the normal build process
15843: with @code{make}. To create a embedded Gforth executable for e.g. the
15844: 8086 processor (running on a DOS machine), type
15845:
15846: @example
15847: make kernl-8086.fi
15848: @end example
15849:
15850: This will use the machine description from the @file{arch/8086}
15851: directory to create a new kernel. A machine file may look like that:
15852:
15853: @example
15854: \ Parameter for target systems 06oct92py
15855:
15856: 4 Constant cell \ cell size in bytes
15857: 2 Constant cell<< \ cell shift to bytes
15858: 5 Constant cell>bit \ cell shift to bits
15859: 8 Constant bits/char \ bits per character
15860: 8 Constant bits/byte \ bits per byte [default: 8]
15861: 8 Constant float \ bytes per float
15862: 8 Constant /maxalign \ maximum alignment in bytes
15863: false Constant bigendian \ byte order
15864: ( true=big, false=little )
15865:
15866: include machpc.fs \ feature list
15867: @end example
15868:
15869: This part is obligatory for the cross compiler itself, the feature list
15870: is used by the kernel to conditionally compile some features in and out,
15871: depending on whether the target supports these features.
15872:
15873: There are some optional features, if you define your own primitives,
15874: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15875: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15876: @code{prims-include} includes primitives, and @code{>boot} prepares for
15877: booting.
15878:
15879: @example
15880: : asm-include ." Include assembler" cr
15881: s" arch/8086/asm.fs" included ;
15882:
15883: : prims-include ." Include primitives" cr
15884: s" arch/8086/prim.fs" included ;
15885:
15886: : >boot ." Prepare booting" cr
15887: s" ' boot >body into-forth 1+ !" evaluate ;
15888: @end example
15889:
15890: These words are used as sort of macro during the cross compilation in
1.81 anton 15891: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15892: be possible --- but more complicated --- to write a new kernel project
15893: file, too.
15894:
15895: @file{kernel/main.fs} expects the machine description file name on the
15896: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15897: @code{mach-file} leaves a counted string on the stack, or
15898: @code{machine-file} leaves an address, count pair of the filename on the
15899: stack.
15900:
15901: The feature list is typically controlled using @code{SetValue}, generic
15902: files that are used by several projects can use @code{DefaultValue}
15903: instead. Both functions work like @code{Value}, when the value isn't
15904: defined, but @code{SetValue} works like @code{to} if the value is
15905: defined, and @code{DefaultValue} doesn't set anything, if the value is
15906: defined.
15907:
15908: @example
15909: \ generic mach file for pc gforth 03sep97jaw
15910:
15911: true DefaultValue NIL \ relocating
15912:
15913: >ENVIRON
15914:
15915: true DefaultValue file \ controls the presence of the
15916: \ file access wordset
15917: true DefaultValue OS \ flag to indicate a operating system
15918:
15919: true DefaultValue prims \ true: primitives are c-code
15920:
15921: true DefaultValue floating \ floating point wordset is present
15922:
15923: true DefaultValue glocals \ gforth locals are present
15924: \ will be loaded
15925: true DefaultValue dcomps \ double number comparisons
15926:
15927: true DefaultValue hash \ hashing primitives are loaded/present
15928:
15929: true DefaultValue xconds \ used together with glocals,
15930: \ special conditionals supporting gforths'
15931: \ local variables
15932: true DefaultValue header \ save a header information
15933:
15934: true DefaultValue backtrace \ enables backtrace code
15935:
15936: false DefaultValue ec
15937: false DefaultValue crlf
15938:
15939: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15940:
15941: &16 KB DefaultValue stack-size
15942: &15 KB &512 + DefaultValue fstack-size
15943: &15 KB DefaultValue rstack-size
15944: &14 KB &512 + DefaultValue lstack-size
15945: @end example
1.13 pazsan 15946:
1.48 anton 15947: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15948: @section How the Cross Compiler Works
1.13 pazsan 15949:
15950: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15951: @appendix Bugs
1.1 anton 15952: @cindex bug reporting
15953:
1.21 crook 15954: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15955:
1.103 anton 15956: If you find a bug, please submit a bug report through
15957: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15958:
15959: @itemize @bullet
15960: @item
1.81 anton 15961: A program (or a sequence of keyboard commands) that reproduces the bug.
15962: @item
15963: A description of what you think constitutes the buggy behaviour.
15964: @item
1.21 crook 15965: The Gforth version used (it is announced at the start of an
15966: interactive Gforth session).
15967: @item
15968: The machine and operating system (on Unix
15969: systems @code{uname -a} will report this information).
15970: @item
1.81 anton 15971: The installation options (you can find the configure options at the
15972: start of @file{config.status}) and configuration (@code{configure}
15973: output or @file{config.cache}).
1.21 crook 15974: @item
15975: A complete list of changes (if any) you (or your installer) have made to the
15976: Gforth sources.
15977: @end itemize
1.1 anton 15978:
15979: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15980: to Report Bugs, gcc.info, GNU C Manual}.
15981:
15982:
1.21 crook 15983: @node Origin, Forth-related information, Bugs, Top
15984: @appendix Authors and Ancestors of Gforth
1.1 anton 15985:
15986: @section Authors and Contributors
15987: @cindex authors of Gforth
15988: @cindex contributors to Gforth
15989:
15990: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15991: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15992: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 15993: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
15994: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
15995: and Stuart Ramsden inspired us with their continuous feedback. Lennart
15996: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
15997: working on automatic support for calling C libraries. Helpful comments
15998: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
15999: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16000: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16001: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16002: comments from many others; thank you all, sorry for not listing you
16003: here (but digging through my mailbox to extract your names is on my
16004: to-do list).
1.1 anton 16005:
16006: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16007: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16008: was developed across the Internet, and its authors did not meet
1.20 pazsan 16009: physically for the first 4 years of development.
1.1 anton 16010:
16011: @section Pedigree
1.26 crook 16012: @cindex pedigree of Gforth
1.1 anton 16013:
1.81 anton 16014: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16015: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16016:
1.20 pazsan 16017: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16018: 32 bit native code version of VolksForth for the Atari ST, written
16019: mostly by Dietrich Weineck.
16020:
1.81 anton 16021: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16022: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16023: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16024:
1.147 anton 16025: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16026: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16027:
16028: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16029: 1979. Robert Selzer and Bill Ragsdale developed the original
16030: implementation of fig-Forth for the 6502 based on microForth.
16031:
16032: The principal architect of microForth was Dean Sanderson. microForth was
16033: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16034: the 1802, and subsequently implemented on the 8080, the 6800 and the
16035: Z80.
16036:
16037: All earlier Forth systems were custom-made, usually by Charles Moore,
16038: who discovered (as he puts it) Forth during the late 60s. The first full
16039: Forth existed in 1971.
16040:
1.81 anton 16041: A part of the information in this section comes from
16042: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16043: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16044: Charles H. Moore, presented at the HOPL-II conference and preprinted
16045: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16046: genealogical information about Forth there. For a more general (and
16047: graphical) Forth family tree look see
16048: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16049: Forth Family Tree and Timeline}.
1.1 anton 16050:
1.81 anton 16051: @c ------------------------------------------------------------------
1.113 anton 16052: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16053: @appendix Other Forth-related information
16054: @cindex Forth-related information
16055:
1.81 anton 16056: @c anton: I threw most of this stuff out, because it can be found through
16057: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16058:
16059: @cindex comp.lang.forth
16060: @cindex frequently asked questions
1.81 anton 16061: There is an active news group (comp.lang.forth) discussing Forth
16062: (including Gforth) and Forth-related issues. Its
16063: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16064: (frequently asked questions and their answers) contains a lot of
16065: information on Forth. You should read it before posting to
16066: comp.lang.forth.
1.21 crook 16067:
1.81 anton 16068: The ANS Forth standard is most usable in its
16069: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16070:
1.113 anton 16071: @c ---------------------------------------------------
16072: @node Licenses, Word Index, Forth-related information, Top
16073: @appendix Licenses
16074:
16075: @menu
16076: * GNU Free Documentation License:: License for copying this manual.
16077: * Copying:: GPL (for copying this software).
16078: @end menu
16079:
16080: @include fdl.texi
16081:
16082: @include gpl.texi
16083:
16084:
16085:
1.81 anton 16086: @c ------------------------------------------------------------------
1.113 anton 16087: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16088: @unnumbered Word Index
16089:
1.26 crook 16090: This index is a list of Forth words that have ``glossary'' entries
16091: within this manual. Each word is listed with its stack effect and
16092: wordset.
1.1 anton 16093:
16094: @printindex fn
16095:
1.81 anton 16096: @c anton: the name index seems superfluous given the word and concept indices.
16097:
16098: @c @node Name Index, Concept Index, Word Index, Top
16099: @c @unnumbered Name Index
1.41 anton 16100:
1.81 anton 16101: @c This index is a list of Forth words that have ``glossary'' entries
16102: @c within this manual.
1.41 anton 16103:
1.81 anton 16104: @c @printindex ky
1.41 anton 16105:
1.113 anton 16106: @c -------------------------------------------------------
1.81 anton 16107: @node Concept Index, , Word Index, Top
1.1 anton 16108: @unnumbered Concept and Word Index
16109:
1.26 crook 16110: Not all entries listed in this index are present verbatim in the
16111: text. This index also duplicates, in abbreviated form, all of the words
16112: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16113:
16114: @printindex cp
16115:
16116: @bye
1.81 anton 16117:
16118:
1.1 anton 16119:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>