Annotation of gforth/doc/gforth.ds, revision 1.151
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.113 anton 14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
1.29 crook 21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
1.29 crook 63:
1.142 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.87 anton 177: * Files Tutorial::
1.48 anton 178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
1.29 crook 188:
1.24 anton 189: An Introduction to ANS Forth
190:
1.67 anton 191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
1.24 anton 199:
1.12 anton 200: Forth Words
201:
202: * Notation::
1.65 anton 203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
1.12 anton 206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
1.65 anton 211: * Interpretation and Compilation Semantics::
1.47 crook 212: * Tokens for Words::
1.81 anton 213: * Compiling words::
1.65 anton 214: * The Text Interpreter::
1.111 anton 215: * The Input Stream::
1.65 anton 216: * Word Lists::
217: * Environmental Queries::
1.12 anton 218: * Files::
219: * Blocks::
220: * Other I/O::
1.121 anton 221: * OS command line arguments::
1.78 anton 222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
1.12 anton 225: * Programming Tools::
1.150 anton 226: * C Interface::
1.12 anton 227: * Assembler and Code Words::
228: * Threading Words::
1.65 anton 229: * Passing Commands to the OS::
230: * Keeping track of Time::
231: * Miscellaneous Words::
1.12 anton 232:
233: Arithmetic
234:
235: * Single precision::
1.67 anton 236: * Double precision:: Double-cell integer arithmetic
1.12 anton 237: * Bitwise operations::
1.67 anton 238: * Numeric comparison::
1.32 anton 239: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 240: * Floating Point::
241:
242: Stack Manipulation
243:
244: * Data stack::
245: * Floating point stack::
246: * Return stack::
247: * Locals stack::
248: * Stack pointer manipulation::
249:
250: Memory
251:
1.32 anton 252: * Memory model::
253: * Dictionary allocation::
254: * Heap Allocation::
255: * Memory Access::
256: * Address arithmetic::
257: * Memory Blocks::
1.12 anton 258:
259: Control Structures
260:
1.41 anton 261: * Selection:: IF ... ELSE ... ENDIF
262: * Simple Loops:: BEGIN ...
1.32 anton 263: * Counted Loops:: DO
1.67 anton 264: * Arbitrary control structures::
265: * Calls and returns::
1.12 anton 266: * Exception Handling::
267:
268: Defining Words
269:
1.67 anton 270: * CREATE::
1.44 crook 271: * Variables:: Variables and user variables
1.67 anton 272: * Constants::
1.44 crook 273: * Values:: Initialised variables
1.67 anton 274: * Colon Definitions::
1.44 crook 275: * Anonymous Definitions:: Definitions without names
1.71 anton 276: * Supplying names:: Passing definition names as strings
1.67 anton 277: * User-defined Defining Words::
1.44 crook 278: * Deferred words:: Allow forward references
1.67 anton 279: * Aliases::
1.47 crook 280:
1.63 anton 281: User-defined Defining Words
282:
283: * CREATE..DOES> applications::
284: * CREATE..DOES> details::
285: * Advanced does> usage example::
1.91 anton 286: * @code{Const-does>}::
1.63 anton 287:
1.47 crook 288: Interpretation and Compilation Semantics
289:
1.67 anton 290: * Combined words::
1.12 anton 291:
1.71 anton 292: Tokens for Words
293:
294: * Execution token:: represents execution/interpretation semantics
295: * Compilation token:: represents compilation semantics
296: * Name token:: represents named words
297:
1.82 anton 298: Compiling words
299:
300: * Literals:: Compiling data values
301: * Macros:: Compiling words
302:
1.21 crook 303: The Text Interpreter
304:
1.67 anton 305: * Input Sources::
306: * Number Conversion::
307: * Interpret/Compile states::
308: * Interpreter Directives::
1.21 crook 309:
1.26 crook 310: Word Lists
311:
1.75 anton 312: * Vocabularies::
1.67 anton 313: * Why use word lists?::
1.75 anton 314: * Word list example::
1.26 crook 315:
316: Files
317:
1.48 anton 318: * Forth source files::
319: * General files::
320: * Search Paths::
321:
322: Search Paths
323:
1.75 anton 324: * Source Search Paths::
1.26 crook 325: * General Search Paths::
326:
327: Other I/O
328:
1.32 anton 329: * Simple numeric output:: Predefined formats
330: * Formatted numeric output:: Formatted (pictured) output
331: * String Formats:: How Forth stores strings in memory
1.67 anton 332: * Displaying characters and strings:: Other stuff
1.32 anton 333: * Input:: Input
1.112 anton 334: * Pipes:: How to create your own pipes
1.149 pazsan 335: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 336:
337: Locals
338:
339: * Gforth locals::
340: * ANS Forth locals::
341:
342: Gforth locals
343:
344: * Where are locals visible by name?::
345: * How long do locals live?::
1.78 anton 346: * Locals programming style::
347: * Locals implementation::
1.26 crook 348:
1.12 anton 349: Structures
350:
351: * Why explicit structure support?::
352: * Structure Usage::
353: * Structure Naming Convention::
354: * Structure Implementation::
355: * Structure Glossary::
356:
357: Object-oriented Forth
358:
1.48 anton 359: * Why object-oriented programming?::
360: * Object-Oriented Terminology::
361: * Objects::
362: * OOF::
363: * Mini-OOF::
1.23 crook 364: * Comparison with other object models::
1.12 anton 365:
1.24 anton 366: The @file{objects.fs} model
1.12 anton 367:
368: * Properties of the Objects model::
369: * Basic Objects Usage::
1.41 anton 370: * The Objects base class::
1.12 anton 371: * Creating objects::
372: * Object-Oriented Programming Style::
373: * Class Binding::
374: * Method conveniences::
375: * Classes and Scoping::
1.41 anton 376: * Dividing classes::
1.12 anton 377: * Object Interfaces::
378: * Objects Implementation::
379: * Objects Glossary::
380:
1.24 anton 381: The @file{oof.fs} model
1.12 anton 382:
1.67 anton 383: * Properties of the OOF model::
384: * Basic OOF Usage::
385: * The OOF base class::
386: * Class Declaration::
387: * Class Implementation::
1.12 anton 388:
1.24 anton 389: The @file{mini-oof.fs} model
1.23 crook 390:
1.48 anton 391: * Basic Mini-OOF Usage::
392: * Mini-OOF Example::
393: * Mini-OOF Implementation::
1.23 crook 394:
1.78 anton 395: Programming Tools
396:
1.150 anton 397: * Examining:: Data and Code.
398: * Forgetting words:: Usually before reloading.
1.78 anton 399: * Debugging:: Simple and quick.
400: * Assertions:: Making your programs self-checking.
401: * Singlestep Debugger:: Executing your program word by word.
402:
403: Assembler and Code Words
404:
405: * Code and ;code::
406: * Common Assembler:: Assembler Syntax
407: * Common Disassembler::
408: * 386 Assembler:: Deviations and special cases
409: * Alpha Assembler:: Deviations and special cases
410: * MIPS assembler:: Deviations and special cases
411: * Other assemblers:: How to write them
412:
1.12 anton 413: Tools
414:
415: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 416: * Stack depth changes:: Where does this stack item come from?
1.12 anton 417:
418: ANS conformance
419:
420: * The Core Words::
421: * The optional Block word set::
422: * The optional Double Number word set::
423: * The optional Exception word set::
424: * The optional Facility word set::
425: * The optional File-Access word set::
426: * The optional Floating-Point word set::
427: * The optional Locals word set::
428: * The optional Memory-Allocation word set::
429: * The optional Programming-Tools word set::
430: * The optional Search-Order word set::
431:
432: The Core Words
433:
434: * core-idef:: Implementation Defined Options
435: * core-ambcond:: Ambiguous Conditions
436: * core-other:: Other System Documentation
437:
438: The optional Block word set
439:
440: * block-idef:: Implementation Defined Options
441: * block-ambcond:: Ambiguous Conditions
442: * block-other:: Other System Documentation
443:
444: The optional Double Number word set
445:
446: * double-ambcond:: Ambiguous Conditions
447:
448: The optional Exception word set
449:
450: * exception-idef:: Implementation Defined Options
451:
452: The optional Facility word set
453:
454: * facility-idef:: Implementation Defined Options
455: * facility-ambcond:: Ambiguous Conditions
456:
457: The optional File-Access word set
458:
459: * file-idef:: Implementation Defined Options
460: * file-ambcond:: Ambiguous Conditions
461:
462: The optional Floating-Point word set
463:
464: * floating-idef:: Implementation Defined Options
465: * floating-ambcond:: Ambiguous Conditions
466:
467: The optional Locals word set
468:
469: * locals-idef:: Implementation Defined Options
470: * locals-ambcond:: Ambiguous Conditions
471:
472: The optional Memory-Allocation word set
473:
474: * memory-idef:: Implementation Defined Options
475:
476: The optional Programming-Tools word set
477:
478: * programming-idef:: Implementation Defined Options
479: * programming-ambcond:: Ambiguous Conditions
480:
481: The optional Search-Order word set
482:
483: * search-idef:: Implementation Defined Options
484: * search-ambcond:: Ambiguous Conditions
485:
1.109 anton 486: Emacs and Gforth
487:
488: * Installing gforth.el:: Making Emacs aware of Forth.
489: * Emacs Tags:: Viewing the source of a word in Emacs.
490: * Hilighting:: Making Forth code look prettier.
491: * Auto-Indentation:: Customizing auto-indentation.
492: * Blocks Files:: Reading and writing blocks files.
493:
1.12 anton 494: Image Files
495:
1.24 anton 496: * Image Licensing Issues:: Distribution terms for images.
497: * Image File Background:: Why have image files?
1.67 anton 498: * Non-Relocatable Image Files:: don't always work.
1.24 anton 499: * Data-Relocatable Image Files:: are better.
1.67 anton 500: * Fully Relocatable Image Files:: better yet.
1.24 anton 501: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 502: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 503: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 504:
505: Fully Relocatable Image Files
506:
1.27 crook 507: * gforthmi:: The normal way
1.12 anton 508: * cross.fs:: The hard way
509:
510: Engine
511:
512: * Portability::
513: * Threading::
514: * Primitives::
515: * Performance::
516:
517: Threading
518:
519: * Scheduling::
520: * Direct or Indirect Threaded?::
1.109 anton 521: * Dynamic Superinstructions::
1.12 anton 522: * DOES>::
523:
524: Primitives
525:
526: * Automatic Generation::
527: * TOS Optimization::
528: * Produced code::
1.13 pazsan 529:
530: Cross Compiler
531:
1.67 anton 532: * Using the Cross Compiler::
533: * How the Cross Compiler Works::
1.13 pazsan 534:
1.113 anton 535: Licenses
536:
537: * GNU Free Documentation License:: License for copying this manual.
538: * Copying:: GPL (for copying this software).
539:
1.24 anton 540: @end detailmenu
1.1 anton 541: @end menu
542:
1.113 anton 543: @c ----------------------------------------------------------
1.1 anton 544: @iftex
545: @unnumbered Preface
546: @cindex Preface
1.21 crook 547: This manual documents Gforth. Some introductory material is provided for
548: readers who are unfamiliar with Forth or who are migrating to Gforth
549: from other Forth compilers. However, this manual is primarily a
550: reference manual.
1.1 anton 551: @end iftex
552:
1.28 crook 553: @comment TODO much more blurb here.
1.26 crook 554:
555: @c ******************************************************************
1.113 anton 556: @node Goals, Gforth Environment, Top, Top
1.26 crook 557: @comment node-name, next, previous, up
558: @chapter Goals of Gforth
559: @cindex goals of the Gforth project
560: The goal of the Gforth Project is to develop a standard model for
561: ANS Forth. This can be split into several subgoals:
562:
563: @itemize @bullet
564: @item
565: Gforth should conform to the ANS Forth Standard.
566: @item
567: It should be a model, i.e. it should define all the
568: implementation-dependent things.
569: @item
570: It should become standard, i.e. widely accepted and used. This goal
571: is the most difficult one.
572: @end itemize
573:
574: To achieve these goals Gforth should be
575: @itemize @bullet
576: @item
577: Similar to previous models (fig-Forth, F83)
578: @item
579: Powerful. It should provide for all the things that are considered
580: necessary today and even some that are not yet considered necessary.
581: @item
582: Efficient. It should not get the reputation of being exceptionally
583: slow.
584: @item
585: Free.
586: @item
587: Available on many machines/easy to port.
588: @end itemize
589:
590: Have we achieved these goals? Gforth conforms to the ANS Forth
591: standard. It may be considered a model, but we have not yet documented
592: which parts of the model are stable and which parts we are likely to
593: change. It certainly has not yet become a de facto standard, but it
594: appears to be quite popular. It has some similarities to and some
595: differences from previous models. It has some powerful features, but not
596: yet everything that we envisioned. We certainly have achieved our
1.65 anton 597: execution speed goals (@pxref{Performance})@footnote{However, in 1998
598: the bar was raised when the major commercial Forth vendors switched to
599: native code compilers.}. It is free and available on many machines.
1.29 crook 600:
1.26 crook 601: @c ******************************************************************
1.48 anton 602: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 603: @chapter Gforth Environment
604: @cindex Gforth environment
1.21 crook 605:
1.45 crook 606: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 607: material in this chapter.
1.21 crook 608:
609: @menu
1.29 crook 610: * Invoking Gforth:: Getting in
611: * Leaving Gforth:: Getting out
612: * Command-line editing::
1.48 anton 613: * Environment variables:: that affect how Gforth starts up
1.29 crook 614: * Gforth Files:: What gets installed and where
1.112 anton 615: * Gforth in pipes::
1.48 anton 616: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 617: @end menu
618:
1.49 anton 619: For related information about the creation of images see @ref{Image Files}.
1.29 crook 620:
1.21 crook 621: @comment ----------------------------------------------
1.48 anton 622: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 623: @section Invoking Gforth
624: @cindex invoking Gforth
625: @cindex running Gforth
626: @cindex command-line options
627: @cindex options on the command line
628: @cindex flags on the command line
1.21 crook 629:
1.30 anton 630: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 631: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 632: will usually just say @code{gforth} -- this automatically loads the
633: default image file @file{gforth.fi}. In many other cases the default
634: Gforth image will be invoked like this:
1.21 crook 635: @example
1.30 anton 636: gforth [file | -e forth-code] ...
1.21 crook 637: @end example
1.29 crook 638: @noindent
639: This interprets the contents of the files and the Forth code in the order they
640: are given.
1.21 crook 641:
1.109 anton 642: In addition to the @command{gforth} engine, there is also an engine
643: called @command{gforth-fast}, which is faster, but gives less
644: informative error messages (@pxref{Error messages}) and may catch some
645: stack underflows later or not at all. You should use it for debugged,
646: performance-critical programs.
647:
648: Moreover, there is an engine called @command{gforth-itc}, which is
649: useful in some backwards-compatibility situations (@pxref{Direct or
650: Indirect Threaded?}).
1.30 anton 651:
1.29 crook 652: In general, the command line looks like this:
1.21 crook 653:
654: @example
1.30 anton 655: gforth[-fast] [engine options] [image options]
1.21 crook 656: @end example
657:
1.30 anton 658: The engine options must come before the rest of the command
1.29 crook 659: line. They are:
1.26 crook 660:
1.29 crook 661: @table @code
662: @cindex -i, command-line option
663: @cindex --image-file, command-line option
664: @item --image-file @i{file}
665: @itemx -i @i{file}
666: Loads the Forth image @i{file} instead of the default
667: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 668:
1.39 anton 669: @cindex --appl-image, command-line option
670: @item --appl-image @i{file}
671: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 672: to the image (instead of processing them as engine options). This is
673: useful for building executable application images on Unix, built with
1.39 anton 674: @code{gforthmi --application ...}.
675:
1.29 crook 676: @cindex --path, command-line option
677: @cindex -p, command-line option
678: @item --path @i{path}
679: @itemx -p @i{path}
680: Uses @i{path} for searching the image file and Forth source code files
681: instead of the default in the environment variable @code{GFORTHPATH} or
682: the path specified at installation time (e.g.,
683: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
684: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 685:
1.29 crook 686: @cindex --dictionary-size, command-line option
687: @cindex -m, command-line option
688: @cindex @i{size} parameters for command-line options
689: @cindex size of the dictionary and the stacks
690: @item --dictionary-size @i{size}
691: @itemx -m @i{size}
692: Allocate @i{size} space for the Forth dictionary space instead of
693: using the default specified in the image (typically 256K). The
694: @i{size} specification for this and subsequent options consists of
695: an integer and a unit (e.g.,
696: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
697: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
698: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
699: @code{e} is used.
1.21 crook 700:
1.29 crook 701: @cindex --data-stack-size, command-line option
702: @cindex -d, command-line option
703: @item --data-stack-size @i{size}
704: @itemx -d @i{size}
705: Allocate @i{size} space for the data stack instead of using the
706: default specified in the image (typically 16K).
1.21 crook 707:
1.29 crook 708: @cindex --return-stack-size, command-line option
709: @cindex -r, command-line option
710: @item --return-stack-size @i{size}
711: @itemx -r @i{size}
712: Allocate @i{size} space for the return stack instead of using the
713: default specified in the image (typically 15K).
1.21 crook 714:
1.29 crook 715: @cindex --fp-stack-size, command-line option
716: @cindex -f, command-line option
717: @item --fp-stack-size @i{size}
718: @itemx -f @i{size}
719: Allocate @i{size} space for the floating point stack instead of
720: using the default specified in the image (typically 15.5K). In this case
721: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 722:
1.48 anton 723: @cindex --locals-stack-size, command-line option
724: @cindex -l, command-line option
725: @item --locals-stack-size @i{size}
726: @itemx -l @i{size}
727: Allocate @i{size} space for the locals stack instead of using the
728: default specified in the image (typically 14.5K).
729:
730: @cindex -h, command-line option
731: @cindex --help, command-line option
732: @item --help
733: @itemx -h
734: Print a message about the command-line options
735:
736: @cindex -v, command-line option
737: @cindex --version, command-line option
738: @item --version
739: @itemx -v
740: Print version and exit
741:
742: @cindex --debug, command-line option
743: @item --debug
744: Print some information useful for debugging on startup.
745:
746: @cindex --offset-image, command-line option
747: @item --offset-image
748: Start the dictionary at a slightly different position than would be used
749: otherwise (useful for creating data-relocatable images,
750: @pxref{Data-Relocatable Image Files}).
751:
752: @cindex --no-offset-im, command-line option
753: @item --no-offset-im
754: Start the dictionary at the normal position.
755:
756: @cindex --clear-dictionary, command-line option
757: @item --clear-dictionary
758: Initialize all bytes in the dictionary to 0 before loading the image
759: (@pxref{Data-Relocatable Image Files}).
760:
761: @cindex --die-on-signal, command-line-option
762: @item --die-on-signal
763: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
764: or the segmentation violation SIGSEGV) by translating it into a Forth
765: @code{THROW}. With this option, Gforth exits if it receives such a
766: signal. This option is useful when the engine and/or the image might be
767: severely broken (such that it causes another signal before recovering
768: from the first); this option avoids endless loops in such cases.
1.109 anton 769:
1.119 anton 770: @cindex --no-dynamic, command-line option
771: @cindex --dynamic, command-line option
1.109 anton 772: @item --no-dynamic
773: @item --dynamic
774: Disable or enable dynamic superinstructions with replication
775: (@pxref{Dynamic Superinstructions}).
776:
1.119 anton 777: @cindex --no-super, command-line option
1.109 anton 778: @item --no-super
1.110 anton 779: Disable dynamic superinstructions, use just dynamic replication; this is
780: useful if you want to patch threaded code (@pxref{Dynamic
781: Superinstructions}).
1.119 anton 782:
783: @cindex --ss-number, command-line option
784: @item --ss-number=@var{N}
785: Use only the first @var{N} static superinstructions compiled into the
786: engine (default: use them all; note that only @code{gforth-fast} has
787: any). This option is useful for measuring the performance impact of
788: static superinstructions.
789:
790: @cindex --ss-min-..., command-line options
791: @item --ss-min-codesize
792: @item --ss-min-ls
793: @item --ss-min-lsu
794: @item --ss-min-nexts
795: Use specified metric for determining the cost of a primitive or static
796: superinstruction for static superinstruction selection. @code{Codesize}
797: is the native code size of the primive or static superinstruction,
798: @code{ls} is the number of loads and stores, @code{lsu} is the number of
799: loads, stores, and updates, and @code{nexts} is the number of dispatches
800: (not taking dynamic superinstructions into account), i.e. every
801: primitive or static superinstruction has cost 1. Default:
802: @code{codesize} if you use dynamic code generation, otherwise
803: @code{nexts}.
804:
805: @cindex --ss-greedy, command-line option
806: @item --ss-greedy
807: This option is useful for measuring the performance impact of static
808: superinstructions. By default, an optimal shortest-path algorithm is
809: used for selecting static superinstructions. With @option{--ss-greedy}
810: this algorithm is modified to assume that anything after the static
811: superinstruction currently under consideration is not combined into
812: static superinstructions. With @option{--ss-min-nexts} this produces
813: the same result as a greedy algorithm that always selects the longest
814: superinstruction available at the moment. E.g., if there are
815: superinstructions AB and BCD, then for the sequence A B C D the optimal
816: algorithm will select A BCD and the greedy algorithm will select AB C D.
817:
818: @cindex --print-metrics, command-line option
819: @item --print-metrics
820: Prints some metrics used during static superinstruction selection:
821: @code{code size} is the actual size of the dynamically generated code.
822: @code{Metric codesize} is the sum of the codesize metrics as seen by
823: static superinstruction selection; there is a difference from @code{code
824: size}, because not all primitives and static superinstructions are
825: compiled into dynamically generated code, and because of markers. The
826: other metrics correspond to the @option{ss-min-...} options. This
827: option is useful for evaluating the effects of the @option{--ss-...}
828: options.
1.109 anton 829:
1.48 anton 830: @end table
831:
832: @cindex loading files at startup
833: @cindex executing code on startup
834: @cindex batch processing with Gforth
835: As explained above, the image-specific command-line arguments for the
836: default image @file{gforth.fi} consist of a sequence of filenames and
837: @code{-e @var{forth-code}} options that are interpreted in the sequence
838: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 839: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
840: option takes only one argument; if you want to evaluate more Forth
841: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 842: after processing the command line (instead of entering interactive mode)
1.121 anton 843: append @code{-e bye} to the command line. You can also process the
844: command-line arguments with a Forth program (@pxref{OS command line
845: arguments}).
1.48 anton 846:
847: @cindex versions, invoking other versions of Gforth
848: If you have several versions of Gforth installed, @code{gforth} will
849: invoke the version that was installed last. @code{gforth-@i{version}}
850: invokes a specific version. If your environment contains the variable
851: @code{GFORTHPATH}, you may want to override it by using the
852: @code{--path} option.
853:
854: Not yet implemented:
855: On startup the system first executes the system initialization file
856: (unless the option @code{--no-init-file} is given; note that the system
857: resulting from using this option may not be ANS Forth conformant). Then
858: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 859: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 860: then in @file{~}, then in the normal path (see above).
861:
862:
863:
864: @comment ----------------------------------------------
865: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
866: @section Leaving Gforth
867: @cindex Gforth - leaving
868: @cindex leaving Gforth
869:
870: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
871: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
872: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 873: data are discarded. For ways of saving the state of the system before
874: leaving Gforth see @ref{Image Files}.
1.48 anton 875:
876: doc-bye
877:
878:
879: @comment ----------------------------------------------
1.65 anton 880: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 881: @section Command-line editing
882: @cindex command-line editing
883:
884: Gforth maintains a history file that records every line that you type to
885: the text interpreter. This file is preserved between sessions, and is
886: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
887: repeatedly you can recall successively older commands from this (or
888: previous) session(s). The full list of command-line editing facilities is:
889:
890: @itemize @bullet
891: @item
892: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
893: commands from the history buffer.
894: @item
895: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
896: from the history buffer.
897: @item
898: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
899: @item
900: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
901: @item
902: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
903: closing up the line.
904: @item
905: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
906: @item
907: @kbd{Ctrl-a} to move the cursor to the start of the line.
908: @item
909: @kbd{Ctrl-e} to move the cursor to the end of the line.
910: @item
911: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
912: line.
913: @item
914: @key{TAB} to step through all possible full-word completions of the word
915: currently being typed.
916: @item
1.65 anton 917: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
918: using @code{bye}).
919: @item
920: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
921: character under the cursor.
1.48 anton 922: @end itemize
923:
924: When editing, displayable characters are inserted to the left of the
925: cursor position; the line is always in ``insert'' (as opposed to
926: ``overstrike'') mode.
927:
928: @cindex history file
929: @cindex @file{.gforth-history}
930: On Unix systems, the history file is @file{~/.gforth-history} by
931: default@footnote{i.e. it is stored in the user's home directory.}. You
932: can find out the name and location of your history file using:
933:
934: @example
935: history-file type \ Unix-class systems
936:
937: history-file type \ Other systems
938: history-dir type
939: @end example
940:
941: If you enter long definitions by hand, you can use a text editor to
942: paste them out of the history file into a Forth source file for reuse at
943: a later time.
944:
945: Gforth never trims the size of the history file, so you should do this
946: periodically, if necessary.
947:
948: @comment this is all defined in history.fs
949: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
950: @comment chosen?
951:
952:
953: @comment ----------------------------------------------
1.65 anton 954: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 955: @section Environment variables
956: @cindex environment variables
957:
958: Gforth uses these environment variables:
959:
960: @itemize @bullet
961: @item
962: @cindex @code{GFORTHHIST} -- environment variable
963: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
964: open/create the history file, @file{.gforth-history}. Default:
965: @code{$HOME}.
966:
967: @item
968: @cindex @code{GFORTHPATH} -- environment variable
969: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
970: for Forth source-code files.
971:
972: @item
1.147 anton 973: @cindex @code{LANG} -- environment variable
974: @code{LANG} -- see @code{LC_CTYPE}
975:
976: @item
977: @cindex @code{LC_ALL} -- environment variable
978: @code{LC_ALL} -- see @code{LC_CTYPE}
979:
980: @item
981: @cindex @code{LC_CTYPE} -- environment variable
982: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
983: startup, Gforth uses the UTF-8 encoding for strings internally and
984: expects its input and produces its output in UTF-8 encoding, otherwise
985: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
986: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
987: that is unset, in @code{LANG}.
988:
989: @item
1.129 anton 990: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
991:
992: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
993: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 994: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 995: and the command are directly concatenated, so if a space between them is
996: necessary, append it to the prefix.
997:
998: @item
1.48 anton 999: @cindex @code{GFORTH} -- environment variable
1.49 anton 1000: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1001:
1002: @item
1003: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1004: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1005:
1006: @item
1007: @cindex @code{TMP}, @code{TEMP} - environment variable
1008: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1009: location for the history file.
1010: @end itemize
1011:
1012: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1013: @comment mentioning these.
1014:
1015: All the Gforth environment variables default to sensible values if they
1016: are not set.
1017:
1018:
1019: @comment ----------------------------------------------
1.112 anton 1020: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1021: @section Gforth files
1022: @cindex Gforth files
1023:
1024: When you install Gforth on a Unix system, it installs files in these
1025: locations by default:
1026:
1027: @itemize @bullet
1028: @item
1029: @file{/usr/local/bin/gforth}
1030: @item
1031: @file{/usr/local/bin/gforthmi}
1032: @item
1033: @file{/usr/local/man/man1/gforth.1} - man page.
1034: @item
1035: @file{/usr/local/info} - the Info version of this manual.
1036: @item
1037: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1038: @item
1039: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1040: @item
1041: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1042: @item
1043: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1044: @end itemize
1045:
1046: You can select different places for installation by using
1047: @code{configure} options (listed with @code{configure --help}).
1048:
1049: @comment ----------------------------------------------
1.112 anton 1050: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1051: @section Gforth in pipes
1052: @cindex pipes, Gforth as part of
1053:
1054: Gforth can be used in pipes created elsewhere (described here). It can
1055: also create pipes on its own (@pxref{Pipes}).
1056:
1057: @cindex input from pipes
1058: If you pipe into Gforth, your program should read with @code{read-file}
1059: or @code{read-line} from @code{stdin} (@pxref{General files}).
1060: @code{Key} does not recognize the end of input. Words like
1061: @code{accept} echo the input and are therefore usually not useful for
1062: reading from a pipe. You have to invoke the Forth program with an OS
1063: command-line option, as you have no chance to use the Forth command line
1064: (the text interpreter would try to interpret the pipe input).
1065:
1066: @cindex output in pipes
1067: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1068:
1069: @cindex silent exiting from Gforth
1070: When you write to a pipe that has been closed at the other end, Gforth
1071: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1072: into the exception @code{broken-pipe-error}. If your application does
1073: not catch that exception, the system catches it and exits, usually
1074: silently (unless you were working on the Forth command line; then it
1075: prints an error message and exits). This is usually the desired
1076: behaviour.
1077:
1078: If you do not like this behaviour, you have to catch the exception
1079: yourself, and react to it.
1080:
1081: Here's an example of an invocation of Gforth that is usable in a pipe:
1082:
1083: @example
1084: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1085: type repeat ; foo bye"
1086: @end example
1087:
1088: This example just copies the input verbatim to the output. A very
1089: simple pipe containing this example looks like this:
1090:
1091: @example
1092: cat startup.fs |
1093: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1094: type repeat ; foo bye"|
1095: head
1096: @end example
1097:
1098: @cindex stderr and pipes
1099: Pipes involving Gforth's @code{stderr} output do not work.
1100:
1101: @comment ----------------------------------------------
1102: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1103: @section Startup speed
1104: @cindex Startup speed
1105: @cindex speed, startup
1106:
1107: If Gforth is used for CGI scripts or in shell scripts, its startup
1108: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1109: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1110: system time.
1111:
1112: If startup speed is a problem, you may consider the following ways to
1113: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1114: (for example, by using Fast-CGI).
1.48 anton 1115:
1.112 anton 1116: An easy step that influences Gforth startup speed is the use of the
1117: @option{--no-dynamic} option; this decreases image loading speed, but
1118: increases compile-time and run-time.
1119:
1120: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1121: building it with @code{XLDFLAGS=-static}. This requires more memory for
1122: the code and will therefore slow down the first invocation, but
1123: subsequent invocations avoid the dynamic linking overhead. Another
1124: disadvantage is that Gforth won't profit from library upgrades. As a
1125: result, @code{gforth-static -e bye} takes about 17.1ms user and
1126: 8.2ms system time.
1127:
1128: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1129: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1130: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1131: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1132: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1133: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1134: address for the dictionary, for whatever reason; so you better provide a
1135: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1136: bye} takes about 15.3ms user and 7.5ms system time.
1137:
1138: The final step is to disable dictionary hashing in Gforth. Gforth
1139: builds the hash table on startup, which takes much of the startup
1140: overhead. You can do this by commenting out the @code{include hash.fs}
1141: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1142: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1143: The disadvantages are that functionality like @code{table} and
1144: @code{ekey} is missing and that text interpretation (e.g., compiling)
1145: now takes much longer. So, you should only use this method if there is
1146: no significant text interpretation to perform (the script should be
1.62 crook 1147: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1148: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1149:
1150: @c ******************************************************************
1151: @node Tutorial, Introduction, Gforth Environment, Top
1152: @chapter Forth Tutorial
1153: @cindex Tutorial
1154: @cindex Forth Tutorial
1155:
1.67 anton 1156: @c Topics from nac's Introduction that could be mentioned:
1157: @c press <ret> after each line
1158: @c Prompt
1159: @c numbers vs. words in dictionary on text interpretation
1160: @c what happens on redefinition
1161: @c parsing words (in particular, defining words)
1162:
1.83 anton 1163: The difference of this chapter from the Introduction
1164: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1165: be used while sitting in front of a computer, and covers much more
1166: material, but does not explain how the Forth system works.
1167:
1.62 crook 1168: This tutorial can be used with any ANS-compliant Forth; any
1169: Gforth-specific features are marked as such and you can skip them if you
1170: work with another Forth. This tutorial does not explain all features of
1171: Forth, just enough to get you started and give you some ideas about the
1172: facilities available in Forth. Read the rest of the manual and the
1173: standard when you are through this.
1.48 anton 1174:
1175: The intended way to use this tutorial is that you work through it while
1176: sitting in front of the console, take a look at the examples and predict
1177: what they will do, then try them out; if the outcome is not as expected,
1178: find out why (e.g., by trying out variations of the example), so you
1179: understand what's going on. There are also some assignments that you
1180: should solve.
1181:
1182: This tutorial assumes that you have programmed before and know what,
1183: e.g., a loop is.
1184:
1185: @c !! explain compat library
1186:
1187: @menu
1188: * Starting Gforth Tutorial::
1189: * Syntax Tutorial::
1190: * Crash Course Tutorial::
1191: * Stack Tutorial::
1192: * Arithmetics Tutorial::
1193: * Stack Manipulation Tutorial::
1194: * Using files for Forth code Tutorial::
1195: * Comments Tutorial::
1196: * Colon Definitions Tutorial::
1197: * Decompilation Tutorial::
1198: * Stack-Effect Comments Tutorial::
1199: * Types Tutorial::
1200: * Factoring Tutorial::
1201: * Designing the stack effect Tutorial::
1202: * Local Variables Tutorial::
1203: * Conditional execution Tutorial::
1204: * Flags and Comparisons Tutorial::
1205: * General Loops Tutorial::
1206: * Counted loops Tutorial::
1207: * Recursion Tutorial::
1208: * Leaving definitions or loops Tutorial::
1209: * Return Stack Tutorial::
1210: * Memory Tutorial::
1211: * Characters and Strings Tutorial::
1212: * Alignment Tutorial::
1.87 anton 1213: * Files Tutorial::
1.48 anton 1214: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1215: * Execution Tokens Tutorial::
1216: * Exceptions Tutorial::
1217: * Defining Words Tutorial::
1218: * Arrays and Records Tutorial::
1219: * POSTPONE Tutorial::
1220: * Literal Tutorial::
1221: * Advanced macros Tutorial::
1222: * Compilation Tokens Tutorial::
1223: * Wordlists and Search Order Tutorial::
1224: @end menu
1225:
1226: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1227: @section Starting Gforth
1.66 anton 1228: @cindex starting Gforth tutorial
1.48 anton 1229: You can start Gforth by typing its name:
1230:
1231: @example
1232: gforth
1233: @end example
1234:
1235: That puts you into interactive mode; you can leave Gforth by typing
1236: @code{bye}. While in Gforth, you can edit the command line and access
1237: the command line history with cursor keys, similar to bash.
1238:
1239:
1240: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1241: @section Syntax
1.66 anton 1242: @cindex syntax tutorial
1.48 anton 1243:
1244: A @dfn{word} is a sequence of arbitrary characters (expcept white
1245: space). Words are separated by white space. E.g., each of the
1246: following lines contains exactly one word:
1247:
1248: @example
1249: word
1250: !@@#$%^&*()
1251: 1234567890
1252: 5!a
1253: @end example
1254:
1255: A frequent beginner's error is to leave away necessary white space,
1256: resulting in an error like @samp{Undefined word}; so if you see such an
1257: error, check if you have put spaces wherever necessary.
1258:
1259: @example
1260: ." hello, world" \ correct
1261: ."hello, world" \ gives an "Undefined word" error
1262: @end example
1263:
1.65 anton 1264: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1265: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1266: your system is case-sensitive, you may have to type all the examples
1267: given here in upper case.
1268:
1269:
1270: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1271: @section Crash Course
1272:
1273: Type
1274:
1275: @example
1276: 0 0 !
1277: here execute
1278: ' catch >body 20 erase abort
1279: ' (quit) >body 20 erase
1280: @end example
1281:
1282: The last two examples are guaranteed to destroy parts of Gforth (and
1283: most other systems), so you better leave Gforth afterwards (if it has
1284: not finished by itself). On some systems you may have to kill gforth
1285: from outside (e.g., in Unix with @code{kill}).
1286:
1287: Now that you know how to produce crashes (and that there's not much to
1288: them), let's learn how to produce meaningful programs.
1289:
1290:
1291: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1292: @section Stack
1.66 anton 1293: @cindex stack tutorial
1.48 anton 1294:
1295: The most obvious feature of Forth is the stack. When you type in a
1296: number, it is pushed on the stack. You can display the content of the
1297: stack with @code{.s}.
1298:
1299: @example
1300: 1 2 .s
1301: 3 .s
1302: @end example
1303:
1304: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1305: appear in @code{.s} output as they appeared in the input.
1306:
1307: You can print the top of stack element with @code{.}.
1308:
1309: @example
1310: 1 2 3 . . .
1311: @end example
1312:
1313: In general, words consume their stack arguments (@code{.s} is an
1314: exception).
1315:
1.141 anton 1316: @quotation Assignment
1.48 anton 1317: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1318: @end quotation
1.48 anton 1319:
1320:
1321: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1322: @section Arithmetics
1.66 anton 1323: @cindex arithmetics tutorial
1.48 anton 1324:
1325: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1326: operate on the top two stack items:
1327:
1328: @example
1.67 anton 1329: 2 2 .s
1330: + .s
1331: .
1.48 anton 1332: 2 1 - .
1333: 7 3 mod .
1334: @end example
1335:
1336: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1337: as in the corresponding infix expression (this is generally the case in
1338: Forth).
1339:
1340: Parentheses are superfluous (and not available), because the order of
1341: the words unambiguously determines the order of evaluation and the
1342: operands:
1343:
1344: @example
1345: 3 4 + 5 * .
1346: 3 4 5 * + .
1347: @end example
1348:
1.141 anton 1349: @quotation Assignment
1.48 anton 1350: What are the infix expressions corresponding to the Forth code above?
1351: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1352: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1353: @end quotation
1.48 anton 1354:
1355: To change the sign, use @code{negate}:
1356:
1357: @example
1358: 2 negate .
1359: @end example
1360:
1.141 anton 1361: @quotation Assignment
1.48 anton 1362: Convert -(-3)*4-5 to Forth.
1.141 anton 1363: @end quotation
1.48 anton 1364:
1365: @code{/mod} performs both @code{/} and @code{mod}.
1366:
1367: @example
1368: 7 3 /mod . .
1369: @end example
1370:
1.66 anton 1371: Reference: @ref{Arithmetic}.
1372:
1373:
1.48 anton 1374: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1375: @section Stack Manipulation
1.66 anton 1376: @cindex stack manipulation tutorial
1.48 anton 1377:
1378: Stack manipulation words rearrange the data on the stack.
1379:
1380: @example
1381: 1 .s drop .s
1382: 1 .s dup .s drop drop .s
1383: 1 2 .s over .s drop drop drop
1384: 1 2 .s swap .s drop drop
1385: 1 2 3 .s rot .s drop drop drop
1386: @end example
1387:
1388: These are the most important stack manipulation words. There are also
1389: variants that manipulate twice as many stack items:
1390:
1391: @example
1392: 1 2 3 4 .s 2swap .s 2drop 2drop
1393: @end example
1394:
1395: Two more stack manipulation words are:
1396:
1397: @example
1398: 1 2 .s nip .s drop
1399: 1 2 .s tuck .s 2drop drop
1400: @end example
1401:
1.141 anton 1402: @quotation Assignment
1.48 anton 1403: Replace @code{nip} and @code{tuck} with combinations of other stack
1404: manipulation words.
1405:
1406: @example
1407: Given: How do you get:
1408: 1 2 3 3 2 1
1409: 1 2 3 1 2 3 2
1410: 1 2 3 1 2 3 3
1411: 1 2 3 1 3 3
1412: 1 2 3 2 1 3
1413: 1 2 3 4 4 3 2 1
1414: 1 2 3 1 2 3 1 2 3
1415: 1 2 3 4 1 2 3 4 1 2
1416: 1 2 3
1417: 1 2 3 1 2 3 4
1418: 1 2 3 1 3
1419: @end example
1.141 anton 1420: @end quotation
1.48 anton 1421:
1422: @example
1423: 5 dup * .
1424: @end example
1425:
1.141 anton 1426: @quotation Assignment
1.48 anton 1427: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1428: Write a piece of Forth code that expects two numbers on the stack
1429: (@var{a} and @var{b}, with @var{b} on top) and computes
1430: @code{(a-b)(a+1)}.
1.141 anton 1431: @end quotation
1.48 anton 1432:
1.66 anton 1433: Reference: @ref{Stack Manipulation}.
1434:
1435:
1.48 anton 1436: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1437: @section Using files for Forth code
1.66 anton 1438: @cindex loading Forth code, tutorial
1439: @cindex files containing Forth code, tutorial
1.48 anton 1440:
1441: While working at the Forth command line is convenient for one-line
1442: examples and short one-off code, you probably want to store your source
1443: code in files for convenient editing and persistence. You can use your
1444: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1445: Gforth}) to create @var{file.fs} and use
1.48 anton 1446:
1447: @example
1.102 anton 1448: s" @var{file.fs}" included
1.48 anton 1449: @end example
1450:
1451: to load it into your Forth system. The file name extension I use for
1452: Forth files is @samp{.fs}.
1453:
1454: You can easily start Gforth with some files loaded like this:
1455:
1456: @example
1.102 anton 1457: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1458: @end example
1459:
1460: If an error occurs during loading these files, Gforth terminates,
1461: whereas an error during @code{INCLUDED} within Gforth usually gives you
1462: a Gforth command line. Starting the Forth system every time gives you a
1463: clean start every time, without interference from the results of earlier
1464: tries.
1465:
1466: I often put all the tests in a file, then load the code and run the
1467: tests with
1468:
1469: @example
1.102 anton 1470: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1471: @end example
1472:
1473: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1474: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1475: restart this command without ado.
1476:
1477: The advantage of this approach is that the tests can be repeated easily
1478: every time the program ist changed, making it easy to catch bugs
1479: introduced by the change.
1480:
1.66 anton 1481: Reference: @ref{Forth source files}.
1482:
1.48 anton 1483:
1484: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1485: @section Comments
1.66 anton 1486: @cindex comments tutorial
1.48 anton 1487:
1488: @example
1489: \ That's a comment; it ends at the end of the line
1490: ( Another comment; it ends here: ) .s
1491: @end example
1492:
1493: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1494: separated with white space from the following text.
1495:
1496: @example
1497: \This gives an "Undefined word" error
1498: @end example
1499:
1500: The first @code{)} ends a comment started with @code{(}, so you cannot
1501: nest @code{(}-comments; and you cannot comment out text containing a
1502: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1503: avoid @code{)} in word names.}.
1504:
1505: I use @code{\}-comments for descriptive text and for commenting out code
1506: of one or more line; I use @code{(}-comments for describing the stack
1507: effect, the stack contents, or for commenting out sub-line pieces of
1508: code.
1509:
1510: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1511: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1512: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1513: with @kbd{M-q}.
1514:
1.66 anton 1515: Reference: @ref{Comments}.
1516:
1.48 anton 1517:
1518: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1519: @section Colon Definitions
1.66 anton 1520: @cindex colon definitions, tutorial
1521: @cindex definitions, tutorial
1522: @cindex procedures, tutorial
1523: @cindex functions, tutorial
1.48 anton 1524:
1525: are similar to procedures and functions in other programming languages.
1526:
1527: @example
1528: : squared ( n -- n^2 )
1529: dup * ;
1530: 5 squared .
1531: 7 squared .
1532: @end example
1533:
1534: @code{:} starts the colon definition; its name is @code{squared}. The
1535: following comment describes its stack effect. The words @code{dup *}
1536: are not executed, but compiled into the definition. @code{;} ends the
1537: colon definition.
1538:
1539: The newly-defined word can be used like any other word, including using
1540: it in other definitions:
1541:
1542: @example
1543: : cubed ( n -- n^3 )
1544: dup squared * ;
1545: -5 cubed .
1546: : fourth-power ( n -- n^4 )
1547: squared squared ;
1548: 3 fourth-power .
1549: @end example
1550:
1.141 anton 1551: @quotation Assignment
1.48 anton 1552: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1553: @code{/mod} in terms of other Forth words, and check if they work (hint:
1554: test your tests on the originals first). Don't let the
1555: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1556: @end quotation
1.48 anton 1557:
1.66 anton 1558: Reference: @ref{Colon Definitions}.
1559:
1.48 anton 1560:
1561: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1562: @section Decompilation
1.66 anton 1563: @cindex decompilation tutorial
1564: @cindex see tutorial
1.48 anton 1565:
1566: You can decompile colon definitions with @code{see}:
1567:
1568: @example
1569: see squared
1570: see cubed
1571: @end example
1572:
1573: In Gforth @code{see} shows you a reconstruction of the source code from
1574: the executable code. Informations that were present in the source, but
1575: not in the executable code, are lost (e.g., comments).
1576:
1.65 anton 1577: You can also decompile the predefined words:
1578:
1579: @example
1580: see .
1581: see +
1582: @end example
1583:
1584:
1.48 anton 1585: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1586: @section Stack-Effect Comments
1.66 anton 1587: @cindex stack-effect comments, tutorial
1588: @cindex --, tutorial
1.48 anton 1589: By convention the comment after the name of a definition describes the
1590: stack effect: The part in from of the @samp{--} describes the state of
1591: the stack before the execution of the definition, i.e., the parameters
1592: that are passed into the colon definition; the part behind the @samp{--}
1593: is the state of the stack after the execution of the definition, i.e.,
1594: the results of the definition. The stack comment only shows the top
1595: stack items that the definition accesses and/or changes.
1596:
1597: You should put a correct stack effect on every definition, even if it is
1598: just @code{( -- )}. You should also add some descriptive comment to
1599: more complicated words (I usually do this in the lines following
1600: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1601: you have to work through every definition before you can understand
1.48 anton 1602: any).
1603:
1.141 anton 1604: @quotation Assignment
1.48 anton 1605: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1606: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1607: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1608: are done, you can compare your stack effects to those in this manual
1.48 anton 1609: (@pxref{Word Index}).
1.141 anton 1610: @end quotation
1.48 anton 1611:
1612: Sometimes programmers put comments at various places in colon
1613: definitions that describe the contents of the stack at that place (stack
1614: comments); i.e., they are like the first part of a stack-effect
1615: comment. E.g.,
1616:
1617: @example
1618: : cubed ( n -- n^3 )
1619: dup squared ( n n^2 ) * ;
1620: @end example
1621:
1622: In this case the stack comment is pretty superfluous, because the word
1623: is simple enough. If you think it would be a good idea to add such a
1624: comment to increase readability, you should also consider factoring the
1625: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1626: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1627: however, if you decide not to refactor it, then having such a comment is
1628: better than not having it.
1629:
1630: The names of the stack items in stack-effect and stack comments in the
1631: standard, in this manual, and in many programs specify the type through
1632: a type prefix, similar to Fortran and Hungarian notation. The most
1633: frequent prefixes are:
1634:
1635: @table @code
1636: @item n
1637: signed integer
1638: @item u
1639: unsigned integer
1640: @item c
1641: character
1642: @item f
1643: Boolean flags, i.e. @code{false} or @code{true}.
1644: @item a-addr,a-
1645: Cell-aligned address
1646: @item c-addr,c-
1647: Char-aligned address (note that a Char may have two bytes in Windows NT)
1648: @item xt
1649: Execution token, same size as Cell
1650: @item w,x
1651: Cell, can contain an integer or an address. It usually takes 32, 64 or
1652: 16 bits (depending on your platform and Forth system). A cell is more
1653: commonly known as machine word, but the term @emph{word} already means
1654: something different in Forth.
1655: @item d
1656: signed double-cell integer
1657: @item ud
1658: unsigned double-cell integer
1659: @item r
1660: Float (on the FP stack)
1661: @end table
1662:
1663: You can find a more complete list in @ref{Notation}.
1664:
1.141 anton 1665: @quotation Assignment
1.48 anton 1666: Write stack-effect comments for all definitions you have written up to
1667: now.
1.141 anton 1668: @end quotation
1.48 anton 1669:
1670:
1671: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1672: @section Types
1.66 anton 1673: @cindex types tutorial
1.48 anton 1674:
1675: In Forth the names of the operations are not overloaded; so similar
1676: operations on different types need different names; e.g., @code{+} adds
1677: integers, and you have to use @code{f+} to add floating-point numbers.
1678: The following prefixes are often used for related operations on
1679: different types:
1680:
1681: @table @code
1682: @item (none)
1683: signed integer
1684: @item u
1685: unsigned integer
1686: @item c
1687: character
1688: @item d
1689: signed double-cell integer
1690: @item ud, du
1691: unsigned double-cell integer
1692: @item 2
1693: two cells (not-necessarily double-cell numbers)
1694: @item m, um
1695: mixed single-cell and double-cell operations
1696: @item f
1697: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1698: and @samp{r} represents FP numbers).
1.48 anton 1699: @end table
1700:
1701: If there are no differences between the signed and the unsigned variant
1702: (e.g., for @code{+}), there is only the prefix-less variant.
1703:
1704: Forth does not perform type checking, neither at compile time, nor at
1705: run time. If you use the wrong oeration, the data are interpreted
1706: incorrectly:
1707:
1708: @example
1709: -1 u.
1710: @end example
1711:
1712: If you have only experience with type-checked languages until now, and
1713: have heard how important type-checking is, don't panic! In my
1714: experience (and that of other Forthers), type errors in Forth code are
1715: usually easy to find (once you get used to it), the increased vigilance
1716: of the programmer tends to catch some harder errors in addition to most
1717: type errors, and you never have to work around the type system, so in
1718: most situations the lack of type-checking seems to be a win (projects to
1719: add type checking to Forth have not caught on).
1720:
1721:
1722: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1723: @section Factoring
1.66 anton 1724: @cindex factoring tutorial
1.48 anton 1725:
1726: If you try to write longer definitions, you will soon find it hard to
1727: keep track of the stack contents. Therefore, good Forth programmers
1728: tend to write only short definitions (e.g., three lines). The art of
1729: finding meaningful short definitions is known as factoring (as in
1730: factoring polynomials).
1731:
1732: Well-factored programs offer additional advantages: smaller, more
1733: general words, are easier to test and debug and can be reused more and
1734: better than larger, specialized words.
1735:
1736: So, if you run into difficulties with stack management, when writing
1737: code, try to define meaningful factors for the word, and define the word
1738: in terms of those. Even if a factor contains only two words, it is
1739: often helpful.
1740:
1.65 anton 1741: Good factoring is not easy, and it takes some practice to get the knack
1742: for it; but even experienced Forth programmers often don't find the
1743: right solution right away, but only when rewriting the program. So, if
1744: you don't come up with a good solution immediately, keep trying, don't
1745: despair.
1.48 anton 1746:
1747: @c example !!
1748:
1749:
1750: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1751: @section Designing the stack effect
1.66 anton 1752: @cindex Stack effect design, tutorial
1753: @cindex design of stack effects, tutorial
1.48 anton 1754:
1755: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1756: function; and since there is only one result, you don't have to deal with
1.48 anton 1757: the order of results, either.
1758:
1.117 anton 1759: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1760: parameter and result order of a definition is important and should be
1761: designed well. The general guideline is to design the stack effect such
1762: that the word is simple to use in most cases, even if that complicates
1763: the implementation of the word. Some concrete rules are:
1764:
1765: @itemize @bullet
1766:
1767: @item
1768: Words consume all of their parameters (e.g., @code{.}).
1769:
1770: @item
1771: If there is a convention on the order of parameters (e.g., from
1772: mathematics or another programming language), stick with it (e.g.,
1773: @code{-}).
1774:
1775: @item
1776: If one parameter usually requires only a short computation (e.g., it is
1777: a constant), pass it on the top of the stack. Conversely, parameters
1778: that usually require a long sequence of code to compute should be passed
1779: as the bottom (i.e., first) parameter. This makes the code easier to
1780: read, because reader does not need to keep track of the bottom item
1781: through a long sequence of code (or, alternatively, through stack
1.49 anton 1782: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1783: address on top of the stack because it is usually simpler to compute
1784: than the stored value (often the address is just a variable).
1785:
1786: @item
1787: Similarly, results that are usually consumed quickly should be returned
1788: on the top of stack, whereas a result that is often used in long
1789: computations should be passed as bottom result. E.g., the file words
1790: like @code{open-file} return the error code on the top of stack, because
1791: it is usually consumed quickly by @code{throw}; moreover, the error code
1792: has to be checked before doing anything with the other results.
1793:
1794: @end itemize
1795:
1796: These rules are just general guidelines, don't lose sight of the overall
1797: goal to make the words easy to use. E.g., if the convention rule
1798: conflicts with the computation-length rule, you might decide in favour
1799: of the convention if the word will be used rarely, and in favour of the
1800: computation-length rule if the word will be used frequently (because
1801: with frequent use the cost of breaking the computation-length rule would
1802: be quite high, and frequent use makes it easier to remember an
1803: unconventional order).
1804:
1805: @c example !! structure package
1806:
1.65 anton 1807:
1.48 anton 1808: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1809: @section Local Variables
1.66 anton 1810: @cindex local variables, tutorial
1.48 anton 1811:
1812: You can define local variables (@emph{locals}) in a colon definition:
1813:
1814: @example
1815: : swap @{ a b -- b a @}
1816: b a ;
1817: 1 2 swap .s 2drop
1818: @end example
1819:
1820: (If your Forth system does not support this syntax, include
1821: @file{compat/anslocals.fs} first).
1822:
1823: In this example @code{@{ a b -- b a @}} is the locals definition; it
1824: takes two cells from the stack, puts the top of stack in @code{b} and
1825: the next stack element in @code{a}. @code{--} starts a comment ending
1826: with @code{@}}. After the locals definition, using the name of the
1827: local will push its value on the stack. You can leave the comment
1828: part (@code{-- b a}) away:
1829:
1830: @example
1831: : swap ( x1 x2 -- x2 x1 )
1832: @{ a b @} b a ;
1833: @end example
1834:
1835: In Gforth you can have several locals definitions, anywhere in a colon
1836: definition; in contrast, in a standard program you can have only one
1837: locals definition per colon definition, and that locals definition must
1838: be outside any controll structure.
1839:
1840: With locals you can write slightly longer definitions without running
1841: into stack trouble. However, I recommend trying to write colon
1842: definitions without locals for exercise purposes to help you gain the
1843: essential factoring skills.
1844:
1.141 anton 1845: @quotation Assignment
1.48 anton 1846: Rewrite your definitions until now with locals
1.141 anton 1847: @end quotation
1.48 anton 1848:
1.66 anton 1849: Reference: @ref{Locals}.
1850:
1.48 anton 1851:
1852: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1853: @section Conditional execution
1.66 anton 1854: @cindex conditionals, tutorial
1855: @cindex if, tutorial
1.48 anton 1856:
1857: In Forth you can use control structures only inside colon definitions.
1858: An @code{if}-structure looks like this:
1859:
1860: @example
1861: : abs ( n1 -- +n2 )
1862: dup 0 < if
1863: negate
1864: endif ;
1865: 5 abs .
1866: -5 abs .
1867: @end example
1868:
1869: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1870: the following code is performed, otherwise execution continues after the
1.51 pazsan 1871: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1872: elements and prioduces a flag:
1873:
1874: @example
1875: 1 2 < .
1876: 2 1 < .
1877: 1 1 < .
1878: @end example
1879:
1880: Actually the standard name for @code{endif} is @code{then}. This
1881: tutorial presents the examples using @code{endif}, because this is often
1882: less confusing for people familiar with other programming languages
1883: where @code{then} has a different meaning. If your system does not have
1884: @code{endif}, define it with
1885:
1886: @example
1887: : endif postpone then ; immediate
1888: @end example
1889:
1890: You can optionally use an @code{else}-part:
1891:
1892: @example
1893: : min ( n1 n2 -- n )
1894: 2dup < if
1895: drop
1896: else
1897: nip
1898: endif ;
1899: 2 3 min .
1900: 3 2 min .
1901: @end example
1902:
1.141 anton 1903: @quotation Assignment
1.48 anton 1904: Write @code{min} without @code{else}-part (hint: what's the definition
1905: of @code{nip}?).
1.141 anton 1906: @end quotation
1.48 anton 1907:
1.66 anton 1908: Reference: @ref{Selection}.
1909:
1.48 anton 1910:
1911: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1912: @section Flags and Comparisons
1.66 anton 1913: @cindex flags tutorial
1914: @cindex comparison tutorial
1.48 anton 1915:
1916: In a false-flag all bits are clear (0 when interpreted as integer). In
1917: a canonical true-flag all bits are set (-1 as a twos-complement signed
1918: integer); in many contexts (e.g., @code{if}) any non-zero value is
1919: treated as true flag.
1920:
1921: @example
1922: false .
1923: true .
1924: true hex u. decimal
1925: @end example
1926:
1927: Comparison words produce canonical flags:
1928:
1929: @example
1930: 1 1 = .
1931: 1 0= .
1932: 0 1 < .
1933: 0 0 < .
1934: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1935: -1 1 < .
1936: @end example
1937:
1.66 anton 1938: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1939: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1940: these combinations are standard (for details see the standard,
1941: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1942:
1943: You can use @code{and or xor invert} can be used as operations on
1944: canonical flags. Actually they are bitwise operations:
1945:
1946: @example
1947: 1 2 and .
1948: 1 2 or .
1949: 1 3 xor .
1950: 1 invert .
1951: @end example
1952:
1953: You can convert a zero/non-zero flag into a canonical flag with
1954: @code{0<>} (and complement it on the way with @code{0=}).
1955:
1956: @example
1957: 1 0= .
1958: 1 0<> .
1959: @end example
1960:
1.65 anton 1961: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1962: operation of the Boolean operations to avoid @code{if}s:
1963:
1964: @example
1965: : foo ( n1 -- n2 )
1966: 0= if
1967: 14
1968: else
1969: 0
1970: endif ;
1971: 0 foo .
1972: 1 foo .
1973:
1974: : foo ( n1 -- n2 )
1975: 0= 14 and ;
1976: 0 foo .
1977: 1 foo .
1978: @end example
1979:
1.141 anton 1980: @quotation Assignment
1.48 anton 1981: Write @code{min} without @code{if}.
1.141 anton 1982: @end quotation
1.48 anton 1983:
1.66 anton 1984: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1985: @ref{Bitwise operations}.
1986:
1.48 anton 1987:
1988: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1989: @section General Loops
1.66 anton 1990: @cindex loops, indefinite, tutorial
1.48 anton 1991:
1992: The endless loop is the most simple one:
1993:
1994: @example
1995: : endless ( -- )
1996: 0 begin
1997: dup . 1+
1998: again ;
1999: endless
2000: @end example
2001:
2002: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2003: does nothing at run-time, @code{again} jumps back to @code{begin}.
2004:
2005: A loop with one exit at any place looks like this:
2006:
2007: @example
2008: : log2 ( +n1 -- n2 )
2009: \ logarithmus dualis of n1>0, rounded down to the next integer
2010: assert( dup 0> )
2011: 2/ 0 begin
2012: over 0> while
2013: 1+ swap 2/ swap
2014: repeat
2015: nip ;
2016: 7 log2 .
2017: 8 log2 .
2018: @end example
2019:
2020: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2021: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2022: continues behind the @code{while}. @code{Repeat} jumps back to
2023: @code{begin}, just like @code{again}.
2024:
2025: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2026: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2027: one bit (arithmetic shift right):
2028:
2029: @example
2030: -5 2 / .
2031: -5 2/ .
2032: @end example
2033:
2034: @code{assert(} is no standard word, but you can get it on systems other
2035: then Gforth by including @file{compat/assert.fs}. You can see what it
2036: does by trying
2037:
2038: @example
2039: 0 log2 .
2040: @end example
2041:
2042: Here's a loop with an exit at the end:
2043:
2044: @example
2045: : log2 ( +n1 -- n2 )
2046: \ logarithmus dualis of n1>0, rounded down to the next integer
2047: assert( dup 0 > )
2048: -1 begin
2049: 1+ swap 2/ swap
2050: over 0 <=
2051: until
2052: nip ;
2053: @end example
2054:
2055: @code{Until} consumes a flag; if it is non-zero, execution continues at
2056: the @code{begin}, otherwise after the @code{until}.
2057:
1.141 anton 2058: @quotation Assignment
1.48 anton 2059: Write a definition for computing the greatest common divisor.
1.141 anton 2060: @end quotation
1.48 anton 2061:
1.66 anton 2062: Reference: @ref{Simple Loops}.
2063:
1.48 anton 2064:
2065: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2066: @section Counted loops
1.66 anton 2067: @cindex loops, counted, tutorial
1.48 anton 2068:
2069: @example
2070: : ^ ( n1 u -- n )
2071: \ n = the uth power of u1
2072: 1 swap 0 u+do
2073: over *
2074: loop
2075: nip ;
2076: 3 2 ^ .
2077: 4 3 ^ .
2078: @end example
2079:
2080: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2081: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2082: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2083: times (or not at all, if @code{u3-u4<0}).
2084:
2085: You can see the stack effect design rules at work in the stack effect of
2086: the loop start words: Since the start value of the loop is more
2087: frequently constant than the end value, the start value is passed on
2088: the top-of-stack.
2089:
2090: You can access the counter of a counted loop with @code{i}:
2091:
2092: @example
2093: : fac ( u -- u! )
2094: 1 swap 1+ 1 u+do
2095: i *
2096: loop ;
2097: 5 fac .
2098: 7 fac .
2099: @end example
2100:
2101: There is also @code{+do}, which expects signed numbers (important for
2102: deciding whether to enter the loop).
2103:
1.141 anton 2104: @quotation Assignment
1.48 anton 2105: Write a definition for computing the nth Fibonacci number.
1.141 anton 2106: @end quotation
1.48 anton 2107:
1.65 anton 2108: You can also use increments other than 1:
2109:
2110: @example
2111: : up2 ( n1 n2 -- )
2112: +do
2113: i .
2114: 2 +loop ;
2115: 10 0 up2
2116:
2117: : down2 ( n1 n2 -- )
2118: -do
2119: i .
2120: 2 -loop ;
2121: 0 10 down2
2122: @end example
1.48 anton 2123:
1.66 anton 2124: Reference: @ref{Counted Loops}.
2125:
1.48 anton 2126:
2127: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2128: @section Recursion
1.66 anton 2129: @cindex recursion tutorial
1.48 anton 2130:
2131: Usually the name of a definition is not visible in the definition; but
2132: earlier definitions are usually visible:
2133:
2134: @example
2135: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2136: : / ( n1 n2 -- n )
2137: dup 0= if
2138: -10 throw \ report division by zero
2139: endif
2140: / \ old version
2141: ;
2142: 1 0 /
2143: @end example
2144:
2145: For recursive definitions you can use @code{recursive} (non-standard) or
2146: @code{recurse}:
2147:
2148: @example
2149: : fac1 ( n -- n! ) recursive
2150: dup 0> if
2151: dup 1- fac1 *
2152: else
2153: drop 1
2154: endif ;
2155: 7 fac1 .
2156:
2157: : fac2 ( n -- n! )
2158: dup 0> if
2159: dup 1- recurse *
2160: else
2161: drop 1
2162: endif ;
2163: 8 fac2 .
2164: @end example
2165:
1.141 anton 2166: @quotation Assignment
1.48 anton 2167: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2168: @end quotation
1.48 anton 2169:
1.66 anton 2170: Reference (including indirect recursion): @xref{Calls and returns}.
2171:
1.48 anton 2172:
2173: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2174: @section Leaving definitions or loops
1.66 anton 2175: @cindex leaving definitions, tutorial
2176: @cindex leaving loops, tutorial
1.48 anton 2177:
2178: @code{EXIT} exits the current definition right away. For every counted
2179: loop that is left in this way, an @code{UNLOOP} has to be performed
2180: before the @code{EXIT}:
2181:
2182: @c !! real examples
2183: @example
2184: : ...
2185: ... u+do
2186: ... if
2187: ... unloop exit
2188: endif
2189: ...
2190: loop
2191: ... ;
2192: @end example
2193:
2194: @code{LEAVE} leaves the innermost counted loop right away:
2195:
2196: @example
2197: : ...
2198: ... u+do
2199: ... if
2200: ... leave
2201: endif
2202: ...
2203: loop
2204: ... ;
2205: @end example
2206:
1.65 anton 2207: @c !! example
1.48 anton 2208:
1.66 anton 2209: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2210:
2211:
1.48 anton 2212: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2213: @section Return Stack
1.66 anton 2214: @cindex return stack tutorial
1.48 anton 2215:
2216: In addition to the data stack Forth also has a second stack, the return
2217: stack; most Forth systems store the return addresses of procedure calls
2218: there (thus its name). Programmers can also use this stack:
2219:
2220: @example
2221: : foo ( n1 n2 -- )
2222: .s
2223: >r .s
1.50 anton 2224: r@@ .
1.48 anton 2225: >r .s
1.50 anton 2226: r@@ .
1.48 anton 2227: r> .
1.50 anton 2228: r@@ .
1.48 anton 2229: r> . ;
2230: 1 2 foo
2231: @end example
2232:
2233: @code{>r} takes an element from the data stack and pushes it onto the
2234: return stack; conversely, @code{r>} moves an elementm from the return to
2235: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2236: on the data stack.
1.48 anton 2237:
2238: Forth programmers usually use the return stack for storing data
2239: temporarily, if using the data stack alone would be too complex, and
2240: factoring and locals are not an option:
2241:
2242: @example
2243: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2244: rot >r rot r> ;
2245: @end example
2246:
2247: The return address of the definition and the loop control parameters of
2248: counted loops usually reside on the return stack, so you have to take
2249: all items, that you have pushed on the return stack in a colon
2250: definition or counted loop, from the return stack before the definition
2251: or loop ends. You cannot access items that you pushed on the return
2252: stack outside some definition or loop within the definition of loop.
2253:
2254: If you miscount the return stack items, this usually ends in a crash:
2255:
2256: @example
2257: : crash ( n -- )
2258: >r ;
2259: 5 crash
2260: @end example
2261:
2262: You cannot mix using locals and using the return stack (according to the
2263: standard; Gforth has no problem). However, they solve the same
2264: problems, so this shouldn't be an issue.
2265:
1.141 anton 2266: @quotation Assignment
1.48 anton 2267: Can you rewrite any of the definitions you wrote until now in a better
2268: way using the return stack?
1.141 anton 2269: @end quotation
1.48 anton 2270:
1.66 anton 2271: Reference: @ref{Return stack}.
2272:
1.48 anton 2273:
2274: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2275: @section Memory
1.66 anton 2276: @cindex memory access/allocation tutorial
1.48 anton 2277:
2278: You can create a global variable @code{v} with
2279:
2280: @example
2281: variable v ( -- addr )
2282: @end example
2283:
2284: @code{v} pushes the address of a cell in memory on the stack. This cell
2285: was reserved by @code{variable}. You can use @code{!} (store) to store
2286: values into this cell and @code{@@} (fetch) to load the value from the
2287: stack into memory:
2288:
2289: @example
2290: v .
2291: 5 v ! .s
1.50 anton 2292: v @@ .
1.48 anton 2293: @end example
2294:
1.65 anton 2295: You can see a raw dump of memory with @code{dump}:
2296:
2297: @example
2298: v 1 cells .s dump
2299: @end example
2300:
2301: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2302: generally, address units (aus)) that @code{n1 cells} occupy. You can
2303: also reserve more memory:
1.48 anton 2304:
2305: @example
2306: create v2 20 cells allot
1.65 anton 2307: v2 20 cells dump
1.48 anton 2308: @end example
2309:
1.65 anton 2310: creates a word @code{v2} and reserves 20 uninitialized cells; the
2311: address pushed by @code{v2} points to the start of these 20 cells. You
2312: can use address arithmetic to access these cells:
1.48 anton 2313:
2314: @example
2315: 3 v2 5 cells + !
1.65 anton 2316: v2 20 cells dump
1.48 anton 2317: @end example
2318:
2319: You can reserve and initialize memory with @code{,}:
2320:
2321: @example
2322: create v3
2323: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2324: v3 @@ .
2325: v3 cell+ @@ .
2326: v3 2 cells + @@ .
1.65 anton 2327: v3 5 cells dump
1.48 anton 2328: @end example
2329:
1.141 anton 2330: @quotation Assignment
1.48 anton 2331: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2332: @code{u} cells, with the first of these cells at @code{addr}, the next
2333: one at @code{addr cell+} etc.
1.141 anton 2334: @end quotation
1.48 anton 2335:
2336: You can also reserve memory without creating a new word:
2337:
2338: @example
1.60 anton 2339: here 10 cells allot .
2340: here .
1.48 anton 2341: @end example
2342:
2343: @code{Here} pushes the start address of the memory area. You should
2344: store it somewhere, or you will have a hard time finding the memory area
2345: again.
2346:
2347: @code{Allot} manages dictionary memory. The dictionary memory contains
2348: the system's data structures for words etc. on Gforth and most other
2349: Forth systems. It is managed like a stack: You can free the memory that
2350: you have just @code{allot}ed with
2351:
2352: @example
2353: -10 cells allot
1.60 anton 2354: here .
1.48 anton 2355: @end example
2356:
2357: Note that you cannot do this if you have created a new word in the
2358: meantime (because then your @code{allot}ed memory is no longer on the
2359: top of the dictionary ``stack'').
2360:
2361: Alternatively, you can use @code{allocate} and @code{free} which allow
2362: freeing memory in any order:
2363:
2364: @example
2365: 10 cells allocate throw .s
2366: 20 cells allocate throw .s
2367: swap
2368: free throw
2369: free throw
2370: @end example
2371:
2372: The @code{throw}s deal with errors (e.g., out of memory).
2373:
1.65 anton 2374: And there is also a
2375: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2376: garbage collector}, which eliminates the need to @code{free} memory
2377: explicitly.
1.48 anton 2378:
1.66 anton 2379: Reference: @ref{Memory}.
2380:
1.48 anton 2381:
2382: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2383: @section Characters and Strings
1.66 anton 2384: @cindex strings tutorial
2385: @cindex characters tutorial
1.48 anton 2386:
2387: On the stack characters take up a cell, like numbers. In memory they
2388: have their own size (one 8-bit byte on most systems), and therefore
2389: require their own words for memory access:
2390:
2391: @example
2392: create v4
2393: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2394: v4 4 chars + c@@ .
1.65 anton 2395: v4 5 chars dump
1.48 anton 2396: @end example
2397:
2398: The preferred representation of strings on the stack is @code{addr
2399: u-count}, where @code{addr} is the address of the first character and
2400: @code{u-count} is the number of characters in the string.
2401:
2402: @example
2403: v4 5 type
2404: @end example
2405:
2406: You get a string constant with
2407:
2408: @example
2409: s" hello, world" .s
2410: type
2411: @end example
2412:
2413: Make sure you have a space between @code{s"} and the string; @code{s"}
2414: is a normal Forth word and must be delimited with white space (try what
2415: happens when you remove the space).
2416:
2417: However, this interpretive use of @code{s"} is quite restricted: the
2418: string exists only until the next call of @code{s"} (some Forth systems
2419: keep more than one of these strings, but usually they still have a
1.62 crook 2420: limited lifetime).
1.48 anton 2421:
2422: @example
2423: s" hello," s" world" .s
2424: type
2425: type
2426: @end example
2427:
1.62 crook 2428: You can also use @code{s"} in a definition, and the resulting
2429: strings then live forever (well, for as long as the definition):
1.48 anton 2430:
2431: @example
2432: : foo s" hello," s" world" ;
2433: foo .s
2434: type
2435: type
2436: @end example
2437:
1.141 anton 2438: @quotation Assignment
1.48 anton 2439: @code{Emit ( c -- )} types @code{c} as character (not a number).
2440: Implement @code{type ( addr u -- )}.
1.141 anton 2441: @end quotation
1.48 anton 2442:
1.66 anton 2443: Reference: @ref{Memory Blocks}.
2444:
2445:
1.84 pazsan 2446: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2447: @section Alignment
1.66 anton 2448: @cindex alignment tutorial
2449: @cindex memory alignment tutorial
1.48 anton 2450:
2451: On many processors cells have to be aligned in memory, if you want to
2452: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2453: not require alignment, access to aligned cells is faster).
1.48 anton 2454:
2455: @code{Create} aligns @code{here} (i.e., the place where the next
2456: allocation will occur, and that the @code{create}d word points to).
2457: Likewise, the memory produced by @code{allocate} starts at an aligned
2458: address. Adding a number of @code{cells} to an aligned address produces
2459: another aligned address.
2460:
2461: However, address arithmetic involving @code{char+} and @code{chars} can
2462: create an address that is not cell-aligned. @code{Aligned ( addr --
2463: a-addr )} produces the next aligned address:
2464:
2465: @example
1.50 anton 2466: v3 char+ aligned .s @@ .
2467: v3 char+ .s @@ .
1.48 anton 2468: @end example
2469:
2470: Similarly, @code{align} advances @code{here} to the next aligned
2471: address:
2472:
2473: @example
2474: create v5 97 c,
2475: here .
2476: align here .
2477: 1000 ,
2478: @end example
2479:
2480: Note that you should use aligned addresses even if your processor does
2481: not require them, if you want your program to be portable.
2482:
1.66 anton 2483: Reference: @ref{Address arithmetic}.
2484:
1.48 anton 2485:
1.84 pazsan 2486: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2487: @section Files
2488: @cindex files tutorial
2489:
2490: This section gives a short introduction into how to use files inside
2491: Forth. It's broken up into five easy steps:
2492:
2493: @enumerate 1
2494: @item Opened an ASCII text file for input
2495: @item Opened a file for output
2496: @item Read input file until string matched (or some other condition matched)
2497: @item Wrote some lines from input ( modified or not) to output
2498: @item Closed the files.
2499: @end enumerate
2500:
2501: @subsection Open file for input
2502:
2503: @example
2504: s" foo.in" r/o open-file throw Value fd-in
2505: @end example
2506:
2507: @subsection Create file for output
2508:
2509: @example
2510: s" foo.out" w/o create-file throw Value fd-out
2511: @end example
2512:
2513: The available file modes are r/o for read-only access, r/w for
2514: read-write access, and w/o for write-only access. You could open both
2515: files with r/w, too, if you like. All file words return error codes; for
2516: most applications, it's best to pass there error codes with @code{throw}
2517: to the outer error handler.
2518:
2519: If you want words for opening and assigning, define them as follows:
2520:
2521: @example
2522: 0 Value fd-in
2523: 0 Value fd-out
2524: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2525: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2526: @end example
2527:
2528: Usage example:
2529:
2530: @example
2531: s" foo.in" open-input
2532: s" foo.out" open-output
2533: @end example
2534:
2535: @subsection Scan file for a particular line
2536:
2537: @example
2538: 256 Constant max-line
2539: Create line-buffer max-line 2 + allot
2540:
2541: : scan-file ( addr u -- )
2542: begin
2543: line-buffer max-line fd-in read-line throw
2544: while
2545: >r 2dup line-buffer r> compare 0=
2546: until
2547: else
2548: drop
2549: then
2550: 2drop ;
2551: @end example
2552:
2553: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2554: the buffer at addr, and returns the number of bytes read, a flag that is
2555: false when the end of file is reached, and an error code.
1.84 pazsan 2556:
2557: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2558: returns zero if both strings are equal. It returns a positive number if
2559: the first string is lexically greater, a negative if the second string
2560: is lexically greater.
2561:
2562: We haven't seen this loop here; it has two exits. Since the @code{while}
2563: exits with the number of bytes read on the stack, we have to clean up
2564: that separately; that's after the @code{else}.
2565:
2566: Usage example:
2567:
2568: @example
2569: s" The text I search is here" scan-file
2570: @end example
2571:
2572: @subsection Copy input to output
2573:
2574: @example
2575: : copy-file ( -- )
2576: begin
2577: line-buffer max-line fd-in read-line throw
2578: while
2579: line-buffer swap fd-out write-file throw
2580: repeat ;
2581: @end example
2582:
2583: @subsection Close files
2584:
2585: @example
2586: fd-in close-file throw
2587: fd-out close-file throw
2588: @end example
2589:
2590: Likewise, you can put that into definitions, too:
2591:
2592: @example
2593: : close-input ( -- ) fd-in close-file throw ;
2594: : close-output ( -- ) fd-out close-file throw ;
2595: @end example
2596:
1.141 anton 2597: @quotation Assignment
1.84 pazsan 2598: How could you modify @code{copy-file} so that it copies until a second line is
2599: matched? Can you write a program that extracts a section of a text file,
2600: given the line that starts and the line that terminates that section?
1.141 anton 2601: @end quotation
1.84 pazsan 2602:
2603: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2604: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2605: @cindex semantics tutorial
2606: @cindex interpretation semantics tutorial
2607: @cindex compilation semantics tutorial
2608: @cindex immediate, tutorial
1.48 anton 2609:
2610: When a word is compiled, it behaves differently from being interpreted.
2611: E.g., consider @code{+}:
2612:
2613: @example
2614: 1 2 + .
2615: : foo + ;
2616: @end example
2617:
2618: These two behaviours are known as compilation and interpretation
2619: semantics. For normal words (e.g., @code{+}), the compilation semantics
2620: is to append the interpretation semantics to the currently defined word
2621: (@code{foo} in the example above). I.e., when @code{foo} is executed
2622: later, the interpretation semantics of @code{+} (i.e., adding two
2623: numbers) will be performed.
2624:
2625: However, there are words with non-default compilation semantics, e.g.,
2626: the control-flow words like @code{if}. You can use @code{immediate} to
2627: change the compilation semantics of the last defined word to be equal to
2628: the interpretation semantics:
2629:
2630: @example
2631: : [FOO] ( -- )
2632: 5 . ; immediate
2633:
2634: [FOO]
2635: : bar ( -- )
2636: [FOO] ;
2637: bar
2638: see bar
2639: @end example
2640:
2641: Two conventions to mark words with non-default compilation semnatics are
2642: names with brackets (more frequently used) and to write them all in
2643: upper case (less frequently used).
2644:
2645: In Gforth (and many other systems) you can also remove the
2646: interpretation semantics with @code{compile-only} (the compilation
2647: semantics is derived from the original interpretation semantics):
2648:
2649: @example
2650: : flip ( -- )
2651: 6 . ; compile-only \ but not immediate
2652: flip
2653:
2654: : flop ( -- )
2655: flip ;
2656: flop
2657: @end example
2658:
2659: In this example the interpretation semantics of @code{flop} is equal to
2660: the original interpretation semantics of @code{flip}.
2661:
2662: The text interpreter has two states: in interpret state, it performs the
2663: interpretation semantics of words it encounters; in compile state, it
2664: performs the compilation semantics of these words.
2665:
2666: Among other things, @code{:} switches into compile state, and @code{;}
2667: switches back to interpret state. They contain the factors @code{]}
2668: (switch to compile state) and @code{[} (switch to interpret state), that
2669: do nothing but switch the state.
2670:
2671: @example
2672: : xxx ( -- )
2673: [ 5 . ]
2674: ;
2675:
2676: xxx
2677: see xxx
2678: @end example
2679:
2680: These brackets are also the source of the naming convention mentioned
2681: above.
2682:
1.66 anton 2683: Reference: @ref{Interpretation and Compilation Semantics}.
2684:
1.48 anton 2685:
2686: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2687: @section Execution Tokens
1.66 anton 2688: @cindex execution tokens tutorial
2689: @cindex XT tutorial
1.48 anton 2690:
2691: @code{' word} gives you the execution token (XT) of a word. The XT is a
2692: cell representing the interpretation semantics of a word. You can
2693: execute this semantics with @code{execute}:
2694:
2695: @example
2696: ' + .s
2697: 1 2 rot execute .
2698: @end example
2699:
2700: The XT is similar to a function pointer in C. However, parameter
2701: passing through the stack makes it a little more flexible:
2702:
2703: @example
2704: : map-array ( ... addr u xt -- ... )
1.50 anton 2705: \ executes xt ( ... x -- ... ) for every element of the array starting
2706: \ at addr and containing u elements
1.48 anton 2707: @{ xt @}
2708: cells over + swap ?do
1.50 anton 2709: i @@ xt execute
1.48 anton 2710: 1 cells +loop ;
2711:
2712: create a 3 , 4 , 2 , -1 , 4 ,
2713: a 5 ' . map-array .s
2714: 0 a 5 ' + map-array .
2715: s" max-n" environment? drop .s
2716: a 5 ' min map-array .
2717: @end example
2718:
2719: You can use map-array with the XTs of words that consume one element
2720: more than they produce. In theory you can also use it with other XTs,
2721: but the stack effect then depends on the size of the array, which is
2722: hard to understand.
2723:
1.51 pazsan 2724: Since XTs are cell-sized, you can store them in memory and manipulate
2725: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2726: word with @code{compile,}:
2727:
2728: @example
2729: : foo1 ( n1 n2 -- n )
2730: [ ' + compile, ] ;
2731: see foo
2732: @end example
2733:
2734: This is non-standard, because @code{compile,} has no compilation
2735: semantics in the standard, but it works in good Forth systems. For the
2736: broken ones, use
2737:
2738: @example
2739: : [compile,] compile, ; immediate
2740:
2741: : foo1 ( n1 n2 -- n )
2742: [ ' + ] [compile,] ;
2743: see foo
2744: @end example
2745:
2746: @code{'} is a word with default compilation semantics; it parses the
2747: next word when its interpretation semantics are executed, not during
2748: compilation:
2749:
2750: @example
2751: : foo ( -- xt )
2752: ' ;
2753: see foo
2754: : bar ( ... "word" -- ... )
2755: ' execute ;
2756: see bar
1.60 anton 2757: 1 2 bar + .
1.48 anton 2758: @end example
2759:
2760: You often want to parse a word during compilation and compile its XT so
2761: it will be pushed on the stack at run-time. @code{[']} does this:
2762:
2763: @example
2764: : xt-+ ( -- xt )
2765: ['] + ;
2766: see xt-+
2767: 1 2 xt-+ execute .
2768: @end example
2769:
2770: Many programmers tend to see @code{'} and the word it parses as one
2771: unit, and expect it to behave like @code{[']} when compiled, and are
2772: confused by the actual behaviour. If you are, just remember that the
2773: Forth system just takes @code{'} as one unit and has no idea that it is
2774: a parsing word (attempts to convenience programmers in this issue have
2775: usually resulted in even worse pitfalls, see
1.66 anton 2776: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2777: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2778:
2779: Note that the state of the interpreter does not come into play when
1.51 pazsan 2780: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2781: compile state, it still gives you the interpretation semantics. And
2782: whatever that state is, @code{execute} performs the semantics
1.66 anton 2783: represented by the XT (i.e., for XTs produced with @code{'} the
2784: interpretation semantics).
2785:
2786: Reference: @ref{Tokens for Words}.
1.48 anton 2787:
2788:
2789: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2790: @section Exceptions
1.66 anton 2791: @cindex exceptions tutorial
1.48 anton 2792:
2793: @code{throw ( n -- )} causes an exception unless n is zero.
2794:
2795: @example
2796: 100 throw .s
2797: 0 throw .s
2798: @end example
2799:
2800: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2801: it catches exceptions and pushes the number of the exception on the
2802: stack (or 0, if the xt executed without exception). If there was an
2803: exception, the stacks have the same depth as when entering @code{catch}:
2804:
2805: @example
2806: .s
2807: 3 0 ' / catch .s
2808: 3 2 ' / catch .s
2809: @end example
2810:
1.141 anton 2811: @quotation Assignment
1.48 anton 2812: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2813: @end quotation
1.48 anton 2814:
2815: @code{Throw} always jumps to the dynamically next enclosing
2816: @code{catch}, even if it has to leave several call levels to achieve
2817: this:
2818:
2819: @example
2820: : foo 100 throw ;
2821: : foo1 foo ." after foo" ;
1.51 pazsan 2822: : bar ['] foo1 catch ;
1.60 anton 2823: bar .
1.48 anton 2824: @end example
2825:
2826: It is often important to restore a value upon leaving a definition, even
2827: if the definition is left through an exception. You can ensure this
2828: like this:
2829:
2830: @example
2831: : ...
2832: save-x
1.51 pazsan 2833: ['] word-changing-x catch ( ... n )
1.48 anton 2834: restore-x
2835: ( ... n ) throw ;
2836: @end example
2837:
1.55 anton 2838: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2839: @code{try ... recover ... endtry}. If the code between @code{try} and
2840: @code{recover} has an exception, the stack depths are restored, the
2841: exception number is pushed on the stack, and the code between
2842: @code{recover} and @code{endtry} is performed. E.g., the definition for
2843: @code{catch} is
2844:
2845: @example
2846: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2847: try
2848: execute 0
2849: recover
2850: nip
2851: endtry ;
2852: @end example
2853:
2854: The equivalent to the restoration code above is
2855:
2856: @example
2857: : ...
2858: save-x
2859: try
1.92 anton 2860: word-changing-x 0
2861: recover endtry
1.48 anton 2862: restore-x
2863: throw ;
2864: @end example
2865:
1.92 anton 2866: This works if @code{word-changing-x} does not change the stack depth,
2867: otherwise you should add some code between @code{recover} and
2868: @code{endtry} to balance the stack.
1.48 anton 2869:
1.66 anton 2870: Reference: @ref{Exception Handling}.
2871:
1.48 anton 2872:
2873: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2874: @section Defining Words
1.66 anton 2875: @cindex defining words tutorial
2876: @cindex does> tutorial
2877: @cindex create...does> tutorial
2878:
2879: @c before semantics?
1.48 anton 2880:
2881: @code{:}, @code{create}, and @code{variable} are definition words: They
2882: define other words. @code{Constant} is another definition word:
2883:
2884: @example
2885: 5 constant foo
2886: foo .
2887: @end example
2888:
2889: You can also use the prefixes @code{2} (double-cell) and @code{f}
2890: (floating point) with @code{variable} and @code{constant}.
2891:
2892: You can also define your own defining words. E.g.:
2893:
2894: @example
2895: : variable ( "name" -- )
2896: create 0 , ;
2897: @end example
2898:
2899: You can also define defining words that create words that do something
2900: other than just producing their address:
2901:
2902: @example
2903: : constant ( n "name" -- )
2904: create ,
2905: does> ( -- n )
1.50 anton 2906: ( addr ) @@ ;
1.48 anton 2907:
2908: 5 constant foo
2909: foo .
2910: @end example
2911:
2912: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2913: @code{does>} replaces @code{;}, but it also does something else: It
2914: changes the last defined word such that it pushes the address of the
2915: body of the word and then performs the code after the @code{does>}
2916: whenever it is called.
2917:
2918: In the example above, @code{constant} uses @code{,} to store 5 into the
2919: body of @code{foo}. When @code{foo} executes, it pushes the address of
2920: the body onto the stack, then (in the code after the @code{does>})
2921: fetches the 5 from there.
2922:
2923: The stack comment near the @code{does>} reflects the stack effect of the
2924: defined word, not the stack effect of the code after the @code{does>}
2925: (the difference is that the code expects the address of the body that
2926: the stack comment does not show).
2927:
2928: You can use these definition words to do factoring in cases that involve
2929: (other) definition words. E.g., a field offset is always added to an
2930: address. Instead of defining
2931:
2932: @example
2933: 2 cells constant offset-field1
2934: @end example
2935:
2936: and using this like
2937:
2938: @example
2939: ( addr ) offset-field1 +
2940: @end example
2941:
2942: you can define a definition word
2943:
2944: @example
2945: : simple-field ( n "name" -- )
2946: create ,
2947: does> ( n1 -- n1+n )
1.50 anton 2948: ( addr ) @@ + ;
1.48 anton 2949: @end example
1.21 crook 2950:
1.48 anton 2951: Definition and use of field offsets now look like this:
1.21 crook 2952:
1.48 anton 2953: @example
2954: 2 cells simple-field field1
1.60 anton 2955: create mystruct 4 cells allot
2956: mystruct .s field1 .s drop
1.48 anton 2957: @end example
1.21 crook 2958:
1.48 anton 2959: If you want to do something with the word without performing the code
2960: after the @code{does>}, you can access the body of a @code{create}d word
2961: with @code{>body ( xt -- addr )}:
1.21 crook 2962:
1.48 anton 2963: @example
2964: : value ( n "name" -- )
2965: create ,
2966: does> ( -- n1 )
1.50 anton 2967: @@ ;
1.48 anton 2968: : to ( n "name" -- )
2969: ' >body ! ;
1.21 crook 2970:
1.48 anton 2971: 5 value foo
2972: foo .
2973: 7 to foo
2974: foo .
2975: @end example
1.21 crook 2976:
1.141 anton 2977: @quotation Assignment
1.48 anton 2978: Define @code{defer ( "name" -- )}, which creates a word that stores an
2979: XT (at the start the XT of @code{abort}), and upon execution
2980: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2981: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2982: recursion is one application of @code{defer}.
1.141 anton 2983: @end quotation
1.29 crook 2984:
1.66 anton 2985: Reference: @ref{User-defined Defining Words}.
2986:
2987:
1.48 anton 2988: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2989: @section Arrays and Records
1.66 anton 2990: @cindex arrays tutorial
2991: @cindex records tutorial
2992: @cindex structs tutorial
1.29 crook 2993:
1.48 anton 2994: Forth has no standard words for defining data structures such as arrays
2995: and records (structs in C terminology), but you can build them yourself
2996: based on address arithmetic. You can also define words for defining
2997: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 2998:
1.48 anton 2999: One of the first projects a Forth newcomer sets out upon when learning
3000: about defining words is an array defining word (possibly for
3001: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3002: learn something from it. However, don't be disappointed when you later
3003: learn that you have little use for these words (inappropriate use would
3004: be even worse). I have not yet found a set of useful array words yet;
3005: the needs are just too diverse, and named, global arrays (the result of
3006: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3007: consider how to pass them as parameters). Another such project is a set
3008: of words to help dealing with strings.
1.29 crook 3009:
1.48 anton 3010: On the other hand, there is a useful set of record words, and it has
3011: been defined in @file{compat/struct.fs}; these words are predefined in
3012: Gforth. They are explained in depth elsewhere in this manual (see
3013: @pxref{Structures}). The @code{simple-field} example above is
3014: simplified variant of fields in this package.
1.21 crook 3015:
3016:
1.48 anton 3017: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3018: @section @code{POSTPONE}
1.66 anton 3019: @cindex postpone tutorial
1.21 crook 3020:
1.48 anton 3021: You can compile the compilation semantics (instead of compiling the
3022: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3023:
1.48 anton 3024: @example
3025: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3026: POSTPONE + ; immediate
1.48 anton 3027: : foo ( n1 n2 -- n )
3028: MY-+ ;
3029: 1 2 foo .
3030: see foo
3031: @end example
1.21 crook 3032:
1.48 anton 3033: During the definition of @code{foo} the text interpreter performs the
3034: compilation semantics of @code{MY-+}, which performs the compilation
3035: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3036:
3037: This example also displays separate stack comments for the compilation
3038: semantics and for the stack effect of the compiled code. For words with
3039: default compilation semantics these stack effects are usually not
3040: displayed; the stack effect of the compilation semantics is always
3041: @code{( -- )} for these words, the stack effect for the compiled code is
3042: the stack effect of the interpretation semantics.
3043:
3044: Note that the state of the interpreter does not come into play when
3045: performing the compilation semantics in this way. You can also perform
3046: it interpretively, e.g.:
3047:
3048: @example
3049: : foo2 ( n1 n2 -- n )
3050: [ MY-+ ] ;
3051: 1 2 foo .
3052: see foo
3053: @end example
1.21 crook 3054:
1.48 anton 3055: However, there are some broken Forth systems where this does not always
1.62 crook 3056: work, and therefore this practice was been declared non-standard in
1.48 anton 3057: 1999.
3058: @c !! repair.fs
3059:
3060: Here is another example for using @code{POSTPONE}:
1.44 crook 3061:
1.48 anton 3062: @example
3063: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3064: POSTPONE negate POSTPONE + ; immediate compile-only
3065: : bar ( n1 n2 -- n )
3066: MY-- ;
3067: 2 1 bar .
3068: see bar
3069: @end example
1.21 crook 3070:
1.48 anton 3071: You can define @code{ENDIF} in this way:
1.21 crook 3072:
1.48 anton 3073: @example
3074: : ENDIF ( Compilation: orig -- )
3075: POSTPONE then ; immediate
3076: @end example
1.21 crook 3077:
1.141 anton 3078: @quotation Assignment
1.48 anton 3079: Write @code{MY-2DUP} that has compilation semantics equivalent to
3080: @code{2dup}, but compiles @code{over over}.
1.141 anton 3081: @end quotation
1.29 crook 3082:
1.66 anton 3083: @c !! @xref{Macros} for reference
3084:
3085:
1.48 anton 3086: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3087: @section @code{Literal}
1.66 anton 3088: @cindex literal tutorial
1.29 crook 3089:
1.48 anton 3090: You cannot @code{POSTPONE} numbers:
1.21 crook 3091:
1.48 anton 3092: @example
3093: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3094: @end example
3095:
1.48 anton 3096: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3097:
1.48 anton 3098: @example
3099: : [FOO] ( compilation: --; run-time: -- n )
3100: 500 POSTPONE literal ; immediate
1.29 crook 3101:
1.60 anton 3102: : flip [FOO] ;
1.48 anton 3103: flip .
3104: see flip
3105: @end example
1.29 crook 3106:
1.48 anton 3107: @code{LITERAL} consumes a number at compile-time (when it's compilation
3108: semantics are executed) and pushes it at run-time (when the code it
3109: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3110: number computed at compile time into the current word:
1.29 crook 3111:
1.48 anton 3112: @example
3113: : bar ( -- n )
3114: [ 2 2 + ] literal ;
3115: see bar
3116: @end example
1.29 crook 3117:
1.141 anton 3118: @quotation Assignment
1.48 anton 3119: Write @code{]L} which allows writing the example above as @code{: bar (
3120: -- n ) [ 2 2 + ]L ;}
1.141 anton 3121: @end quotation
1.48 anton 3122:
1.66 anton 3123: @c !! @xref{Macros} for reference
3124:
1.48 anton 3125:
3126: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3127: @section Advanced macros
1.66 anton 3128: @cindex macros, advanced tutorial
3129: @cindex run-time code generation, tutorial
1.48 anton 3130:
1.66 anton 3131: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3132: Execution Tokens}. It frequently performs @code{execute}, a relatively
3133: expensive operation in some Forth implementations. You can use
1.48 anton 3134: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3135: and produce a word that contains the word to be performed directly:
3136:
3137: @c use ]] ... [[
3138: @example
3139: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3140: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3141: \ array beginning at addr and containing u elements
3142: @{ xt @}
3143: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3144: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3145: 1 cells POSTPONE literal POSTPONE +loop ;
3146:
3147: : sum-array ( addr u -- n )
3148: 0 rot rot [ ' + compile-map-array ] ;
3149: see sum-array
3150: a 5 sum-array .
3151: @end example
3152:
3153: You can use the full power of Forth for generating the code; here's an
3154: example where the code is generated in a loop:
3155:
3156: @example
3157: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3158: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3159: POSTPONE tuck POSTPONE @@
1.48 anton 3160: POSTPONE literal POSTPONE * POSTPONE +
3161: POSTPONE swap POSTPONE cell+ ;
3162:
3163: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3164: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3165: 0 postpone literal postpone swap
3166: [ ' compile-vmul-step compile-map-array ]
3167: postpone drop ;
3168: see compile-vmul
3169:
3170: : a-vmul ( addr -- n )
1.51 pazsan 3171: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3172: [ a 5 compile-vmul ] ;
3173: see a-vmul
3174: a a-vmul .
3175: @end example
3176:
3177: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3178: also use @code{map-array} instead (try it now!).
1.48 anton 3179:
3180: You can use this technique for efficient multiplication of large
3181: matrices. In matrix multiplication, you multiply every line of one
3182: matrix with every column of the other matrix. You can generate the code
3183: for one line once, and use it for every column. The only downside of
3184: this technique is that it is cumbersome to recover the memory consumed
3185: by the generated code when you are done (and in more complicated cases
3186: it is not possible portably).
3187:
1.66 anton 3188: @c !! @xref{Macros} for reference
3189:
3190:
1.48 anton 3191: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3192: @section Compilation Tokens
1.66 anton 3193: @cindex compilation tokens, tutorial
3194: @cindex CT, tutorial
1.48 anton 3195:
3196: This section is Gforth-specific. You can skip it.
3197:
3198: @code{' word compile,} compiles the interpretation semantics. For words
3199: with default compilation semantics this is the same as performing the
3200: compilation semantics. To represent the compilation semantics of other
3201: words (e.g., words like @code{if} that have no interpretation
3202: semantics), Gforth has the concept of a compilation token (CT,
3203: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3204: You can perform the compilation semantics represented by a CT with
3205: @code{execute}:
1.29 crook 3206:
1.48 anton 3207: @example
3208: : foo2 ( n1 n2 -- n )
3209: [ comp' + execute ] ;
3210: see foo
3211: @end example
1.29 crook 3212:
1.48 anton 3213: You can compile the compilation semantics represented by a CT with
3214: @code{postpone,}:
1.30 anton 3215:
1.48 anton 3216: @example
3217: : foo3 ( -- )
3218: [ comp' + postpone, ] ;
3219: see foo3
3220: @end example
1.30 anton 3221:
1.51 pazsan 3222: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3223: @code{comp'} is particularly useful for words that have no
3224: interpretation semantics:
1.29 crook 3225:
1.30 anton 3226: @example
1.48 anton 3227: ' if
1.60 anton 3228: comp' if .s 2drop
1.30 anton 3229: @end example
3230:
1.66 anton 3231: Reference: @ref{Tokens for Words}.
3232:
1.29 crook 3233:
1.48 anton 3234: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3235: @section Wordlists and Search Order
1.66 anton 3236: @cindex wordlists tutorial
3237: @cindex search order, tutorial
1.48 anton 3238:
3239: The dictionary is not just a memory area that allows you to allocate
3240: memory with @code{allot}, it also contains the Forth words, arranged in
3241: several wordlists. When searching for a word in a wordlist,
3242: conceptually you start searching at the youngest and proceed towards
3243: older words (in reality most systems nowadays use hash-tables); i.e., if
3244: you define a word with the same name as an older word, the new word
3245: shadows the older word.
3246:
3247: Which wordlists are searched in which order is determined by the search
3248: order. You can display the search order with @code{order}. It displays
3249: first the search order, starting with the wordlist searched first, then
3250: it displays the wordlist that will contain newly defined words.
1.21 crook 3251:
1.48 anton 3252: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3253:
1.48 anton 3254: @example
3255: wordlist constant mywords
3256: @end example
1.21 crook 3257:
1.48 anton 3258: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3259: defined words (the @emph{current} wordlist):
1.21 crook 3260:
1.48 anton 3261: @example
3262: mywords set-current
3263: order
3264: @end example
1.26 crook 3265:
1.48 anton 3266: Gforth does not display a name for the wordlist in @code{mywords}
3267: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3268:
1.48 anton 3269: You can get the current wordlist with @code{get-current ( -- wid)}. If
3270: you want to put something into a specific wordlist without overall
3271: effect on the current wordlist, this typically looks like this:
1.21 crook 3272:
1.48 anton 3273: @example
3274: get-current mywords set-current ( wid )
3275: create someword
3276: ( wid ) set-current
3277: @end example
1.21 crook 3278:
1.48 anton 3279: You can write the search order with @code{set-order ( wid1 .. widn n --
3280: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3281: searched wordlist is topmost.
1.21 crook 3282:
1.48 anton 3283: @example
3284: get-order mywords swap 1+ set-order
3285: order
3286: @end example
1.21 crook 3287:
1.48 anton 3288: Yes, the order of wordlists in the output of @code{order} is reversed
3289: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3290:
1.141 anton 3291: @quotation Assignment
1.48 anton 3292: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3293: wordlist to the search order. Define @code{previous ( -- )}, which
3294: removes the first searched wordlist from the search order. Experiment
3295: with boundary conditions (you will see some crashes or situations that
3296: are hard or impossible to leave).
1.141 anton 3297: @end quotation
1.21 crook 3298:
1.48 anton 3299: The search order is a powerful foundation for providing features similar
3300: to Modula-2 modules and C++ namespaces. However, trying to modularize
3301: programs in this way has disadvantages for debugging and reuse/factoring
3302: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3303: though). These disadvantages are not so clear in other
1.82 anton 3304: languages/programming environments, because these languages are not so
1.48 anton 3305: strong in debugging and reuse.
1.21 crook 3306:
1.66 anton 3307: @c !! example
3308:
3309: Reference: @ref{Word Lists}.
1.21 crook 3310:
1.29 crook 3311: @c ******************************************************************
1.48 anton 3312: @node Introduction, Words, Tutorial, Top
1.29 crook 3313: @comment node-name, next, previous, up
3314: @chapter An Introduction to ANS Forth
3315: @cindex Forth - an introduction
1.21 crook 3316:
1.83 anton 3317: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3318: that it is slower-paced in its examples, but uses them to dive deep into
3319: explaining Forth internals (not covered by the Tutorial). Apart from
3320: that, this chapter covers far less material. It is suitable for reading
3321: without using a computer.
3322:
1.29 crook 3323: The primary purpose of this manual is to document Gforth. However, since
3324: Forth is not a widely-known language and there is a lack of up-to-date
3325: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3326: material. For other sources of Forth-related
3327: information, see @ref{Forth-related information}.
1.21 crook 3328:
1.29 crook 3329: The examples in this section should work on any ANS Forth; the
3330: output shown was produced using Gforth. Each example attempts to
3331: reproduce the exact output that Gforth produces. If you try out the
3332: examples (and you should), what you should type is shown @kbd{like this}
3333: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3334: that, where the example shows @key{RET} it means that you should
1.29 crook 3335: press the ``carriage return'' key. Unfortunately, some output formats for
3336: this manual cannot show the difference between @kbd{this} and
3337: @code{this} which will make trying out the examples harder (but not
3338: impossible).
1.21 crook 3339:
1.29 crook 3340: Forth is an unusual language. It provides an interactive development
3341: environment which includes both an interpreter and compiler. Forth
3342: programming style encourages you to break a problem down into many
3343: @cindex factoring
3344: small fragments (@dfn{factoring}), and then to develop and test each
3345: fragment interactively. Forth advocates assert that breaking the
3346: edit-compile-test cycle used by conventional programming languages can
3347: lead to great productivity improvements.
1.21 crook 3348:
1.29 crook 3349: @menu
1.67 anton 3350: * Introducing the Text Interpreter::
3351: * Stacks and Postfix notation::
3352: * Your first definition::
3353: * How does that work?::
3354: * Forth is written in Forth::
3355: * Review - elements of a Forth system::
3356: * Where to go next::
3357: * Exercises::
1.29 crook 3358: @end menu
1.21 crook 3359:
1.29 crook 3360: @comment ----------------------------------------------
3361: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3362: @section Introducing the Text Interpreter
3363: @cindex text interpreter
3364: @cindex outer interpreter
1.21 crook 3365:
1.30 anton 3366: @c IMO this is too detailed and the pace is too slow for
3367: @c an introduction. If you know German, take a look at
3368: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3369: @c to see how I do it - anton
3370:
1.44 crook 3371: @c nac-> Where I have accepted your comments 100% and modified the text
3372: @c accordingly, I have deleted your comments. Elsewhere I have added a
3373: @c response like this to attempt to rationalise what I have done. Of
3374: @c course, this is a very clumsy mechanism for something that would be
3375: @c done far more efficiently over a beer. Please delete any dialogue
3376: @c you consider closed.
3377:
1.29 crook 3378: When you invoke the Forth image, you will see a startup banner printed
3379: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3380: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3381: its command line interpreter, which is called the @dfn{Text Interpreter}
3382: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3383: about the text interpreter as you read through this chapter, for more
3384: detail @pxref{The Text Interpreter}).
1.21 crook 3385:
1.29 crook 3386: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3387: input. Type a number and press the @key{RET} key:
1.21 crook 3388:
1.26 crook 3389: @example
1.30 anton 3390: @kbd{45@key{RET}} ok
1.26 crook 3391: @end example
1.21 crook 3392:
1.29 crook 3393: Rather than give you a prompt to invite you to input something, the text
3394: interpreter prints a status message @i{after} it has processed a line
3395: of input. The status message in this case (``@code{ ok}'' followed by
3396: carriage-return) indicates that the text interpreter was able to process
3397: all of your input successfully. Now type something illegal:
3398:
3399: @example
1.30 anton 3400: @kbd{qwer341@key{RET}}
1.134 anton 3401: *the terminal*:2: Undefined word
3402: >>>qwer341<<<
3403: Backtrace:
3404: $2A95B42A20 throw
3405: $2A95B57FB8 no.extensions
1.29 crook 3406: @end example
1.23 crook 3407:
1.134 anton 3408: The exact text, other than the ``Undefined word'' may differ slightly
3409: on your system, but the effect is the same; when the text interpreter
1.29 crook 3410: detects an error, it discards any remaining text on a line, resets
1.134 anton 3411: certain internal state and prints an error message. For a detailed
3412: description of error messages see @ref{Error messages}.
1.23 crook 3413:
1.29 crook 3414: The text interpreter waits for you to press carriage-return, and then
3415: processes your input line. Starting at the beginning of the line, it
3416: breaks the line into groups of characters separated by spaces. For each
3417: group of characters in turn, it makes two attempts to do something:
1.23 crook 3418:
1.29 crook 3419: @itemize @bullet
3420: @item
1.44 crook 3421: @cindex name dictionary
1.29 crook 3422: It tries to treat it as a command. It does this by searching a @dfn{name
3423: dictionary}. If the group of characters matches an entry in the name
3424: dictionary, the name dictionary provides the text interpreter with
3425: information that allows the text interpreter perform some actions. In
3426: Forth jargon, we say that the group
3427: @cindex word
3428: @cindex definition
3429: @cindex execution token
3430: @cindex xt
3431: of characters names a @dfn{word}, that the dictionary search returns an
3432: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3433: word, and that the text interpreter executes the xt. Often, the terms
3434: @dfn{word} and @dfn{definition} are used interchangeably.
3435: @item
3436: If the text interpreter fails to find a match in the name dictionary, it
3437: tries to treat the group of characters as a number in the current number
3438: base (when you start up Forth, the current number base is base 10). If
3439: the group of characters legitimately represents a number, the text
3440: interpreter pushes the number onto a stack (we'll learn more about that
3441: in the next section).
3442: @end itemize
1.23 crook 3443:
1.29 crook 3444: If the text interpreter is unable to do either of these things with any
3445: group of characters, it discards the group of characters and the rest of
3446: the line, then prints an error message. If the text interpreter reaches
3447: the end of the line without error, it prints the status message ``@code{ ok}''
3448: followed by carriage-return.
1.21 crook 3449:
1.29 crook 3450: This is the simplest command we can give to the text interpreter:
1.23 crook 3451:
3452: @example
1.30 anton 3453: @key{RET} ok
1.23 crook 3454: @end example
1.21 crook 3455:
1.29 crook 3456: The text interpreter did everything we asked it to do (nothing) without
3457: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3458: command:
1.21 crook 3459:
1.23 crook 3460: @example
1.30 anton 3461: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3462: *the terminal*:3: Undefined word
3463: 12 dup >>>fred<<< dup
3464: Backtrace:
3465: $2A95B42A20 throw
3466: $2A95B57FB8 no.extensions
1.23 crook 3467: @end example
1.21 crook 3468:
1.29 crook 3469: When you press the carriage-return key, the text interpreter starts to
3470: work its way along the line:
1.21 crook 3471:
1.29 crook 3472: @itemize @bullet
3473: @item
3474: When it gets to the space after the @code{2}, it takes the group of
3475: characters @code{12} and looks them up in the name
3476: dictionary@footnote{We can't tell if it found them or not, but assume
3477: for now that it did not}. There is no match for this group of characters
3478: in the name dictionary, so it tries to treat them as a number. It is
3479: able to do this successfully, so it puts the number, 12, ``on the stack''
3480: (whatever that means).
3481: @item
3482: The text interpreter resumes scanning the line and gets the next group
3483: of characters, @code{dup}. It looks it up in the name dictionary and
3484: (you'll have to take my word for this) finds it, and executes the word
3485: @code{dup} (whatever that means).
3486: @item
3487: Once again, the text interpreter resumes scanning the line and gets the
3488: group of characters @code{fred}. It looks them up in the name
3489: dictionary, but can't find them. It tries to treat them as a number, but
3490: they don't represent any legal number.
3491: @end itemize
1.21 crook 3492:
1.29 crook 3493: At this point, the text interpreter gives up and prints an error
3494: message. The error message shows exactly how far the text interpreter
3495: got in processing the line. In particular, it shows that the text
3496: interpreter made no attempt to do anything with the final character
3497: group, @code{dup}, even though we have good reason to believe that the
3498: text interpreter would have no problem looking that word up and
3499: executing it a second time.
1.21 crook 3500:
3501:
1.29 crook 3502: @comment ----------------------------------------------
3503: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3504: @section Stacks, postfix notation and parameter passing
3505: @cindex text interpreter
3506: @cindex outer interpreter
1.21 crook 3507:
1.29 crook 3508: In procedural programming languages (like C and Pascal), the
3509: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3510: functions or procedures are called with @dfn{explicit parameters}. For
3511: example, in C we might write:
1.21 crook 3512:
1.23 crook 3513: @example
1.29 crook 3514: total = total + new_volume(length,height,depth);
1.23 crook 3515: @end example
1.21 crook 3516:
1.23 crook 3517: @noindent
1.29 crook 3518: where new_volume is a function-call to another piece of code, and total,
3519: length, height and depth are all variables. length, height and depth are
3520: parameters to the function-call.
1.21 crook 3521:
1.29 crook 3522: In Forth, the equivalent of the function or procedure is the
3523: @dfn{definition} and parameters are implicitly passed between
3524: definitions using a shared stack that is visible to the
3525: programmer. Although Forth does support variables, the existence of the
3526: stack means that they are used far less often than in most other
3527: programming languages. When the text interpreter encounters a number, it
3528: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3529: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3530: used for any operation is implied unambiguously by the operation being
3531: performed. The stack used for all integer operations is called the @dfn{data
3532: stack} and, since this is the stack used most commonly, references to
3533: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3534:
1.29 crook 3535: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3536:
1.23 crook 3537: @example
1.30 anton 3538: @kbd{1 2 3@key{RET}} ok
1.23 crook 3539: @end example
1.21 crook 3540:
1.29 crook 3541: Then this instructs the text interpreter to placed three numbers on the
3542: (data) stack. An analogy for the behaviour of the stack is to take a
3543: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3544: the table. The 3 was the last card onto the pile (``last-in'') and if
3545: you take a card off the pile then, unless you're prepared to fiddle a
3546: bit, the card that you take off will be the 3 (``first-out''). The
3547: number that will be first-out of the stack is called the @dfn{top of
3548: stack}, which
3549: @cindex TOS definition
3550: is often abbreviated to @dfn{TOS}.
1.21 crook 3551:
1.29 crook 3552: To understand how parameters are passed in Forth, consider the
3553: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3554: be surprised to learn that this definition performs addition. More
3555: precisely, it adds two number together and produces a result. Where does
3556: it get the two numbers from? It takes the top two numbers off the
3557: stack. Where does it place the result? On the stack. You can act-out the
3558: behaviour of @code{+} with your playing cards like this:
1.21 crook 3559:
3560: @itemize @bullet
3561: @item
1.29 crook 3562: Pick up two cards from the stack on the table
1.21 crook 3563: @item
1.29 crook 3564: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3565: numbers''
1.21 crook 3566: @item
1.29 crook 3567: Decide that the answer is 5
1.21 crook 3568: @item
1.29 crook 3569: Shuffle the two cards back into the pack and find a 5
1.21 crook 3570: @item
1.29 crook 3571: Put a 5 on the remaining ace that's on the table.
1.21 crook 3572: @end itemize
3573:
1.29 crook 3574: If you don't have a pack of cards handy but you do have Forth running,
3575: you can use the definition @code{.s} to show the current state of the stack,
3576: without affecting the stack. Type:
1.21 crook 3577:
3578: @example
1.124 anton 3579: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3580: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3581: @end example
3582:
1.124 anton 3583: The text interpreter looks up the word @code{clearstacks} and executes
3584: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3585: left on it by earlier examples. The text interpreter pushes each of the
3586: three numbers in turn onto the stack. Finally, the text interpreter
3587: looks up the word @code{.s} and executes it. The effect of executing
3588: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3589: followed by a list of all the items on the stack; the item on the far
3590: right-hand side is the TOS.
1.21 crook 3591:
1.29 crook 3592: You can now type:
1.21 crook 3593:
1.29 crook 3594: @example
1.30 anton 3595: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3596: @end example
1.21 crook 3597:
1.29 crook 3598: @noindent
3599: which is correct; there are now 2 items on the stack and the result of
3600: the addition is 5.
1.23 crook 3601:
1.29 crook 3602: If you're playing with cards, try doing a second addition: pick up the
3603: two cards, work out that their sum is 6, shuffle them into the pack,
3604: look for a 6 and place that on the table. You now have just one item on
3605: the stack. What happens if you try to do a third addition? Pick up the
3606: first card, pick up the second card -- ah! There is no second card. This
3607: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3608: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3609: Underflow or an Invalid Memory Address error).
1.23 crook 3610:
1.29 crook 3611: The opposite situation to a stack underflow is a @dfn{stack overflow},
3612: which simply accepts that there is a finite amount of storage space
3613: reserved for the stack. To stretch the playing card analogy, if you had
3614: enough packs of cards and you piled the cards up on the table, you would
3615: eventually be unable to add another card; you'd hit the ceiling. Gforth
3616: allows you to set the maximum size of the stacks. In general, the only
3617: time that you will get a stack overflow is because a definition has a
3618: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3619:
1.29 crook 3620: There's one final use for the playing card analogy. If you model your
3621: stack using a pack of playing cards, the maximum number of items on
3622: your stack will be 52 (I assume you didn't use the Joker). The maximum
3623: @i{value} of any item on the stack is 13 (the King). In fact, the only
3624: possible numbers are positive integer numbers 1 through 13; you can't
3625: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3626: think about some of the cards, you can accommodate different
3627: numbers. For example, you could think of the Jack as representing 0,
3628: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3629: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3630: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3631:
1.29 crook 3632: In that analogy, the limit was the amount of information that a single
3633: stack entry could hold, and Forth has a similar limit. In Forth, the
3634: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3635: implementation dependent and affects the maximum value that a stack
3636: entry can hold. A Standard Forth provides a cell size of at least
3637: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3638:
1.29 crook 3639: Forth does not do any type checking for you, so you are free to
3640: manipulate and combine stack items in any way you wish. A convenient way
3641: of treating stack items is as 2's complement signed integers, and that
3642: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3643:
1.29 crook 3644: @example
1.30 anton 3645: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3646: @end example
1.21 crook 3647:
1.29 crook 3648: If you use numbers and definitions like @code{+} in order to turn Forth
3649: into a great big pocket calculator, you will realise that it's rather
3650: different from a normal calculator. Rather than typing 2 + 3 = you had
3651: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3652: result). The terminology used to describe this difference is to say that
3653: your calculator uses @dfn{Infix Notation} (parameters and operators are
3654: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3655: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3656:
1.29 crook 3657: Whilst postfix notation might look confusing to begin with, it has
3658: several important advantages:
1.21 crook 3659:
1.23 crook 3660: @itemize @bullet
3661: @item
1.29 crook 3662: it is unambiguous
1.23 crook 3663: @item
1.29 crook 3664: it is more concise
1.23 crook 3665: @item
1.29 crook 3666: it fits naturally with a stack-based system
1.23 crook 3667: @end itemize
1.21 crook 3668:
1.29 crook 3669: To examine these claims in more detail, consider these sums:
1.21 crook 3670:
1.29 crook 3671: @example
3672: 6 + 5 * 4 =
3673: 4 * 5 + 6 =
3674: @end example
1.21 crook 3675:
1.29 crook 3676: If you're just learning maths or your maths is very rusty, you will
3677: probably come up with the answer 44 for the first and 26 for the
3678: second. If you are a bit of a whizz at maths you will remember the
3679: @i{convention} that multiplication takes precendence over addition, and
3680: you'd come up with the answer 26 both times. To explain the answer 26
3681: to someone who got the answer 44, you'd probably rewrite the first sum
3682: like this:
1.21 crook 3683:
1.29 crook 3684: @example
3685: 6 + (5 * 4) =
3686: @end example
1.21 crook 3687:
1.29 crook 3688: If what you really wanted was to perform the addition before the
3689: multiplication, you would have to use parentheses to force it.
1.21 crook 3690:
1.29 crook 3691: If you did the first two sums on a pocket calculator you would probably
3692: get the right answers, unless you were very cautious and entered them using
3693: these keystroke sequences:
1.21 crook 3694:
1.29 crook 3695: 6 + 5 = * 4 =
3696: 4 * 5 = + 6 =
1.21 crook 3697:
1.29 crook 3698: Postfix notation is unambiguous because the order that the operators
3699: are applied is always explicit; that also means that parentheses are
3700: never required. The operators are @i{active} (the act of quoting the
3701: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3702:
1.29 crook 3703: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3704: equivalent ways:
1.26 crook 3705:
3706: @example
1.29 crook 3707: 6 5 4 * + or:
3708: 5 4 * 6 +
1.26 crook 3709: @end example
1.23 crook 3710:
1.29 crook 3711: An important thing that you should notice about this notation is that
3712: the @i{order} of the numbers does not change; if you want to subtract
3713: 2 from 10 you type @code{10 2 -}.
1.1 anton 3714:
1.29 crook 3715: The reason that Forth uses postfix notation is very simple to explain: it
3716: makes the implementation extremely simple, and it follows naturally from
3717: using the stack as a mechanism for passing parameters. Another way of
3718: thinking about this is to realise that all Forth definitions are
3719: @i{active}; they execute as they are encountered by the text
3720: interpreter. The result of this is that the syntax of Forth is trivially
3721: simple.
1.1 anton 3722:
3723:
3724:
1.29 crook 3725: @comment ----------------------------------------------
3726: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3727: @section Your first Forth definition
3728: @cindex first definition
1.1 anton 3729:
1.29 crook 3730: Until now, the examples we've seen have been trivial; we've just been
3731: using Forth as a bigger-than-pocket calculator. Also, each calculation
3732: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3733: again@footnote{That's not quite true. If you press the up-arrow key on
3734: your keyboard you should be able to scroll back to any earlier command,
3735: edit it and re-enter it.} In this section we'll see how to add new
3736: words to Forth's vocabulary.
1.1 anton 3737:
1.29 crook 3738: The easiest way to create a new word is to use a @dfn{colon
3739: definition}. We'll define a few and try them out before worrying too
3740: much about how they work. Try typing in these examples; be careful to
3741: copy the spaces accurately:
1.1 anton 3742:
1.29 crook 3743: @example
3744: : add-two 2 + . ;
3745: : greet ." Hello and welcome" ;
3746: : demo 5 add-two ;
3747: @end example
1.1 anton 3748:
1.29 crook 3749: @noindent
3750: Now try them out:
1.1 anton 3751:
1.29 crook 3752: @example
1.30 anton 3753: @kbd{greet@key{RET}} Hello and welcome ok
3754: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3755: @kbd{4 add-two@key{RET}} 6 ok
3756: @kbd{demo@key{RET}} 7 ok
3757: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3758: @end example
1.1 anton 3759:
1.29 crook 3760: The first new thing that we've introduced here is the pair of words
3761: @code{:} and @code{;}. These are used to start and terminate a new
3762: definition, respectively. The first word after the @code{:} is the name
3763: for the new definition.
1.1 anton 3764:
1.29 crook 3765: As you can see from the examples, a definition is built up of words that
3766: have already been defined; Forth makes no distinction between
3767: definitions that existed when you started the system up, and those that
3768: you define yourself.
1.1 anton 3769:
1.29 crook 3770: The examples also introduce the words @code{.} (dot), @code{."}
3771: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3772: the stack and displays it. It's like @code{.s} except that it only
3773: displays the top item of the stack and it is destructive; after it has
3774: executed, the number is no longer on the stack. There is always one
3775: space printed after the number, and no spaces before it. Dot-quote
3776: defines a string (a sequence of characters) that will be printed when
3777: the word is executed. The string can contain any printable characters
3778: except @code{"}. A @code{"} has a special function; it is not a Forth
3779: word but it acts as a delimiter (the way that delimiters work is
3780: described in the next section). Finally, @code{dup} duplicates the value
3781: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3782:
1.29 crook 3783: We already know that the text interpreter searches through the
3784: dictionary to locate names. If you've followed the examples earlier, you
3785: will already have a definition called @code{add-two}. Lets try modifying
3786: it by typing in a new definition:
1.1 anton 3787:
1.29 crook 3788: @example
1.30 anton 3789: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3790: @end example
1.5 anton 3791:
1.29 crook 3792: Forth recognised that we were defining a word that already exists, and
3793: printed a message to warn us of that fact. Let's try out the new
3794: definition:
1.5 anton 3795:
1.29 crook 3796: @example
1.30 anton 3797: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3798: @end example
1.1 anton 3799:
1.29 crook 3800: @noindent
3801: All that we've actually done here, though, is to create a new
3802: definition, with a particular name. The fact that there was already a
3803: definition with the same name did not make any difference to the way
3804: that the new definition was created (except that Forth printed a warning
3805: message). The old definition of add-two still exists (try @code{demo}
3806: again to see that this is true). Any new definition will use the new
3807: definition of @code{add-two}, but old definitions continue to use the
3808: version that already existed at the time that they were @code{compiled}.
1.1 anton 3809:
1.29 crook 3810: Before you go on to the next section, try defining and redefining some
3811: words of your own.
1.1 anton 3812:
1.29 crook 3813: @comment ----------------------------------------------
3814: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3815: @section How does that work?
3816: @cindex parsing words
1.1 anton 3817:
1.30 anton 3818: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3819:
3820: @c Is it a good idea to talk about the interpretation semantics of a
3821: @c number? We don't have an xt to go along with it. - anton
3822:
3823: @c Now that I have eliminated execution semantics, I wonder if it would not
3824: @c be better to keep them (or add run-time semantics), to make it easier to
3825: @c explain what compilation semantics usually does. - anton
3826:
1.44 crook 3827: @c nac-> I removed the term ``default compilation sematics'' from the
3828: @c introductory chapter. Removing ``execution semantics'' was making
3829: @c everything simpler to explain, then I think the use of this term made
3830: @c everything more complex again. I replaced it with ``default
3831: @c semantics'' (which is used elsewhere in the manual) by which I mean
3832: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3833: @c flag set''.
3834:
3835: @c anton: I have eliminated default semantics (except in one place where it
3836: @c means "default interpretation and compilation semantics"), because it
3837: @c makes no sense in the presence of combined words. I reverted to
3838: @c "execution semantics" where necessary.
3839:
3840: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3841: @c section (and, unusually for me, I think I even made it shorter!). See
3842: @c what you think -- I know I have not addressed your primary concern
3843: @c that it is too heavy-going for an introduction. From what I understood
3844: @c of your course notes it looks as though they might be a good framework.
3845: @c Things that I've tried to capture here are some things that came as a
3846: @c great revelation here when I first understood them. Also, I like the
3847: @c fact that a very simple code example shows up almost all of the issues
3848: @c that you need to understand to see how Forth works. That's unique and
3849: @c worthwhile to emphasise.
3850:
1.83 anton 3851: @c anton: I think it's a good idea to present the details, especially those
3852: @c that you found to be a revelation, and probably the tutorial tries to be
3853: @c too superficial and does not get some of the things across that make
3854: @c Forth special. I do believe that most of the time these things should
3855: @c be discussed at the end of a section or in separate sections instead of
3856: @c in the middle of a section (e.g., the stuff you added in "User-defined
3857: @c defining words" leads in a completely different direction from the rest
3858: @c of the section).
3859:
1.29 crook 3860: Now we're going to take another look at the definition of @code{add-two}
3861: from the previous section. From our knowledge of the way that the text
3862: interpreter works, we would have expected this result when we tried to
3863: define @code{add-two}:
1.21 crook 3864:
1.29 crook 3865: @example
1.44 crook 3866: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3867: *the terminal*:4: Undefined word
3868: : >>>add-two<<< 2 + . ;
1.29 crook 3869: @end example
1.28 crook 3870:
1.29 crook 3871: The reason that this didn't happen is bound up in the way that @code{:}
3872: works. The word @code{:} does two special things. The first special
3873: thing that it does prevents the text interpreter from ever seeing the
3874: characters @code{add-two}. The text interpreter uses a variable called
3875: @cindex modifying >IN
1.44 crook 3876: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3877: input line. When it encounters the word @code{:} it behaves in exactly
3878: the same way as it does for any other word; it looks it up in the name
3879: dictionary, finds its xt and executes it. When @code{:} executes, it
3880: looks at the input buffer, finds the word @code{add-two} and advances the
3881: value of @code{>IN} to point past it. It then does some other stuff
3882: associated with creating the new definition (including creating an entry
3883: for @code{add-two} in the name dictionary). When the execution of @code{:}
3884: completes, control returns to the text interpreter, which is oblivious
3885: to the fact that it has been tricked into ignoring part of the input
3886: line.
1.21 crook 3887:
1.29 crook 3888: @cindex parsing words
3889: Words like @code{:} -- words that advance the value of @code{>IN} and so
3890: prevent the text interpreter from acting on the whole of the input line
3891: -- are called @dfn{parsing words}.
1.21 crook 3892:
1.29 crook 3893: @cindex @code{state} - effect on the text interpreter
3894: @cindex text interpreter - effect of state
3895: The second special thing that @code{:} does is change the value of a
3896: variable called @code{state}, which affects the way that the text
3897: interpreter behaves. When Gforth starts up, @code{state} has the value
3898: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3899: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3900: the text interpreter is said to be @dfn{compiling}.
3901:
3902: In this example, the text interpreter is compiling when it processes the
3903: string ``@code{2 + . ;}''. It still breaks the string down into
3904: character sequences in the same way. However, instead of pushing the
3905: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3906: into the definition of @code{add-two} that will make the number @code{2} get
3907: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3908: the behaviours of @code{+} and @code{.} are also compiled into the
3909: definition.
3910:
3911: One category of words don't get compiled. These so-called @dfn{immediate
3912: words} get executed (performed @i{now}) regardless of whether the text
3913: interpreter is interpreting or compiling. The word @code{;} is an
3914: immediate word. Rather than being compiled into the definition, it
3915: executes. Its effect is to terminate the current definition, which
3916: includes changing the value of @code{state} back to 0.
3917:
3918: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3919: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3920: definition.
1.28 crook 3921:
1.30 anton 3922: In Forth, every word or number can be described in terms of two
1.29 crook 3923: properties:
1.28 crook 3924:
3925: @itemize @bullet
3926: @item
1.29 crook 3927: @cindex interpretation semantics
1.44 crook 3928: Its @dfn{interpretation semantics} describe how it will behave when the
3929: text interpreter encounters it in @dfn{interpret} state. The
3930: interpretation semantics of a word are represented by an @dfn{execution
3931: token}.
1.28 crook 3932: @item
1.29 crook 3933: @cindex compilation semantics
1.44 crook 3934: Its @dfn{compilation semantics} describe how it will behave when the
3935: text interpreter encounters it in @dfn{compile} state. The compilation
3936: semantics of a word are represented in an implementation-dependent way;
3937: Gforth uses a @dfn{compilation token}.
1.29 crook 3938: @end itemize
3939:
3940: @noindent
3941: Numbers are always treated in a fixed way:
3942:
3943: @itemize @bullet
1.28 crook 3944: @item
1.44 crook 3945: When the number is @dfn{interpreted}, its behaviour is to push the
3946: number onto the stack.
1.28 crook 3947: @item
1.30 anton 3948: When the number is @dfn{compiled}, a piece of code is appended to the
3949: current definition that pushes the number when it runs. (In other words,
3950: the compilation semantics of a number are to postpone its interpretation
3951: semantics until the run-time of the definition that it is being compiled
3952: into.)
1.29 crook 3953: @end itemize
3954:
1.44 crook 3955: Words don't behave in such a regular way, but most have @i{default
3956: semantics} which means that they behave like this:
1.29 crook 3957:
3958: @itemize @bullet
1.28 crook 3959: @item
1.30 anton 3960: The @dfn{interpretation semantics} of the word are to do something useful.
3961: @item
1.29 crook 3962: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3963: @dfn{interpretation semantics} to the current definition (so that its
3964: run-time behaviour is to do something useful).
1.28 crook 3965: @end itemize
3966:
1.30 anton 3967: @cindex immediate words
1.44 crook 3968: The actual behaviour of any particular word can be controlled by using
3969: the words @code{immediate} and @code{compile-only} when the word is
3970: defined. These words set flags in the name dictionary entry of the most
3971: recently defined word, and these flags are retrieved by the text
3972: interpreter when it finds the word in the name dictionary.
3973:
3974: A word that is marked as @dfn{immediate} has compilation semantics that
3975: are identical to its interpretation semantics. In other words, it
3976: behaves like this:
1.29 crook 3977:
3978: @itemize @bullet
3979: @item
1.30 anton 3980: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3981: @item
1.30 anton 3982: The @dfn{compilation semantics} of the word are to do something useful
3983: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3984: @end itemize
1.28 crook 3985:
1.44 crook 3986: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3987: performing the interpretation semantics of the word directly; an attempt
3988: to do so will generate an error. It is never necessary to use
3989: @code{compile-only} (and it is not even part of ANS Forth, though it is
3990: provided by many implementations) but it is good etiquette to apply it
3991: to a word that will not behave correctly (and might have unexpected
3992: side-effects) in interpret state. For example, it is only legal to use
3993: the conditional word @code{IF} within a definition. If you forget this
3994: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3995: @code{compile-only} allows the text interpreter to generate a helpful
3996: error message rather than subjecting you to the consequences of your
3997: folly.
3998:
1.29 crook 3999: This example shows the difference between an immediate and a
4000: non-immediate word:
1.28 crook 4001:
1.29 crook 4002: @example
4003: : show-state state @@ . ;
4004: : show-state-now show-state ; immediate
4005: : word1 show-state ;
4006: : word2 show-state-now ;
1.28 crook 4007: @end example
1.23 crook 4008:
1.29 crook 4009: The word @code{immediate} after the definition of @code{show-state-now}
4010: makes that word an immediate word. These definitions introduce a new
4011: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4012: variable, and leaves it on the stack. Therefore, the behaviour of
4013: @code{show-state} is to print a number that represents the current value
4014: of @code{state}.
1.28 crook 4015:
1.29 crook 4016: When you execute @code{word1}, it prints the number 0, indicating that
4017: the system is interpreting. When the text interpreter compiled the
4018: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4019: compilation semantics are to append its interpretation semantics to the
1.29 crook 4020: current definition. When you execute @code{word1}, it performs the
1.30 anton 4021: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4022: (and therefore @code{show-state}) are executed, the system is
4023: interpreting.
1.28 crook 4024:
1.30 anton 4025: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4026: you should have seen the number -1 printed, followed by ``@code{
4027: ok}''. When the text interpreter compiled the definition of
4028: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4029: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4030: semantics. It is executed straight away (even before the text
4031: interpreter has moved on to process another group of characters; the
4032: @code{;} in this example). The effect of executing it are to display the
4033: value of @code{state} @i{at the time that the definition of}
4034: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4035: system is compiling at this time. If you execute @code{word2} it does
4036: nothing at all.
1.28 crook 4037:
1.29 crook 4038: @cindex @code{."}, how it works
4039: Before leaving the subject of immediate words, consider the behaviour of
4040: @code{."} in the definition of @code{greet}, in the previous
4041: section. This word is both a parsing word and an immediate word. Notice
4042: that there is a space between @code{."} and the start of the text
4043: @code{Hello and welcome}, but that there is no space between the last
4044: letter of @code{welcome} and the @code{"} character. The reason for this
4045: is that @code{."} is a Forth word; it must have a space after it so that
4046: the text interpreter can identify it. The @code{"} is not a Forth word;
4047: it is a @dfn{delimiter}. The examples earlier show that, when the string
4048: is displayed, there is neither a space before the @code{H} nor after the
4049: @code{e}. Since @code{."} is an immediate word, it executes at the time
4050: that @code{greet} is defined. When it executes, its behaviour is to
4051: search forward in the input line looking for the delimiter. When it
4052: finds the delimiter, it updates @code{>IN} to point past the
4053: delimiter. It also compiles some magic code into the definition of
4054: @code{greet}; the xt of a run-time routine that prints a text string. It
4055: compiles the string @code{Hello and welcome} into memory so that it is
4056: available to be printed later. When the text interpreter gains control,
4057: the next word it finds in the input stream is @code{;} and so it
4058: terminates the definition of @code{greet}.
1.28 crook 4059:
4060:
4061: @comment ----------------------------------------------
1.29 crook 4062: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4063: @section Forth is written in Forth
4064: @cindex structure of Forth programs
4065:
4066: When you start up a Forth compiler, a large number of definitions
4067: already exist. In Forth, you develop a new application using bottom-up
4068: programming techniques to create new definitions that are defined in
4069: terms of existing definitions. As you create each definition you can
4070: test and debug it interactively.
4071:
4072: If you have tried out the examples in this section, you will probably
4073: have typed them in by hand; when you leave Gforth, your definitions will
4074: be lost. You can avoid this by using a text editor to enter Forth source
4075: code into a file, and then loading code from the file using
1.49 anton 4076: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4077: processed by the text interpreter, just as though you had typed it in by
4078: hand@footnote{Actually, there are some subtle differences -- see
4079: @ref{The Text Interpreter}.}.
4080:
4081: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4082: files for program entry (@pxref{Blocks}).
1.28 crook 4083:
1.29 crook 4084: In common with many, if not most, Forth compilers, most of Gforth is
4085: actually written in Forth. All of the @file{.fs} files in the
4086: installation directory@footnote{For example,
1.30 anton 4087: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4088: study to see examples of Forth programming.
1.28 crook 4089:
1.29 crook 4090: Gforth maintains a history file that records every line that you type to
4091: the text interpreter. This file is preserved between sessions, and is
4092: used to provide a command-line recall facility. If you enter long
4093: definitions by hand, you can use a text editor to paste them out of the
4094: history file into a Forth source file for reuse at a later time
1.49 anton 4095: (for more information @pxref{Command-line editing}).
1.28 crook 4096:
4097:
4098: @comment ----------------------------------------------
1.29 crook 4099: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4100: @section Review - elements of a Forth system
4101: @cindex elements of a Forth system
1.28 crook 4102:
1.29 crook 4103: To summarise this chapter:
1.28 crook 4104:
4105: @itemize @bullet
4106: @item
1.29 crook 4107: Forth programs use @dfn{factoring} to break a problem down into small
4108: fragments called @dfn{words} or @dfn{definitions}.
4109: @item
4110: Forth program development is an interactive process.
4111: @item
4112: The main command loop that accepts input, and controls both
4113: interpretation and compilation, is called the @dfn{text interpreter}
4114: (also known as the @dfn{outer interpreter}).
4115: @item
4116: Forth has a very simple syntax, consisting of words and numbers
4117: separated by spaces or carriage-return characters. Any additional syntax
4118: is imposed by @dfn{parsing words}.
4119: @item
4120: Forth uses a stack to pass parameters between words. As a result, it
4121: uses postfix notation.
4122: @item
4123: To use a word that has previously been defined, the text interpreter
4124: searches for the word in the @dfn{name dictionary}.
4125: @item
1.30 anton 4126: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4127: @item
1.29 crook 4128: The text interpreter uses the value of @code{state} to select between
4129: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4130: semantics} of a word that it encounters.
1.28 crook 4131: @item
1.30 anton 4132: The relationship between the @dfn{interpretation semantics} and
4133: @dfn{compilation semantics} for a word
1.29 crook 4134: depend upon the way in which the word was defined (for example, whether
4135: it is an @dfn{immediate} word).
1.28 crook 4136: @item
1.29 crook 4137: Forth definitions can be implemented in Forth (called @dfn{high-level
4138: definitions}) or in some other way (usually a lower-level language and
4139: as a result often called @dfn{low-level definitions}, @dfn{code
4140: definitions} or @dfn{primitives}).
1.28 crook 4141: @item
1.29 crook 4142: Many Forth systems are implemented mainly in Forth.
1.28 crook 4143: @end itemize
4144:
4145:
1.29 crook 4146: @comment ----------------------------------------------
1.48 anton 4147: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4148: @section Where To Go Next
4149: @cindex where to go next
1.28 crook 4150:
1.29 crook 4151: Amazing as it may seem, if you have read (and understood) this far, you
4152: know almost all the fundamentals about the inner workings of a Forth
4153: system. You certainly know enough to be able to read and understand the
4154: rest of this manual and the ANS Forth document, to learn more about the
4155: facilities that Forth in general and Gforth in particular provide. Even
4156: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4157: However, that's not a good idea just yet... better to try writing some
1.29 crook 4158: programs in Gforth.
1.28 crook 4159:
1.29 crook 4160: Forth has such a rich vocabulary that it can be hard to know where to
4161: start in learning it. This section suggests a few sets of words that are
4162: enough to write small but useful programs. Use the word index in this
4163: document to learn more about each word, then try it out and try to write
4164: small definitions using it. Start by experimenting with these words:
1.28 crook 4165:
4166: @itemize @bullet
4167: @item
1.29 crook 4168: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4169: @item
4170: Comparison: @code{MIN MAX =}
4171: @item
4172: Logic: @code{AND OR XOR NOT}
4173: @item
4174: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4175: @item
1.29 crook 4176: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4177: @item
1.29 crook 4178: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4179: @item
1.29 crook 4180: Defining words: @code{: ; CREATE}
1.28 crook 4181: @item
1.29 crook 4182: Memory allocation words: @code{ALLOT ,}
1.28 crook 4183: @item
1.29 crook 4184: Tools: @code{SEE WORDS .S MARKER}
4185: @end itemize
4186:
4187: When you have mastered those, go on to:
4188:
4189: @itemize @bullet
1.28 crook 4190: @item
1.29 crook 4191: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4192: @item
1.29 crook 4193: Memory access: @code{@@ !}
1.28 crook 4194: @end itemize
1.23 crook 4195:
1.29 crook 4196: When you have mastered these, there's nothing for it but to read through
4197: the whole of this manual and find out what you've missed.
4198:
4199: @comment ----------------------------------------------
1.48 anton 4200: @node Exercises, , Where to go next, Introduction
1.29 crook 4201: @section Exercises
4202: @cindex exercises
4203:
4204: TODO: provide a set of programming excercises linked into the stuff done
4205: already and into other sections of the manual. Provide solutions to all
4206: the exercises in a .fs file in the distribution.
4207:
4208: @c Get some inspiration from Starting Forth and Kelly&Spies.
4209:
4210: @c excercises:
4211: @c 1. take inches and convert to feet and inches.
4212: @c 2. take temperature and convert from fahrenheight to celcius;
4213: @c may need to care about symmetric vs floored??
4214: @c 3. take input line and do character substitution
4215: @c to encipher or decipher
4216: @c 4. as above but work on a file for in and out
4217: @c 5. take input line and convert to pig-latin
4218: @c
4219: @c thing of sets of things to exercise then come up with
4220: @c problems that need those things.
4221:
4222:
1.26 crook 4223: @c ******************************************************************
1.29 crook 4224: @node Words, Error messages, Introduction, Top
1.1 anton 4225: @chapter Forth Words
1.26 crook 4226: @cindex words
1.1 anton 4227:
4228: @menu
4229: * Notation::
1.65 anton 4230: * Case insensitivity::
4231: * Comments::
4232: * Boolean Flags::
1.1 anton 4233: * Arithmetic::
4234: * Stack Manipulation::
1.5 anton 4235: * Memory::
1.1 anton 4236: * Control Structures::
4237: * Defining Words::
1.65 anton 4238: * Interpretation and Compilation Semantics::
1.47 crook 4239: * Tokens for Words::
1.81 anton 4240: * Compiling words::
1.65 anton 4241: * The Text Interpreter::
1.111 anton 4242: * The Input Stream::
1.65 anton 4243: * Word Lists::
4244: * Environmental Queries::
1.12 anton 4245: * Files::
4246: * Blocks::
4247: * Other I/O::
1.121 anton 4248: * OS command line arguments::
1.78 anton 4249: * Locals::
4250: * Structures::
4251: * Object-oriented Forth::
1.12 anton 4252: * Programming Tools::
1.150 anton 4253: * C Interface::
1.12 anton 4254: * Assembler and Code Words::
4255: * Threading Words::
1.65 anton 4256: * Passing Commands to the OS::
4257: * Keeping track of Time::
4258: * Miscellaneous Words::
1.1 anton 4259: @end menu
4260:
1.65 anton 4261: @node Notation, Case insensitivity, Words, Words
1.1 anton 4262: @section Notation
4263: @cindex notation of glossary entries
4264: @cindex format of glossary entries
4265: @cindex glossary notation format
4266: @cindex word glossary entry format
4267:
4268: The Forth words are described in this section in the glossary notation
1.67 anton 4269: that has become a de-facto standard for Forth texts:
1.1 anton 4270:
4271: @format
1.29 crook 4272: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4273: @end format
1.29 crook 4274: @i{Description}
1.1 anton 4275:
4276: @table @var
4277: @item word
1.28 crook 4278: The name of the word.
1.1 anton 4279:
4280: @item Stack effect
4281: @cindex stack effect
1.29 crook 4282: The stack effect is written in the notation @code{@i{before} --
4283: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4284: stack entries before and after the execution of the word. The rest of
4285: the stack is not touched by the word. The top of stack is rightmost,
4286: i.e., a stack sequence is written as it is typed in. Note that Gforth
4287: uses a separate floating point stack, but a unified stack
1.29 crook 4288: notation. Also, return stack effects are not shown in @i{stack
4289: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4290: the type and/or the function of the item. See below for a discussion of
4291: the types.
4292:
4293: All words have two stack effects: A compile-time stack effect and a
4294: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4295: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4296: this standard behaviour, or the word does other unusual things at
4297: compile time, both stack effects are shown; otherwise only the run-time
4298: stack effect is shown.
4299:
4300: @cindex pronounciation of words
4301: @item pronunciation
4302: How the word is pronounced.
4303:
4304: @cindex wordset
1.67 anton 4305: @cindex environment wordset
1.1 anton 4306: @item wordset
1.21 crook 4307: The ANS Forth standard is divided into several word sets. A standard
4308: system need not support all of them. Therefore, in theory, the fewer
4309: word sets your program uses the more portable it will be. However, we
4310: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4311: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4312: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4313: describes words that will work in future releases of Gforth;
4314: @code{gforth-internal} words are more volatile. Environmental query
4315: strings are also displayed like words; you can recognize them by the
1.21 crook 4316: @code{environment} in the word set field.
1.1 anton 4317:
4318: @item Description
4319: A description of the behaviour of the word.
4320: @end table
4321:
4322: @cindex types of stack items
4323: @cindex stack item types
4324: The type of a stack item is specified by the character(s) the name
4325: starts with:
4326:
4327: @table @code
4328: @item f
4329: @cindex @code{f}, stack item type
4330: Boolean flags, i.e. @code{false} or @code{true}.
4331: @item c
4332: @cindex @code{c}, stack item type
4333: Char
4334: @item w
4335: @cindex @code{w}, stack item type
4336: Cell, can contain an integer or an address
4337: @item n
4338: @cindex @code{n}, stack item type
4339: signed integer
4340: @item u
4341: @cindex @code{u}, stack item type
4342: unsigned integer
4343: @item d
4344: @cindex @code{d}, stack item type
4345: double sized signed integer
4346: @item ud
4347: @cindex @code{ud}, stack item type
4348: double sized unsigned integer
4349: @item r
4350: @cindex @code{r}, stack item type
4351: Float (on the FP stack)
1.21 crook 4352: @item a-
1.1 anton 4353: @cindex @code{a_}, stack item type
4354: Cell-aligned address
1.21 crook 4355: @item c-
1.1 anton 4356: @cindex @code{c_}, stack item type
4357: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4358: @item f-
1.1 anton 4359: @cindex @code{f_}, stack item type
4360: Float-aligned address
1.21 crook 4361: @item df-
1.1 anton 4362: @cindex @code{df_}, stack item type
4363: Address aligned for IEEE double precision float
1.21 crook 4364: @item sf-
1.1 anton 4365: @cindex @code{sf_}, stack item type
4366: Address aligned for IEEE single precision float
4367: @item xt
4368: @cindex @code{xt}, stack item type
4369: Execution token, same size as Cell
4370: @item wid
4371: @cindex @code{wid}, stack item type
1.21 crook 4372: Word list ID, same size as Cell
1.68 anton 4373: @item ior, wior
4374: @cindex ior type description
4375: @cindex wior type description
4376: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4377: @item f83name
4378: @cindex @code{f83name}, stack item type
4379: Pointer to a name structure
4380: @item "
4381: @cindex @code{"}, stack item type
1.12 anton 4382: string in the input stream (not on the stack). The terminating character
4383: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4384: quotes.
4385: @end table
4386:
1.65 anton 4387: @comment ----------------------------------------------
4388: @node Case insensitivity, Comments, Notation, Words
4389: @section Case insensitivity
4390: @cindex case sensitivity
4391: @cindex upper and lower case
4392:
4393: Gforth is case-insensitive; you can enter definitions and invoke
4394: Standard words using upper, lower or mixed case (however,
4395: @pxref{core-idef, Implementation-defined options, Implementation-defined
4396: options}).
4397:
4398: ANS Forth only @i{requires} implementations to recognise Standard words
4399: when they are typed entirely in upper case. Therefore, a Standard
4400: program must use upper case for all Standard words. You can use whatever
4401: case you like for words that you define, but in a Standard program you
4402: have to use the words in the same case that you defined them.
4403:
4404: Gforth supports case sensitivity through @code{table}s (case-sensitive
4405: wordlists, @pxref{Word Lists}).
4406:
4407: Two people have asked how to convert Gforth to be case-sensitive; while
4408: we think this is a bad idea, you can change all wordlists into tables
4409: like this:
4410:
4411: @example
4412: ' table-find forth-wordlist wordlist-map @ !
4413: @end example
4414:
4415: Note that you now have to type the predefined words in the same case
4416: that we defined them, which are varying. You may want to convert them
4417: to your favourite case before doing this operation (I won't explain how,
4418: because if you are even contemplating doing this, you'd better have
4419: enough knowledge of Forth systems to know this already).
4420:
4421: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4422: @section Comments
1.26 crook 4423: @cindex comments
1.21 crook 4424:
1.29 crook 4425: Forth supports two styles of comment; the traditional @i{in-line} comment,
4426: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4427:
1.44 crook 4428:
1.23 crook 4429: doc-(
1.21 crook 4430: doc-\
1.23 crook 4431: doc-\G
1.21 crook 4432:
1.44 crook 4433:
1.21 crook 4434: @node Boolean Flags, Arithmetic, Comments, Words
4435: @section Boolean Flags
1.26 crook 4436: @cindex Boolean flags
1.21 crook 4437:
4438: A Boolean flag is cell-sized. A cell with all bits clear represents the
4439: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4440: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4441: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4442: @c on and off to Memory?
4443: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4444:
1.21 crook 4445: doc-true
4446: doc-false
1.29 crook 4447: doc-on
4448: doc-off
1.21 crook 4449:
1.44 crook 4450:
1.21 crook 4451: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4452: @section Arithmetic
4453: @cindex arithmetic words
4454:
4455: @cindex division with potentially negative operands
4456: Forth arithmetic is not checked, i.e., you will not hear about integer
4457: overflow on addition or multiplication, you may hear about division by
4458: zero if you are lucky. The operator is written after the operands, but
4459: the operands are still in the original order. I.e., the infix @code{2-1}
4460: corresponds to @code{2 1 -}. Forth offers a variety of division
4461: operators. If you perform division with potentially negative operands,
4462: you do not want to use @code{/} or @code{/mod} with its undefined
4463: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4464: former, @pxref{Mixed precision}).
1.26 crook 4465: @comment TODO discuss the different division forms and the std approach
1.1 anton 4466:
4467: @menu
4468: * Single precision::
1.67 anton 4469: * Double precision:: Double-cell integer arithmetic
1.1 anton 4470: * Bitwise operations::
1.67 anton 4471: * Numeric comparison::
1.29 crook 4472: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4473: * Floating Point::
4474: @end menu
4475:
1.67 anton 4476: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4477: @subsection Single precision
4478: @cindex single precision arithmetic words
4479:
1.67 anton 4480: @c !! cell undefined
4481:
4482: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4483: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4484: treat them. For the rules used by the text interpreter for recognising
4485: single-precision integers see @ref{Number Conversion}.
1.21 crook 4486:
1.67 anton 4487: These words are all defined for signed operands, but some of them also
4488: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4489: @code{*}.
1.44 crook 4490:
1.1 anton 4491: doc-+
1.21 crook 4492: doc-1+
1.128 anton 4493: doc-under+
1.1 anton 4494: doc--
1.21 crook 4495: doc-1-
1.1 anton 4496: doc-*
4497: doc-/
4498: doc-mod
4499: doc-/mod
4500: doc-negate
4501: doc-abs
4502: doc-min
4503: doc-max
1.27 crook 4504: doc-floored
1.1 anton 4505:
1.44 crook 4506:
1.67 anton 4507: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4508: @subsection Double precision
4509: @cindex double precision arithmetic words
4510:
1.49 anton 4511: For the rules used by the text interpreter for
4512: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4513:
4514: A double precision number is represented by a cell pair, with the most
1.67 anton 4515: significant cell at the TOS. It is trivial to convert an unsigned single
4516: to a double: simply push a @code{0} onto the TOS. Since numbers are
4517: represented by Gforth using 2's complement arithmetic, converting a
4518: signed single to a (signed) double requires sign-extension across the
4519: most significant cell. This can be achieved using @code{s>d}. The moral
4520: of the story is that you cannot convert a number without knowing whether
4521: it represents an unsigned or a signed number.
1.21 crook 4522:
1.67 anton 4523: These words are all defined for signed operands, but some of them also
4524: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4525:
1.21 crook 4526: doc-s>d
1.67 anton 4527: doc-d>s
1.21 crook 4528: doc-d+
4529: doc-d-
4530: doc-dnegate
4531: doc-dabs
4532: doc-dmin
4533: doc-dmax
4534:
1.44 crook 4535:
1.67 anton 4536: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4537: @subsection Bitwise operations
4538: @cindex bitwise operation words
4539:
4540:
4541: doc-and
4542: doc-or
4543: doc-xor
4544: doc-invert
4545: doc-lshift
4546: doc-rshift
4547: doc-2*
4548: doc-d2*
4549: doc-2/
4550: doc-d2/
4551:
4552:
4553: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4554: @subsection Numeric comparison
4555: @cindex numeric comparison words
4556:
1.67 anton 4557: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4558: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4559:
1.28 crook 4560: doc-<
4561: doc-<=
4562: doc-<>
4563: doc-=
4564: doc->
4565: doc->=
4566:
1.21 crook 4567: doc-0<
1.23 crook 4568: doc-0<=
1.21 crook 4569: doc-0<>
4570: doc-0=
1.23 crook 4571: doc-0>
4572: doc-0>=
1.28 crook 4573:
4574: doc-u<
4575: doc-u<=
1.44 crook 4576: @c u<> and u= exist but are the same as <> and =
1.31 anton 4577: @c doc-u<>
4578: @c doc-u=
1.28 crook 4579: doc-u>
4580: doc-u>=
4581:
4582: doc-within
4583:
4584: doc-d<
4585: doc-d<=
4586: doc-d<>
4587: doc-d=
4588: doc-d>
4589: doc-d>=
1.23 crook 4590:
1.21 crook 4591: doc-d0<
1.23 crook 4592: doc-d0<=
4593: doc-d0<>
1.21 crook 4594: doc-d0=
1.23 crook 4595: doc-d0>
4596: doc-d0>=
4597:
1.21 crook 4598: doc-du<
1.28 crook 4599: doc-du<=
1.44 crook 4600: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4601: @c doc-du<>
4602: @c doc-du=
1.28 crook 4603: doc-du>
4604: doc-du>=
1.1 anton 4605:
1.44 crook 4606:
1.21 crook 4607: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4608: @subsection Mixed precision
4609: @cindex mixed precision arithmetic words
4610:
1.44 crook 4611:
1.1 anton 4612: doc-m+
4613: doc-*/
4614: doc-*/mod
4615: doc-m*
4616: doc-um*
4617: doc-m*/
4618: doc-um/mod
4619: doc-fm/mod
4620: doc-sm/rem
4621:
1.44 crook 4622:
1.21 crook 4623: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4624: @subsection Floating Point
4625: @cindex floating point arithmetic words
4626:
1.49 anton 4627: For the rules used by the text interpreter for
4628: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4629:
1.67 anton 4630: Gforth has a separate floating point stack, but the documentation uses
4631: the unified notation.@footnote{It's easy to generate the separate
4632: notation from that by just separating the floating-point numbers out:
4633: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4634: r3 )}.}
1.1 anton 4635:
4636: @cindex floating-point arithmetic, pitfalls
4637: Floating point numbers have a number of unpleasant surprises for the
4638: unwary (e.g., floating point addition is not associative) and even a few
4639: for the wary. You should not use them unless you know what you are doing
4640: or you don't care that the results you get are totally bogus. If you
4641: want to learn about the problems of floating point numbers (and how to
1.66 anton 4642: avoid them), you might start with @cite{David Goldberg,
4643: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4644: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4645: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4646:
1.44 crook 4647:
1.21 crook 4648: doc-d>f
4649: doc-f>d
1.1 anton 4650: doc-f+
4651: doc-f-
4652: doc-f*
4653: doc-f/
4654: doc-fnegate
4655: doc-fabs
4656: doc-fmax
4657: doc-fmin
4658: doc-floor
4659: doc-fround
4660: doc-f**
4661: doc-fsqrt
4662: doc-fexp
4663: doc-fexpm1
4664: doc-fln
4665: doc-flnp1
4666: doc-flog
4667: doc-falog
1.32 anton 4668: doc-f2*
4669: doc-f2/
4670: doc-1/f
4671: doc-precision
4672: doc-set-precision
4673:
4674: @cindex angles in trigonometric operations
4675: @cindex trigonometric operations
4676: Angles in floating point operations are given in radians (a full circle
4677: has 2 pi radians).
4678:
1.1 anton 4679: doc-fsin
4680: doc-fcos
4681: doc-fsincos
4682: doc-ftan
4683: doc-fasin
4684: doc-facos
4685: doc-fatan
4686: doc-fatan2
4687: doc-fsinh
4688: doc-fcosh
4689: doc-ftanh
4690: doc-fasinh
4691: doc-facosh
4692: doc-fatanh
1.21 crook 4693: doc-pi
1.28 crook 4694:
1.32 anton 4695: @cindex equality of floats
4696: @cindex floating-point comparisons
1.31 anton 4697: One particular problem with floating-point arithmetic is that comparison
4698: for equality often fails when you would expect it to succeed. For this
4699: reason approximate equality is often preferred (but you still have to
1.67 anton 4700: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4701: differently from what you might expect. The comparison words are:
1.31 anton 4702:
4703: doc-f~rel
4704: doc-f~abs
1.68 anton 4705: doc-f~
1.31 anton 4706: doc-f=
4707: doc-f<>
4708:
4709: doc-f<
4710: doc-f<=
4711: doc-f>
4712: doc-f>=
4713:
1.21 crook 4714: doc-f0<
1.28 crook 4715: doc-f0<=
4716: doc-f0<>
1.21 crook 4717: doc-f0=
1.28 crook 4718: doc-f0>
4719: doc-f0>=
4720:
1.1 anton 4721:
4722: @node Stack Manipulation, Memory, Arithmetic, Words
4723: @section Stack Manipulation
4724: @cindex stack manipulation words
4725:
4726: @cindex floating-point stack in the standard
1.21 crook 4727: Gforth maintains a number of separate stacks:
4728:
1.29 crook 4729: @cindex data stack
4730: @cindex parameter stack
1.21 crook 4731: @itemize @bullet
4732: @item
1.29 crook 4733: A data stack (also known as the @dfn{parameter stack}) -- for
4734: characters, cells, addresses, and double cells.
1.21 crook 4735:
1.29 crook 4736: @cindex floating-point stack
1.21 crook 4737: @item
1.44 crook 4738: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4739:
1.29 crook 4740: @cindex return stack
1.21 crook 4741: @item
1.44 crook 4742: A return stack -- for holding the return addresses of colon
1.32 anton 4743: definitions and other (non-FP) data.
1.21 crook 4744:
1.29 crook 4745: @cindex locals stack
1.21 crook 4746: @item
1.44 crook 4747: A locals stack -- for holding local variables.
1.21 crook 4748: @end itemize
4749:
1.1 anton 4750: @menu
4751: * Data stack::
4752: * Floating point stack::
4753: * Return stack::
4754: * Locals stack::
4755: * Stack pointer manipulation::
4756: @end menu
4757:
4758: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4759: @subsection Data stack
4760: @cindex data stack manipulation words
4761: @cindex stack manipulations words, data stack
4762:
1.44 crook 4763:
1.1 anton 4764: doc-drop
4765: doc-nip
4766: doc-dup
4767: doc-over
4768: doc-tuck
4769: doc-swap
1.21 crook 4770: doc-pick
1.1 anton 4771: doc-rot
4772: doc--rot
4773: doc-?dup
4774: doc-roll
4775: doc-2drop
4776: doc-2nip
4777: doc-2dup
4778: doc-2over
4779: doc-2tuck
4780: doc-2swap
4781: doc-2rot
4782:
1.44 crook 4783:
1.1 anton 4784: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4785: @subsection Floating point stack
4786: @cindex floating-point stack manipulation words
4787: @cindex stack manipulation words, floating-point stack
4788:
1.32 anton 4789: Whilst every sane Forth has a separate floating-point stack, it is not
4790: strictly required; an ANS Forth system could theoretically keep
4791: floating-point numbers on the data stack. As an additional difficulty,
4792: you don't know how many cells a floating-point number takes. It is
4793: reportedly possible to write words in a way that they work also for a
4794: unified stack model, but we do not recommend trying it. Instead, just
4795: say that your program has an environmental dependency on a separate
4796: floating-point stack.
4797:
4798: doc-floating-stack
4799:
1.1 anton 4800: doc-fdrop
4801: doc-fnip
4802: doc-fdup
4803: doc-fover
4804: doc-ftuck
4805: doc-fswap
1.21 crook 4806: doc-fpick
1.1 anton 4807: doc-frot
4808:
1.44 crook 4809:
1.1 anton 4810: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4811: @subsection Return stack
4812: @cindex return stack manipulation words
4813: @cindex stack manipulation words, return stack
4814:
1.32 anton 4815: @cindex return stack and locals
4816: @cindex locals and return stack
4817: A Forth system is allowed to keep local variables on the
4818: return stack. This is reasonable, as local variables usually eliminate
4819: the need to use the return stack explicitly. So, if you want to produce
4820: a standard compliant program and you are using local variables in a
4821: word, forget about return stack manipulations in that word (refer to the
4822: standard document for the exact rules).
4823:
1.1 anton 4824: doc->r
4825: doc-r>
4826: doc-r@
4827: doc-rdrop
4828: doc-2>r
4829: doc-2r>
4830: doc-2r@
4831: doc-2rdrop
4832:
1.44 crook 4833:
1.1 anton 4834: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4835: @subsection Locals stack
4836:
1.78 anton 4837: Gforth uses an extra locals stack. It is described, along with the
4838: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4839:
1.1 anton 4840: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4841: @subsection Stack pointer manipulation
4842: @cindex stack pointer manipulation words
4843:
1.44 crook 4844: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4845: doc-sp0
1.1 anton 4846: doc-sp@
4847: doc-sp!
1.21 crook 4848: doc-fp0
1.1 anton 4849: doc-fp@
4850: doc-fp!
1.21 crook 4851: doc-rp0
1.1 anton 4852: doc-rp@
4853: doc-rp!
1.21 crook 4854: doc-lp0
1.1 anton 4855: doc-lp@
4856: doc-lp!
4857:
1.44 crook 4858:
1.1 anton 4859: @node Memory, Control Structures, Stack Manipulation, Words
4860: @section Memory
1.26 crook 4861: @cindex memory words
1.1 anton 4862:
1.32 anton 4863: @menu
4864: * Memory model::
4865: * Dictionary allocation::
4866: * Heap Allocation::
4867: * Memory Access::
4868: * Address arithmetic::
4869: * Memory Blocks::
4870: @end menu
4871:
1.67 anton 4872: In addition to the standard Forth memory allocation words, there is also
4873: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4874: garbage collector}.
4875:
1.32 anton 4876: @node Memory model, Dictionary allocation, Memory, Memory
4877: @subsection ANS Forth and Gforth memory models
4878:
4879: @c The ANS Forth description is a mess (e.g., is the heap part of
4880: @c the dictionary?), so let's not stick to closely with it.
4881:
1.67 anton 4882: ANS Forth considers a Forth system as consisting of several address
4883: spaces, of which only @dfn{data space} is managed and accessible with
4884: the memory words. Memory not necessarily in data space includes the
4885: stacks, the code (called code space) and the headers (called name
4886: space). In Gforth everything is in data space, but the code for the
4887: primitives is usually read-only.
1.32 anton 4888:
4889: Data space is divided into a number of areas: The (data space portion of
4890: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4891: refer to the search data structure embodied in word lists and headers,
4892: because it is used for looking up names, just as you would in a
4893: conventional dictionary.}, the heap, and a number of system-allocated
4894: buffers.
4895:
1.68 anton 4896: @cindex address arithmetic restrictions, ANS vs. Gforth
4897: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4898: In ANS Forth data space is also divided into contiguous regions. You
4899: can only use address arithmetic within a contiguous region, not between
4900: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4901: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4902: allocation}).
4903:
4904: Gforth provides one big address space, and address arithmetic can be
4905: performed between any addresses. However, in the dictionary headers or
4906: code are interleaved with data, so almost the only contiguous data space
4907: regions there are those described by ANS Forth as contiguous; but you
4908: can be sure that the dictionary is allocated towards increasing
4909: addresses even between contiguous regions. The memory order of
4910: allocations in the heap is platform-dependent (and possibly different
4911: from one run to the next).
4912:
1.27 crook 4913:
1.32 anton 4914: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4915: @subsection Dictionary allocation
1.27 crook 4916: @cindex reserving data space
4917: @cindex data space - reserving some
4918:
1.32 anton 4919: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4920: you want to deallocate X, you also deallocate everything
4921: allocated after X.
4922:
1.68 anton 4923: @cindex contiguous regions in dictionary allocation
1.32 anton 4924: The allocations using the words below are contiguous and grow the region
4925: towards increasing addresses. Other words that allocate dictionary
4926: memory of any kind (i.e., defining words including @code{:noname}) end
4927: the contiguous region and start a new one.
4928:
4929: In ANS Forth only @code{create}d words are guaranteed to produce an
4930: address that is the start of the following contiguous region. In
4931: particular, the cell allocated by @code{variable} is not guaranteed to
4932: be contiguous with following @code{allot}ed memory.
4933:
4934: You can deallocate memory by using @code{allot} with a negative argument
4935: (with some restrictions, see @code{allot}). For larger deallocations use
4936: @code{marker}.
1.27 crook 4937:
1.29 crook 4938:
1.27 crook 4939: doc-here
4940: doc-unused
4941: doc-allot
4942: doc-c,
1.29 crook 4943: doc-f,
1.27 crook 4944: doc-,
4945: doc-2,
4946:
1.32 anton 4947: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4948: course you should allocate memory in an aligned way, too. I.e., before
4949: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4950: The words below align @code{here} if it is not already. Basically it is
4951: only already aligned for a type, if the last allocation was a multiple
4952: of the size of this type and if @code{here} was aligned for this type
4953: before.
4954:
4955: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4956: ANS Forth (@code{maxalign}ed in Gforth).
4957:
4958: doc-align
4959: doc-falign
4960: doc-sfalign
4961: doc-dfalign
4962: doc-maxalign
4963: doc-cfalign
4964:
4965:
4966: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4967: @subsection Heap allocation
4968: @cindex heap allocation
4969: @cindex dynamic allocation of memory
4970: @cindex memory-allocation word set
4971:
1.68 anton 4972: @cindex contiguous regions and heap allocation
1.32 anton 4973: Heap allocation supports deallocation of allocated memory in any
4974: order. Dictionary allocation is not affected by it (i.e., it does not
4975: end a contiguous region). In Gforth, these words are implemented using
4976: the standard C library calls malloc(), free() and resize().
4977:
1.68 anton 4978: The memory region produced by one invocation of @code{allocate} or
4979: @code{resize} is internally contiguous. There is no contiguity between
4980: such a region and any other region (including others allocated from the
4981: heap).
4982:
1.32 anton 4983: doc-allocate
4984: doc-free
4985: doc-resize
4986:
1.27 crook 4987:
1.32 anton 4988: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4989: @subsection Memory Access
4990: @cindex memory access words
4991:
4992: doc-@
4993: doc-!
4994: doc-+!
4995: doc-c@
4996: doc-c!
4997: doc-2@
4998: doc-2!
4999: doc-f@
5000: doc-f!
5001: doc-sf@
5002: doc-sf!
5003: doc-df@
5004: doc-df!
1.144 anton 5005: doc-sw@
5006: doc-uw@
5007: doc-w!
5008: doc-sl@
5009: doc-ul@
5010: doc-l!
1.68 anton 5011:
1.32 anton 5012: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5013: @subsection Address arithmetic
1.1 anton 5014: @cindex address arithmetic words
5015:
1.67 anton 5016: Address arithmetic is the foundation on which you can build data
5017: structures like arrays, records (@pxref{Structures}) and objects
5018: (@pxref{Object-oriented Forth}).
1.32 anton 5019:
1.68 anton 5020: @cindex address unit
5021: @cindex au (address unit)
1.1 anton 5022: ANS Forth does not specify the sizes of the data types. Instead, it
5023: offers a number of words for computing sizes and doing address
1.29 crook 5024: arithmetic. Address arithmetic is performed in terms of address units
5025: (aus); on most systems the address unit is one byte. Note that a
5026: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5027: platforms where it is a noop, it compiles to nothing).
1.1 anton 5028:
1.67 anton 5029: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5030: you have the address of a cell, perform @code{1 cells +}, and you will
5031: have the address of the next cell.
5032:
1.68 anton 5033: @cindex contiguous regions and address arithmetic
1.67 anton 5034: In ANS Forth you can perform address arithmetic only within a contiguous
5035: region, i.e., if you have an address into one region, you can only add
5036: and subtract such that the result is still within the region; you can
5037: only subtract or compare addresses from within the same contiguous
5038: region. Reasons: several contiguous regions can be arranged in memory
5039: in any way; on segmented systems addresses may have unusual
5040: representations, such that address arithmetic only works within a
5041: region. Gforth provides a few more guarantees (linear address space,
5042: dictionary grows upwards), but in general I have found it easy to stay
5043: within contiguous regions (exception: computing and comparing to the
5044: address just beyond the end of an array).
5045:
1.1 anton 5046: @cindex alignment of addresses for types
5047: ANS Forth also defines words for aligning addresses for specific
5048: types. Many computers require that accesses to specific data types
5049: must only occur at specific addresses; e.g., that cells may only be
5050: accessed at addresses divisible by 4. Even if a machine allows unaligned
5051: accesses, it can usually perform aligned accesses faster.
5052:
5053: For the performance-conscious: alignment operations are usually only
5054: necessary during the definition of a data structure, not during the
5055: (more frequent) accesses to it.
5056:
5057: ANS Forth defines no words for character-aligning addresses. This is not
5058: an oversight, but reflects the fact that addresses that are not
5059: char-aligned have no use in the standard and therefore will not be
5060: created.
5061:
5062: @cindex @code{CREATE} and alignment
1.29 crook 5063: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5064: are cell-aligned; in addition, Gforth guarantees that these addresses
5065: are aligned for all purposes.
5066:
1.26 crook 5067: Note that the ANS Forth word @code{char} has nothing to do with address
5068: arithmetic.
1.1 anton 5069:
1.44 crook 5070:
1.1 anton 5071: doc-chars
5072: doc-char+
5073: doc-cells
5074: doc-cell+
5075: doc-cell
5076: doc-aligned
5077: doc-floats
5078: doc-float+
5079: doc-float
5080: doc-faligned
5081: doc-sfloats
5082: doc-sfloat+
5083: doc-sfaligned
5084: doc-dfloats
5085: doc-dfloat+
5086: doc-dfaligned
5087: doc-maxaligned
5088: doc-cfaligned
5089: doc-address-unit-bits
1.145 anton 5090: doc-/w
5091: doc-/l
1.44 crook 5092:
1.32 anton 5093: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5094: @subsection Memory Blocks
5095: @cindex memory block words
1.27 crook 5096: @cindex character strings - moving and copying
5097:
1.49 anton 5098: Memory blocks often represent character strings; For ways of storing
5099: character strings in memory see @ref{String Formats}. For other
5100: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5101:
1.67 anton 5102: A few of these words work on address unit blocks. In that case, you
5103: usually have to insert @code{CHARS} before the word when working on
5104: character strings. Most words work on character blocks, and expect a
5105: char-aligned address.
5106:
5107: When copying characters between overlapping memory regions, use
5108: @code{chars move} or choose carefully between @code{cmove} and
5109: @code{cmove>}.
1.44 crook 5110:
1.1 anton 5111: doc-move
5112: doc-erase
5113: doc-cmove
5114: doc-cmove>
5115: doc-fill
5116: doc-blank
1.21 crook 5117: doc-compare
1.111 anton 5118: doc-str=
5119: doc-str<
5120: doc-string-prefix?
1.21 crook 5121: doc-search
1.27 crook 5122: doc--trailing
5123: doc-/string
1.82 anton 5124: doc-bounds
1.141 anton 5125: doc-pad
1.111 anton 5126:
1.27 crook 5127: @comment TODO examples
5128:
1.1 anton 5129:
1.26 crook 5130: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5131: @section Control Structures
5132: @cindex control structures
5133:
1.33 anton 5134: Control structures in Forth cannot be used interpretively, only in a
5135: colon definition@footnote{To be precise, they have no interpretation
5136: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5137: not like this limitation, but have not seen a satisfying way around it
5138: yet, although many schemes have been proposed.
1.1 anton 5139:
5140: @menu
1.33 anton 5141: * Selection:: IF ... ELSE ... ENDIF
5142: * Simple Loops:: BEGIN ...
1.29 crook 5143: * Counted Loops:: DO
1.67 anton 5144: * Arbitrary control structures::
5145: * Calls and returns::
1.1 anton 5146: * Exception Handling::
5147: @end menu
5148:
5149: @node Selection, Simple Loops, Control Structures, Control Structures
5150: @subsection Selection
5151: @cindex selection control structures
5152: @cindex control structures for selection
5153:
5154: @cindex @code{IF} control structure
5155: @example
1.29 crook 5156: @i{flag}
1.1 anton 5157: IF
1.29 crook 5158: @i{code}
1.1 anton 5159: ENDIF
5160: @end example
1.21 crook 5161: @noindent
1.33 anton 5162:
1.44 crook 5163: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5164: with any bit set represents truth) @i{code} is executed.
1.33 anton 5165:
1.1 anton 5166: @example
1.29 crook 5167: @i{flag}
1.1 anton 5168: IF
1.29 crook 5169: @i{code1}
1.1 anton 5170: ELSE
1.29 crook 5171: @i{code2}
1.1 anton 5172: ENDIF
5173: @end example
5174:
1.44 crook 5175: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5176: executed.
1.33 anton 5177:
1.1 anton 5178: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5179: standard, and @code{ENDIF} is not, although it is quite popular. We
5180: recommend using @code{ENDIF}, because it is less confusing for people
5181: who also know other languages (and is not prone to reinforcing negative
5182: prejudices against Forth in these people). Adding @code{ENDIF} to a
5183: system that only supplies @code{THEN} is simple:
5184: @example
1.82 anton 5185: : ENDIF POSTPONE then ; immediate
1.1 anton 5186: @end example
5187:
5188: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5189: (adv.)} has the following meanings:
5190: @quotation
5191: ... 2b: following next after in order ... 3d: as a necessary consequence
5192: (if you were there, then you saw them).
5193: @end quotation
5194: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5195: and many other programming languages has the meaning 3d.]
5196:
1.21 crook 5197: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5198: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5199: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5200: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5201: @file{compat/control.fs}.
5202:
5203: @cindex @code{CASE} control structure
5204: @example
1.29 crook 5205: @i{n}
1.1 anton 5206: CASE
1.29 crook 5207: @i{n1} OF @i{code1} ENDOF
5208: @i{n2} OF @i{code2} ENDOF
1.1 anton 5209: @dots{}
1.68 anton 5210: ( n ) @i{default-code} ( n )
1.131 anton 5211: ENDCASE ( )
1.1 anton 5212: @end example
5213:
1.131 anton 5214: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5215: no @i{ni} matches, the optional @i{default-code} is executed. The
5216: optional default case can be added by simply writing the code after
5217: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5218: but must not consume it. The value @i{n} is consumed by this
5219: construction (either by a OF that matches, or by the ENDCASE, if no OF
5220: matches).
1.1 anton 5221:
1.69 anton 5222: @progstyle
1.131 anton 5223: To keep the code understandable, you should ensure that you change the
5224: stack in the same way (wrt. number and types of stack items consumed
5225: and pushed) on all paths through a selection construct.
1.69 anton 5226:
1.1 anton 5227: @node Simple Loops, Counted Loops, Selection, Control Structures
5228: @subsection Simple Loops
5229: @cindex simple loops
5230: @cindex loops without count
5231:
5232: @cindex @code{WHILE} loop
5233: @example
5234: BEGIN
1.29 crook 5235: @i{code1}
5236: @i{flag}
1.1 anton 5237: WHILE
1.29 crook 5238: @i{code2}
1.1 anton 5239: REPEAT
5240: @end example
5241:
1.29 crook 5242: @i{code1} is executed and @i{flag} is computed. If it is true,
5243: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5244: false, execution continues after the @code{REPEAT}.
5245:
5246: @cindex @code{UNTIL} loop
5247: @example
5248: BEGIN
1.29 crook 5249: @i{code}
5250: @i{flag}
1.1 anton 5251: UNTIL
5252: @end example
5253:
1.29 crook 5254: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5255:
1.69 anton 5256: @progstyle
5257: To keep the code understandable, a complete iteration of the loop should
5258: not change the number and types of the items on the stacks.
5259:
1.1 anton 5260: @cindex endless loop
5261: @cindex loops, endless
5262: @example
5263: BEGIN
1.29 crook 5264: @i{code}
1.1 anton 5265: AGAIN
5266: @end example
5267:
5268: This is an endless loop.
5269:
5270: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5271: @subsection Counted Loops
5272: @cindex counted loops
5273: @cindex loops, counted
5274: @cindex @code{DO} loops
5275:
5276: The basic counted loop is:
5277: @example
1.29 crook 5278: @i{limit} @i{start}
1.1 anton 5279: ?DO
1.29 crook 5280: @i{body}
1.1 anton 5281: LOOP
5282: @end example
5283:
1.29 crook 5284: This performs one iteration for every integer, starting from @i{start}
5285: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5286: accessed with @code{i}. For example, the loop:
1.1 anton 5287: @example
5288: 10 0 ?DO
5289: i .
5290: LOOP
5291: @end example
1.21 crook 5292: @noindent
5293: prints @code{0 1 2 3 4 5 6 7 8 9}
5294:
1.1 anton 5295: The index of the innermost loop can be accessed with @code{i}, the index
5296: of the next loop with @code{j}, and the index of the third loop with
5297: @code{k}.
5298:
1.44 crook 5299:
1.1 anton 5300: doc-i
5301: doc-j
5302: doc-k
5303:
1.44 crook 5304:
1.1 anton 5305: The loop control data are kept on the return stack, so there are some
1.21 crook 5306: restrictions on mixing return stack accesses and counted loop words. In
5307: particuler, if you put values on the return stack outside the loop, you
5308: cannot read them inside the loop@footnote{well, not in a way that is
5309: portable.}. If you put values on the return stack within a loop, you
5310: have to remove them before the end of the loop and before accessing the
5311: index of the loop.
1.1 anton 5312:
5313: There are several variations on the counted loop:
5314:
1.21 crook 5315: @itemize @bullet
5316: @item
5317: @code{LEAVE} leaves the innermost counted loop immediately; execution
5318: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5319:
5320: @example
5321: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5322: @end example
5323: prints @code{0 1 2 3}
5324:
1.1 anton 5325:
1.21 crook 5326: @item
5327: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5328: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5329: return stack so @code{EXIT} can get to its return address. For example:
5330:
5331: @example
5332: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5333: @end example
5334: prints @code{0 1 2 3}
5335:
5336:
5337: @item
1.29 crook 5338: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5339: (and @code{LOOP} iterates until they become equal by wrap-around
5340: arithmetic). This behaviour is usually not what you want. Therefore,
5341: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5342: @code{?DO}), which do not enter the loop if @i{start} is greater than
5343: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5344: unsigned loop parameters.
5345:
1.21 crook 5346: @item
5347: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5348: the loop, independent of the loop parameters. Do not use @code{DO}, even
5349: if you know that the loop is entered in any case. Such knowledge tends
5350: to become invalid during maintenance of a program, and then the
5351: @code{DO} will make trouble.
5352:
5353: @item
1.29 crook 5354: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5355: index by @i{n} instead of by 1. The loop is terminated when the border
5356: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5357:
1.21 crook 5358: @example
5359: 4 0 +DO i . 2 +LOOP
5360: @end example
5361: @noindent
5362: prints @code{0 2}
5363:
5364: @example
5365: 4 1 +DO i . 2 +LOOP
5366: @end example
5367: @noindent
5368: prints @code{1 3}
1.1 anton 5369:
1.68 anton 5370: @item
1.1 anton 5371: @cindex negative increment for counted loops
5372: @cindex counted loops with negative increment
1.29 crook 5373: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5374:
1.21 crook 5375: @example
5376: -1 0 ?DO i . -1 +LOOP
5377: @end example
5378: @noindent
5379: prints @code{0 -1}
1.1 anton 5380:
1.21 crook 5381: @example
5382: 0 0 ?DO i . -1 +LOOP
5383: @end example
5384: prints nothing.
1.1 anton 5385:
1.29 crook 5386: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5387: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5388: index by @i{u} each iteration. The loop is terminated when the border
5389: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5390: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5391:
1.21 crook 5392: @example
5393: -2 0 -DO i . 1 -LOOP
5394: @end example
5395: @noindent
5396: prints @code{0 -1}
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}
5403:
5404: @example
5405: 0 0 -DO i . 1 -LOOP
5406: @end example
5407: @noindent
5408: prints nothing.
1.1 anton 5409:
1.21 crook 5410: @end itemize
1.1 anton 5411:
5412: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5413: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5414: for these words that uses only standard words is provided in
5415: @file{compat/loops.fs}.
1.1 anton 5416:
5417:
5418: @cindex @code{FOR} loops
1.26 crook 5419: Another counted loop is:
1.1 anton 5420: @example
1.29 crook 5421: @i{n}
1.1 anton 5422: FOR
1.29 crook 5423: @i{body}
1.1 anton 5424: NEXT
5425: @end example
5426: This is the preferred loop of native code compiler writers who are too
1.26 crook 5427: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5428: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5429: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5430: Forth systems may behave differently, even if they support @code{FOR}
5431: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5432:
5433: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5434: @subsection Arbitrary control structures
5435: @cindex control structures, user-defined
5436:
5437: @cindex control-flow stack
5438: ANS Forth permits and supports using control structures in a non-nested
5439: way. Information about incomplete control structures is stored on the
5440: control-flow stack. This stack may be implemented on the Forth data
5441: stack, and this is what we have done in Gforth.
5442:
5443: @cindex @code{orig}, control-flow stack item
5444: @cindex @code{dest}, control-flow stack item
5445: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5446: entry represents a backward branch target. A few words are the basis for
5447: building any control structure possible (except control structures that
5448: need storage, like calls, coroutines, and backtracking).
5449:
1.44 crook 5450:
1.1 anton 5451: doc-if
5452: doc-ahead
5453: doc-then
5454: doc-begin
5455: doc-until
5456: doc-again
5457: doc-cs-pick
5458: doc-cs-roll
5459:
1.44 crook 5460:
1.21 crook 5461: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5462: manipulate the control-flow stack in a portable way. Without them, you
5463: would need to know how many stack items are occupied by a control-flow
5464: entry (many systems use one cell. In Gforth they currently take three,
5465: but this may change in the future).
5466:
1.1 anton 5467: Some standard control structure words are built from these words:
5468:
1.44 crook 5469:
1.1 anton 5470: doc-else
5471: doc-while
5472: doc-repeat
5473:
1.44 crook 5474:
5475: @noindent
1.1 anton 5476: Gforth adds some more control-structure words:
5477:
1.44 crook 5478:
1.1 anton 5479: doc-endif
5480: doc-?dup-if
5481: doc-?dup-0=-if
5482:
1.44 crook 5483:
5484: @noindent
1.1 anton 5485: Counted loop words constitute a separate group of words:
5486:
1.44 crook 5487:
1.1 anton 5488: doc-?do
5489: doc-+do
5490: doc-u+do
5491: doc--do
5492: doc-u-do
5493: doc-do
5494: doc-for
5495: doc-loop
5496: doc-+loop
5497: doc--loop
5498: doc-next
5499: doc-leave
5500: doc-?leave
5501: doc-unloop
5502: doc-done
5503:
1.44 crook 5504:
1.21 crook 5505: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5506: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5507: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5508: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5509: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5510: resolved (by using one of the loop-ending words or @code{DONE}).
5511:
1.44 crook 5512: @noindent
1.26 crook 5513: Another group of control structure words are:
1.1 anton 5514:
1.44 crook 5515:
1.1 anton 5516: doc-case
5517: doc-endcase
5518: doc-of
5519: doc-endof
5520:
1.44 crook 5521:
1.21 crook 5522: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5523: @code{CS-ROLL}.
1.1 anton 5524:
5525: @subsubsection Programming Style
1.47 crook 5526: @cindex control structures programming style
5527: @cindex programming style, arbitrary control structures
1.1 anton 5528:
5529: In order to ensure readability we recommend that you do not create
5530: arbitrary control structures directly, but define new control structure
5531: words for the control structure you want and use these words in your
1.26 crook 5532: program. For example, instead of writing:
1.1 anton 5533:
5534: @example
1.26 crook 5535: BEGIN
1.1 anton 5536: ...
1.26 crook 5537: IF [ 1 CS-ROLL ]
1.1 anton 5538: ...
1.26 crook 5539: AGAIN THEN
1.1 anton 5540: @end example
5541:
1.21 crook 5542: @noindent
1.1 anton 5543: we recommend defining control structure words, e.g.,
5544:
5545: @example
1.26 crook 5546: : WHILE ( DEST -- ORIG DEST )
5547: POSTPONE IF
5548: 1 CS-ROLL ; immediate
5549:
5550: : REPEAT ( orig dest -- )
5551: POSTPONE AGAIN
5552: POSTPONE THEN ; immediate
1.1 anton 5553: @end example
5554:
1.21 crook 5555: @noindent
1.1 anton 5556: and then using these to create the control structure:
5557:
5558: @example
1.26 crook 5559: BEGIN
1.1 anton 5560: ...
1.26 crook 5561: WHILE
1.1 anton 5562: ...
1.26 crook 5563: REPEAT
1.1 anton 5564: @end example
5565:
5566: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5567: @code{WHILE} are predefined, so in this example it would not be
5568: necessary to define them.
5569:
5570: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5571: @subsection Calls and returns
5572: @cindex calling a definition
5573: @cindex returning from a definition
5574:
1.3 anton 5575: @cindex recursive definitions
5576: A definition can be called simply be writing the name of the definition
1.26 crook 5577: to be called. Normally a definition is invisible during its own
1.3 anton 5578: definition. If you want to write a directly recursive definition, you
1.26 crook 5579: can use @code{recursive} to make the current definition visible, or
5580: @code{recurse} to call the current definition directly.
1.3 anton 5581:
1.44 crook 5582:
1.3 anton 5583: doc-recursive
5584: doc-recurse
5585:
1.44 crook 5586:
1.21 crook 5587: @comment TODO add example of the two recursion methods
1.12 anton 5588: @quotation
5589: @progstyle
5590: I prefer using @code{recursive} to @code{recurse}, because calling the
5591: definition by name is more descriptive (if the name is well-chosen) than
5592: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5593: implementation, it is much better to read (and think) ``now sort the
5594: partitions'' than to read ``now do a recursive call''.
5595: @end quotation
1.3 anton 5596:
1.29 crook 5597: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5598:
5599: @example
1.28 crook 5600: Defer foo
1.3 anton 5601:
5602: : bar ( ... -- ... )
5603: ... foo ... ;
5604:
5605: :noname ( ... -- ... )
5606: ... bar ... ;
5607: IS foo
5608: @end example
5609:
1.44 crook 5610: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5611:
1.26 crook 5612: The current definition returns control to the calling definition when
1.33 anton 5613: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5614:
5615: doc-exit
5616: doc-;s
5617:
1.44 crook 5618:
1.1 anton 5619: @node Exception Handling, , Calls and returns, Control Structures
5620: @subsection Exception Handling
1.26 crook 5621: @cindex exceptions
1.1 anton 5622:
1.68 anton 5623: @c quit is a very bad idea for error handling,
5624: @c because it does not translate into a THROW
5625: @c it also does not belong into this chapter
5626:
5627: If a word detects an error condition that it cannot handle, it can
5628: @code{throw} an exception. In the simplest case, this will terminate
5629: your program, and report an appropriate error.
1.21 crook 5630:
1.68 anton 5631: doc-throw
1.1 anton 5632:
1.69 anton 5633: @code{Throw} consumes a cell-sized error number on the stack. There are
5634: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5635: Gforth (and most other systems) you can use the iors produced by various
5636: words as error numbers (e.g., a typical use of @code{allocate} is
5637: @code{allocate throw}). Gforth also provides the word @code{exception}
5638: to define your own error numbers (with decent error reporting); an ANS
5639: Forth version of this word (but without the error messages) is available
5640: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5641: numbers (anything outside the range -4095..0), but won't get nice error
5642: messages, only numbers. For example, try:
5643:
5644: @example
1.69 anton 5645: -10 throw \ ANS defined
5646: -267 throw \ system defined
5647: s" my error" exception throw \ user defined
5648: 7 throw \ arbitrary number
1.68 anton 5649: @end example
5650:
5651: doc---exception-exception
1.1 anton 5652:
1.69 anton 5653: A common idiom to @code{THROW} a specific error if a flag is true is
5654: this:
5655:
5656: @example
5657: @code{( flag ) 0<> @i{errno} and throw}
5658: @end example
5659:
5660: Your program can provide exception handlers to catch exceptions. An
5661: exception handler can be used to correct the problem, or to clean up
5662: some data structures and just throw the exception to the next exception
5663: handler. Note that @code{throw} jumps to the dynamically innermost
5664: exception handler. The system's exception handler is outermost, and just
5665: prints an error and restarts command-line interpretation (or, in batch
5666: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5667:
1.68 anton 5668: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5669:
1.68 anton 5670: doc-catch
5671:
5672: The most common use of exception handlers is to clean up the state when
5673: an error happens. E.g.,
1.1 anton 5674:
1.26 crook 5675: @example
1.68 anton 5676: base @ >r hex \ actually the hex should be inside foo, or we h
5677: ['] foo catch ( nerror|0 )
5678: r> base !
1.69 anton 5679: ( nerror|0 ) throw \ pass it on
1.26 crook 5680: @end example
1.1 anton 5681:
1.69 anton 5682: A use of @code{catch} for handling the error @code{myerror} might look
5683: like this:
1.44 crook 5684:
1.68 anton 5685: @example
1.69 anton 5686: ['] foo catch
5687: CASE
5688: myerror OF ... ( do something about it ) ENDOF
5689: dup throw \ default: pass other errors on, do nothing on non-errors
5690: ENDCASE
1.68 anton 5691: @end example
1.44 crook 5692:
1.68 anton 5693: Having to wrap the code into a separate word is often cumbersome,
5694: therefore Gforth provides an alternative syntax:
1.1 anton 5695:
5696: @example
1.69 anton 5697: TRY
1.68 anton 5698: @i{code1}
1.69 anton 5699: RECOVER \ optional
1.68 anton 5700: @i{code2} \ optional
1.69 anton 5701: ENDTRY
1.1 anton 5702: @end example
5703:
1.68 anton 5704: This performs @i{Code1}. If @i{code1} completes normally, execution
5705: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5706: reset to the state during @code{try}, the throw value is pushed on the
5707: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5708: through the @code{endtry} into the following code.
1.26 crook 5709:
1.68 anton 5710: doc-try
5711: doc-recover
5712: doc-endtry
1.26 crook 5713:
1.69 anton 5714: The cleanup example from above in this syntax:
1.26 crook 5715:
1.68 anton 5716: @example
1.69 anton 5717: base @ >r TRY
1.68 anton 5718: hex foo \ now the hex is placed correctly
1.69 anton 5719: 0 \ value for throw
1.92 anton 5720: RECOVER ENDTRY
1.68 anton 5721: r> base ! throw
1.1 anton 5722: @end example
5723:
1.69 anton 5724: And here's the error handling example:
1.1 anton 5725:
1.68 anton 5726: @example
1.69 anton 5727: TRY
1.68 anton 5728: foo
1.69 anton 5729: RECOVER
5730: CASE
5731: myerror OF ... ( do something about it ) ENDOF
5732: throw \ pass other errors on
5733: ENDCASE
5734: ENDTRY
1.68 anton 5735: @end example
1.1 anton 5736:
1.69 anton 5737: @progstyle
5738: As usual, you should ensure that the stack depth is statically known at
5739: the end: either after the @code{throw} for passing on errors, or after
5740: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5741: selection construct for handling the error).
5742:
1.68 anton 5743: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5744: and you can provide an error message. @code{Abort} just produces an
5745: ``Aborted'' error.
1.1 anton 5746:
1.68 anton 5747: The problem with these words is that exception handlers cannot
5748: differentiate between different @code{abort"}s; they just look like
5749: @code{-2 throw} to them (the error message cannot be accessed by
5750: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5751: exception handlers.
1.44 crook 5752:
1.68 anton 5753: doc-abort"
1.26 crook 5754: doc-abort
1.29 crook 5755:
5756:
1.44 crook 5757:
1.29 crook 5758: @c -------------------------------------------------------------
1.47 crook 5759: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5760: @section Defining Words
5761: @cindex defining words
5762:
1.47 crook 5763: Defining words are used to extend Forth by creating new entries in the dictionary.
5764:
1.29 crook 5765: @menu
1.67 anton 5766: * CREATE::
1.44 crook 5767: * Variables:: Variables and user variables
1.67 anton 5768: * Constants::
1.44 crook 5769: * Values:: Initialised variables
1.67 anton 5770: * Colon Definitions::
1.44 crook 5771: * Anonymous Definitions:: Definitions without names
1.69 anton 5772: * Supplying names:: Passing definition names as strings
1.67 anton 5773: * User-defined Defining Words::
1.44 crook 5774: * Deferred words:: Allow forward references
1.67 anton 5775: * Aliases::
1.29 crook 5776: @end menu
5777:
1.44 crook 5778: @node CREATE, Variables, Defining Words, Defining Words
5779: @subsection @code{CREATE}
1.29 crook 5780: @cindex simple defining words
5781: @cindex defining words, simple
5782:
5783: Defining words are used to create new entries in the dictionary. The
5784: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5785: this:
5786:
5787: @example
5788: CREATE new-word1
5789: @end example
5790:
1.69 anton 5791: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5792: input stream (@code{new-word1} in our example). It generates a
5793: dictionary entry for @code{new-word1}. When @code{new-word1} is
5794: executed, all that it does is leave an address on the stack. The address
5795: represents the value of the data space pointer (@code{HERE}) at the time
5796: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5797: associating a name with the address of a region of memory.
1.29 crook 5798:
1.34 anton 5799: doc-create
5800:
1.69 anton 5801: Note that in ANS Forth guarantees only for @code{create} that its body
5802: is in dictionary data space (i.e., where @code{here}, @code{allot}
5803: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5804: @code{create}d words can be modified with @code{does>}
5805: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5806: can only be applied to @code{create}d words.
5807:
1.29 crook 5808: By extending this example to reserve some memory in data space, we end
1.69 anton 5809: up with something like a @i{variable}. Here are two different ways to do
5810: it:
1.29 crook 5811:
5812: @example
5813: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5814: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5815: @end example
5816:
5817: The variable can be examined and modified using @code{@@} (``fetch'') and
5818: @code{!} (``store'') like this:
5819:
5820: @example
5821: new-word2 @@ . \ get address, fetch from it and display
5822: 1234 new-word2 ! \ new value, get address, store to it
5823: @end example
5824:
1.44 crook 5825: @cindex arrays
5826: A similar mechanism can be used to create arrays. For example, an
5827: 80-character text input buffer:
1.29 crook 5828:
5829: @example
1.44 crook 5830: CREATE text-buf 80 chars allot
5831:
5832: text-buf 0 chars c@@ \ the 1st character (offset 0)
5833: text-buf 3 chars c@@ \ the 4th character (offset 3)
5834: @end example
1.29 crook 5835:
1.44 crook 5836: You can build arbitrarily complex data structures by allocating
1.49 anton 5837: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5838: learn about some Gforth tools that make it easier,
1.49 anton 5839: @xref{Structures}.
1.44 crook 5840:
5841:
5842: @node Variables, Constants, CREATE, Defining Words
5843: @subsection Variables
5844: @cindex variables
5845:
5846: The previous section showed how a sequence of commands could be used to
5847: generate a variable. As a final refinement, the whole code sequence can
5848: be wrapped up in a defining word (pre-empting the subject of the next
5849: section), making it easier to create new variables:
5850:
5851: @example
5852: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5853: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5854:
5855: myvariableX foo \ variable foo starts off with an unknown value
5856: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5857:
5858: 45 3 * foo ! \ set foo to 135
5859: 1234 joe ! \ set joe to 1234
5860: 3 joe +! \ increment joe by 3.. to 1237
5861: @end example
5862:
5863: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5864: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5865: guarantee that a @code{Variable} is initialised when it is created
5866: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5867: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5868: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5869: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5870: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5871: store a boolean, you can use @code{on} and @code{off} to toggle its
5872: state.
1.29 crook 5873:
1.34 anton 5874: doc-variable
5875: doc-2variable
5876: doc-fvariable
5877:
1.29 crook 5878: @cindex user variables
5879: @cindex user space
5880: The defining word @code{User} behaves in the same way as @code{Variable}.
5881: The difference is that it reserves space in @i{user (data) space} rather
5882: than normal data space. In a Forth system that has a multi-tasker, each
5883: task has its own set of user variables.
5884:
1.34 anton 5885: doc-user
1.67 anton 5886: @c doc-udp
5887: @c doc-uallot
1.34 anton 5888:
1.29 crook 5889: @comment TODO is that stuff about user variables strictly correct? Is it
5890: @comment just terminal tasks that have user variables?
5891: @comment should document tasker.fs (with some examples) elsewhere
5892: @comment in this manual, then expand on user space and user variables.
5893:
1.44 crook 5894: @node Constants, Values, Variables, Defining Words
5895: @subsection Constants
5896: @cindex constants
5897:
5898: @code{Constant} allows you to declare a fixed value and refer to it by
5899: name. For example:
1.29 crook 5900:
5901: @example
5902: 12 Constant INCHES-PER-FOOT
5903: 3E+08 fconstant SPEED-O-LIGHT
5904: @end example
5905:
5906: A @code{Variable} can be both read and written, so its run-time
5907: behaviour is to supply an address through which its current value can be
5908: manipulated. In contrast, the value of a @code{Constant} cannot be
5909: changed once it has been declared@footnote{Well, often it can be -- but
5910: not in a Standard, portable way. It's safer to use a @code{Value} (read
5911: on).} so it's not necessary to supply the address -- it is more
5912: efficient to return the value of the constant directly. That's exactly
5913: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5914: the top of the stack (You can find one
5915: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5916:
1.69 anton 5917: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5918: double and floating-point constants, respectively.
5919:
1.34 anton 5920: doc-constant
5921: doc-2constant
5922: doc-fconstant
5923:
5924: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5925: @c nac-> How could that not be true in an ANS Forth? You can't define a
5926: @c constant, use it and then delete the definition of the constant..
1.69 anton 5927:
5928: @c anton->An ANS Forth system can compile a constant to a literal; On
5929: @c decompilation you would see only the number, just as if it had been used
5930: @c in the first place. The word will stay, of course, but it will only be
5931: @c used by the text interpreter (no run-time duties, except when it is
5932: @c POSTPONEd or somesuch).
5933:
5934: @c nac:
1.44 crook 5935: @c I agree that it's rather deep, but IMO it is an important difference
5936: @c relative to other programming languages.. often it's annoying: it
5937: @c certainly changes my programming style relative to C.
5938:
1.69 anton 5939: @c anton: In what way?
5940:
1.29 crook 5941: Constants in Forth behave differently from their equivalents in other
5942: programming languages. In other languages, a constant (such as an EQU in
5943: assembler or a #define in C) only exists at compile-time; in the
5944: executable program the constant has been translated into an absolute
5945: number and, unless you are using a symbolic debugger, it's impossible to
5946: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5947: an entry in the header space and remains there after the code that uses
5948: it has been defined. In fact, it must remain in the dictionary since it
5949: has run-time duties to perform. For example:
1.29 crook 5950:
5951: @example
5952: 12 Constant INCHES-PER-FOOT
5953: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5954: @end example
5955:
5956: @cindex in-lining of constants
5957: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5958: associated with the constant @code{INCHES-PER-FOOT}. If you use
5959: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5960: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5961: attempt to optimise constants by in-lining them where they are used. You
5962: can force Gforth to in-line a constant like this:
5963:
5964: @example
5965: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5966: @end example
5967:
5968: If you use @code{see} to decompile @i{this} version of
5969: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5970: longer present. To understand how this works, read
5971: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5972:
5973: In-lining constants in this way might improve execution time
5974: fractionally, and can ensure that a constant is now only referenced at
5975: compile-time. However, the definition of the constant still remains in
5976: the dictionary. Some Forth compilers provide a mechanism for controlling
5977: a second dictionary for holding transient words such that this second
5978: dictionary can be deleted later in order to recover memory
5979: space. However, there is no standard way of doing this.
5980:
5981:
1.44 crook 5982: @node Values, Colon Definitions, Constants, Defining Words
5983: @subsection Values
5984: @cindex values
1.34 anton 5985:
1.69 anton 5986: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5987: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5988: (not in ANS Forth) you can access (and change) a @code{value} also with
5989: @code{>body}.
5990:
5991: Here are some
5992: examples:
1.29 crook 5993:
5994: @example
1.69 anton 5995: 12 Value APPLES \ Define APPLES with an initial value of 12
5996: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5997: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5998: APPLES \ puts 35 on the top of the stack.
1.29 crook 5999: @end example
6000:
1.44 crook 6001: doc-value
6002: doc-to
1.29 crook 6003:
1.35 anton 6004:
1.69 anton 6005:
1.44 crook 6006: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6007: @subsection Colon Definitions
6008: @cindex colon definitions
1.35 anton 6009:
6010: @example
1.44 crook 6011: : name ( ... -- ... )
6012: word1 word2 word3 ;
1.29 crook 6013: @end example
6014:
1.44 crook 6015: @noindent
6016: Creates a word called @code{name} that, upon execution, executes
6017: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6018:
1.49 anton 6019: The explanation above is somewhat superficial. For simple examples of
6020: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6021: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6022: Compilation Semantics}.
1.29 crook 6023:
1.44 crook 6024: doc-:
6025: doc-;
1.1 anton 6026:
1.34 anton 6027:
1.69 anton 6028: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6029: @subsection Anonymous Definitions
6030: @cindex colon definitions
6031: @cindex defining words without name
1.34 anton 6032:
1.44 crook 6033: Sometimes you want to define an @dfn{anonymous word}; a word without a
6034: name. You can do this with:
1.1 anton 6035:
1.44 crook 6036: doc-:noname
1.1 anton 6037:
1.44 crook 6038: This leaves the execution token for the word on the stack after the
6039: closing @code{;}. Here's an example in which a deferred word is
6040: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6041:
1.29 crook 6042: @example
1.44 crook 6043: Defer deferred
6044: :noname ( ... -- ... )
6045: ... ;
6046: IS deferred
1.29 crook 6047: @end example
1.26 crook 6048:
1.44 crook 6049: @noindent
6050: Gforth provides an alternative way of doing this, using two separate
6051: words:
1.27 crook 6052:
1.44 crook 6053: doc-noname
6054: @cindex execution token of last defined word
1.116 anton 6055: doc-latestxt
1.1 anton 6056:
1.44 crook 6057: @noindent
6058: The previous example can be rewritten using @code{noname} and
1.116 anton 6059: @code{latestxt}:
1.1 anton 6060:
1.26 crook 6061: @example
1.44 crook 6062: Defer deferred
6063: noname : ( ... -- ... )
6064: ... ;
1.116 anton 6065: latestxt IS deferred
1.26 crook 6066: @end example
1.1 anton 6067:
1.29 crook 6068: @noindent
1.44 crook 6069: @code{noname} works with any defining word, not just @code{:}.
6070:
1.116 anton 6071: @code{latestxt} also works when the last word was not defined as
1.71 anton 6072: @code{noname}. It does not work for combined words, though. It also has
6073: the useful property that is is valid as soon as the header for a
6074: definition has been built. Thus:
1.44 crook 6075:
6076: @example
1.116 anton 6077: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6078: @end example
1.1 anton 6079:
1.44 crook 6080: @noindent
6081: prints 3 numbers; the last two are the same.
1.26 crook 6082:
1.69 anton 6083: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6084: @subsection Supplying the name of a defined word
6085: @cindex names for defined words
6086: @cindex defining words, name given in a string
6087:
6088: By default, a defining word takes the name for the defined word from the
6089: input stream. Sometimes you want to supply the name from a string. You
6090: can do this with:
6091:
6092: doc-nextname
6093:
6094: For example:
6095:
6096: @example
6097: s" foo" nextname create
6098: @end example
6099:
6100: @noindent
6101: is equivalent to:
6102:
6103: @example
6104: create foo
6105: @end example
6106:
6107: @noindent
6108: @code{nextname} works with any defining word.
6109:
1.1 anton 6110:
1.69 anton 6111: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6112: @subsection User-defined Defining Words
6113: @cindex user-defined defining words
6114: @cindex defining words, user-defined
1.1 anton 6115:
1.29 crook 6116: You can create a new defining word by wrapping defining-time code around
6117: an existing defining word and putting the sequence in a colon
1.69 anton 6118: definition.
6119:
6120: @c anton: This example is very complex and leads in a quite different
6121: @c direction from the CREATE-DOES> stuff that follows. It should probably
6122: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6123: @c subsection of Defining Words)
6124:
6125: For example, suppose that you have a word @code{stats} that
1.29 crook 6126: gathers statistics about colon definitions given the @i{xt} of the
6127: definition, and you want every colon definition in your application to
6128: make a call to @code{stats}. You can define and use a new version of
6129: @code{:} like this:
6130:
6131: @example
6132: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6133: ... ; \ other code
6134:
1.116 anton 6135: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6136:
6137: my: foo + - ;
6138: @end example
6139:
6140: When @code{foo} is defined using @code{my:} these steps occur:
6141:
6142: @itemize @bullet
6143: @item
6144: @code{my:} is executed.
6145: @item
6146: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6147: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6148: the input stream for a name, builds a dictionary header for the name
6149: @code{foo} and switches @code{state} from interpret to compile.
6150: @item
1.116 anton 6151: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6152: being defined -- @code{foo} -- onto the stack.
6153: @item
6154: The code that was produced by @code{postpone literal} is executed; this
6155: causes the value on the stack to be compiled as a literal in the code
6156: area of @code{foo}.
6157: @item
6158: The code @code{['] stats} compiles a literal into the definition of
6159: @code{my:}. When @code{compile,} is executed, that literal -- the
6160: execution token for @code{stats} -- is layed down in the code area of
6161: @code{foo} , following the literal@footnote{Strictly speaking, the
6162: mechanism that @code{compile,} uses to convert an @i{xt} into something
6163: in the code area is implementation-dependent. A threaded implementation
6164: might spit out the execution token directly whilst another
6165: implementation might spit out a native code sequence.}.
6166: @item
6167: At this point, the execution of @code{my:} is complete, and control
6168: returns to the text interpreter. The text interpreter is in compile
6169: state, so subsequent text @code{+ -} is compiled into the definition of
6170: @code{foo} and the @code{;} terminates the definition as always.
6171: @end itemize
6172:
6173: You can use @code{see} to decompile a word that was defined using
6174: @code{my:} and see how it is different from a normal @code{:}
6175: definition. For example:
6176:
6177: @example
6178: : bar + - ; \ like foo but using : rather than my:
6179: see bar
6180: : bar
6181: + - ;
6182: see foo
6183: : foo
6184: 107645672 stats + - ;
6185:
1.140 anton 6186: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6187: @end example
6188:
6189: You can use techniques like this to make new defining words in terms of
6190: @i{any} existing defining word.
1.1 anton 6191:
6192:
1.29 crook 6193: @cindex defining defining words
1.26 crook 6194: @cindex @code{CREATE} ... @code{DOES>}
6195: If you want the words defined with your defining words to behave
6196: differently from words defined with standard defining words, you can
6197: write your defining word like this:
1.1 anton 6198:
6199: @example
1.26 crook 6200: : def-word ( "name" -- )
1.29 crook 6201: CREATE @i{code1}
1.26 crook 6202: DOES> ( ... -- ... )
1.29 crook 6203: @i{code2} ;
1.26 crook 6204:
6205: def-word name
1.1 anton 6206: @end example
6207:
1.29 crook 6208: @cindex child words
6209: This fragment defines a @dfn{defining word} @code{def-word} and then
6210: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6211: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6212: is not executed at this time. The word @code{name} is sometimes called a
6213: @dfn{child} of @code{def-word}.
6214:
6215: When you execute @code{name}, the address of the body of @code{name} is
6216: put on the data stack and @i{code2} is executed (the address of the body
6217: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6218: @code{CREATE}, i.e., the address a @code{create}d word returns by
6219: default).
6220:
6221: @c anton:
6222: @c www.dictionary.com says:
6223: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6224: @c several generations of absence, usually caused by the chance
6225: @c recombination of genes. 2.An individual or a part that exhibits
6226: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6227: @c of previous behavior after a period of absence.
6228: @c
6229: @c Doesn't seem to fit.
1.29 crook 6230:
1.69 anton 6231: @c @cindex atavism in child words
1.33 anton 6232: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6233: similarly; they all have a common run-time behaviour determined by
6234: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6235: body of the child word. The structure of the data is common to all
6236: children of @code{def-word}, but the data values are specific -- and
6237: private -- to each child word. When a child word is executed, the
6238: address of its private data area is passed as a parameter on TOS to be
6239: used and manipulated@footnote{It is legitimate both to read and write to
6240: this data area.} by @i{code2}.
1.29 crook 6241:
6242: The two fragments of code that make up the defining words act (are
6243: executed) at two completely separate times:
1.1 anton 6244:
1.29 crook 6245: @itemize @bullet
6246: @item
6247: At @i{define time}, the defining word executes @i{code1} to generate a
6248: child word
6249: @item
6250: At @i{child execution time}, when a child word is invoked, @i{code2}
6251: is executed, using parameters (data) that are private and specific to
6252: the child word.
6253: @end itemize
6254:
1.44 crook 6255: Another way of understanding the behaviour of @code{def-word} and
6256: @code{name} is to say that, if you make the following definitions:
1.33 anton 6257: @example
6258: : def-word1 ( "name" -- )
6259: CREATE @i{code1} ;
6260:
6261: : action1 ( ... -- ... )
6262: @i{code2} ;
6263:
6264: def-word1 name1
6265: @end example
6266:
1.44 crook 6267: @noindent
6268: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6269:
1.29 crook 6270: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6271:
1.1 anton 6272: @example
1.29 crook 6273: : CONSTANT ( w "name" -- )
6274: CREATE ,
1.26 crook 6275: DOES> ( -- w )
6276: @@ ;
1.1 anton 6277: @end example
6278:
1.29 crook 6279: @comment There is a beautiful description of how this works and what
6280: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6281: @comment commentary on the Counting Fruits problem.
6282:
6283: When you create a constant with @code{5 CONSTANT five}, a set of
6284: define-time actions take place; first a new word @code{five} is created,
6285: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6286: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6287: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6288: no code of its own; it simply contains a data field and a pointer to the
6289: code that follows @code{DOES>} in its defining word. That makes words
6290: created in this way very compact.
6291:
6292: The final example in this section is intended to remind you that space
6293: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6294: both read and written by a Standard program@footnote{Exercise: use this
6295: example as a starting point for your own implementation of @code{Value}
6296: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6297: @code{[']}.}:
6298:
6299: @example
6300: : foo ( "name" -- )
6301: CREATE -1 ,
6302: DOES> ( -- )
1.33 anton 6303: @@ . ;
1.29 crook 6304:
6305: foo first-word
6306: foo second-word
6307:
6308: 123 ' first-word >BODY !
6309: @end example
6310:
6311: If @code{first-word} had been a @code{CREATE}d word, we could simply
6312: have executed it to get the address of its data field. However, since it
6313: was defined to have @code{DOES>} actions, its execution semantics are to
6314: perform those @code{DOES>} actions. To get the address of its data field
6315: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6316: translate the xt into the address of the data field. When you execute
6317: @code{first-word}, it will display @code{123}. When you execute
6318: @code{second-word} it will display @code{-1}.
1.26 crook 6319:
6320: @cindex stack effect of @code{DOES>}-parts
6321: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6322: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6323: the stack effect of the defined words, not the stack effect of the
6324: following code (the following code expects the address of the body on
6325: the top of stack, which is not reflected in the stack comment). This is
6326: the convention that I use and recommend (it clashes a bit with using
6327: locals declarations for stack effect specification, though).
1.1 anton 6328:
1.53 anton 6329: @menu
6330: * CREATE..DOES> applications::
6331: * CREATE..DOES> details::
1.63 anton 6332: * Advanced does> usage example::
1.91 anton 6333: * @code{Const-does>}::
1.53 anton 6334: @end menu
6335:
6336: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6337: @subsubsection Applications of @code{CREATE..DOES>}
6338: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6339:
1.26 crook 6340: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6341:
1.26 crook 6342: @cindex factoring similar colon definitions
6343: When you see a sequence of code occurring several times, and you can
6344: identify a meaning, you will factor it out as a colon definition. When
6345: you see similar colon definitions, you can factor them using
6346: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6347: that look very similar:
1.1 anton 6348: @example
1.26 crook 6349: : ori, ( reg-target reg-source n -- )
6350: 0 asm-reg-reg-imm ;
6351: : andi, ( reg-target reg-source n -- )
6352: 1 asm-reg-reg-imm ;
1.1 anton 6353: @end example
6354:
1.26 crook 6355: @noindent
6356: This could be factored with:
6357: @example
6358: : reg-reg-imm ( op-code -- )
6359: CREATE ,
6360: DOES> ( reg-target reg-source n -- )
6361: @@ asm-reg-reg-imm ;
6362:
6363: 0 reg-reg-imm ori,
6364: 1 reg-reg-imm andi,
6365: @end example
1.1 anton 6366:
1.26 crook 6367: @cindex currying
6368: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6369: supply a part of the parameters for a word (known as @dfn{currying} in
6370: the functional language community). E.g., @code{+} needs two
6371: parameters. Creating versions of @code{+} with one parameter fixed can
6372: be done like this:
1.82 anton 6373:
1.1 anton 6374: @example
1.82 anton 6375: : curry+ ( n1 "name" -- )
1.26 crook 6376: CREATE ,
6377: DOES> ( n2 -- n1+n2 )
6378: @@ + ;
6379:
6380: 3 curry+ 3+
6381: -2 curry+ 2-
1.1 anton 6382: @end example
6383:
1.91 anton 6384:
1.63 anton 6385: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6386: @subsubsection The gory details of @code{CREATE..DOES>}
6387: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6388:
1.26 crook 6389: doc-does>
1.1 anton 6390:
1.26 crook 6391: @cindex @code{DOES>} in a separate definition
6392: This means that you need not use @code{CREATE} and @code{DOES>} in the
6393: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6394: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6395: @example
6396: : does1
6397: DOES> ( ... -- ... )
1.44 crook 6398: ... ;
6399:
6400: : does2
6401: DOES> ( ... -- ... )
6402: ... ;
6403:
6404: : def-word ( ... -- ... )
6405: create ...
6406: IF
6407: does1
6408: ELSE
6409: does2
6410: ENDIF ;
6411: @end example
6412:
6413: In this example, the selection of whether to use @code{does1} or
1.69 anton 6414: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6415: @code{CREATE}d.
6416:
6417: @cindex @code{DOES>} in interpretation state
6418: In a standard program you can apply a @code{DOES>}-part only if the last
6419: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6420: will override the behaviour of the last word defined in any case. In a
6421: standard program, you can use @code{DOES>} only in a colon
6422: definition. In Gforth, you can also use it in interpretation state, in a
6423: kind of one-shot mode; for example:
6424: @example
6425: CREATE name ( ... -- ... )
6426: @i{initialization}
6427: DOES>
6428: @i{code} ;
6429: @end example
6430:
6431: @noindent
6432: is equivalent to the standard:
6433: @example
6434: :noname
6435: DOES>
6436: @i{code} ;
6437: CREATE name EXECUTE ( ... -- ... )
6438: @i{initialization}
6439: @end example
6440:
1.53 anton 6441: doc->body
6442:
1.91 anton 6443: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6444: @subsubsection Advanced does> usage example
6445:
6446: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6447: for disassembling instructions, that follow a very repetetive scheme:
6448:
6449: @example
6450: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6451: @var{entry-num} cells @var{table} + !
6452: @end example
6453:
6454: Of course, this inspires the idea to factor out the commonalities to
6455: allow a definition like
6456:
6457: @example
6458: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6459: @end example
6460:
6461: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6462: correlated. Moreover, before I wrote the disassembler, there already
6463: existed code that defines instructions like this:
1.63 anton 6464:
6465: @example
6466: @var{entry-num} @var{inst-format} @var{inst-name}
6467: @end example
6468:
6469: This code comes from the assembler and resides in
6470: @file{arch/mips/insts.fs}.
6471:
6472: So I had to define the @var{inst-format} words that performed the scheme
6473: above when executed. At first I chose to use run-time code-generation:
6474:
6475: @example
6476: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6477: :noname Postpone @var{disasm-operands}
6478: name Postpone sliteral Postpone type Postpone ;
6479: swap cells @var{table} + ! ;
6480: @end example
6481:
6482: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6483:
1.63 anton 6484: An alternative would have been to write this using
6485: @code{create}/@code{does>}:
6486:
6487: @example
6488: : @var{inst-format} ( entry-num "name" -- )
6489: here name string, ( entry-num c-addr ) \ parse and save "name"
6490: noname create , ( entry-num )
1.116 anton 6491: latestxt swap cells @var{table} + !
1.63 anton 6492: does> ( addr w -- )
6493: \ disassemble instruction w at addr
6494: @@ >r
6495: @var{disasm-operands}
6496: r> count type ;
6497: @end example
6498:
6499: Somehow the first solution is simpler, mainly because it's simpler to
6500: shift a string from definition-time to use-time with @code{sliteral}
6501: than with @code{string,} and friends.
6502:
6503: I wrote a lot of words following this scheme and soon thought about
6504: factoring out the commonalities among them. Note that this uses a
6505: two-level defining word, i.e., a word that defines ordinary defining
6506: words.
6507:
6508: This time a solution involving @code{postpone} and friends seemed more
6509: difficult (try it as an exercise), so I decided to use a
6510: @code{create}/@code{does>} word; since I was already at it, I also used
6511: @code{create}/@code{does>} for the lower level (try using
6512: @code{postpone} etc. as an exercise), resulting in the following
6513: definition:
6514:
6515: @example
6516: : define-format ( disasm-xt table-xt -- )
6517: \ define an instruction format that uses disasm-xt for
6518: \ disassembling and enters the defined instructions into table
6519: \ table-xt
6520: create 2,
6521: does> ( u "inst" -- )
6522: \ defines an anonymous word for disassembling instruction inst,
6523: \ and enters it as u-th entry into table-xt
6524: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6525: noname create 2, \ define anonymous word
1.116 anton 6526: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6527: does> ( addr w -- )
6528: \ disassemble instruction w at addr
6529: 2@@ >r ( addr w disasm-xt R: c-addr )
6530: execute ( R: c-addr ) \ disassemble operands
6531: r> count type ; \ print name
6532: @end example
6533:
6534: Note that the tables here (in contrast to above) do the @code{cells +}
6535: by themselves (that's why you have to pass an xt). This word is used in
6536: the following way:
6537:
6538: @example
6539: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6540: @end example
6541:
1.71 anton 6542: As shown above, the defined instruction format is then used like this:
6543:
6544: @example
6545: @var{entry-num} @var{inst-format} @var{inst-name}
6546: @end example
6547:
1.63 anton 6548: In terms of currying, this kind of two-level defining word provides the
6549: parameters in three stages: first @var{disasm-operands} and @var{table},
6550: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6551: the instruction to be disassembled.
6552:
6553: Of course this did not quite fit all the instruction format names used
6554: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6555: the parameters into the right form.
6556:
6557: If you have trouble following this section, don't worry. First, this is
6558: involved and takes time (and probably some playing around) to
6559: understand; second, this is the first two-level
6560: @code{create}/@code{does>} word I have written in seventeen years of
6561: Forth; and if I did not have @file{insts.fs} to start with, I may well
6562: have elected to use just a one-level defining word (with some repeating
6563: of parameters when using the defining word). So it is not necessary to
6564: understand this, but it may improve your understanding of Forth.
1.44 crook 6565:
6566:
1.91 anton 6567: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6568: @subsubsection @code{Const-does>}
6569:
6570: A frequent use of @code{create}...@code{does>} is for transferring some
6571: values from definition-time to run-time. Gforth supports this use with
6572:
6573: doc-const-does>
6574:
6575: A typical use of this word is:
6576:
6577: @example
6578: : curry+ ( n1 "name" -- )
6579: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6580: + ;
6581:
6582: 3 curry+ 3+
6583: @end example
6584:
6585: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6586: definition to run-time.
6587:
6588: The advantages of using @code{const-does>} are:
6589:
6590: @itemize
6591:
6592: @item
6593: You don't have to deal with storing and retrieving the values, i.e.,
6594: your program becomes more writable and readable.
6595:
6596: @item
6597: When using @code{does>}, you have to introduce a @code{@@} that cannot
6598: be optimized away (because you could change the data using
6599: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6600:
6601: @end itemize
6602:
6603: An ANS Forth implementation of @code{const-does>} is available in
6604: @file{compat/const-does.fs}.
6605:
6606:
1.44 crook 6607: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6608: @subsection Deferred words
6609: @cindex deferred words
6610:
6611: The defining word @code{Defer} allows you to define a word by name
6612: without defining its behaviour; the definition of its behaviour is
6613: deferred. Here are two situation where this can be useful:
6614:
6615: @itemize @bullet
6616: @item
6617: Where you want to allow the behaviour of a word to be altered later, and
6618: for all precompiled references to the word to change when its behaviour
6619: is changed.
6620: @item
6621: For mutual recursion; @xref{Calls and returns}.
6622: @end itemize
6623:
6624: In the following example, @code{foo} always invokes the version of
6625: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6626: always invokes the version that prints ``@code{Hello}''. There is no way
6627: of getting @code{foo} to use the later version without re-ordering the
6628: source code and recompiling it.
6629:
6630: @example
6631: : greet ." Good morning" ;
6632: : foo ... greet ... ;
6633: : greet ." Hello" ;
6634: : bar ... greet ... ;
6635: @end example
6636:
6637: This problem can be solved by defining @code{greet} as a @code{Defer}red
6638: word. The behaviour of a @code{Defer}red word can be defined and
6639: redefined at any time by using @code{IS} to associate the xt of a
6640: previously-defined word with it. The previous example becomes:
6641:
6642: @example
1.69 anton 6643: Defer greet ( -- )
1.44 crook 6644: : foo ... greet ... ;
6645: : bar ... greet ... ;
1.69 anton 6646: : greet1 ( -- ) ." Good morning" ;
6647: : greet2 ( -- ) ." Hello" ;
1.132 anton 6648: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6649: @end example
6650:
1.69 anton 6651: @progstyle
6652: You should write a stack comment for every deferred word, and put only
6653: XTs into deferred words that conform to this stack effect. Otherwise
6654: it's too difficult to use the deferred word.
6655:
1.44 crook 6656: A deferred word can be used to improve the statistics-gathering example
6657: from @ref{User-defined Defining Words}; rather than edit the
6658: application's source code to change every @code{:} to a @code{my:}, do
6659: this:
6660:
6661: @example
6662: : real: : ; \ retain access to the original
6663: defer : \ redefine as a deferred word
1.132 anton 6664: ' my: IS : \ use special version of :
1.44 crook 6665: \
6666: \ load application here
6667: \
1.132 anton 6668: ' real: IS : \ go back to the original
1.44 crook 6669: @end example
6670:
6671:
1.132 anton 6672: One thing to note is that @code{IS} has special compilation semantics,
6673: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6674:
6675: @example
6676: : set-greet ( xt -- )
1.132 anton 6677: IS greet ;
1.44 crook 6678:
6679: ' greet1 set-greet
6680: @end example
6681:
1.132 anton 6682: In situations where @code{IS} does not fit, use @code{defer!} instead.
6683:
1.69 anton 6684: A deferred word can only inherit execution semantics from the xt
6685: (because that is all that an xt can represent -- for more discussion of
6686: this @pxref{Tokens for Words}); by default it will have default
6687: interpretation and compilation semantics deriving from this execution
6688: semantics. However, you can change the interpretation and compilation
6689: semantics of the deferred word in the usual ways:
1.44 crook 6690:
6691: @example
1.132 anton 6692: : bar .... ; immediate
1.44 crook 6693: Defer fred immediate
6694: Defer jim
6695:
1.132 anton 6696: ' bar IS jim \ jim has default semantics
6697: ' bar IS fred \ fred is immediate
1.44 crook 6698: @end example
6699:
6700: doc-defer
1.132 anton 6701: doc-defer!
1.44 crook 6702: doc-is
1.132 anton 6703: doc-defer@
6704: doc-action-of
1.44 crook 6705: @comment TODO document these: what's defers [is]
6706: doc-defers
6707:
6708: @c Use @code{words-deferred} to see a list of deferred words.
6709:
1.132 anton 6710: Definitions of these words (except @code{defers}) in ANS Forth are
6711: provided in @file{compat/defer.fs}.
1.44 crook 6712:
6713:
1.69 anton 6714: @node Aliases, , Deferred words, Defining Words
1.44 crook 6715: @subsection Aliases
6716: @cindex aliases
1.1 anton 6717:
1.44 crook 6718: The defining word @code{Alias} allows you to define a word by name that
6719: has the same behaviour as some other word. Here are two situation where
6720: this can be useful:
1.1 anton 6721:
1.44 crook 6722: @itemize @bullet
6723: @item
6724: When you want access to a word's definition from a different word list
6725: (for an example of this, see the definition of the @code{Root} word list
6726: in the Gforth source).
6727: @item
6728: When you want to create a synonym; a definition that can be known by
6729: either of two names (for example, @code{THEN} and @code{ENDIF} are
6730: aliases).
6731: @end itemize
1.1 anton 6732:
1.69 anton 6733: Like deferred words, an alias has default compilation and interpretation
6734: semantics at the beginning (not the modifications of the other word),
6735: but you can change them in the usual ways (@code{immediate},
6736: @code{compile-only}). For example:
1.1 anton 6737:
6738: @example
1.44 crook 6739: : foo ... ; immediate
6740:
6741: ' foo Alias bar \ bar is not an immediate word
6742: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6743: @end example
6744:
1.44 crook 6745: Words that are aliases have the same xt, different headers in the
6746: dictionary, and consequently different name tokens (@pxref{Tokens for
6747: Words}) and possibly different immediate flags. An alias can only have
6748: default or immediate compilation semantics; you can define aliases for
6749: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6750:
1.44 crook 6751: doc-alias
1.1 anton 6752:
6753:
1.47 crook 6754: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6755: @section Interpretation and Compilation Semantics
1.26 crook 6756: @cindex semantics, interpretation and compilation
1.1 anton 6757:
1.71 anton 6758: @c !! state and ' are used without explanation
6759: @c example for immediate/compile-only? or is the tutorial enough
6760:
1.26 crook 6761: @cindex interpretation semantics
1.71 anton 6762: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6763: interpreter does when it encounters the word in interpret state. It also
6764: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6765: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6766: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6767: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6768:
1.26 crook 6769: @cindex compilation semantics
1.71 anton 6770: The @dfn{compilation semantics} of a (named) word are what the text
6771: interpreter does when it encounters the word in compile state. It also
6772: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6773: compiles@footnote{In standard terminology, ``appends to the current
6774: definition''.} the compilation semantics of @i{word}.
1.1 anton 6775:
1.26 crook 6776: @cindex execution semantics
6777: The standard also talks about @dfn{execution semantics}. They are used
6778: only for defining the interpretation and compilation semantics of many
6779: words. By default, the interpretation semantics of a word are to
6780: @code{execute} its execution semantics, and the compilation semantics of
6781: a word are to @code{compile,} its execution semantics.@footnote{In
6782: standard terminology: The default interpretation semantics are its
6783: execution semantics; the default compilation semantics are to append its
6784: execution semantics to the execution semantics of the current
6785: definition.}
6786:
1.71 anton 6787: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6788: the text interpreter, ticked, or @code{postpone}d, so they have no
6789: interpretation or compilation semantics. Their behaviour is represented
6790: by their XT (@pxref{Tokens for Words}), and we call it execution
6791: semantics, too.
6792:
1.26 crook 6793: @comment TODO expand, make it co-operate with new sections on text interpreter.
6794:
6795: @cindex immediate words
6796: @cindex compile-only words
6797: You can change the semantics of the most-recently defined word:
6798:
1.44 crook 6799:
1.26 crook 6800: doc-immediate
6801: doc-compile-only
6802: doc-restrict
6803:
1.82 anton 6804: By convention, words with non-default compilation semantics (e.g.,
6805: immediate words) often have names surrounded with brackets (e.g.,
6806: @code{[']}, @pxref{Execution token}).
1.44 crook 6807:
1.26 crook 6808: Note that ticking (@code{'}) a compile-only word gives an error
6809: (``Interpreting a compile-only word'').
1.1 anton 6810:
1.47 crook 6811: @menu
1.67 anton 6812: * Combined words::
1.47 crook 6813: @end menu
1.44 crook 6814:
1.71 anton 6815:
1.48 anton 6816: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6817: @subsection Combined Words
6818: @cindex combined words
6819:
6820: Gforth allows you to define @dfn{combined words} -- words that have an
6821: arbitrary combination of interpretation and compilation semantics.
6822:
1.26 crook 6823: doc-interpret/compile:
1.1 anton 6824:
1.26 crook 6825: This feature was introduced for implementing @code{TO} and @code{S"}. I
6826: recommend that you do not define such words, as cute as they may be:
6827: they make it hard to get at both parts of the word in some contexts.
6828: E.g., assume you want to get an execution token for the compilation
6829: part. Instead, define two words, one that embodies the interpretation
6830: part, and one that embodies the compilation part. Once you have done
6831: that, you can define a combined word with @code{interpret/compile:} for
6832: the convenience of your users.
1.1 anton 6833:
1.26 crook 6834: You might try to use this feature to provide an optimizing
6835: implementation of the default compilation semantics of a word. For
6836: example, by defining:
1.1 anton 6837: @example
1.26 crook 6838: :noname
6839: foo bar ;
6840: :noname
6841: POSTPONE foo POSTPONE bar ;
1.29 crook 6842: interpret/compile: opti-foobar
1.1 anton 6843: @end example
1.26 crook 6844:
1.23 crook 6845: @noindent
1.26 crook 6846: as an optimizing version of:
6847:
1.1 anton 6848: @example
1.26 crook 6849: : foobar
6850: foo bar ;
1.1 anton 6851: @end example
6852:
1.26 crook 6853: Unfortunately, this does not work correctly with @code{[compile]},
6854: because @code{[compile]} assumes that the compilation semantics of all
6855: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6856: opti-foobar} would compile compilation semantics, whereas
6857: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6858:
1.26 crook 6859: @cindex state-smart words (are a bad idea)
1.82 anton 6860: @anchor{state-smartness}
1.29 crook 6861: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6862: by @code{interpret/compile:} (words are state-smart if they check
6863: @code{STATE} during execution). E.g., they would try to code
6864: @code{foobar} like this:
1.1 anton 6865:
1.26 crook 6866: @example
6867: : foobar
6868: STATE @@
6869: IF ( compilation state )
6870: POSTPONE foo POSTPONE bar
6871: ELSE
6872: foo bar
6873: ENDIF ; immediate
6874: @end example
1.1 anton 6875:
1.26 crook 6876: Although this works if @code{foobar} is only processed by the text
6877: interpreter, it does not work in other contexts (like @code{'} or
6878: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6879: for a state-smart word, not for the interpretation semantics of the
6880: original @code{foobar}; when you execute this execution token (directly
6881: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6882: state, the result will not be what you expected (i.e., it will not
6883: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6884: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6885: M. Anton Ertl,
6886: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6887: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6888:
1.26 crook 6889: @cindex defining words with arbitrary semantics combinations
6890: It is also possible to write defining words that define words with
6891: arbitrary combinations of interpretation and compilation semantics. In
6892: general, they look like this:
1.1 anton 6893:
1.26 crook 6894: @example
6895: : def-word
6896: create-interpret/compile
1.29 crook 6897: @i{code1}
1.26 crook 6898: interpretation>
1.29 crook 6899: @i{code2}
1.26 crook 6900: <interpretation
6901: compilation>
1.29 crook 6902: @i{code3}
1.26 crook 6903: <compilation ;
6904: @end example
1.1 anton 6905:
1.29 crook 6906: For a @i{word} defined with @code{def-word}, the interpretation
6907: semantics are to push the address of the body of @i{word} and perform
6908: @i{code2}, and the compilation semantics are to push the address of
6909: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6910: can also be defined like this (except that the defined constants don't
6911: behave correctly when @code{[compile]}d):
1.1 anton 6912:
1.26 crook 6913: @example
6914: : constant ( n "name" -- )
6915: create-interpret/compile
6916: ,
6917: interpretation> ( -- n )
6918: @@
6919: <interpretation
6920: compilation> ( compilation. -- ; run-time. -- n )
6921: @@ postpone literal
6922: <compilation ;
6923: @end example
1.1 anton 6924:
1.44 crook 6925:
1.26 crook 6926: doc-create-interpret/compile
6927: doc-interpretation>
6928: doc-<interpretation
6929: doc-compilation>
6930: doc-<compilation
1.1 anton 6931:
1.44 crook 6932:
1.29 crook 6933: Words defined with @code{interpret/compile:} and
1.26 crook 6934: @code{create-interpret/compile} have an extended header structure that
6935: differs from other words; however, unless you try to access them with
6936: plain address arithmetic, you should not notice this. Words for
6937: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6938: @code{'} @i{word} @code{>body} also gives you the body of a word created
6939: with @code{create-interpret/compile}.
1.1 anton 6940:
1.44 crook 6941:
1.47 crook 6942: @c -------------------------------------------------------------
1.81 anton 6943: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6944: @section Tokens for Words
6945: @cindex tokens for words
6946:
6947: This section describes the creation and use of tokens that represent
6948: words.
6949:
1.71 anton 6950: @menu
6951: * Execution token:: represents execution/interpretation semantics
6952: * Compilation token:: represents compilation semantics
6953: * Name token:: represents named words
6954: @end menu
1.47 crook 6955:
1.71 anton 6956: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6957: @subsection Execution token
1.47 crook 6958:
6959: @cindex xt
6960: @cindex execution token
1.71 anton 6961: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6962: You can use @code{execute} to invoke this behaviour.
1.47 crook 6963:
1.71 anton 6964: @cindex tick (')
6965: You can use @code{'} to get an execution token that represents the
6966: interpretation semantics of a named word:
1.47 crook 6967:
6968: @example
1.97 anton 6969: 5 ' . ( n xt )
6970: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6971: @end example
1.47 crook 6972:
1.71 anton 6973: doc-'
6974:
6975: @code{'} parses at run-time; there is also a word @code{[']} that parses
6976: when it is compiled, and compiles the resulting XT:
6977:
6978: @example
6979: : foo ['] . execute ;
6980: 5 foo
6981: : bar ' execute ; \ by contrast,
6982: 5 bar . \ ' parses "." when bar executes
6983: @end example
6984:
6985: doc-[']
6986:
6987: If you want the execution token of @i{word}, write @code{['] @i{word}}
6988: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6989: @code{'} and @code{[']} behave somewhat unusually by complaining about
6990: compile-only words (because these words have no interpretation
6991: semantics). You might get what you want by using @code{COMP' @i{word}
6992: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6993: token}).
6994:
1.116 anton 6995: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 6996: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6997: for the only behaviour the word has (the execution semantics). For
1.116 anton 6998: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 6999: would produce if the word was defined anonymously.
7000:
7001: @example
7002: :noname ." hello" ;
7003: execute
1.47 crook 7004: @end example
7005:
1.71 anton 7006: An XT occupies one cell and can be manipulated like any other cell.
7007:
1.47 crook 7008: @cindex code field address
7009: @cindex CFA
1.71 anton 7010: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7011: operations that produce or consume it). For old hands: In Gforth, the
7012: XT is implemented as a code field address (CFA).
7013:
7014: doc-execute
7015: doc-perform
7016:
7017: @node Compilation token, Name token, Execution token, Tokens for Words
7018: @subsection Compilation token
1.47 crook 7019:
7020: @cindex compilation token
1.71 anton 7021: @cindex CT (compilation token)
7022: Gforth represents the compilation semantics of a named word by a
1.47 crook 7023: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7024: @i{xt} is an execution token. The compilation semantics represented by
7025: the compilation token can be performed with @code{execute}, which
7026: consumes the whole compilation token, with an additional stack effect
7027: determined by the represented compilation semantics.
7028:
7029: At present, the @i{w} part of a compilation token is an execution token,
7030: and the @i{xt} part represents either @code{execute} or
7031: @code{compile,}@footnote{Depending upon the compilation semantics of the
7032: word. If the word has default compilation semantics, the @i{xt} will
7033: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7034: @i{xt} will represent @code{execute}.}. However, don't rely on that
7035: knowledge, unless necessary; future versions of Gforth may introduce
7036: unusual compilation tokens (e.g., a compilation token that represents
7037: the compilation semantics of a literal).
7038:
1.71 anton 7039: You can perform the compilation semantics represented by the compilation
7040: token with @code{execute}. You can compile the compilation semantics
7041: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7042: equivalent to @code{postpone @i{word}}.
7043:
7044: doc-[comp']
7045: doc-comp'
7046: doc-postpone,
7047:
7048: @node Name token, , Compilation token, Tokens for Words
7049: @subsection Name token
1.47 crook 7050:
7051: @cindex name token
1.116 anton 7052: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7053: token is an abstract data type that occurs as argument or result of the
7054: words below.
7055:
7056: @c !! put this elswhere?
1.47 crook 7057: @cindex name field address
7058: @cindex NFA
1.116 anton 7059: The closest thing to the nt in older Forth systems is the name field
7060: address (NFA), but there are significant differences: in older Forth
7061: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7062: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7063: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7064: is a link field in the structure identified by the name token, but
7065: searching usually uses a hash table external to these structures; the
7066: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7067: implemented as the address of that count field.
1.47 crook 7068:
7069: doc-find-name
1.116 anton 7070: doc-latest
7071: doc->name
1.47 crook 7072: doc-name>int
7073: doc-name?int
7074: doc-name>comp
7075: doc-name>string
1.109 anton 7076: doc-id.
7077: doc-.name
7078: doc-.id
1.47 crook 7079:
1.81 anton 7080: @c ----------------------------------------------------------
7081: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7082: @section Compiling words
7083: @cindex compiling words
7084: @cindex macros
7085:
7086: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7087: between compilation and run-time. E.g., you can run arbitrary code
7088: between defining words (or for computing data used by defining words
7089: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7090: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7091: running arbitrary code while compiling a colon definition (exception:
7092: you must not allot dictionary space).
7093:
7094: @menu
7095: * Literals:: Compiling data values
7096: * Macros:: Compiling words
7097: @end menu
7098:
7099: @node Literals, Macros, Compiling words, Compiling words
7100: @subsection Literals
7101: @cindex Literals
7102:
7103: The simplest and most frequent example is to compute a literal during
7104: compilation. E.g., the following definition prints an array of strings,
7105: one string per line:
7106:
7107: @example
7108: : .strings ( addr u -- ) \ gforth
7109: 2* cells bounds U+DO
7110: cr i 2@@ type
7111: 2 cells +LOOP ;
7112: @end example
1.81 anton 7113:
1.82 anton 7114: With a simple-minded compiler like Gforth's, this computes @code{2
7115: cells} on every loop iteration. You can compute this value once and for
7116: all at compile time and compile it into the definition like this:
7117:
7118: @example
7119: : .strings ( addr u -- ) \ gforth
7120: 2* cells bounds U+DO
7121: cr i 2@@ type
7122: [ 2 cells ] literal +LOOP ;
7123: @end example
7124:
7125: @code{[} switches the text interpreter to interpret state (you will get
7126: an @code{ok} prompt if you type this example interactively and insert a
7127: newline between @code{[} and @code{]}), so it performs the
7128: interpretation semantics of @code{2 cells}; this computes a number.
7129: @code{]} switches the text interpreter back into compile state. It then
7130: performs @code{Literal}'s compilation semantics, which are to compile
7131: this number into the current word. You can decompile the word with
7132: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7133:
1.82 anton 7134: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7135: *} in this way.
1.81 anton 7136:
1.82 anton 7137: doc-[
7138: doc-]
1.81 anton 7139: doc-literal
7140: doc-]L
1.82 anton 7141:
7142: There are also words for compiling other data types than single cells as
7143: literals:
7144:
1.81 anton 7145: doc-2literal
7146: doc-fliteral
1.82 anton 7147: doc-sliteral
7148:
7149: @cindex colon-sys, passing data across @code{:}
7150: @cindex @code{:}, passing data across
7151: You might be tempted to pass data from outside a colon definition to the
7152: inside on the data stack. This does not work, because @code{:} puhes a
7153: colon-sys, making stuff below unaccessible. E.g., this does not work:
7154:
7155: @example
7156: 5 : foo literal ; \ error: "unstructured"
7157: @end example
7158:
7159: Instead, you have to pass the value in some other way, e.g., through a
7160: variable:
7161:
7162: @example
7163: variable temp
7164: 5 temp !
7165: : foo [ temp @@ ] literal ;
7166: @end example
7167:
7168:
7169: @node Macros, , Literals, Compiling words
7170: @subsection Macros
7171: @cindex Macros
7172: @cindex compiling compilation semantics
7173:
7174: @code{Literal} and friends compile data values into the current
7175: definition. You can also write words that compile other words into the
7176: current definition. E.g.,
7177:
7178: @example
7179: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7180: POSTPONE + ;
7181:
7182: : foo ( n1 n2 -- n )
7183: [ compile-+ ] ;
7184: 1 2 foo .
7185: @end example
7186:
7187: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7188: What happens in this example? @code{Postpone} compiles the compilation
7189: semantics of @code{+} into @code{compile-+}; later the text interpreter
7190: executes @code{compile-+} and thus the compilation semantics of +, which
7191: compile (the execution semantics of) @code{+} into
7192: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7193: should only be executed in compile state, so this example is not
7194: guaranteed to work on all standard systems, but on any decent system it
7195: will work.}
7196:
7197: doc-postpone
7198: doc-[compile]
7199:
7200: Compiling words like @code{compile-+} are usually immediate (or similar)
7201: so you do not have to switch to interpret state to execute them;
7202: mopifying the last example accordingly produces:
7203:
7204: @example
7205: : [compile-+] ( compilation: --; interpretation: -- )
7206: \ compiled code: ( n1 n2 -- n )
7207: POSTPONE + ; immediate
7208:
7209: : foo ( n1 n2 -- n )
7210: [compile-+] ;
7211: 1 2 foo .
7212: @end example
7213:
7214: Immediate compiling words are similar to macros in other languages (in
7215: particular, Lisp). The important differences to macros in, e.g., C are:
7216:
7217: @itemize @bullet
7218:
7219: @item
7220: You use the same language for defining and processing macros, not a
7221: separate preprocessing language and processor.
7222:
7223: @item
7224: Consequently, the full power of Forth is available in macro definitions.
7225: E.g., you can perform arbitrarily complex computations, or generate
7226: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7227: Tutorial}). This power is very useful when writing a parser generators
7228: or other code-generating software.
7229:
7230: @item
7231: Macros defined using @code{postpone} etc. deal with the language at a
7232: higher level than strings; name binding happens at macro definition
7233: time, so you can avoid the pitfalls of name collisions that can happen
7234: in C macros. Of course, Forth is a liberal language and also allows to
7235: shoot yourself in the foot with text-interpreted macros like
7236:
7237: @example
7238: : [compile-+] s" +" evaluate ; immediate
7239: @end example
7240:
7241: Apart from binding the name at macro use time, using @code{evaluate}
7242: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7243: @end itemize
7244:
7245: You may want the macro to compile a number into a word. The word to do
7246: it is @code{literal}, but you have to @code{postpone} it, so its
7247: compilation semantics take effect when the macro is executed, not when
7248: it is compiled:
7249:
7250: @example
7251: : [compile-5] ( -- ) \ compiled code: ( -- n )
7252: 5 POSTPONE literal ; immediate
7253:
7254: : foo [compile-5] ;
7255: foo .
7256: @end example
7257:
7258: You may want to pass parameters to a macro, that the macro should
7259: compile into the current definition. If the parameter is a number, then
7260: you can use @code{postpone literal} (similar for other values).
7261:
7262: If you want to pass a word that is to be compiled, the usual way is to
7263: pass an execution token and @code{compile,} it:
7264:
7265: @example
7266: : twice1 ( xt -- ) \ compiled code: ... -- ...
7267: dup compile, compile, ;
7268:
7269: : 2+ ( n1 -- n2 )
7270: [ ' 1+ twice1 ] ;
7271: @end example
7272:
7273: doc-compile,
7274:
7275: An alternative available in Gforth, that allows you to pass compile-only
7276: words as parameters is to use the compilation token (@pxref{Compilation
7277: token}). The same example in this technique:
7278:
7279: @example
7280: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7281: 2dup 2>r execute 2r> execute ;
7282:
7283: : 2+ ( n1 -- n2 )
7284: [ comp' 1+ twice ] ;
7285: @end example
7286:
7287: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7288: works even if the executed compilation semantics has an effect on the
7289: data stack.
7290:
7291: You can also define complete definitions with these words; this provides
7292: an alternative to using @code{does>} (@pxref{User-defined Defining
7293: Words}). E.g., instead of
7294:
7295: @example
7296: : curry+ ( n1 "name" -- )
7297: CREATE ,
7298: DOES> ( n2 -- n1+n2 )
7299: @@ + ;
7300: @end example
7301:
7302: you could define
7303:
7304: @example
7305: : curry+ ( n1 "name" -- )
7306: \ name execution: ( n2 -- n1+n2 )
7307: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7308:
1.82 anton 7309: -3 curry+ 3-
7310: see 3-
7311: @end example
1.81 anton 7312:
1.82 anton 7313: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7314: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7315:
1.82 anton 7316: This way of writing defining words is sometimes more, sometimes less
7317: convenient than using @code{does>} (@pxref{Advanced does> usage
7318: example}). One advantage of this method is that it can be optimized
7319: better, because the compiler knows that the value compiled with
7320: @code{literal} is fixed, whereas the data associated with a
7321: @code{create}d word can be changed.
1.47 crook 7322:
1.26 crook 7323: @c ----------------------------------------------------------
1.111 anton 7324: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7325: @section The Text Interpreter
7326: @cindex interpreter - outer
7327: @cindex text interpreter
7328: @cindex outer interpreter
1.1 anton 7329:
1.34 anton 7330: @c Should we really describe all these ugly details? IMO the text
7331: @c interpreter should be much cleaner, but that may not be possible within
7332: @c ANS Forth. - anton
1.44 crook 7333: @c nac-> I wanted to explain how it works to show how you can exploit
7334: @c it in your own programs. When I was writing a cross-compiler, figuring out
7335: @c some of these gory details was very helpful to me. None of the textbooks
7336: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7337: @c seems to positively avoid going into too much detail for some of
7338: @c the internals.
1.34 anton 7339:
1.71 anton 7340: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7341: @c it is; for the ugly details, I would prefer another place. I wonder
7342: @c whether we should have a chapter before "Words" that describes some
7343: @c basic concepts referred to in words, and a chapter after "Words" that
7344: @c describes implementation details.
7345:
1.29 crook 7346: The text interpreter@footnote{This is an expanded version of the
7347: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7348: that processes input from the current input device. It is also called
7349: the outer interpreter, in contrast to the inner interpreter
7350: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7351: implementations.
1.27 crook 7352:
1.29 crook 7353: @cindex interpret state
7354: @cindex compile state
7355: The text interpreter operates in one of two states: @dfn{interpret
7356: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7357: aptly-named variable @code{state}.
1.29 crook 7358:
7359: This section starts by describing how the text interpreter behaves when
7360: it is in interpret state, processing input from the user input device --
7361: the keyboard. This is the mode that a Forth system is in after it starts
7362: up.
7363:
7364: @cindex input buffer
7365: @cindex terminal input buffer
7366: The text interpreter works from an area of memory called the @dfn{input
7367: buffer}@footnote{When the text interpreter is processing input from the
7368: keyboard, this area of memory is called the @dfn{terminal input buffer}
7369: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7370: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7371: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7372: leading spaces (called @dfn{delimiters}) then parses a string (a
7373: sequence of non-space characters) until it reaches either a space
7374: character or the end of the buffer. Having parsed a string, it makes two
7375: attempts to process it:
1.27 crook 7376:
1.29 crook 7377: @cindex dictionary
1.27 crook 7378: @itemize @bullet
7379: @item
1.29 crook 7380: It looks for the string in a @dfn{dictionary} of definitions. If the
7381: string is found, the string names a @dfn{definition} (also known as a
7382: @dfn{word}) and the dictionary search returns information that allows
7383: the text interpreter to perform the word's @dfn{interpretation
7384: semantics}. In most cases, this simply means that the word will be
7385: executed.
1.27 crook 7386: @item
7387: If the string is not found in the dictionary, the text interpreter
1.29 crook 7388: attempts to treat it as a number, using the rules described in
7389: @ref{Number Conversion}. If the string represents a legal number in the
7390: current radix, the number is pushed onto a parameter stack (the data
7391: stack for integers, the floating-point stack for floating-point
7392: numbers).
7393: @end itemize
7394:
7395: If both attempts fail, or if the word is found in the dictionary but has
7396: no interpretation semantics@footnote{This happens if the word was
7397: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7398: remainder of the input buffer, issues an error message and waits for
7399: more input. If one of the attempts succeeds, the text interpreter
7400: repeats the parsing process until the whole of the input buffer has been
7401: processed, at which point it prints the status message ``@code{ ok}''
7402: and waits for more input.
7403:
1.71 anton 7404: @c anton: this should be in the input stream subsection (or below it)
7405:
1.29 crook 7406: @cindex parse area
7407: The text interpreter keeps track of its position in the input buffer by
7408: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7409: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7410: of the input buffer. The region from offset @code{>IN @@} to the end of
7411: the input buffer is called the @dfn{parse area}@footnote{In other words,
7412: the text interpreter processes the contents of the input buffer by
7413: parsing strings from the parse area until the parse area is empty.}.
7414: This example shows how @code{>IN} changes as the text interpreter parses
7415: the input buffer:
7416:
7417: @example
7418: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7419: CR ." ->" TYPE ." <-" ; IMMEDIATE
7420:
7421: 1 2 3 remaining + remaining .
7422:
7423: : foo 1 2 3 remaining SWAP remaining ;
7424: @end example
7425:
7426: @noindent
7427: The result is:
7428:
7429: @example
7430: ->+ remaining .<-
7431: ->.<-5 ok
7432:
7433: ->SWAP remaining ;-<
7434: ->;<- ok
7435: @end example
7436:
7437: @cindex parsing words
7438: The value of @code{>IN} can also be modified by a word in the input
7439: buffer that is executed by the text interpreter. This means that a word
7440: can ``trick'' the text interpreter into either skipping a section of the
7441: input buffer@footnote{This is how parsing words work.} or into parsing a
7442: section twice. For example:
1.27 crook 7443:
1.29 crook 7444: @example
1.71 anton 7445: : lat ." <<foo>>" ;
7446: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7447: @end example
7448:
7449: @noindent
7450: When @code{flat} is executed, this output is produced@footnote{Exercise
7451: for the reader: what would happen if the @code{3} were replaced with
7452: @code{4}?}:
7453:
7454: @example
1.71 anton 7455: <<bar>><<foo>>
1.29 crook 7456: @end example
7457:
1.71 anton 7458: This technique can be used to work around some of the interoperability
7459: problems of parsing words. Of course, it's better to avoid parsing
7460: words where possible.
7461:
1.29 crook 7462: @noindent
7463: Two important notes about the behaviour of the text interpreter:
1.27 crook 7464:
7465: @itemize @bullet
7466: @item
7467: It processes each input string to completion before parsing additional
1.29 crook 7468: characters from the input buffer.
7469: @item
7470: It treats the input buffer as a read-only region (and so must your code).
7471: @end itemize
7472:
7473: @noindent
7474: When the text interpreter is in compile state, its behaviour changes in
7475: these ways:
7476:
7477: @itemize @bullet
7478: @item
7479: If a parsed string is found in the dictionary, the text interpreter will
7480: perform the word's @dfn{compilation semantics}. In most cases, this
7481: simply means that the execution semantics of the word will be appended
7482: to the current definition.
1.27 crook 7483: @item
1.29 crook 7484: When a number is encountered, it is compiled into the current definition
7485: (as a literal) rather than being pushed onto a parameter stack.
7486: @item
7487: If an error occurs, @code{state} is modified to put the text interpreter
7488: back into interpret state.
7489: @item
7490: Each time a line is entered from the keyboard, Gforth prints
7491: ``@code{ compiled}'' rather than `` @code{ok}''.
7492: @end itemize
7493:
7494: @cindex text interpreter - input sources
7495: When the text interpreter is using an input device other than the
7496: keyboard, its behaviour changes in these ways:
7497:
7498: @itemize @bullet
7499: @item
7500: When the parse area is empty, the text interpreter attempts to refill
7501: the input buffer from the input source. When the input source is
1.71 anton 7502: exhausted, the input source is set back to the previous input source.
1.29 crook 7503: @item
7504: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7505: time the parse area is emptied.
7506: @item
7507: If an error occurs, the input source is set back to the user input
7508: device.
1.27 crook 7509: @end itemize
1.21 crook 7510:
1.49 anton 7511: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7512:
1.26 crook 7513: doc->in
1.27 crook 7514: doc-source
7515:
1.26 crook 7516: doc-tib
7517: doc-#tib
1.1 anton 7518:
1.44 crook 7519:
1.26 crook 7520: @menu
1.67 anton 7521: * Input Sources::
7522: * Number Conversion::
7523: * Interpret/Compile states::
7524: * Interpreter Directives::
1.26 crook 7525: @end menu
1.1 anton 7526:
1.29 crook 7527: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7528: @subsection Input Sources
7529: @cindex input sources
7530: @cindex text interpreter - input sources
7531:
1.44 crook 7532: By default, the text interpreter processes input from the user input
1.29 crook 7533: device (the keyboard) when Forth starts up. The text interpreter can
7534: process input from any of these sources:
7535:
7536: @itemize @bullet
7537: @item
7538: The user input device -- the keyboard.
7539: @item
7540: A file, using the words described in @ref{Forth source files}.
7541: @item
7542: A block, using the words described in @ref{Blocks}.
7543: @item
7544: A text string, using @code{evaluate}.
7545: @end itemize
7546:
7547: A program can identify the current input device from the values of
7548: @code{source-id} and @code{blk}.
7549:
1.44 crook 7550:
1.29 crook 7551: doc-source-id
7552: doc-blk
7553:
7554: doc-save-input
7555: doc-restore-input
7556:
7557: doc-evaluate
1.111 anton 7558: doc-query
1.1 anton 7559:
1.29 crook 7560:
1.44 crook 7561:
1.29 crook 7562: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7563: @subsection Number Conversion
7564: @cindex number conversion
7565: @cindex double-cell numbers, input format
7566: @cindex input format for double-cell numbers
7567: @cindex single-cell numbers, input format
7568: @cindex input format for single-cell numbers
7569: @cindex floating-point numbers, input format
7570: @cindex input format for floating-point numbers
1.1 anton 7571:
1.29 crook 7572: This section describes the rules that the text interpreter uses when it
7573: tries to convert a string into a number.
1.1 anton 7574:
1.26 crook 7575: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7576: number base@footnote{For example, 0-9 when the number base is decimal or
7577: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7578:
1.26 crook 7579: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7580:
1.29 crook 7581: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7582: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7583:
1.26 crook 7584: Let * represent any number of instances of the previous character
7585: (including none).
1.1 anton 7586:
1.26 crook 7587: Let any other character represent itself.
1.1 anton 7588:
1.29 crook 7589: @noindent
1.26 crook 7590: Now, the conversion rules are:
1.21 crook 7591:
1.26 crook 7592: @itemize @bullet
7593: @item
7594: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7595: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7596: @item
7597: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7598: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7599: arithmetic. Examples are -45 -5681 -0
7600: @item
7601: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7602: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7603: (all three of these represent the same number).
1.26 crook 7604: @item
7605: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7606: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7607: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7608: -34.65 (all three of these represent the same number).
1.26 crook 7609: @item
1.29 crook 7610: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7611: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7612: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7613: number) +12.E-4
1.26 crook 7614: @end itemize
1.1 anton 7615:
1.26 crook 7616: By default, the number base used for integer number conversion is given
1.35 anton 7617: by the contents of the variable @code{base}. Note that a lot of
7618: confusion can result from unexpected values of @code{base}. If you
7619: change @code{base} anywhere, make sure to save the old value and restore
7620: it afterwards. In general I recommend keeping @code{base} decimal, and
7621: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7622:
1.29 crook 7623: doc-dpl
1.26 crook 7624: doc-base
7625: doc-hex
7626: doc-decimal
1.1 anton 7627:
1.26 crook 7628: @cindex '-prefix for character strings
7629: @cindex &-prefix for decimal numbers
1.133 anton 7630: @cindex #-prefix for decimal numbers
1.26 crook 7631: @cindex %-prefix for binary numbers
7632: @cindex $-prefix for hexadecimal numbers
1.133 anton 7633: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7634: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7635: prefix@footnote{Some Forth implementations provide a similar scheme by
7636: implementing @code{$} etc. as parsing words that process the subsequent
7637: number in the input stream and push it onto the stack. For example, see
7638: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7639: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7640: is required between the prefix and the number.} before the first digit
1.133 anton 7641: of an (integer) number. The following prefixes are supported:
1.1 anton 7642:
1.26 crook 7643: @itemize @bullet
7644: @item
1.35 anton 7645: @code{&} -- decimal
1.26 crook 7646: @item
1.133 anton 7647: @code{#} -- decimal
7648: @item
1.35 anton 7649: @code{%} -- binary
1.26 crook 7650: @item
1.35 anton 7651: @code{$} -- hexadecimal
1.26 crook 7652: @item
1.133 anton 7653: @code{0x} -- hexadecimal, if base<33.
7654: @item
7655: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7656: optional @code{'} may be present after the character.
1.26 crook 7657: @end itemize
1.1 anton 7658:
1.26 crook 7659: Here are some examples, with the equivalent decimal number shown after
7660: in braces:
1.1 anton 7661:
1.26 crook 7662: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7663: 'A (65),
7664: -'a' (-97),
1.26 crook 7665: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7666:
1.26 crook 7667: @cindex number conversion - traps for the unwary
1.29 crook 7668: @noindent
1.26 crook 7669: Number conversion has a number of traps for the unwary:
1.1 anton 7670:
1.26 crook 7671: @itemize @bullet
7672: @item
7673: You cannot determine the current number base using the code sequence
1.35 anton 7674: @code{base @@ .} -- the number base is always 10 in the current number
7675: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7676: @item
7677: If the number base is set to a value greater than 14 (for example,
7678: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7679: it to be intepreted as either a single-precision integer or a
7680: floating-point number (Gforth treats it as an integer). The ambiguity
7681: can be resolved by explicitly stating the sign of the mantissa and/or
7682: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7683: ambiguity arises; either representation will be treated as a
7684: floating-point number.
7685: @item
1.29 crook 7686: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7687: It is used to specify file types.
7688: @item
1.72 anton 7689: ANS Forth requires the @code{.} of a double-precision number to be the
7690: final character in the string. Gforth allows the @code{.} to be
7691: anywhere after the first digit.
1.26 crook 7692: @item
7693: The number conversion process does not check for overflow.
7694: @item
1.72 anton 7695: In an ANS Forth program @code{base} is required to be decimal when
7696: converting floating-point numbers. In Gforth, number conversion to
7697: floating-point numbers always uses base &10, irrespective of the value
7698: of @code{base}.
1.26 crook 7699: @end itemize
1.1 anton 7700:
1.49 anton 7701: You can read numbers into your programs with the words described in
7702: @ref{Input}.
1.1 anton 7703:
1.82 anton 7704: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7705: @subsection Interpret/Compile states
7706: @cindex Interpret/Compile states
1.1 anton 7707:
1.29 crook 7708: A standard program is not permitted to change @code{state}
7709: explicitly. However, it can change @code{state} implicitly, using the
7710: words @code{[} and @code{]}. When @code{[} is executed it switches
7711: @code{state} to interpret state, and therefore the text interpreter
7712: starts interpreting. When @code{]} is executed it switches @code{state}
7713: to compile state and therefore the text interpreter starts
1.44 crook 7714: compiling. The most common usage for these words is for switching into
7715: interpret state and back from within a colon definition; this technique
1.49 anton 7716: can be used to compile a literal (for an example, @pxref{Literals}) or
7717: for conditional compilation (for an example, @pxref{Interpreter
7718: Directives}).
1.44 crook 7719:
1.35 anton 7720:
7721: @c This is a bad example: It's non-standard, and it's not necessary.
7722: @c However, I can't think of a good example for switching into compile
7723: @c state when there is no current word (@code{state}-smart words are not a
7724: @c good reason). So maybe we should use an example for switching into
7725: @c interpret @code{state} in a colon def. - anton
1.44 crook 7726: @c nac-> I agree. I started out by putting in the example, then realised
7727: @c that it was non-ANS, so wrote more words around it. I hope this
7728: @c re-written version is acceptable to you. I do want to keep the example
7729: @c as it is helpful for showing what is and what is not portable, particularly
7730: @c where it outlaws a style in common use.
7731:
1.72 anton 7732: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7733: @c that, we can also show what's not. In any case, I have written a
7734: @c section Compiling Words which also deals with [ ].
1.35 anton 7735:
1.95 anton 7736: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7737:
1.95 anton 7738: @c @code{[} and @code{]} also give you the ability to switch into compile
7739: @c state and back, but we cannot think of any useful Standard application
7740: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7741:
7742: @c @example
7743: @c : AA ." this is A" ;
7744: @c : BB ." this is B" ;
7745: @c : CC ." this is C" ;
7746:
7747: @c create table ] aa bb cc [
7748:
7749: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7750: @c cells table + @@ execute ;
7751: @c @end example
7752:
7753: @c This example builds a jump table; @code{0 go} will display ``@code{this
7754: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7755: @c defining @code{table} like this:
7756:
7757: @c @example
7758: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7759: @c @end example
7760:
7761: @c The problem with this code is that the definition of @code{table} is not
7762: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7763: @c @i{may} work on systems where code space and data space co-incide, the
7764: @c Standard only allows data space to be assigned for a @code{CREATE}d
7765: @c word. In addition, the Standard only allows @code{@@} to access data
7766: @c space, whilst this example is using it to access code space. The only
7767: @c portable, Standard way to build this table is to build it in data space,
7768: @c like this:
7769:
7770: @c @example
7771: @c create table ' aa , ' bb , ' cc ,
7772: @c @end example
1.29 crook 7773:
1.95 anton 7774: @c doc-state
1.44 crook 7775:
1.29 crook 7776:
1.82 anton 7777: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7778: @subsection Interpreter Directives
7779: @cindex interpreter directives
1.72 anton 7780: @cindex conditional compilation
1.1 anton 7781:
1.29 crook 7782: These words are usually used in interpret state; typically to control
7783: which parts of a source file are processed by the text
1.26 crook 7784: interpreter. There are only a few ANS Forth Standard words, but Gforth
7785: supplements these with a rich set of immediate control structure words
7786: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7787: used in compile state (@pxref{Control Structures}). Typical usages:
7788:
7789: @example
1.72 anton 7790: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7791: .
7792: .
1.72 anton 7793: HAVE-ASSEMBLER [IF]
1.29 crook 7794: : ASSEMBLER-FEATURE
7795: ...
7796: ;
7797: [ENDIF]
7798: .
7799: .
7800: : SEE
7801: ... \ general-purpose SEE code
1.72 anton 7802: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7803: ... \ assembler-specific SEE code
7804: [ [ENDIF] ]
7805: ;
7806: @end example
1.1 anton 7807:
1.44 crook 7808:
1.26 crook 7809: doc-[IF]
7810: doc-[ELSE]
7811: doc-[THEN]
7812: doc-[ENDIF]
1.1 anton 7813:
1.26 crook 7814: doc-[IFDEF]
7815: doc-[IFUNDEF]
1.1 anton 7816:
1.26 crook 7817: doc-[?DO]
7818: doc-[DO]
7819: doc-[FOR]
7820: doc-[LOOP]
7821: doc-[+LOOP]
7822: doc-[NEXT]
1.1 anton 7823:
1.26 crook 7824: doc-[BEGIN]
7825: doc-[UNTIL]
7826: doc-[AGAIN]
7827: doc-[WHILE]
7828: doc-[REPEAT]
1.1 anton 7829:
1.27 crook 7830:
1.26 crook 7831: @c -------------------------------------------------------------
1.111 anton 7832: @node The Input Stream, Word Lists, The Text Interpreter, Words
7833: @section The Input Stream
7834: @cindex input stream
7835:
7836: @c !! integrate this better with the "Text Interpreter" section
7837: The text interpreter reads from the input stream, which can come from
7838: several sources (@pxref{Input Sources}). Some words, in particular
7839: defining words, but also words like @code{'}, read parameters from the
7840: input stream instead of from the stack.
7841:
7842: Such words are called parsing words, because they parse the input
7843: stream. Parsing words are hard to use in other words, because it is
7844: hard to pass program-generated parameters through the input stream.
7845: They also usually have an unintuitive combination of interpretation and
7846: compilation semantics when implemented naively, leading to various
7847: approaches that try to produce a more intuitive behaviour
7848: (@pxref{Combined words}).
7849:
7850: It should be obvious by now that parsing words are a bad idea. If you
7851: want to implement a parsing word for convenience, also provide a factor
7852: of the word that does not parse, but takes the parameters on the stack.
7853: To implement the parsing word on top if it, you can use the following
7854: words:
7855:
7856: @c anton: these belong in the input stream section
7857: doc-parse
1.138 anton 7858: doc-parse-name
1.111 anton 7859: doc-parse-word
7860: doc-name
7861: doc-word
7862: doc-\"-parse
7863: doc-refill
7864:
7865: Conversely, if you have the bad luck (or lack of foresight) to have to
7866: deal with parsing words without having such factors, how do you pass a
7867: string that is not in the input stream to it?
7868:
7869: doc-execute-parsing
7870:
1.146 anton 7871: A definition of this word in ANS Forth is provided in
7872: @file{compat/execute-parsing.fs}.
7873:
1.111 anton 7874: If you want to run a parsing word on a file, the following word should
7875: help:
7876:
7877: doc-execute-parsing-file
7878:
7879: @c -------------------------------------------------------------
7880: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7881: @section Word Lists
7882: @cindex word lists
1.32 anton 7883: @cindex header space
1.1 anton 7884:
1.36 anton 7885: A wordlist is a list of named words; you can add new words and look up
7886: words by name (and you can remove words in a restricted way with
7887: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7888:
7889: @cindex search order stack
7890: The text interpreter searches the wordlists present in the search order
7891: (a stack of wordlists), from the top to the bottom. Within each
7892: wordlist, the search starts conceptually at the newest word; i.e., if
7893: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7894:
1.26 crook 7895: @cindex compilation word list
1.36 anton 7896: New words are added to the @dfn{compilation wordlist} (aka current
7897: wordlist).
1.1 anton 7898:
1.36 anton 7899: @cindex wid
7900: A word list is identified by a cell-sized word list identifier (@i{wid})
7901: in much the same way as a file is identified by a file handle. The
7902: numerical value of the wid has no (portable) meaning, and might change
7903: from session to session.
1.1 anton 7904:
1.29 crook 7905: The ANS Forth ``Search order'' word set is intended to provide a set of
7906: low-level tools that allow various different schemes to be
1.74 anton 7907: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7908: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7909: Forth.
1.1 anton 7910:
1.27 crook 7911: @comment TODO: locals section refers to here, saying that every word list (aka
7912: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7913: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7914:
1.45 crook 7915: @comment TODO: document markers, reveal, tables, mappedwordlist
7916:
7917: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7918: @comment word from the source files, rather than some alias.
1.44 crook 7919:
1.26 crook 7920: doc-forth-wordlist
7921: doc-definitions
7922: doc-get-current
7923: doc-set-current
7924: doc-get-order
1.45 crook 7925: doc---gforthman-set-order
1.26 crook 7926: doc-wordlist
1.30 anton 7927: doc-table
1.79 anton 7928: doc->order
1.36 anton 7929: doc-previous
1.26 crook 7930: doc-also
1.45 crook 7931: doc---gforthman-forth
1.26 crook 7932: doc-only
1.45 crook 7933: doc---gforthman-order
1.15 anton 7934:
1.26 crook 7935: doc-find
7936: doc-search-wordlist
1.15 anton 7937:
1.26 crook 7938: doc-words
7939: doc-vlist
1.44 crook 7940: @c doc-words-deferred
1.1 anton 7941:
1.74 anton 7942: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7943: doc-root
7944: doc-vocabulary
7945: doc-seal
7946: doc-vocs
7947: doc-current
7948: doc-context
1.1 anton 7949:
1.44 crook 7950:
1.26 crook 7951: @menu
1.75 anton 7952: * Vocabularies::
1.67 anton 7953: * Why use word lists?::
1.75 anton 7954: * Word list example::
1.26 crook 7955: @end menu
7956:
1.75 anton 7957: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7958: @subsection Vocabularies
7959: @cindex Vocabularies, detailed explanation
7960:
7961: Here is an example of creating and using a new wordlist using ANS
7962: Forth words:
7963:
7964: @example
7965: wordlist constant my-new-words-wordlist
7966: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7967:
7968: \ add it to the search order
7969: also my-new-words
7970:
7971: \ alternatively, add it to the search order and make it
7972: \ the compilation word list
7973: also my-new-words definitions
7974: \ type "order" to see the problem
7975: @end example
7976:
7977: The problem with this example is that @code{order} has no way to
7978: associate the name @code{my-new-words} with the wid of the word list (in
7979: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7980: that has no associated name). There is no Standard way of associating a
7981: name with a wid.
7982:
7983: In Gforth, this example can be re-coded using @code{vocabulary}, which
7984: associates a name with a wid:
7985:
7986: @example
7987: vocabulary my-new-words
7988:
7989: \ add it to the search order
7990: also my-new-words
7991:
7992: \ alternatively, add it to the search order and make it
7993: \ the compilation word list
7994: my-new-words definitions
7995: \ type "order" to see that the problem is solved
7996: @end example
7997:
7998:
7999: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8000: @subsection Why use word lists?
8001: @cindex word lists - why use them?
8002:
1.74 anton 8003: Here are some reasons why people use wordlists:
1.26 crook 8004:
8005: @itemize @bullet
1.74 anton 8006:
8007: @c anton: Gforth's hashing implementation makes the search speed
8008: @c independent from the number of words. But it is linear with the number
8009: @c of wordlists that have to be searched, so in effect using more wordlists
8010: @c actually slows down compilation.
8011:
8012: @c @item
8013: @c To improve compilation speed by reducing the number of header space
8014: @c entries that must be searched. This is achieved by creating a new
8015: @c word list that contains all of the definitions that are used in the
8016: @c definition of a Forth system but which would not usually be used by
8017: @c programs running on that system. That word list would be on the search
8018: @c list when the Forth system was compiled but would be removed from the
8019: @c search list for normal operation. This can be a useful technique for
8020: @c low-performance systems (for example, 8-bit processors in embedded
8021: @c systems) but is unlikely to be necessary in high-performance desktop
8022: @c systems.
8023:
1.26 crook 8024: @item
8025: To prevent a set of words from being used outside the context in which
8026: they are valid. Two classic examples of this are an integrated editor
8027: (all of the edit commands are defined in a separate word list; the
8028: search order is set to the editor word list when the editor is invoked;
8029: the old search order is restored when the editor is terminated) and an
8030: integrated assembler (the op-codes for the machine are defined in a
8031: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8032:
8033: @item
8034: To organize the words of an application or library into a user-visible
8035: set (in @code{forth-wordlist} or some other common wordlist) and a set
8036: of helper words used just for the implementation (hidden in a separate
1.75 anton 8037: wordlist). This keeps @code{words}' output smaller, separates
8038: implementation and interface, and reduces the chance of name conflicts
8039: within the common wordlist.
1.74 anton 8040:
1.26 crook 8041: @item
8042: To prevent a name-space clash between multiple definitions with the same
8043: name. For example, when building a cross-compiler you might have a word
8044: @code{IF} that generates conditional code for your target system. By
8045: placing this definition in a different word list you can control whether
8046: the host system's @code{IF} or the target system's @code{IF} get used in
8047: any particular context by controlling the order of the word lists on the
8048: search order stack.
1.74 anton 8049:
1.26 crook 8050: @end itemize
1.1 anton 8051:
1.74 anton 8052: The downsides of using wordlists are:
8053:
8054: @itemize
8055:
8056: @item
8057: Debugging becomes more cumbersome.
8058:
8059: @item
8060: Name conflicts worked around with wordlists are still there, and you
8061: have to arrange the search order carefully to get the desired results;
8062: if you forget to do that, you get hard-to-find errors (as in any case
8063: where you read the code differently from the compiler; @code{see} can
1.75 anton 8064: help seeing which of several possible words the name resolves to in such
8065: cases). @code{See} displays just the name of the words, not what
8066: wordlist they belong to, so it might be misleading. Using unique names
8067: is a better approach to avoid name conflicts.
1.74 anton 8068:
8069: @item
8070: You have to explicitly undo any changes to the search order. In many
8071: cases it would be more convenient if this happened implicitly. Gforth
8072: currently does not provide such a feature, but it may do so in the
8073: future.
8074: @end itemize
8075:
8076:
1.75 anton 8077: @node Word list example, , Why use word lists?, Word Lists
8078: @subsection Word list example
8079: @cindex word lists - example
1.1 anton 8080:
1.74 anton 8081: The following example is from the
8082: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8083: garbage collector} and uses wordlists to separate public words from
8084: helper words:
8085:
8086: @example
8087: get-current ( wid )
8088: vocabulary garbage-collector also garbage-collector definitions
8089: ... \ define helper words
8090: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8091: ... \ define the public (i.e., API) words
8092: \ they can refer to the helper words
8093: previous \ restore original search order (helper words become invisible)
8094: @end example
8095:
1.26 crook 8096: @c -------------------------------------------------------------
8097: @node Environmental Queries, Files, Word Lists, Words
8098: @section Environmental Queries
8099: @cindex environmental queries
1.21 crook 8100:
1.26 crook 8101: ANS Forth introduced the idea of ``environmental queries'' as a way
8102: for a program running on a system to determine certain characteristics of the system.
8103: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8104:
1.32 anton 8105: The Standard requires that the header space used for environmental queries
8106: be distinct from the header space used for definitions.
1.21 crook 8107:
1.26 crook 8108: Typically, environmental queries are supported by creating a set of
1.29 crook 8109: definitions in a word list that is @i{only} used during environmental
1.26 crook 8110: queries; that is what Gforth does. There is no Standard way of adding
8111: definitions to the set of recognised environmental queries, but any
8112: implementation that supports the loading of optional word sets must have
8113: some mechanism for doing this (after loading the word set, the
8114: associated environmental query string must return @code{true}). In
8115: Gforth, the word list used to honour environmental queries can be
8116: manipulated just like any other word list.
1.21 crook 8117:
1.44 crook 8118:
1.26 crook 8119: doc-environment?
8120: doc-environment-wordlist
1.21 crook 8121:
1.26 crook 8122: doc-gforth
8123: doc-os-class
1.21 crook 8124:
1.44 crook 8125:
1.26 crook 8126: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8127: returning two items on the stack, querying it using @code{environment?}
8128: will return an additional item; the @code{true} flag that shows that the
8129: string was recognised.
1.21 crook 8130:
1.26 crook 8131: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8132:
1.26 crook 8133: Here are some examples of using environmental queries:
1.21 crook 8134:
1.26 crook 8135: @example
8136: s" address-unit-bits" environment? 0=
8137: [IF]
8138: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8139: [ELSE]
8140: drop \ ensure balanced stack effect
1.26 crook 8141: [THEN]
1.21 crook 8142:
1.75 anton 8143: \ this might occur in the prelude of a standard program that uses THROW
8144: s" exception" environment? [IF]
8145: 0= [IF]
8146: : throw abort" exception thrown" ;
8147: [THEN]
8148: [ELSE] \ we don't know, so make sure
8149: : throw abort" exception thrown" ;
8150: [THEN]
1.21 crook 8151:
1.26 crook 8152: s" gforth" environment? [IF] .( Gforth version ) TYPE
8153: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8154:
8155: \ a program using v*
8156: s" gforth" environment? [IF]
8157: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8158: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8159: >r swap 2swap swap 0e r> 0 ?DO
8160: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8161: LOOP
8162: 2drop 2drop ;
8163: [THEN]
8164: [ELSE] \
8165: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8166: ...
8167: [THEN]
1.26 crook 8168: @end example
1.21 crook 8169:
1.26 crook 8170: Here is an example of adding a definition to the environment word list:
1.21 crook 8171:
1.26 crook 8172: @example
8173: get-current environment-wordlist set-current
8174: true constant block
8175: true constant block-ext
8176: set-current
8177: @end example
1.21 crook 8178:
1.26 crook 8179: You can see what definitions are in the environment word list like this:
1.21 crook 8180:
1.26 crook 8181: @example
1.79 anton 8182: environment-wordlist >order words previous
1.26 crook 8183: @end example
1.21 crook 8184:
8185:
1.26 crook 8186: @c -------------------------------------------------------------
8187: @node Files, Blocks, Environmental Queries, Words
8188: @section Files
1.28 crook 8189: @cindex files
8190: @cindex I/O - file-handling
1.21 crook 8191:
1.26 crook 8192: Gforth provides facilities for accessing files that are stored in the
8193: host operating system's file-system. Files that are processed by Gforth
8194: can be divided into two categories:
1.21 crook 8195:
1.23 crook 8196: @itemize @bullet
8197: @item
1.29 crook 8198: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8199: @item
1.29 crook 8200: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8201: @end itemize
8202:
8203: @menu
1.48 anton 8204: * Forth source files::
8205: * General files::
8206: * Search Paths::
1.26 crook 8207: @end menu
8208:
8209: @c -------------------------------------------------------------
8210: @node Forth source files, General files, Files, Files
8211: @subsection Forth source files
8212: @cindex including files
8213: @cindex Forth source files
1.21 crook 8214:
1.26 crook 8215: The simplest way to interpret the contents of a file is to use one of
8216: these two formats:
1.21 crook 8217:
1.26 crook 8218: @example
8219: include mysource.fs
8220: s" mysource.fs" included
8221: @end example
1.21 crook 8222:
1.75 anton 8223: You usually want to include a file only if it is not included already
1.26 crook 8224: (by, say, another source file). In that case, you can use one of these
1.45 crook 8225: three formats:
1.21 crook 8226:
1.26 crook 8227: @example
8228: require mysource.fs
8229: needs mysource.fs
8230: s" mysource.fs" required
8231: @end example
1.21 crook 8232:
1.26 crook 8233: @cindex stack effect of included files
8234: @cindex including files, stack effect
1.45 crook 8235: It is good practice to write your source files such that interpreting them
8236: does not change the stack. Source files designed in this way can be used with
1.26 crook 8237: @code{required} and friends without complications. For example:
1.21 crook 8238:
1.26 crook 8239: @example
1.75 anton 8240: 1024 require foo.fs drop
1.26 crook 8241: @end example
1.21 crook 8242:
1.75 anton 8243: Here you want to pass the argument 1024 (e.g., a buffer size) to
8244: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8245: ), which allows its use with @code{require}. Of course with such
8246: parameters to required files, you have to ensure that the first
8247: @code{require} fits for all uses (i.e., @code{require} it early in the
8248: master load file).
1.44 crook 8249:
1.26 crook 8250: doc-include-file
8251: doc-included
1.28 crook 8252: doc-included?
1.26 crook 8253: doc-include
8254: doc-required
8255: doc-require
8256: doc-needs
1.75 anton 8257: @c doc-init-included-files @c internal
8258: doc-sourcefilename
8259: doc-sourceline#
1.44 crook 8260:
1.26 crook 8261: A definition in ANS Forth for @code{required} is provided in
8262: @file{compat/required.fs}.
1.21 crook 8263:
1.26 crook 8264: @c -------------------------------------------------------------
8265: @node General files, Search Paths, Forth source files, Files
8266: @subsection General files
8267: @cindex general files
8268: @cindex file-handling
1.21 crook 8269:
1.75 anton 8270: Files are opened/created by name and type. The following file access
8271: methods (FAMs) are recognised:
1.44 crook 8272:
1.75 anton 8273: @cindex fam (file access method)
1.26 crook 8274: doc-r/o
8275: doc-r/w
8276: doc-w/o
8277: doc-bin
1.1 anton 8278:
1.44 crook 8279:
1.26 crook 8280: When a file is opened/created, it returns a file identifier,
1.29 crook 8281: @i{wfileid} that is used for all other file commands. All file
8282: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8283: successful operation and an implementation-defined non-zero value in the
8284: case of an error.
1.21 crook 8285:
1.44 crook 8286:
1.26 crook 8287: doc-open-file
8288: doc-create-file
1.21 crook 8289:
1.26 crook 8290: doc-close-file
8291: doc-delete-file
8292: doc-rename-file
8293: doc-read-file
8294: doc-read-line
8295: doc-write-file
8296: doc-write-line
8297: doc-emit-file
8298: doc-flush-file
1.21 crook 8299:
1.26 crook 8300: doc-file-status
8301: doc-file-position
8302: doc-reposition-file
8303: doc-file-size
8304: doc-resize-file
1.21 crook 8305:
1.93 anton 8306: doc-slurp-file
8307: doc-slurp-fid
1.112 anton 8308: doc-stdin
8309: doc-stdout
8310: doc-stderr
1.44 crook 8311:
1.26 crook 8312: @c ---------------------------------------------------------
1.48 anton 8313: @node Search Paths, , General files, Files
1.26 crook 8314: @subsection Search Paths
8315: @cindex path for @code{included}
8316: @cindex file search path
8317: @cindex @code{include} search path
8318: @cindex search path for files
1.21 crook 8319:
1.26 crook 8320: If you specify an absolute filename (i.e., a filename starting with
8321: @file{/} or @file{~}, or with @file{:} in the second position (as in
8322: @samp{C:...})) for @code{included} and friends, that file is included
8323: just as you would expect.
1.21 crook 8324:
1.75 anton 8325: If the filename starts with @file{./}, this refers to the directory that
8326: the present file was @code{included} from. This allows files to include
8327: other files relative to their own position (irrespective of the current
8328: working directory or the absolute position). This feature is essential
8329: for libraries consisting of several files, where a file may include
8330: other files from the library. It corresponds to @code{#include "..."}
8331: in C. If the current input source is not a file, @file{.} refers to the
8332: directory of the innermost file being included, or, if there is no file
8333: being included, to the current working directory.
8334:
8335: For relative filenames (not starting with @file{./}), Gforth uses a
8336: search path similar to Forth's search order (@pxref{Word Lists}). It
8337: tries to find the given filename in the directories present in the path,
8338: and includes the first one it finds. There are separate search paths for
8339: Forth source files and general files. If the search path contains the
8340: directory @file{.}, this refers to the directory of the current file, or
8341: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8342:
1.26 crook 8343: Use @file{~+} to refer to the current working directory (as in the
8344: @code{bash}).
1.1 anton 8345:
1.75 anton 8346: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8347:
1.48 anton 8348: @menu
1.75 anton 8349: * Source Search Paths::
1.48 anton 8350: * General Search Paths::
8351: @end menu
8352:
1.26 crook 8353: @c ---------------------------------------------------------
1.75 anton 8354: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8355: @subsubsection Source Search Paths
8356: @cindex search path control, source files
1.5 anton 8357:
1.26 crook 8358: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8359: Gforth}). You can display it and change it using @code{fpath} in
8360: combination with the general path handling words.
1.5 anton 8361:
1.75 anton 8362: doc-fpath
8363: @c the functionality of the following words is easily available through
8364: @c fpath and the general path words. The may go away.
8365: @c doc-.fpath
8366: @c doc-fpath+
8367: @c doc-fpath=
8368: @c doc-open-fpath-file
1.44 crook 8369:
8370: @noindent
1.26 crook 8371: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8372:
1.26 crook 8373: @example
1.75 anton 8374: fpath path= /usr/lib/forth/|./
1.26 crook 8375: require timer.fs
8376: @end example
1.5 anton 8377:
1.75 anton 8378:
1.26 crook 8379: @c ---------------------------------------------------------
1.75 anton 8380: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8381: @subsubsection General Search Paths
1.75 anton 8382: @cindex search path control, source files
1.5 anton 8383:
1.26 crook 8384: Your application may need to search files in several directories, like
8385: @code{included} does. To facilitate this, Gforth allows you to define
8386: and use your own search paths, by providing generic equivalents of the
8387: Forth search path words:
1.5 anton 8388:
1.75 anton 8389: doc-open-path-file
8390: doc-path-allot
8391: doc-clear-path
8392: doc-also-path
1.26 crook 8393: doc-.path
8394: doc-path+
8395: doc-path=
1.5 anton 8396:
1.75 anton 8397: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8398:
1.75 anton 8399: Here's an example of creating an empty search path:
8400: @c
1.26 crook 8401: @example
1.75 anton 8402: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8403: @end example
1.5 anton 8404:
1.26 crook 8405: @c -------------------------------------------------------------
8406: @node Blocks, Other I/O, Files, Words
8407: @section Blocks
1.28 crook 8408: @cindex I/O - blocks
8409: @cindex blocks
8410:
8411: When you run Gforth on a modern desk-top computer, it runs under the
8412: control of an operating system which provides certain services. One of
8413: these services is @var{file services}, which allows Forth source code
8414: and data to be stored in files and read into Gforth (@pxref{Files}).
8415:
8416: Traditionally, Forth has been an important programming language on
8417: systems where it has interfaced directly to the underlying hardware with
8418: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8419: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8420:
8421: A block is a 1024-byte data area, which can be used to hold data or
8422: Forth source code. No structure is imposed on the contents of the
8423: block. A block is identified by its number; blocks are numbered
8424: contiguously from 1 to an implementation-defined maximum.
8425:
8426: A typical system that used blocks but no operating system might use a
8427: single floppy-disk drive for mass storage, with the disks formatted to
8428: provide 256-byte sectors. Blocks would be implemented by assigning the
8429: first four sectors of the disk to block 1, the second four sectors to
8430: block 2 and so on, up to the limit of the capacity of the disk. The disk
8431: would not contain any file system information, just the set of blocks.
8432:
1.29 crook 8433: @cindex blocks file
1.28 crook 8434: On systems that do provide file services, blocks are typically
1.29 crook 8435: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8436: file}. The size of the blocks file will be an exact multiple of 1024
8437: bytes, corresponding to the number of blocks it contains. This is the
8438: mechanism that Gforth uses.
8439:
1.29 crook 8440: @cindex @file{blocks.fb}
1.75 anton 8441: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8442: having specified a blocks file, Gforth defaults to the blocks file
8443: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8444: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8445:
1.29 crook 8446: @cindex block buffers
1.28 crook 8447: When you read and write blocks under program control, Gforth uses a
1.29 crook 8448: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8449: not used when you use @code{load} to interpret the contents of a block.
8450:
1.75 anton 8451: The behaviour of the block buffers is analagous to that of a cache.
8452: Each block buffer has three states:
1.28 crook 8453:
8454: @itemize @bullet
8455: @item
8456: Unassigned
8457: @item
8458: Assigned-clean
8459: @item
8460: Assigned-dirty
8461: @end itemize
8462:
1.29 crook 8463: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8464: block, the block (specified by its block number) must be assigned to a
8465: block buffer.
8466:
8467: The assignment of a block to a block buffer is performed by @code{block}
8468: or @code{buffer}. Use @code{block} when you wish to modify the existing
8469: contents of a block. Use @code{buffer} when you don't care about the
8470: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8471: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8472: with the particular block is already stored in a block buffer due to an
8473: earlier @code{block} command, @code{buffer} will return that block
8474: buffer and the existing contents of the block will be
8475: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8476: block buffer for the block.}.
1.28 crook 8477:
1.47 crook 8478: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8479: @code{buffer}, that block buffer becomes the @i{current block
8480: buffer}. Data may only be manipulated (read or written) within the
8481: current block buffer.
1.47 crook 8482:
8483: When the contents of the current block buffer has been modified it is
1.48 anton 8484: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8485: either abandon the changes (by doing nothing) or mark the block as
8486: changed (assigned-dirty), using @code{update}. Using @code{update} does
8487: not change the blocks file; it simply changes a block buffer's state to
8488: @i{assigned-dirty}. The block will be written implicitly when it's
8489: buffer is needed for another block, or explicitly by @code{flush} or
8490: @code{save-buffers}.
8491:
8492: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8493: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8494: @code{flush}.
1.28 crook 8495:
1.29 crook 8496: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8497: algorithm to assign a block buffer to a block. That means that any
8498: particular block can only be assigned to one specific block buffer,
1.29 crook 8499: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8500: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8501: the new block immediately. If it is @i{assigned-dirty} its current
8502: contents are written back to the blocks file on disk before it is
1.28 crook 8503: allocated to the new block.
8504:
8505: Although no structure is imposed on the contents of a block, it is
8506: traditional to display the contents as 16 lines each of 64 characters. A
8507: block provides a single, continuous stream of input (for example, it
8508: acts as a single parse area) -- there are no end-of-line characters
8509: within a block, and no end-of-file character at the end of a
8510: block. There are two consequences of this:
1.26 crook 8511:
1.28 crook 8512: @itemize @bullet
8513: @item
8514: The last character of one line wraps straight into the first character
8515: of the following line
8516: @item
8517: The word @code{\} -- comment to end of line -- requires special
8518: treatment; in the context of a block it causes all characters until the
8519: end of the current 64-character ``line'' to be ignored.
8520: @end itemize
8521:
8522: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8523: the current blocks file will be extended to the appropriate size and the
1.28 crook 8524: block buffer will be initialised with spaces.
8525:
1.47 crook 8526: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8527: for details) but doesn't encourage the use of blocks; the mechanism is
8528: only provided for backward compatibility -- ANS Forth requires blocks to
8529: be available when files are.
1.28 crook 8530:
8531: Common techniques that are used when working with blocks include:
8532:
8533: @itemize @bullet
8534: @item
8535: A screen editor that allows you to edit blocks without leaving the Forth
8536: environment.
8537: @item
8538: Shadow screens; where every code block has an associated block
8539: containing comments (for example: code in odd block numbers, comments in
8540: even block numbers). Typically, the block editor provides a convenient
8541: mechanism to toggle between code and comments.
8542: @item
8543: Load blocks; a single block (typically block 1) contains a number of
8544: @code{thru} commands which @code{load} the whole of the application.
8545: @end itemize
1.26 crook 8546:
1.29 crook 8547: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8548: integrated into a Forth programming environment.
1.26 crook 8549:
8550: @comment TODO what about errors on open-blocks?
1.44 crook 8551:
1.26 crook 8552: doc-open-blocks
8553: doc-use
1.75 anton 8554: doc-block-offset
1.26 crook 8555: doc-get-block-fid
8556: doc-block-position
1.28 crook 8557:
1.75 anton 8558: doc-list
1.28 crook 8559: doc-scr
8560:
1.45 crook 8561: doc---gforthman-block
1.28 crook 8562: doc-buffer
8563:
1.75 anton 8564: doc-empty-buffers
8565: doc-empty-buffer
1.26 crook 8566: doc-update
1.28 crook 8567: doc-updated?
1.26 crook 8568: doc-save-buffers
1.75 anton 8569: doc-save-buffer
1.26 crook 8570: doc-flush
1.28 crook 8571:
1.26 crook 8572: doc-load
8573: doc-thru
8574: doc-+load
8575: doc-+thru
1.45 crook 8576: doc---gforthman--->
1.26 crook 8577: doc-block-included
8578:
1.44 crook 8579:
1.26 crook 8580: @c -------------------------------------------------------------
1.126 pazsan 8581: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8582: @section Other I/O
1.28 crook 8583: @cindex I/O - keyboard and display
1.26 crook 8584:
8585: @menu
8586: * Simple numeric output:: Predefined formats
8587: * Formatted numeric output:: Formatted (pictured) output
8588: * String Formats:: How Forth stores strings in memory
1.67 anton 8589: * Displaying characters and strings:: Other stuff
1.26 crook 8590: * Input:: Input
1.112 anton 8591: * Pipes:: How to create your own pipes
1.149 pazsan 8592: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8593: @end menu
8594:
8595: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8596: @subsection Simple numeric output
1.28 crook 8597: @cindex numeric output - simple/free-format
1.5 anton 8598:
1.26 crook 8599: The simplest output functions are those that display numbers from the
8600: data or floating-point stacks. Floating-point output is always displayed
8601: using base 10. Numbers displayed from the data stack use the value stored
8602: in @code{base}.
1.5 anton 8603:
1.44 crook 8604:
1.26 crook 8605: doc-.
8606: doc-dec.
8607: doc-hex.
8608: doc-u.
8609: doc-.r
8610: doc-u.r
8611: doc-d.
8612: doc-ud.
8613: doc-d.r
8614: doc-ud.r
8615: doc-f.
8616: doc-fe.
8617: doc-fs.
1.111 anton 8618: doc-f.rdp
1.44 crook 8619:
1.26 crook 8620: Examples of printing the number 1234.5678E23 in the different floating-point output
8621: formats are shown below:
1.5 anton 8622:
8623: @example
1.26 crook 8624: f. 123456779999999000000000000.
8625: fe. 123.456779999999E24
8626: fs. 1.23456779999999E26
1.5 anton 8627: @end example
8628:
8629:
1.26 crook 8630: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8631: @subsection Formatted numeric output
1.28 crook 8632: @cindex formatted numeric output
1.26 crook 8633: @cindex pictured numeric output
1.28 crook 8634: @cindex numeric output - formatted
1.26 crook 8635:
1.29 crook 8636: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8637: output} for formatted printing of integers. In this technique, digits
8638: are extracted from the number (using the current output radix defined by
8639: @code{base}), converted to ASCII codes and appended to a string that is
8640: built in a scratch-pad area of memory (@pxref{core-idef,
8641: Implementation-defined options, Implementation-defined
8642: options}). Arbitrary characters can be appended to the string during the
8643: extraction process. The completed string is specified by an address
8644: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8645: under program control.
1.5 anton 8646:
1.75 anton 8647: All of the integer output words described in the previous section
8648: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8649: numeric output.
1.5 anton 8650:
1.47 crook 8651: Three important things to remember about pictured numeric output:
1.5 anton 8652:
1.26 crook 8653: @itemize @bullet
8654: @item
1.28 crook 8655: It always operates on double-precision numbers; to display a
1.49 anton 8656: single-precision number, convert it first (for ways of doing this
8657: @pxref{Double precision}).
1.26 crook 8658: @item
1.28 crook 8659: It always treats the double-precision number as though it were
8660: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8661: @item
8662: The string is built up from right to left; least significant digit first.
8663: @end itemize
1.5 anton 8664:
1.44 crook 8665:
1.26 crook 8666: doc-<#
1.47 crook 8667: doc-<<#
1.26 crook 8668: doc-#
8669: doc-#s
8670: doc-hold
8671: doc-sign
8672: doc-#>
1.47 crook 8673: doc-#>>
1.5 anton 8674:
1.26 crook 8675: doc-represent
1.111 anton 8676: doc-f>str-rdp
8677: doc-f>buf-rdp
1.5 anton 8678:
1.44 crook 8679:
8680: @noindent
1.26 crook 8681: Here are some examples of using pictured numeric output:
1.5 anton 8682:
8683: @example
1.26 crook 8684: : my-u. ( u -- )
8685: \ Simplest use of pns.. behaves like Standard u.
8686: 0 \ convert to unsigned double
1.75 anton 8687: <<# \ start conversion
1.26 crook 8688: #s \ convert all digits
8689: #> \ complete conversion
1.75 anton 8690: TYPE SPACE \ display, with trailing space
8691: #>> ; \ release hold area
1.5 anton 8692:
1.26 crook 8693: : cents-only ( u -- )
8694: 0 \ convert to unsigned double
1.75 anton 8695: <<# \ start conversion
1.26 crook 8696: # # \ convert two least-significant digits
8697: #> \ complete conversion, discard other digits
1.75 anton 8698: TYPE SPACE \ display, with trailing space
8699: #>> ; \ release hold area
1.5 anton 8700:
1.26 crook 8701: : dollars-and-cents ( u -- )
8702: 0 \ convert to unsigned double
1.75 anton 8703: <<# \ start conversion
1.26 crook 8704: # # \ convert two least-significant digits
8705: [char] . hold \ insert decimal point
8706: #s \ convert remaining digits
8707: [char] $ hold \ append currency symbol
8708: #> \ complete conversion
1.75 anton 8709: TYPE SPACE \ display, with trailing space
8710: #>> ; \ release hold area
1.5 anton 8711:
1.26 crook 8712: : my-. ( n -- )
8713: \ handling negatives.. behaves like Standard .
8714: s>d \ convert to signed double
8715: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8716: <<# \ start conversion
1.26 crook 8717: #s \ convert all digits
8718: rot sign \ get at sign byte, append "-" if needed
8719: #> \ complete conversion
1.75 anton 8720: TYPE SPACE \ display, with trailing space
8721: #>> ; \ release hold area
1.5 anton 8722:
1.26 crook 8723: : account. ( n -- )
1.75 anton 8724: \ accountants don't like minus signs, they use parentheses
1.26 crook 8725: \ for negative numbers
8726: s>d \ convert to signed double
8727: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8728: <<# \ start conversion
1.26 crook 8729: 2 pick \ get copy of sign byte
8730: 0< IF [char] ) hold THEN \ right-most character of output
8731: #s \ convert all digits
8732: rot \ get at sign byte
8733: 0< IF [char] ( hold THEN
8734: #> \ complete conversion
1.75 anton 8735: TYPE SPACE \ display, with trailing space
8736: #>> ; \ release hold area
8737:
1.5 anton 8738: @end example
8739:
1.26 crook 8740: Here are some examples of using these words:
1.5 anton 8741:
8742: @example
1.26 crook 8743: 1 my-u. 1
8744: hex -1 my-u. decimal FFFFFFFF
8745: 1 cents-only 01
8746: 1234 cents-only 34
8747: 2 dollars-and-cents $0.02
8748: 1234 dollars-and-cents $12.34
8749: 123 my-. 123
8750: -123 my. -123
8751: 123 account. 123
8752: -456 account. (456)
1.5 anton 8753: @end example
8754:
8755:
1.26 crook 8756: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8757: @subsection String Formats
1.27 crook 8758: @cindex strings - see character strings
8759: @cindex character strings - formats
1.28 crook 8760: @cindex I/O - see character strings
1.75 anton 8761: @cindex counted strings
8762:
8763: @c anton: this does not really belong here; maybe the memory section,
8764: @c or the principles chapter
1.26 crook 8765:
1.27 crook 8766: Forth commonly uses two different methods for representing character
8767: strings:
1.26 crook 8768:
8769: @itemize @bullet
8770: @item
8771: @cindex address of counted string
1.45 crook 8772: @cindex counted string
1.29 crook 8773: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8774: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8775: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8776: memory.
8777: @item
1.29 crook 8778: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8779: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8780: first byte of the string.
8781: @end itemize
8782:
8783: ANS Forth encourages the use of the second format when representing
1.75 anton 8784: strings.
1.26 crook 8785:
1.44 crook 8786:
1.26 crook 8787: doc-count
8788:
1.44 crook 8789:
1.49 anton 8790: For words that move, copy and search for strings see @ref{Memory
8791: Blocks}. For words that display characters and strings see
8792: @ref{Displaying characters and strings}.
1.26 crook 8793:
8794: @node Displaying characters and strings, Input, String Formats, Other I/O
8795: @subsection Displaying characters and strings
1.27 crook 8796: @cindex characters - compiling and displaying
8797: @cindex character strings - compiling and displaying
1.26 crook 8798:
8799: This section starts with a glossary of Forth words and ends with a set
8800: of examples.
8801:
1.44 crook 8802:
1.26 crook 8803: doc-bl
8804: doc-space
8805: doc-spaces
8806: doc-emit
8807: doc-toupper
8808: doc-."
8809: doc-.(
1.98 anton 8810: doc-.\"
1.26 crook 8811: doc-type
1.44 crook 8812: doc-typewhite
1.26 crook 8813: doc-cr
1.27 crook 8814: @cindex cursor control
1.26 crook 8815: doc-at-xy
8816: doc-page
8817: doc-s"
1.98 anton 8818: doc-s\"
1.26 crook 8819: doc-c"
8820: doc-char
8821: doc-[char]
8822:
1.44 crook 8823:
8824: @noindent
1.26 crook 8825: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8826:
8827: @example
1.26 crook 8828: .( text-1)
8829: : my-word
8830: ." text-2" cr
8831: .( text-3)
8832: ;
8833:
8834: ." text-4"
8835:
8836: : my-char
8837: [char] ALPHABET emit
8838: char emit
8839: ;
1.5 anton 8840: @end example
8841:
1.26 crook 8842: When you load this code into Gforth, the following output is generated:
1.5 anton 8843:
1.26 crook 8844: @example
1.30 anton 8845: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8846: @end example
1.5 anton 8847:
1.26 crook 8848: @itemize @bullet
8849: @item
8850: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8851: is an immediate word; it behaves in the same way whether it is used inside
8852: or outside a colon definition.
8853: @item
8854: Message @code{text-4} is displayed because of Gforth's added interpretation
8855: semantics for @code{."}.
8856: @item
1.29 crook 8857: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8858: performs the compilation semantics for @code{."} within the definition of
8859: @code{my-word}.
8860: @end itemize
1.5 anton 8861:
1.26 crook 8862: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8863:
1.26 crook 8864: @example
1.30 anton 8865: @kbd{my-word @key{RET}} text-2
1.26 crook 8866: ok
1.30 anton 8867: @kbd{my-char fred @key{RET}} Af ok
8868: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8869: @end example
1.5 anton 8870:
8871: @itemize @bullet
8872: @item
1.26 crook 8873: Message @code{text-2} is displayed because of the run-time behaviour of
8874: @code{."}.
8875: @item
8876: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8877: on the stack at run-time. @code{emit} always displays the character
8878: when @code{my-char} is executed.
8879: @item
8880: @code{char} parses a string at run-time and the second @code{emit} displays
8881: the first character of the string.
1.5 anton 8882: @item
1.26 crook 8883: If you type @code{see my-char} you can see that @code{[char]} discarded
8884: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8885: definition of @code{my-char}.
1.5 anton 8886: @end itemize
8887:
8888:
8889:
1.112 anton 8890: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8891: @subsection Input
8892: @cindex input
1.28 crook 8893: @cindex I/O - see input
8894: @cindex parsing a string
1.5 anton 8895:
1.49 anton 8896: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8897:
1.27 crook 8898: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8899: @comment then index them
1.27 crook 8900:
1.44 crook 8901:
1.27 crook 8902: doc-key
8903: doc-key?
1.45 crook 8904: doc-ekey
1.141 anton 8905: doc-ekey>char
1.45 crook 8906: doc-ekey?
1.141 anton 8907:
8908: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
8909: you need the ANSI.SYS driver to get that behaviour). These are the
8910: keyboard events produced by various common keys:
8911:
8912: doc-k-left
8913: doc-k-right
8914: doc-k-up
8915: doc-k-down
8916: doc-k-home
8917: doc-k-end
8918: doc-k-prior
8919: doc-k-next
8920: doc-k-insert
8921: doc-k-delete
8922:
8923: The function keys (aka keypad keys) are:
8924:
8925: doc-k1
8926: doc-k2
8927: doc-k3
8928: doc-k4
8929: doc-k5
8930: doc-k6
8931: doc-k7
8932: doc-k8
8933: doc-k9
8934: doc-k10
8935: doc-k11
8936: doc-k12
8937:
8938: Note that K11 and K12 are not as widely available. The shifted
8939: function keys are also not very widely available:
8940:
8941: doc-s-k8
8942: doc-s-k1
8943: doc-s-k2
8944: doc-s-k3
8945: doc-s-k4
8946: doc-s-k5
8947: doc-s-k6
8948: doc-s-k7
8949: doc-s-k8
8950: doc-s-k9
8951: doc-s-k10
8952: doc-s-k11
8953: doc-s-k12
8954:
8955: Words for inputting one line from the keyboard:
8956:
8957: doc-accept
8958: doc-edit-line
8959:
8960: Conversion words:
8961:
1.143 anton 8962: doc-s>number?
8963: doc-s>unumber?
1.26 crook 8964: doc->number
8965: doc->float
1.143 anton 8966:
1.141 anton 8967:
1.27 crook 8968: @comment obsolescent words..
1.141 anton 8969: Obsolescent input and conversion words:
8970:
1.27 crook 8971: doc-convert
1.26 crook 8972: doc-expect
1.27 crook 8973: doc-span
1.5 anton 8974:
8975:
1.149 pazsan 8976: @node Pipes, Xchars and Unicode, Input, Other I/O
1.112 anton 8977: @subsection Pipes
8978: @cindex pipes, creating your own
8979:
8980: In addition to using Gforth in pipes created by other processes
8981: (@pxref{Gforth in pipes}), you can create your own pipe with
8982: @code{open-pipe}, and read from or write to it.
8983:
8984: doc-open-pipe
8985: doc-close-pipe
8986:
8987: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8988: you don't catch this exception, Gforth will catch it and exit, usually
8989: silently (@pxref{Gforth in pipes}). Since you probably do not want
8990: this, you should wrap a @code{catch} or @code{try} block around the code
8991: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8992: problem yourself, and then return to regular processing.
8993:
8994: doc-broken-pipe-error
8995:
1.149 pazsan 8996: @node Xchars and Unicode, , Pipes, Other I/O
8997:
8998: This chapter needs completion
1.112 anton 8999:
1.121 anton 9000: @node OS command line arguments, Locals, Other I/O, Words
9001: @section OS command line arguments
9002: @cindex OS command line arguments
9003: @cindex command line arguments, OS
9004: @cindex arguments, OS command line
9005:
9006: The usual way to pass arguments to Gforth programs on the command line
9007: is via the @option{-e} option, e.g.
9008:
9009: @example
9010: gforth -e "123 456" foo.fs -e bye
9011: @end example
9012:
9013: However, you may want to interpret the command-line arguments directly.
9014: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9015: through @code{next-arg}:
1.121 anton 9016:
1.123 anton 9017: doc-next-arg
1.121 anton 9018:
1.123 anton 9019: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9020:
9021: @example
9022: : echo ( -- )
1.122 anton 9023: begin
1.123 anton 9024: next-arg 2dup 0 0 d<> while
9025: type space
9026: repeat
9027: 2drop ;
1.121 anton 9028:
9029: echo cr bye
9030: @end example
9031:
9032: This can be invoked with
9033:
9034: @example
9035: gforth echo.fs hello world
9036: @end example
1.123 anton 9037:
9038: and it will print
9039:
9040: @example
9041: hello world
9042: @end example
9043:
9044: The next lower level of dealing with the OS command line are the
9045: following words:
9046:
9047: doc-arg
9048: doc-shift-args
9049:
9050: Finally, at the lowest level Gforth provides the following words:
9051:
9052: doc-argc
9053: doc-argv
1.121 anton 9054:
1.78 anton 9055: @c -------------------------------------------------------------
1.126 pazsan 9056: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9057: @section Locals
9058: @cindex locals
9059:
9060: Local variables can make Forth programming more enjoyable and Forth
9061: programs easier to read. Unfortunately, the locals of ANS Forth are
9062: laden with restrictions. Therefore, we provide not only the ANS Forth
9063: locals wordset, but also our own, more powerful locals wordset (we
9064: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9065:
1.78 anton 9066: The ideas in this section have also been published in M. Anton Ertl,
9067: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9068: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9069:
9070: @menu
1.78 anton 9071: * Gforth locals::
9072: * ANS Forth locals::
1.5 anton 9073: @end menu
9074:
1.78 anton 9075: @node Gforth locals, ANS Forth locals, Locals, Locals
9076: @subsection Gforth locals
9077: @cindex Gforth locals
9078: @cindex locals, Gforth style
1.5 anton 9079:
1.78 anton 9080: Locals can be defined with
1.44 crook 9081:
1.78 anton 9082: @example
9083: @{ local1 local2 ... -- comment @}
9084: @end example
9085: or
9086: @example
9087: @{ local1 local2 ... @}
9088: @end example
1.5 anton 9089:
1.78 anton 9090: E.g.,
9091: @example
9092: : max @{ n1 n2 -- n3 @}
9093: n1 n2 > if
9094: n1
9095: else
9096: n2
9097: endif ;
9098: @end example
1.44 crook 9099:
1.78 anton 9100: The similarity of locals definitions with stack comments is intended. A
9101: locals definition often replaces the stack comment of a word. The order
9102: of the locals corresponds to the order in a stack comment and everything
9103: after the @code{--} is really a comment.
1.77 anton 9104:
1.78 anton 9105: This similarity has one disadvantage: It is too easy to confuse locals
9106: declarations with stack comments, causing bugs and making them hard to
9107: find. However, this problem can be avoided by appropriate coding
9108: conventions: Do not use both notations in the same program. If you do,
9109: they should be distinguished using additional means, e.g. by position.
1.77 anton 9110:
1.78 anton 9111: @cindex types of locals
9112: @cindex locals types
9113: The name of the local may be preceded by a type specifier, e.g.,
9114: @code{F:} for a floating point value:
1.5 anton 9115:
1.78 anton 9116: @example
9117: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9118: \ complex multiplication
9119: Ar Br f* Ai Bi f* f-
9120: Ar Bi f* Ai Br f* f+ ;
9121: @end example
1.44 crook 9122:
1.78 anton 9123: @cindex flavours of locals
9124: @cindex locals flavours
9125: @cindex value-flavoured locals
9126: @cindex variable-flavoured locals
9127: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9128: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9129: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9130: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9131: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9132: produces its address (which becomes invalid when the variable's scope is
9133: left). E.g., the standard word @code{emit} can be defined in terms of
9134: @code{type} like this:
1.5 anton 9135:
1.78 anton 9136: @example
9137: : emit @{ C^ char* -- @}
9138: char* 1 type ;
9139: @end example
1.5 anton 9140:
1.78 anton 9141: @cindex default type of locals
9142: @cindex locals, default type
9143: A local without type specifier is a @code{W:} local. Both flavours of
9144: locals are initialized with values from the data or FP stack.
1.44 crook 9145:
1.78 anton 9146: Currently there is no way to define locals with user-defined data
9147: structures, but we are working on it.
1.5 anton 9148:
1.78 anton 9149: Gforth allows defining locals everywhere in a colon definition. This
9150: poses the following questions:
1.5 anton 9151:
1.78 anton 9152: @menu
9153: * Where are locals visible by name?::
9154: * How long do locals live?::
9155: * Locals programming style::
9156: * Locals implementation::
9157: @end menu
1.44 crook 9158:
1.78 anton 9159: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9160: @subsubsection Where are locals visible by name?
9161: @cindex locals visibility
9162: @cindex visibility of locals
9163: @cindex scope of locals
1.5 anton 9164:
1.78 anton 9165: Basically, the answer is that locals are visible where you would expect
9166: it in block-structured languages, and sometimes a little longer. If you
9167: want to restrict the scope of a local, enclose its definition in
9168: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9169:
9170:
1.78 anton 9171: doc-scope
9172: doc-endscope
1.5 anton 9173:
9174:
1.78 anton 9175: These words behave like control structure words, so you can use them
9176: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9177: arbitrary ways.
1.77 anton 9178:
1.78 anton 9179: If you want a more exact answer to the visibility question, here's the
9180: basic principle: A local is visible in all places that can only be
9181: reached through the definition of the local@footnote{In compiler
9182: construction terminology, all places dominated by the definition of the
9183: local.}. In other words, it is not visible in places that can be reached
9184: without going through the definition of the local. E.g., locals defined
9185: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9186: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9187: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9188:
1.78 anton 9189: The reasoning behind this solution is: We want to have the locals
9190: visible as long as it is meaningful. The user can always make the
9191: visibility shorter by using explicit scoping. In a place that can
9192: only be reached through the definition of a local, the meaning of a
9193: local name is clear. In other places it is not: How is the local
9194: initialized at the control flow path that does not contain the
9195: definition? Which local is meant, if the same name is defined twice in
9196: two independent control flow paths?
1.77 anton 9197:
1.78 anton 9198: This should be enough detail for nearly all users, so you can skip the
9199: rest of this section. If you really must know all the gory details and
9200: options, read on.
1.77 anton 9201:
1.78 anton 9202: In order to implement this rule, the compiler has to know which places
9203: are unreachable. It knows this automatically after @code{AHEAD},
9204: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9205: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9206: compiler that the control flow never reaches that place. If
9207: @code{UNREACHABLE} is not used where it could, the only consequence is
9208: that the visibility of some locals is more limited than the rule above
9209: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9210: lie to the compiler), buggy code will be produced.
1.77 anton 9211:
1.5 anton 9212:
1.78 anton 9213: doc-unreachable
1.5 anton 9214:
1.23 crook 9215:
1.78 anton 9216: Another problem with this rule is that at @code{BEGIN}, the compiler
9217: does not know which locals will be visible on the incoming
9218: back-edge. All problems discussed in the following are due to this
9219: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9220: loops as examples; the discussion also applies to @code{?DO} and other
9221: loops). Perhaps the most insidious example is:
1.26 crook 9222: @example
1.78 anton 9223: AHEAD
9224: BEGIN
9225: x
9226: [ 1 CS-ROLL ] THEN
9227: @{ x @}
9228: ...
9229: UNTIL
1.26 crook 9230: @end example
1.23 crook 9231:
1.78 anton 9232: This should be legal according to the visibility rule. The use of
9233: @code{x} can only be reached through the definition; but that appears
9234: textually below the use.
9235:
9236: From this example it is clear that the visibility rules cannot be fully
9237: implemented without major headaches. Our implementation treats common
9238: cases as advertised and the exceptions are treated in a safe way: The
9239: compiler makes a reasonable guess about the locals visible after a
9240: @code{BEGIN}; if it is too pessimistic, the
9241: user will get a spurious error about the local not being defined; if the
9242: compiler is too optimistic, it will notice this later and issue a
9243: warning. In the case above the compiler would complain about @code{x}
9244: being undefined at its use. You can see from the obscure examples in
9245: this section that it takes quite unusual control structures to get the
9246: compiler into trouble, and even then it will often do fine.
1.23 crook 9247:
1.78 anton 9248: If the @code{BEGIN} is reachable from above, the most optimistic guess
9249: is that all locals visible before the @code{BEGIN} will also be
9250: visible after the @code{BEGIN}. This guess is valid for all loops that
9251: are entered only through the @code{BEGIN}, in particular, for normal
9252: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9253: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9254: compiler. When the branch to the @code{BEGIN} is finally generated by
9255: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9256: warns the user if it was too optimistic:
1.26 crook 9257: @example
1.78 anton 9258: IF
9259: @{ x @}
9260: BEGIN
9261: \ x ?
9262: [ 1 cs-roll ] THEN
9263: ...
9264: UNTIL
1.26 crook 9265: @end example
1.23 crook 9266:
1.78 anton 9267: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9268: optimistically assumes that it lives until the @code{THEN}. It notices
9269: this difference when it compiles the @code{UNTIL} and issues a
9270: warning. The user can avoid the warning, and make sure that @code{x}
9271: is not used in the wrong area by using explicit scoping:
9272: @example
9273: IF
9274: SCOPE
9275: @{ x @}
9276: ENDSCOPE
9277: BEGIN
9278: [ 1 cs-roll ] THEN
9279: ...
9280: UNTIL
9281: @end example
1.23 crook 9282:
1.78 anton 9283: Since the guess is optimistic, there will be no spurious error messages
9284: about undefined locals.
1.44 crook 9285:
1.78 anton 9286: If the @code{BEGIN} is not reachable from above (e.g., after
9287: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9288: optimistic guess, as the locals visible after the @code{BEGIN} may be
9289: defined later. Therefore, the compiler assumes that no locals are
9290: visible after the @code{BEGIN}. However, the user can use
9291: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9292: visible at the BEGIN as at the point where the top control-flow stack
9293: item was created.
1.23 crook 9294:
1.44 crook 9295:
1.78 anton 9296: doc-assume-live
1.26 crook 9297:
1.23 crook 9298:
1.78 anton 9299: @noindent
9300: E.g.,
9301: @example
9302: @{ x @}
9303: AHEAD
9304: ASSUME-LIVE
9305: BEGIN
9306: x
9307: [ 1 CS-ROLL ] THEN
9308: ...
9309: UNTIL
9310: @end example
1.44 crook 9311:
1.78 anton 9312: Other cases where the locals are defined before the @code{BEGIN} can be
9313: handled by inserting an appropriate @code{CS-ROLL} before the
9314: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9315: behind the @code{ASSUME-LIVE}).
1.23 crook 9316:
1.78 anton 9317: Cases where locals are defined after the @code{BEGIN} (but should be
9318: visible immediately after the @code{BEGIN}) can only be handled by
9319: rearranging the loop. E.g., the ``most insidious'' example above can be
9320: arranged into:
9321: @example
9322: BEGIN
9323: @{ x @}
9324: ... 0=
9325: WHILE
9326: x
9327: REPEAT
9328: @end example
1.44 crook 9329:
1.78 anton 9330: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9331: @subsubsection How long do locals live?
9332: @cindex locals lifetime
9333: @cindex lifetime of locals
1.23 crook 9334:
1.78 anton 9335: The right answer for the lifetime question would be: A local lives at
9336: least as long as it can be accessed. For a value-flavoured local this
9337: means: until the end of its visibility. However, a variable-flavoured
9338: local could be accessed through its address far beyond its visibility
9339: scope. Ultimately, this would mean that such locals would have to be
9340: garbage collected. Since this entails un-Forth-like implementation
9341: complexities, I adopted the same cowardly solution as some other
9342: languages (e.g., C): The local lives only as long as it is visible;
9343: afterwards its address is invalid (and programs that access it
9344: afterwards are erroneous).
1.23 crook 9345:
1.78 anton 9346: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9347: @subsubsection Locals programming style
9348: @cindex locals programming style
9349: @cindex programming style, locals
1.23 crook 9350:
1.78 anton 9351: The freedom to define locals anywhere has the potential to change
9352: programming styles dramatically. In particular, the need to use the
9353: return stack for intermediate storage vanishes. Moreover, all stack
9354: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9355: determined arguments) can be eliminated: If the stack items are in the
9356: wrong order, just write a locals definition for all of them; then
9357: write the items in the order you want.
1.23 crook 9358:
1.78 anton 9359: This seems a little far-fetched and eliminating stack manipulations is
9360: unlikely to become a conscious programming objective. Still, the number
9361: of stack manipulations will be reduced dramatically if local variables
9362: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9363: a traditional implementation of @code{max}).
1.23 crook 9364:
1.78 anton 9365: This shows one potential benefit of locals: making Forth programs more
9366: readable. Of course, this benefit will only be realized if the
9367: programmers continue to honour the principle of factoring instead of
9368: using the added latitude to make the words longer.
1.23 crook 9369:
1.78 anton 9370: @cindex single-assignment style for locals
9371: Using @code{TO} can and should be avoided. Without @code{TO},
9372: every value-flavoured local has only a single assignment and many
9373: advantages of functional languages apply to Forth. I.e., programs are
9374: easier to analyse, to optimize and to read: It is clear from the
9375: definition what the local stands for, it does not turn into something
9376: different later.
1.23 crook 9377:
1.78 anton 9378: E.g., a definition using @code{TO} might look like this:
9379: @example
9380: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9381: u1 u2 min 0
9382: ?do
9383: addr1 c@@ addr2 c@@ -
9384: ?dup-if
9385: unloop exit
9386: then
9387: addr1 char+ TO addr1
9388: addr2 char+ TO addr2
9389: loop
9390: u1 u2 - ;
1.26 crook 9391: @end example
1.78 anton 9392: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9393: every loop iteration. @code{strcmp} is a typical example of the
9394: readability problems of using @code{TO}. When you start reading
9395: @code{strcmp}, you think that @code{addr1} refers to the start of the
9396: string. Only near the end of the loop you realize that it is something
9397: else.
1.23 crook 9398:
1.78 anton 9399: This can be avoided by defining two locals at the start of the loop that
9400: are initialized with the right value for the current iteration.
9401: @example
9402: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9403: addr1 addr2
9404: u1 u2 min 0
9405: ?do @{ s1 s2 @}
9406: s1 c@@ s2 c@@ -
9407: ?dup-if
9408: unloop exit
9409: then
9410: s1 char+ s2 char+
9411: loop
9412: 2drop
9413: u1 u2 - ;
9414: @end example
9415: Here it is clear from the start that @code{s1} has a different value
9416: in every loop iteration.
1.23 crook 9417:
1.78 anton 9418: @node Locals implementation, , Locals programming style, Gforth locals
9419: @subsubsection Locals implementation
9420: @cindex locals implementation
9421: @cindex implementation of locals
1.23 crook 9422:
1.78 anton 9423: @cindex locals stack
9424: Gforth uses an extra locals stack. The most compelling reason for
9425: this is that the return stack is not float-aligned; using an extra stack
9426: also eliminates the problems and restrictions of using the return stack
9427: as locals stack. Like the other stacks, the locals stack grows toward
9428: lower addresses. A few primitives allow an efficient implementation:
9429:
9430:
9431: doc-@local#
9432: doc-f@local#
9433: doc-laddr#
9434: doc-lp+!#
9435: doc-lp!
9436: doc->l
9437: doc-f>l
9438:
9439:
9440: In addition to these primitives, some specializations of these
9441: primitives for commonly occurring inline arguments are provided for
9442: efficiency reasons, e.g., @code{@@local0} as specialization of
9443: @code{@@local#} for the inline argument 0. The following compiling words
9444: compile the right specialized version, or the general version, as
9445: appropriate:
1.23 crook 9446:
1.5 anton 9447:
1.107 dvdkhlng 9448: @c doc-compile-@local
9449: @c doc-compile-f@local
1.78 anton 9450: doc-compile-lp+!
1.5 anton 9451:
9452:
1.78 anton 9453: Combinations of conditional branches and @code{lp+!#} like
9454: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9455: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9456:
1.78 anton 9457: A special area in the dictionary space is reserved for keeping the
9458: local variable names. @code{@{} switches the dictionary pointer to this
9459: area and @code{@}} switches it back and generates the locals
9460: initializing code. @code{W:} etc.@ are normal defining words. This
9461: special area is cleared at the start of every colon definition.
1.5 anton 9462:
1.78 anton 9463: @cindex word list for defining locals
9464: A special feature of Gforth's dictionary is used to implement the
9465: definition of locals without type specifiers: every word list (aka
9466: vocabulary) has its own methods for searching
9467: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9468: with a special search method: When it is searched for a word, it
9469: actually creates that word using @code{W:}. @code{@{} changes the search
9470: order to first search the word list containing @code{@}}, @code{W:} etc.,
9471: and then the word list for defining locals without type specifiers.
1.5 anton 9472:
1.78 anton 9473: The lifetime rules support a stack discipline within a colon
9474: definition: The lifetime of a local is either nested with other locals
9475: lifetimes or it does not overlap them.
1.23 crook 9476:
1.78 anton 9477: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9478: pointer manipulation is generated. Between control structure words
9479: locals definitions can push locals onto the locals stack. @code{AGAIN}
9480: is the simplest of the other three control flow words. It has to
9481: restore the locals stack depth of the corresponding @code{BEGIN}
9482: before branching. The code looks like this:
9483: @format
9484: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9485: @code{branch} <begin>
9486: @end format
1.26 crook 9487:
1.78 anton 9488: @code{UNTIL} is a little more complicated: If it branches back, it
9489: must adjust the stack just like @code{AGAIN}. But if it falls through,
9490: the locals stack must not be changed. The compiler generates the
9491: following code:
9492: @format
9493: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9494: @end format
9495: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9496:
1.78 anton 9497: @code{THEN} can produce somewhat inefficient code:
9498: @format
9499: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9500: <orig target>:
9501: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9502: @end format
9503: The second @code{lp+!#} adjusts the locals stack pointer from the
9504: level at the @i{orig} point to the level after the @code{THEN}. The
9505: first @code{lp+!#} adjusts the locals stack pointer from the current
9506: level to the level at the orig point, so the complete effect is an
9507: adjustment from the current level to the right level after the
9508: @code{THEN}.
1.26 crook 9509:
1.78 anton 9510: @cindex locals information on the control-flow stack
9511: @cindex control-flow stack items, locals information
9512: In a conventional Forth implementation a dest control-flow stack entry
9513: is just the target address and an orig entry is just the address to be
9514: patched. Our locals implementation adds a word list to every orig or dest
9515: item. It is the list of locals visible (or assumed visible) at the point
9516: described by the entry. Our implementation also adds a tag to identify
9517: the kind of entry, in particular to differentiate between live and dead
9518: (reachable and unreachable) orig entries.
1.26 crook 9519:
1.78 anton 9520: A few unusual operations have to be performed on locals word lists:
1.44 crook 9521:
1.5 anton 9522:
1.78 anton 9523: doc-common-list
9524: doc-sub-list?
9525: doc-list-size
1.52 anton 9526:
9527:
1.78 anton 9528: Several features of our locals word list implementation make these
9529: operations easy to implement: The locals word lists are organised as
9530: linked lists; the tails of these lists are shared, if the lists
9531: contain some of the same locals; and the address of a name is greater
9532: than the address of the names behind it in the list.
1.5 anton 9533:
1.78 anton 9534: Another important implementation detail is the variable
9535: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9536: determine if they can be reached directly or only through the branch
9537: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9538: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9539: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9540:
1.78 anton 9541: Counted loops are similar to other loops in most respects, but
9542: @code{LEAVE} requires special attention: It performs basically the same
9543: service as @code{AHEAD}, but it does not create a control-flow stack
9544: entry. Therefore the information has to be stored elsewhere;
9545: traditionally, the information was stored in the target fields of the
9546: branches created by the @code{LEAVE}s, by organizing these fields into a
9547: linked list. Unfortunately, this clever trick does not provide enough
9548: space for storing our extended control flow information. Therefore, we
9549: introduce another stack, the leave stack. It contains the control-flow
9550: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9551:
1.78 anton 9552: Local names are kept until the end of the colon definition, even if
9553: they are no longer visible in any control-flow path. In a few cases
9554: this may lead to increased space needs for the locals name area, but
9555: usually less than reclaiming this space would cost in code size.
1.5 anton 9556:
1.44 crook 9557:
1.78 anton 9558: @node ANS Forth locals, , Gforth locals, Locals
9559: @subsection ANS Forth locals
9560: @cindex locals, ANS Forth style
1.5 anton 9561:
1.78 anton 9562: The ANS Forth locals wordset does not define a syntax for locals, but
9563: words that make it possible to define various syntaxes. One of the
9564: possible syntaxes is a subset of the syntax we used in the Gforth locals
9565: wordset, i.e.:
1.29 crook 9566:
9567: @example
1.78 anton 9568: @{ local1 local2 ... -- comment @}
9569: @end example
9570: @noindent
9571: or
9572: @example
9573: @{ local1 local2 ... @}
1.29 crook 9574: @end example
9575:
1.78 anton 9576: The order of the locals corresponds to the order in a stack comment. The
9577: restrictions are:
1.5 anton 9578:
1.78 anton 9579: @itemize @bullet
9580: @item
9581: Locals can only be cell-sized values (no type specifiers are allowed).
9582: @item
9583: Locals can be defined only outside control structures.
9584: @item
9585: Locals can interfere with explicit usage of the return stack. For the
9586: exact (and long) rules, see the standard. If you don't use return stack
9587: accessing words in a definition using locals, you will be all right. The
9588: purpose of this rule is to make locals implementation on the return
9589: stack easier.
9590: @item
9591: The whole definition must be in one line.
9592: @end itemize
1.5 anton 9593:
1.78 anton 9594: Locals defined in ANS Forth behave like @code{VALUE}s
9595: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9596: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9597:
1.78 anton 9598: Since the syntax above is supported by Gforth directly, you need not do
9599: anything to use it. If you want to port a program using this syntax to
9600: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9601: syntax on the other system.
1.5 anton 9602:
1.78 anton 9603: Note that a syntax shown in the standard, section A.13 looks
9604: similar, but is quite different in having the order of locals
9605: reversed. Beware!
1.5 anton 9606:
1.78 anton 9607: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9608:
1.78 anton 9609: doc-(local)
1.5 anton 9610:
1.78 anton 9611: The ANS Forth locals extension wordset defines a syntax using
9612: @code{locals|}, but it is so awful that we strongly recommend not to use
9613: it. We have implemented this syntax to make porting to Gforth easy, but
9614: do not document it here. The problem with this syntax is that the locals
9615: are defined in an order reversed with respect to the standard stack
9616: comment notation, making programs harder to read, and easier to misread
9617: and miswrite. The only merit of this syntax is that it is easy to
9618: implement using the ANS Forth locals wordset.
1.53 anton 9619:
9620:
1.78 anton 9621: @c ----------------------------------------------------------
9622: @node Structures, Object-oriented Forth, Locals, Words
9623: @section Structures
9624: @cindex structures
9625: @cindex records
1.53 anton 9626:
1.78 anton 9627: This section presents the structure package that comes with Gforth. A
9628: version of the package implemented in ANS Forth is available in
9629: @file{compat/struct.fs}. This package was inspired by a posting on
9630: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9631: possibly John Hayes). A version of this section has been published in
9632: M. Anton Ertl,
9633: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9634: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9635: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9636:
1.78 anton 9637: @menu
9638: * Why explicit structure support?::
9639: * Structure Usage::
9640: * Structure Naming Convention::
9641: * Structure Implementation::
9642: * Structure Glossary::
9643: @end menu
1.55 anton 9644:
1.78 anton 9645: @node Why explicit structure support?, Structure Usage, Structures, Structures
9646: @subsection Why explicit structure support?
1.53 anton 9647:
1.78 anton 9648: @cindex address arithmetic for structures
9649: @cindex structures using address arithmetic
9650: If we want to use a structure containing several fields, we could simply
9651: reserve memory for it, and access the fields using address arithmetic
9652: (@pxref{Address arithmetic}). As an example, consider a structure with
9653: the following fields
1.57 anton 9654:
1.78 anton 9655: @table @code
9656: @item a
9657: is a float
9658: @item b
9659: is a cell
9660: @item c
9661: is a float
9662: @end table
1.57 anton 9663:
1.78 anton 9664: Given the (float-aligned) base address of the structure we get the
9665: address of the field
1.52 anton 9666:
1.78 anton 9667: @table @code
9668: @item a
9669: without doing anything further.
9670: @item b
9671: with @code{float+}
9672: @item c
9673: with @code{float+ cell+ faligned}
9674: @end table
1.52 anton 9675:
1.78 anton 9676: It is easy to see that this can become quite tiring.
1.52 anton 9677:
1.78 anton 9678: Moreover, it is not very readable, because seeing a
9679: @code{cell+} tells us neither which kind of structure is
9680: accessed nor what field is accessed; we have to somehow infer the kind
9681: of structure, and then look up in the documentation, which field of
9682: that structure corresponds to that offset.
1.53 anton 9683:
1.78 anton 9684: Finally, this kind of address arithmetic also causes maintenance
9685: troubles: If you add or delete a field somewhere in the middle of the
9686: structure, you have to find and change all computations for the fields
9687: afterwards.
1.52 anton 9688:
1.78 anton 9689: So, instead of using @code{cell+} and friends directly, how
9690: about storing the offsets in constants:
1.52 anton 9691:
1.78 anton 9692: @example
9693: 0 constant a-offset
9694: 0 float+ constant b-offset
9695: 0 float+ cell+ faligned c-offset
9696: @end example
1.64 pazsan 9697:
1.78 anton 9698: Now we can get the address of field @code{x} with @code{x-offset
9699: +}. This is much better in all respects. Of course, you still
9700: have to change all later offset definitions if you add a field. You can
9701: fix this by declaring the offsets in the following way:
1.57 anton 9702:
1.78 anton 9703: @example
9704: 0 constant a-offset
9705: a-offset float+ constant b-offset
9706: b-offset cell+ faligned constant c-offset
9707: @end example
1.57 anton 9708:
1.78 anton 9709: Since we always use the offsets with @code{+}, we could use a defining
9710: word @code{cfield} that includes the @code{+} in the action of the
9711: defined word:
1.64 pazsan 9712:
1.78 anton 9713: @example
9714: : cfield ( n "name" -- )
9715: create ,
9716: does> ( name execution: addr1 -- addr2 )
9717: @@ + ;
1.64 pazsan 9718:
1.78 anton 9719: 0 cfield a
9720: 0 a float+ cfield b
9721: 0 b cell+ faligned cfield c
9722: @end example
1.64 pazsan 9723:
1.78 anton 9724: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9725:
1.78 anton 9726: The structure field words now can be used quite nicely. However,
9727: their definition is still a bit cumbersome: We have to repeat the
9728: name, the information about size and alignment is distributed before
9729: and after the field definitions etc. The structure package presented
9730: here addresses these problems.
1.64 pazsan 9731:
1.78 anton 9732: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9733: @subsection Structure Usage
9734: @cindex structure usage
1.57 anton 9735:
1.78 anton 9736: @cindex @code{field} usage
9737: @cindex @code{struct} usage
9738: @cindex @code{end-struct} usage
9739: You can define a structure for a (data-less) linked list with:
1.57 anton 9740: @example
1.78 anton 9741: struct
9742: cell% field list-next
9743: end-struct list%
1.57 anton 9744: @end example
9745:
1.78 anton 9746: With the address of the list node on the stack, you can compute the
9747: address of the field that contains the address of the next node with
9748: @code{list-next}. E.g., you can determine the length of a list
9749: with:
1.57 anton 9750:
9751: @example
1.78 anton 9752: : list-length ( list -- n )
9753: \ "list" is a pointer to the first element of a linked list
9754: \ "n" is the length of the list
9755: 0 BEGIN ( list1 n1 )
9756: over
9757: WHILE ( list1 n1 )
9758: 1+ swap list-next @@ swap
9759: REPEAT
9760: nip ;
1.57 anton 9761: @end example
9762:
1.78 anton 9763: You can reserve memory for a list node in the dictionary with
9764: @code{list% %allot}, which leaves the address of the list node on the
9765: stack. For the equivalent allocation on the heap you can use @code{list%
9766: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9767: use @code{list% %allocate}). You can get the the size of a list
9768: node with @code{list% %size} and its alignment with @code{list%
9769: %alignment}.
9770:
9771: Note that in ANS Forth the body of a @code{create}d word is
9772: @code{aligned} but not necessarily @code{faligned};
9773: therefore, if you do a:
1.57 anton 9774:
9775: @example
1.78 anton 9776: create @emph{name} foo% %allot drop
1.57 anton 9777: @end example
9778:
1.78 anton 9779: @noindent
9780: then the memory alloted for @code{foo%} is guaranteed to start at the
9781: body of @code{@emph{name}} only if @code{foo%} contains only character,
9782: cell and double fields. Therefore, if your structure contains floats,
9783: better use
1.57 anton 9784:
9785: @example
1.78 anton 9786: foo% %allot constant @emph{name}
1.57 anton 9787: @end example
9788:
1.78 anton 9789: @cindex structures containing structures
9790: You can include a structure @code{foo%} as a field of
9791: another structure, like this:
1.65 anton 9792: @example
1.78 anton 9793: struct
9794: ...
9795: foo% field ...
9796: ...
9797: end-struct ...
1.65 anton 9798: @end example
1.52 anton 9799:
1.78 anton 9800: @cindex structure extension
9801: @cindex extended records
9802: Instead of starting with an empty structure, you can extend an
9803: existing structure. E.g., a plain linked list without data, as defined
9804: above, is hardly useful; You can extend it to a linked list of integers,
9805: like this:@footnote{This feature is also known as @emph{extended
9806: records}. It is the main innovation in the Oberon language; in other
9807: words, adding this feature to Modula-2 led Wirth to create a new
9808: language, write a new compiler etc. Adding this feature to Forth just
9809: required a few lines of code.}
1.52 anton 9810:
1.78 anton 9811: @example
9812: list%
9813: cell% field intlist-int
9814: end-struct intlist%
9815: @end example
1.55 anton 9816:
1.78 anton 9817: @code{intlist%} is a structure with two fields:
9818: @code{list-next} and @code{intlist-int}.
1.55 anton 9819:
1.78 anton 9820: @cindex structures containing arrays
9821: You can specify an array type containing @emph{n} elements of
9822: type @code{foo%} like this:
1.55 anton 9823:
9824: @example
1.78 anton 9825: foo% @emph{n} *
1.56 anton 9826: @end example
1.55 anton 9827:
1.78 anton 9828: You can use this array type in any place where you can use a normal
9829: type, e.g., when defining a @code{field}, or with
9830: @code{%allot}.
9831:
9832: @cindex first field optimization
9833: The first field is at the base address of a structure and the word for
9834: this field (e.g., @code{list-next}) actually does not change the address
9835: on the stack. You may be tempted to leave it away in the interest of
9836: run-time and space efficiency. This is not necessary, because the
9837: structure package optimizes this case: If you compile a first-field
9838: words, no code is generated. So, in the interest of readability and
9839: maintainability you should include the word for the field when accessing
9840: the field.
1.52 anton 9841:
9842:
1.78 anton 9843: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9844: @subsection Structure Naming Convention
9845: @cindex structure naming convention
1.52 anton 9846:
1.78 anton 9847: The field names that come to (my) mind are often quite generic, and,
9848: if used, would cause frequent name clashes. E.g., many structures
9849: probably contain a @code{counter} field. The structure names
9850: that come to (my) mind are often also the logical choice for the names
9851: of words that create such a structure.
1.52 anton 9852:
1.78 anton 9853: Therefore, I have adopted the following naming conventions:
1.52 anton 9854:
1.78 anton 9855: @itemize @bullet
9856: @cindex field naming convention
9857: @item
9858: The names of fields are of the form
9859: @code{@emph{struct}-@emph{field}}, where
9860: @code{@emph{struct}} is the basic name of the structure, and
9861: @code{@emph{field}} is the basic name of the field. You can
9862: think of field words as converting the (address of the)
9863: structure into the (address of the) field.
1.52 anton 9864:
1.78 anton 9865: @cindex structure naming convention
9866: @item
9867: The names of structures are of the form
9868: @code{@emph{struct}%}, where
9869: @code{@emph{struct}} is the basic name of the structure.
9870: @end itemize
1.52 anton 9871:
1.78 anton 9872: This naming convention does not work that well for fields of extended
9873: structures; e.g., the integer list structure has a field
9874: @code{intlist-int}, but has @code{list-next}, not
9875: @code{intlist-next}.
1.53 anton 9876:
1.78 anton 9877: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9878: @subsection Structure Implementation
9879: @cindex structure implementation
9880: @cindex implementation of structures
1.52 anton 9881:
1.78 anton 9882: The central idea in the implementation is to pass the data about the
9883: structure being built on the stack, not in some global
9884: variable. Everything else falls into place naturally once this design
9885: decision is made.
1.53 anton 9886:
1.78 anton 9887: The type description on the stack is of the form @emph{align
9888: size}. Keeping the size on the top-of-stack makes dealing with arrays
9889: very simple.
1.53 anton 9890:
1.78 anton 9891: @code{field} is a defining word that uses @code{Create}
9892: and @code{DOES>}. The body of the field contains the offset
9893: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9894:
9895: @example
1.78 anton 9896: @@ +
1.53 anton 9897: @end example
9898:
1.78 anton 9899: @noindent
9900: i.e., add the offset to the address, giving the stack effect
9901: @i{addr1 -- addr2} for a field.
9902:
9903: @cindex first field optimization, implementation
9904: This simple structure is slightly complicated by the optimization
9905: for fields with offset 0, which requires a different
9906: @code{DOES>}-part (because we cannot rely on there being
9907: something on the stack if such a field is invoked during
9908: compilation). Therefore, we put the different @code{DOES>}-parts
9909: in separate words, and decide which one to invoke based on the
9910: offset. For a zero offset, the field is basically a noop; it is
9911: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9912:
1.78 anton 9913: @node Structure Glossary, , Structure Implementation, Structures
9914: @subsection Structure Glossary
9915: @cindex structure glossary
1.53 anton 9916:
1.5 anton 9917:
1.78 anton 9918: doc-%align
9919: doc-%alignment
9920: doc-%alloc
9921: doc-%allocate
9922: doc-%allot
9923: doc-cell%
9924: doc-char%
9925: doc-dfloat%
9926: doc-double%
9927: doc-end-struct
9928: doc-field
9929: doc-float%
9930: doc-naligned
9931: doc-sfloat%
9932: doc-%size
9933: doc-struct
1.54 anton 9934:
9935:
1.26 crook 9936: @c -------------------------------------------------------------
1.78 anton 9937: @node Object-oriented Forth, Programming Tools, Structures, Words
9938: @section Object-oriented Forth
9939:
9940: Gforth comes with three packages for object-oriented programming:
9941: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9942: is preloaded, so you have to @code{include} them before use. The most
9943: important differences between these packages (and others) are discussed
9944: in @ref{Comparison with other object models}. All packages are written
9945: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9946:
1.78 anton 9947: @menu
9948: * Why object-oriented programming?::
9949: * Object-Oriented Terminology::
9950: * Objects::
9951: * OOF::
9952: * Mini-OOF::
9953: * Comparison with other object models::
9954: @end menu
1.5 anton 9955:
1.78 anton 9956: @c ----------------------------------------------------------------
9957: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9958: @subsection Why object-oriented programming?
9959: @cindex object-oriented programming motivation
9960: @cindex motivation for object-oriented programming
1.44 crook 9961:
1.78 anton 9962: Often we have to deal with several data structures (@emph{objects}),
9963: that have to be treated similarly in some respects, but differently in
9964: others. Graphical objects are the textbook example: circles, triangles,
9965: dinosaurs, icons, and others, and we may want to add more during program
9966: development. We want to apply some operations to any graphical object,
9967: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9968: has to do something different for every kind of object.
9969: @comment TODO add some other operations eg perimeter, area
9970: @comment and tie in to concrete examples later..
1.5 anton 9971:
1.78 anton 9972: We could implement @code{draw} as a big @code{CASE}
9973: control structure that executes the appropriate code depending on the
9974: kind of object to be drawn. This would be not be very elegant, and,
9975: moreover, we would have to change @code{draw} every time we add
9976: a new kind of graphical object (say, a spaceship).
1.44 crook 9977:
1.78 anton 9978: What we would rather do is: When defining spaceships, we would tell
9979: the system: ``Here's how you @code{draw} a spaceship; you figure
9980: out the rest''.
1.5 anton 9981:
1.78 anton 9982: This is the problem that all systems solve that (rightfully) call
9983: themselves object-oriented; the object-oriented packages presented here
9984: solve this problem (and not much else).
9985: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9986:
1.78 anton 9987: @c ------------------------------------------------------------------------
9988: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9989: @subsection Object-Oriented Terminology
9990: @cindex object-oriented terminology
9991: @cindex terminology for object-oriented programming
1.5 anton 9992:
1.78 anton 9993: This section is mainly for reference, so you don't have to understand
9994: all of it right away. The terminology is mainly Smalltalk-inspired. In
9995: short:
1.44 crook 9996:
1.78 anton 9997: @table @emph
9998: @cindex class
9999: @item class
10000: a data structure definition with some extras.
1.5 anton 10001:
1.78 anton 10002: @cindex object
10003: @item object
10004: an instance of the data structure described by the class definition.
1.5 anton 10005:
1.78 anton 10006: @cindex instance variables
10007: @item instance variables
10008: fields of the data structure.
1.5 anton 10009:
1.78 anton 10010: @cindex selector
10011: @cindex method selector
10012: @cindex virtual function
10013: @item selector
10014: (or @emph{method selector}) a word (e.g.,
10015: @code{draw}) that performs an operation on a variety of data
10016: structures (classes). A selector describes @emph{what} operation to
10017: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10018:
1.78 anton 10019: @cindex method
10020: @item method
10021: the concrete definition that performs the operation
10022: described by the selector for a specific class. A method specifies
10023: @emph{how} the operation is performed for a specific class.
1.5 anton 10024:
1.78 anton 10025: @cindex selector invocation
10026: @cindex message send
10027: @cindex invoking a selector
10028: @item selector invocation
10029: a call of a selector. One argument of the call (the TOS (top-of-stack))
10030: is used for determining which method is used. In Smalltalk terminology:
10031: a message (consisting of the selector and the other arguments) is sent
10032: to the object.
1.5 anton 10033:
1.78 anton 10034: @cindex receiving object
10035: @item receiving object
10036: the object used for determining the method executed by a selector
10037: invocation. In the @file{objects.fs} model, it is the object that is on
10038: the TOS when the selector is invoked. (@emph{Receiving} comes from
10039: the Smalltalk @emph{message} terminology.)
1.5 anton 10040:
1.78 anton 10041: @cindex child class
10042: @cindex parent class
10043: @cindex inheritance
10044: @item child class
10045: a class that has (@emph{inherits}) all properties (instance variables,
10046: selectors, methods) from a @emph{parent class}. In Smalltalk
10047: terminology: The subclass inherits from the superclass. In C++
10048: terminology: The derived class inherits from the base class.
1.5 anton 10049:
1.78 anton 10050: @end table
1.5 anton 10051:
1.78 anton 10052: @c If you wonder about the message sending terminology, it comes from
10053: @c a time when each object had it's own task and objects communicated via
10054: @c message passing; eventually the Smalltalk developers realized that
10055: @c they can do most things through simple (indirect) calls. They kept the
10056: @c terminology.
1.5 anton 10057:
1.78 anton 10058: @c --------------------------------------------------------------
10059: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10060: @subsection The @file{objects.fs} model
10061: @cindex objects
10062: @cindex object-oriented programming
1.26 crook 10063:
1.78 anton 10064: @cindex @file{objects.fs}
10065: @cindex @file{oof.fs}
1.26 crook 10066:
1.78 anton 10067: This section describes the @file{objects.fs} package. This material also
10068: has been published in M. Anton Ertl,
10069: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10070: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10071: 37--43.
10072: @c McKewan's and Zsoter's packages
1.26 crook 10073:
1.78 anton 10074: This section assumes that you have read @ref{Structures}.
1.5 anton 10075:
1.78 anton 10076: The techniques on which this model is based have been used to implement
10077: the parser generator, Gray, and have also been used in Gforth for
10078: implementing the various flavours of word lists (hashed or not,
10079: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10080:
10081:
1.26 crook 10082: @menu
1.78 anton 10083: * Properties of the Objects model::
10084: * Basic Objects Usage::
10085: * The Objects base class::
10086: * Creating objects::
10087: * Object-Oriented Programming Style::
10088: * Class Binding::
10089: * Method conveniences::
10090: * Classes and Scoping::
10091: * Dividing classes::
10092: * Object Interfaces::
10093: * Objects Implementation::
10094: * Objects Glossary::
1.26 crook 10095: @end menu
1.5 anton 10096:
1.78 anton 10097: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10098:
1.78 anton 10099: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10100: @subsubsection Properties of the @file{objects.fs} model
10101: @cindex @file{objects.fs} properties
1.5 anton 10102:
1.78 anton 10103: @itemize @bullet
10104: @item
10105: It is straightforward to pass objects on the stack. Passing
10106: selectors on the stack is a little less convenient, but possible.
1.44 crook 10107:
1.78 anton 10108: @item
10109: Objects are just data structures in memory, and are referenced by their
10110: address. You can create words for objects with normal defining words
10111: like @code{constant}. Likewise, there is no difference between instance
10112: variables that contain objects and those that contain other data.
1.5 anton 10113:
1.78 anton 10114: @item
10115: Late binding is efficient and easy to use.
1.44 crook 10116:
1.78 anton 10117: @item
10118: It avoids parsing, and thus avoids problems with state-smartness
10119: and reduced extensibility; for convenience there are a few parsing
10120: words, but they have non-parsing counterparts. There are also a few
10121: defining words that parse. This is hard to avoid, because all standard
10122: defining words parse (except @code{:noname}); however, such
10123: words are not as bad as many other parsing words, because they are not
10124: state-smart.
1.5 anton 10125:
1.78 anton 10126: @item
10127: It does not try to incorporate everything. It does a few things and does
10128: them well (IMO). In particular, this model was not designed to support
10129: information hiding (although it has features that may help); you can use
10130: a separate package for achieving this.
1.5 anton 10131:
1.78 anton 10132: @item
10133: It is layered; you don't have to learn and use all features to use this
10134: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10135: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10136: are optional and independent of each other.
1.5 anton 10137:
1.78 anton 10138: @item
10139: An implementation in ANS Forth is available.
1.5 anton 10140:
1.78 anton 10141: @end itemize
1.5 anton 10142:
1.44 crook 10143:
1.78 anton 10144: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10145: @subsubsection Basic @file{objects.fs} Usage
10146: @cindex basic objects usage
10147: @cindex objects, basic usage
1.5 anton 10148:
1.78 anton 10149: You can define a class for graphical objects like this:
1.44 crook 10150:
1.78 anton 10151: @cindex @code{class} usage
10152: @cindex @code{end-class} usage
10153: @cindex @code{selector} usage
1.5 anton 10154: @example
1.78 anton 10155: object class \ "object" is the parent class
10156: selector draw ( x y graphical -- )
10157: end-class graphical
10158: @end example
10159:
10160: This code defines a class @code{graphical} with an
10161: operation @code{draw}. We can perform the operation
10162: @code{draw} on any @code{graphical} object, e.g.:
10163:
10164: @example
10165: 100 100 t-rex draw
1.26 crook 10166: @end example
1.5 anton 10167:
1.78 anton 10168: @noindent
10169: where @code{t-rex} is a word (say, a constant) that produces a
10170: graphical object.
10171:
10172: @comment TODO add a 2nd operation eg perimeter.. and use for
10173: @comment a concrete example
1.5 anton 10174:
1.78 anton 10175: @cindex abstract class
10176: How do we create a graphical object? With the present definitions,
10177: we cannot create a useful graphical object. The class
10178: @code{graphical} describes graphical objects in general, but not
10179: any concrete graphical object type (C++ users would call it an
10180: @emph{abstract class}); e.g., there is no method for the selector
10181: @code{draw} in the class @code{graphical}.
1.5 anton 10182:
1.78 anton 10183: For concrete graphical objects, we define child classes of the
10184: class @code{graphical}, e.g.:
1.5 anton 10185:
1.78 anton 10186: @cindex @code{overrides} usage
10187: @cindex @code{field} usage in class definition
1.26 crook 10188: @example
1.78 anton 10189: graphical class \ "graphical" is the parent class
10190: cell% field circle-radius
1.5 anton 10191:
1.78 anton 10192: :noname ( x y circle -- )
10193: circle-radius @@ draw-circle ;
10194: overrides draw
1.5 anton 10195:
1.78 anton 10196: :noname ( n-radius circle -- )
10197: circle-radius ! ;
10198: overrides construct
1.5 anton 10199:
1.78 anton 10200: end-class circle
10201: @end example
1.44 crook 10202:
1.78 anton 10203: Here we define a class @code{circle} as a child of @code{graphical},
10204: with field @code{circle-radius} (which behaves just like a field
10205: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10206: for the selectors @code{draw} and @code{construct} (@code{construct} is
10207: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10208:
1.78 anton 10209: Now we can create a circle on the heap (i.e.,
10210: @code{allocate}d memory) with:
1.44 crook 10211:
1.78 anton 10212: @cindex @code{heap-new} usage
1.5 anton 10213: @example
1.78 anton 10214: 50 circle heap-new constant my-circle
1.5 anton 10215: @end example
10216:
1.78 anton 10217: @noindent
10218: @code{heap-new} invokes @code{construct}, thus
10219: initializing the field @code{circle-radius} with 50. We can draw
10220: this new circle at (100,100) with:
1.5 anton 10221:
10222: @example
1.78 anton 10223: 100 100 my-circle draw
1.5 anton 10224: @end example
10225:
1.78 anton 10226: @cindex selector invocation, restrictions
10227: @cindex class definition, restrictions
10228: Note: You can only invoke a selector if the object on the TOS
10229: (the receiving object) belongs to the class where the selector was
10230: defined or one of its descendents; e.g., you can invoke
10231: @code{draw} only for objects belonging to @code{graphical}
10232: or its descendents (e.g., @code{circle}). Immediately before
10233: @code{end-class}, the search order has to be the same as
10234: immediately after @code{class}.
10235:
10236: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10237: @subsubsection The @file{object.fs} base class
10238: @cindex @code{object} class
10239:
10240: When you define a class, you have to specify a parent class. So how do
10241: you start defining classes? There is one class available from the start:
10242: @code{object}. It is ancestor for all classes and so is the
10243: only class that has no parent. It has two selectors: @code{construct}
10244: and @code{print}.
10245:
10246: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10247: @subsubsection Creating objects
10248: @cindex creating objects
10249: @cindex object creation
10250: @cindex object allocation options
10251:
10252: @cindex @code{heap-new} discussion
10253: @cindex @code{dict-new} discussion
10254: @cindex @code{construct} discussion
10255: You can create and initialize an object of a class on the heap with
10256: @code{heap-new} ( ... class -- object ) and in the dictionary
10257: (allocation with @code{allot}) with @code{dict-new} (
10258: ... class -- object ). Both words invoke @code{construct}, which
10259: consumes the stack items indicated by "..." above.
10260:
10261: @cindex @code{init-object} discussion
10262: @cindex @code{class-inst-size} discussion
10263: If you want to allocate memory for an object yourself, you can get its
10264: alignment and size with @code{class-inst-size 2@@} ( class --
10265: align size ). Once you have memory for an object, you can initialize
10266: it with @code{init-object} ( ... class object -- );
10267: @code{construct} does only a part of the necessary work.
10268:
10269: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10270: @subsubsection Object-Oriented Programming Style
10271: @cindex object-oriented programming style
10272: @cindex programming style, object-oriented
1.5 anton 10273:
1.78 anton 10274: This section is not exhaustive.
1.5 anton 10275:
1.78 anton 10276: @cindex stack effects of selectors
10277: @cindex selectors and stack effects
10278: In general, it is a good idea to ensure that all methods for the
10279: same selector have the same stack effect: when you invoke a selector,
10280: you often have no idea which method will be invoked, so, unless all
10281: methods have the same stack effect, you will not know the stack effect
10282: of the selector invocation.
1.5 anton 10283:
1.78 anton 10284: One exception to this rule is methods for the selector
10285: @code{construct}. We know which method is invoked, because we
10286: specify the class to be constructed at the same place. Actually, I
10287: defined @code{construct} as a selector only to give the users a
10288: convenient way to specify initialization. The way it is used, a
10289: mechanism different from selector invocation would be more natural
10290: (but probably would take more code and more space to explain).
1.5 anton 10291:
1.78 anton 10292: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10293: @subsubsection Class Binding
10294: @cindex class binding
10295: @cindex early binding
1.5 anton 10296:
1.78 anton 10297: @cindex late binding
10298: Normal selector invocations determine the method at run-time depending
10299: on the class of the receiving object. This run-time selection is called
10300: @i{late binding}.
1.5 anton 10301:
1.78 anton 10302: Sometimes it's preferable to invoke a different method. For example,
10303: you might want to use the simple method for @code{print}ing
10304: @code{object}s instead of the possibly long-winded @code{print} method
10305: of the receiver class. You can achieve this by replacing the invocation
10306: of @code{print} with:
1.5 anton 10307:
1.78 anton 10308: @cindex @code{[bind]} usage
1.5 anton 10309: @example
1.78 anton 10310: [bind] object print
1.5 anton 10311: @end example
10312:
1.78 anton 10313: @noindent
10314: in compiled code or:
10315:
10316: @cindex @code{bind} usage
1.5 anton 10317: @example
1.78 anton 10318: bind object print
1.5 anton 10319: @end example
10320:
1.78 anton 10321: @cindex class binding, alternative to
10322: @noindent
10323: in interpreted code. Alternatively, you can define the method with a
10324: name (e.g., @code{print-object}), and then invoke it through the
10325: name. Class binding is just a (often more convenient) way to achieve
10326: the same effect; it avoids name clutter and allows you to invoke
10327: methods directly without naming them first.
1.5 anton 10328:
1.78 anton 10329: @cindex superclass binding
10330: @cindex parent class binding
10331: A frequent use of class binding is this: When we define a method
10332: for a selector, we often want the method to do what the selector does
10333: in the parent class, and a little more. There is a special word for
10334: this purpose: @code{[parent]}; @code{[parent]
10335: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10336: selector}}, where @code{@emph{parent}} is the parent
10337: class of the current class. E.g., a method definition might look like:
1.44 crook 10338:
1.78 anton 10339: @cindex @code{[parent]} usage
10340: @example
10341: :noname
10342: dup [parent] foo \ do parent's foo on the receiving object
10343: ... \ do some more
10344: ; overrides foo
10345: @end example
1.6 pazsan 10346:
1.78 anton 10347: @cindex class binding as optimization
10348: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10349: March 1997), Andrew McKewan presents class binding as an optimization
10350: technique. I recommend not using it for this purpose unless you are in
10351: an emergency. Late binding is pretty fast with this model anyway, so the
10352: benefit of using class binding is small; the cost of using class binding
10353: where it is not appropriate is reduced maintainability.
1.44 crook 10354:
1.78 anton 10355: While we are at programming style questions: You should bind
10356: selectors only to ancestor classes of the receiving object. E.g., say,
10357: you know that the receiving object is of class @code{foo} or its
10358: descendents; then you should bind only to @code{foo} and its
10359: ancestors.
1.12 anton 10360:
1.78 anton 10361: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10362: @subsubsection Method conveniences
10363: @cindex method conveniences
1.44 crook 10364:
1.78 anton 10365: In a method you usually access the receiving object pretty often. If
10366: you define the method as a plain colon definition (e.g., with
10367: @code{:noname}), you may have to do a lot of stack
10368: gymnastics. To avoid this, you can define the method with @code{m:
10369: ... ;m}. E.g., you could define the method for
10370: @code{draw}ing a @code{circle} with
1.6 pazsan 10371:
1.78 anton 10372: @cindex @code{this} usage
10373: @cindex @code{m:} usage
10374: @cindex @code{;m} usage
10375: @example
10376: m: ( x y circle -- )
10377: ( x y ) this circle-radius @@ draw-circle ;m
10378: @end example
1.6 pazsan 10379:
1.78 anton 10380: @cindex @code{exit} in @code{m: ... ;m}
10381: @cindex @code{exitm} discussion
10382: @cindex @code{catch} in @code{m: ... ;m}
10383: When this method is executed, the receiver object is removed from the
10384: stack; you can access it with @code{this} (admittedly, in this
10385: example the use of @code{m: ... ;m} offers no advantage). Note
10386: that I specify the stack effect for the whole method (i.e. including
10387: the receiver object), not just for the code between @code{m:}
10388: and @code{;m}. You cannot use @code{exit} in
10389: @code{m:...;m}; instead, use
10390: @code{exitm}.@footnote{Moreover, for any word that calls
10391: @code{catch} and was defined before loading
10392: @code{objects.fs}, you have to redefine it like I redefined
10393: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10394:
1.78 anton 10395: @cindex @code{inst-var} usage
10396: You will frequently use sequences of the form @code{this
10397: @emph{field}} (in the example above: @code{this
10398: circle-radius}). If you use the field only in this way, you can
10399: define it with @code{inst-var} and eliminate the
10400: @code{this} before the field name. E.g., the @code{circle}
10401: class above could also be defined with:
1.6 pazsan 10402:
1.78 anton 10403: @example
10404: graphical class
10405: cell% inst-var radius
1.6 pazsan 10406:
1.78 anton 10407: m: ( x y circle -- )
10408: radius @@ draw-circle ;m
10409: overrides draw
1.6 pazsan 10410:
1.78 anton 10411: m: ( n-radius circle -- )
10412: radius ! ;m
10413: overrides construct
1.6 pazsan 10414:
1.78 anton 10415: end-class circle
10416: @end example
1.6 pazsan 10417:
1.78 anton 10418: @code{radius} can only be used in @code{circle} and its
10419: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10420:
1.78 anton 10421: @cindex @code{inst-value} usage
10422: You can also define fields with @code{inst-value}, which is
10423: to @code{inst-var} what @code{value} is to
10424: @code{variable}. You can change the value of such a field with
10425: @code{[to-inst]}. E.g., we could also define the class
10426: @code{circle} like this:
1.44 crook 10427:
1.78 anton 10428: @example
10429: graphical class
10430: inst-value radius
1.6 pazsan 10431:
1.78 anton 10432: m: ( x y circle -- )
10433: radius draw-circle ;m
10434: overrides draw
1.44 crook 10435:
1.78 anton 10436: m: ( n-radius circle -- )
10437: [to-inst] radius ;m
10438: overrides construct
1.6 pazsan 10439:
1.78 anton 10440: end-class circle
10441: @end example
1.6 pazsan 10442:
1.78 anton 10443: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10444:
1.78 anton 10445: @c Finally, you can define named methods with @code{:m}. One use of this
10446: @c feature is the definition of words that occur only in one class and are
10447: @c not intended to be overridden, but which still need method context
10448: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10449: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10450:
10451:
1.78 anton 10452: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10453: @subsubsection Classes and Scoping
10454: @cindex classes and scoping
10455: @cindex scoping and classes
1.6 pazsan 10456:
1.78 anton 10457: Inheritance is frequent, unlike structure extension. This exacerbates
10458: the problem with the field name convention (@pxref{Structure Naming
10459: Convention}): One always has to remember in which class the field was
10460: originally defined; changing a part of the class structure would require
10461: changes for renaming in otherwise unaffected code.
1.6 pazsan 10462:
1.78 anton 10463: @cindex @code{inst-var} visibility
10464: @cindex @code{inst-value} visibility
10465: To solve this problem, I added a scoping mechanism (which was not in my
10466: original charter): A field defined with @code{inst-var} (or
10467: @code{inst-value}) is visible only in the class where it is defined and in
10468: the descendent classes of this class. Using such fields only makes
10469: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10470:
1.78 anton 10471: This scoping mechanism allows us to use the unadorned field name,
10472: because name clashes with unrelated words become much less likely.
1.6 pazsan 10473:
1.78 anton 10474: @cindex @code{protected} discussion
10475: @cindex @code{private} discussion
10476: Once we have this mechanism, we can also use it for controlling the
10477: visibility of other words: All words defined after
10478: @code{protected} are visible only in the current class and its
10479: descendents. @code{public} restores the compilation
10480: (i.e. @code{current}) word list that was in effect before. If you
10481: have several @code{protected}s without an intervening
10482: @code{public} or @code{set-current}, @code{public}
10483: will restore the compilation word list in effect before the first of
10484: these @code{protected}s.
1.6 pazsan 10485:
1.78 anton 10486: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10487: @subsubsection Dividing classes
10488: @cindex Dividing classes
10489: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10490:
1.78 anton 10491: You may want to do the definition of methods separate from the
10492: definition of the class, its selectors, fields, and instance variables,
10493: i.e., separate the implementation from the definition. You can do this
10494: in the following way:
1.6 pazsan 10495:
1.78 anton 10496: @example
10497: graphical class
10498: inst-value radius
10499: end-class circle
1.6 pazsan 10500:
1.78 anton 10501: ... \ do some other stuff
1.6 pazsan 10502:
1.78 anton 10503: circle methods \ now we are ready
1.44 crook 10504:
1.78 anton 10505: m: ( x y circle -- )
10506: radius draw-circle ;m
10507: overrides draw
1.6 pazsan 10508:
1.78 anton 10509: m: ( n-radius circle -- )
10510: [to-inst] radius ;m
10511: overrides construct
1.44 crook 10512:
1.78 anton 10513: end-methods
10514: @end example
1.7 pazsan 10515:
1.78 anton 10516: You can use several @code{methods}...@code{end-methods} sections. The
10517: only things you can do to the class in these sections are: defining
10518: methods, and overriding the class's selectors. You must not define new
10519: selectors or fields.
1.7 pazsan 10520:
1.78 anton 10521: Note that you often have to override a selector before using it. In
10522: particular, you usually have to override @code{construct} with a new
10523: method before you can invoke @code{heap-new} and friends. E.g., you
10524: must not create a circle before the @code{overrides construct} sequence
10525: in the example above.
1.7 pazsan 10526:
1.78 anton 10527: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10528: @subsubsection Object Interfaces
10529: @cindex object interfaces
10530: @cindex interfaces for objects
1.7 pazsan 10531:
1.78 anton 10532: In this model you can only call selectors defined in the class of the
10533: receiving objects or in one of its ancestors. If you call a selector
10534: with a receiving object that is not in one of these classes, the
10535: result is undefined; if you are lucky, the program crashes
10536: immediately.
1.7 pazsan 10537:
1.78 anton 10538: @cindex selectors common to hardly-related classes
10539: Now consider the case when you want to have a selector (or several)
10540: available in two classes: You would have to add the selector to a
10541: common ancestor class, in the worst case to @code{object}. You
10542: may not want to do this, e.g., because someone else is responsible for
10543: this ancestor class.
1.7 pazsan 10544:
1.78 anton 10545: The solution for this problem is interfaces. An interface is a
10546: collection of selectors. If a class implements an interface, the
10547: selectors become available to the class and its descendents. A class
10548: can implement an unlimited number of interfaces. For the problem
10549: discussed above, we would define an interface for the selector(s), and
10550: both classes would implement the interface.
1.7 pazsan 10551:
1.78 anton 10552: As an example, consider an interface @code{storage} for
10553: writing objects to disk and getting them back, and a class
10554: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10555:
1.78 anton 10556: @cindex @code{interface} usage
10557: @cindex @code{end-interface} usage
10558: @cindex @code{implementation} usage
10559: @example
10560: interface
10561: selector write ( file object -- )
10562: selector read1 ( file object -- )
10563: end-interface storage
1.13 pazsan 10564:
1.78 anton 10565: bar class
10566: storage implementation
1.13 pazsan 10567:
1.78 anton 10568: ... overrides write
10569: ... overrides read1
10570: ...
10571: end-class foo
10572: @end example
1.13 pazsan 10573:
1.78 anton 10574: @noindent
10575: (I would add a word @code{read} @i{( file -- object )} that uses
10576: @code{read1} internally, but that's beyond the point illustrated
10577: here.)
1.13 pazsan 10578:
1.78 anton 10579: Note that you cannot use @code{protected} in an interface; and
10580: of course you cannot define fields.
1.13 pazsan 10581:
1.78 anton 10582: In the Neon model, all selectors are available for all classes;
10583: therefore it does not need interfaces. The price you pay in this model
10584: is slower late binding, and therefore, added complexity to avoid late
10585: binding.
1.13 pazsan 10586:
1.78 anton 10587: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10588: @subsubsection @file{objects.fs} Implementation
10589: @cindex @file{objects.fs} implementation
1.13 pazsan 10590:
1.78 anton 10591: @cindex @code{object-map} discussion
10592: An object is a piece of memory, like one of the data structures
10593: described with @code{struct...end-struct}. It has a field
10594: @code{object-map} that points to the method map for the object's
10595: class.
1.13 pazsan 10596:
1.78 anton 10597: @cindex method map
10598: @cindex virtual function table
10599: The @emph{method map}@footnote{This is Self terminology; in C++
10600: terminology: virtual function table.} is an array that contains the
10601: execution tokens (@i{xt}s) of the methods for the object's class. Each
10602: selector contains an offset into a method map.
1.13 pazsan 10603:
1.78 anton 10604: @cindex @code{selector} implementation, class
10605: @code{selector} is a defining word that uses
10606: @code{CREATE} and @code{DOES>}. The body of the
10607: selector contains the offset; the @code{DOES>} action for a
10608: class selector is, basically:
1.8 pazsan 10609:
10610: @example
1.78 anton 10611: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10612: @end example
10613:
1.78 anton 10614: Since @code{object-map} is the first field of the object, it
10615: does not generate any code. As you can see, calling a selector has a
10616: small, constant cost.
1.26 crook 10617:
1.78 anton 10618: @cindex @code{current-interface} discussion
10619: @cindex class implementation and representation
10620: A class is basically a @code{struct} combined with a method
10621: map. During the class definition the alignment and size of the class
10622: are passed on the stack, just as with @code{struct}s, so
10623: @code{field} can also be used for defining class
10624: fields. However, passing more items on the stack would be
10625: inconvenient, so @code{class} builds a data structure in memory,
10626: which is accessed through the variable
10627: @code{current-interface}. After its definition is complete, the
10628: class is represented on the stack by a pointer (e.g., as parameter for
10629: a child class definition).
1.26 crook 10630:
1.78 anton 10631: A new class starts off with the alignment and size of its parent,
10632: and a copy of the parent's method map. Defining new fields extends the
10633: size and alignment; likewise, defining new selectors extends the
10634: method map. @code{overrides} just stores a new @i{xt} in the method
10635: map at the offset given by the selector.
1.13 pazsan 10636:
1.78 anton 10637: @cindex class binding, implementation
10638: Class binding just gets the @i{xt} at the offset given by the selector
10639: from the class's method map and @code{compile,}s (in the case of
10640: @code{[bind]}) it.
1.13 pazsan 10641:
1.78 anton 10642: @cindex @code{this} implementation
10643: @cindex @code{catch} and @code{this}
10644: @cindex @code{this} and @code{catch}
10645: I implemented @code{this} as a @code{value}. At the
10646: start of an @code{m:...;m} method the old @code{this} is
10647: stored to the return stack and restored at the end; and the object on
10648: the TOS is stored @code{TO this}. This technique has one
10649: disadvantage: If the user does not leave the method via
10650: @code{;m}, but via @code{throw} or @code{exit},
10651: @code{this} is not restored (and @code{exit} may
10652: crash). To deal with the @code{throw} problem, I have redefined
10653: @code{catch} to save and restore @code{this}; the same
10654: should be done with any word that can catch an exception. As for
10655: @code{exit}, I simply forbid it (as a replacement, there is
10656: @code{exitm}).
1.13 pazsan 10657:
1.78 anton 10658: @cindex @code{inst-var} implementation
10659: @code{inst-var} is just the same as @code{field}, with
10660: a different @code{DOES>} action:
1.13 pazsan 10661: @example
1.78 anton 10662: @@ this +
1.8 pazsan 10663: @end example
1.78 anton 10664: Similar for @code{inst-value}.
1.8 pazsan 10665:
1.78 anton 10666: @cindex class scoping implementation
10667: Each class also has a word list that contains the words defined with
10668: @code{inst-var} and @code{inst-value}, and its protected
10669: words. It also has a pointer to its parent. @code{class} pushes
10670: the word lists of the class and all its ancestors onto the search order stack,
10671: and @code{end-class} drops them.
1.20 pazsan 10672:
1.78 anton 10673: @cindex interface implementation
10674: An interface is like a class without fields, parent and protected
10675: words; i.e., it just has a method map. If a class implements an
10676: interface, its method map contains a pointer to the method map of the
10677: interface. The positive offsets in the map are reserved for class
10678: methods, therefore interface map pointers have negative
10679: offsets. Interfaces have offsets that are unique throughout the
10680: system, unlike class selectors, whose offsets are only unique for the
10681: classes where the selector is available (invokable).
1.20 pazsan 10682:
1.78 anton 10683: This structure means that interface selectors have to perform one
10684: indirection more than class selectors to find their method. Their body
10685: contains the interface map pointer offset in the class method map, and
10686: the method offset in the interface method map. The
10687: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10688:
10689: @example
1.78 anton 10690: ( object selector-body )
10691: 2dup selector-interface @@ ( object selector-body object interface-offset )
10692: swap object-map @@ + @@ ( object selector-body map )
10693: swap selector-offset @@ + @@ execute
1.20 pazsan 10694: @end example
10695:
1.78 anton 10696: where @code{object-map} and @code{selector-offset} are
10697: first fields and generate no code.
1.20 pazsan 10698:
1.78 anton 10699: As a concrete example, consider the following code:
1.20 pazsan 10700:
10701: @example
1.78 anton 10702: interface
10703: selector if1sel1
10704: selector if1sel2
10705: end-interface if1
1.20 pazsan 10706:
1.78 anton 10707: object class
10708: if1 implementation
10709: selector cl1sel1
10710: cell% inst-var cl1iv1
1.20 pazsan 10711:
1.78 anton 10712: ' m1 overrides construct
10713: ' m2 overrides if1sel1
10714: ' m3 overrides if1sel2
10715: ' m4 overrides cl1sel2
10716: end-class cl1
1.20 pazsan 10717:
1.78 anton 10718: create obj1 object dict-new drop
10719: create obj2 cl1 dict-new drop
10720: @end example
1.20 pazsan 10721:
1.78 anton 10722: The data structure created by this code (including the data structure
10723: for @code{object}) is shown in the
10724: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10725: @comment TODO add this diagram..
1.20 pazsan 10726:
1.78 anton 10727: @node Objects Glossary, , Objects Implementation, Objects
10728: @subsubsection @file{objects.fs} Glossary
10729: @cindex @file{objects.fs} Glossary
1.20 pazsan 10730:
10731:
1.78 anton 10732: doc---objects-bind
10733: doc---objects-<bind>
10734: doc---objects-bind'
10735: doc---objects-[bind]
10736: doc---objects-class
10737: doc---objects-class->map
10738: doc---objects-class-inst-size
10739: doc---objects-class-override!
1.79 anton 10740: doc---objects-class-previous
10741: doc---objects-class>order
1.78 anton 10742: doc---objects-construct
10743: doc---objects-current'
10744: doc---objects-[current]
10745: doc---objects-current-interface
10746: doc---objects-dict-new
10747: doc---objects-end-class
10748: doc---objects-end-class-noname
10749: doc---objects-end-interface
10750: doc---objects-end-interface-noname
10751: doc---objects-end-methods
10752: doc---objects-exitm
10753: doc---objects-heap-new
10754: doc---objects-implementation
10755: doc---objects-init-object
10756: doc---objects-inst-value
10757: doc---objects-inst-var
10758: doc---objects-interface
10759: doc---objects-m:
10760: doc---objects-:m
10761: doc---objects-;m
10762: doc---objects-method
10763: doc---objects-methods
10764: doc---objects-object
10765: doc---objects-overrides
10766: doc---objects-[parent]
10767: doc---objects-print
10768: doc---objects-protected
10769: doc---objects-public
10770: doc---objects-selector
10771: doc---objects-this
10772: doc---objects-<to-inst>
10773: doc---objects-[to-inst]
10774: doc---objects-to-this
10775: doc---objects-xt-new
1.20 pazsan 10776:
10777:
1.78 anton 10778: @c -------------------------------------------------------------
10779: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10780: @subsection The @file{oof.fs} model
10781: @cindex oof
10782: @cindex object-oriented programming
1.20 pazsan 10783:
1.78 anton 10784: @cindex @file{objects.fs}
10785: @cindex @file{oof.fs}
1.20 pazsan 10786:
1.78 anton 10787: This section describes the @file{oof.fs} package.
1.20 pazsan 10788:
1.78 anton 10789: The package described in this section has been used in bigFORTH since 1991, and
10790: used for two large applications: a chromatographic system used to
10791: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10792:
1.78 anton 10793: You can find a description (in German) of @file{oof.fs} in @cite{Object
10794: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10795: 10(2), 1994.
1.20 pazsan 10796:
1.78 anton 10797: @menu
10798: * Properties of the OOF model::
10799: * Basic OOF Usage::
10800: * The OOF base class::
10801: * Class Declaration::
10802: * Class Implementation::
10803: @end menu
1.20 pazsan 10804:
1.78 anton 10805: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10806: @subsubsection Properties of the @file{oof.fs} model
10807: @cindex @file{oof.fs} properties
1.20 pazsan 10808:
1.78 anton 10809: @itemize @bullet
10810: @item
10811: This model combines object oriented programming with information
10812: hiding. It helps you writing large application, where scoping is
10813: necessary, because it provides class-oriented scoping.
1.20 pazsan 10814:
1.78 anton 10815: @item
10816: Named objects, object pointers, and object arrays can be created,
10817: selector invocation uses the ``object selector'' syntax. Selector invocation
10818: to objects and/or selectors on the stack is a bit less convenient, but
10819: possible.
1.44 crook 10820:
1.78 anton 10821: @item
10822: Selector invocation and instance variable usage of the active object is
10823: straightforward, since both make use of the active object.
1.44 crook 10824:
1.78 anton 10825: @item
10826: Late binding is efficient and easy to use.
1.20 pazsan 10827:
1.78 anton 10828: @item
10829: State-smart objects parse selectors. However, extensibility is provided
10830: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10831:
1.78 anton 10832: @item
10833: An implementation in ANS Forth is available.
1.20 pazsan 10834:
1.78 anton 10835: @end itemize
1.23 crook 10836:
10837:
1.78 anton 10838: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10839: @subsubsection Basic @file{oof.fs} Usage
10840: @cindex @file{oof.fs} usage
1.23 crook 10841:
1.78 anton 10842: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10843:
1.78 anton 10844: You can define a class for graphical objects like this:
1.23 crook 10845:
1.78 anton 10846: @cindex @code{class} usage
10847: @cindex @code{class;} usage
10848: @cindex @code{method} usage
10849: @example
10850: object class graphical \ "object" is the parent class
1.139 pazsan 10851: method draw ( x y -- )
1.78 anton 10852: class;
10853: @end example
1.23 crook 10854:
1.78 anton 10855: This code defines a class @code{graphical} with an
10856: operation @code{draw}. We can perform the operation
10857: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10858:
1.78 anton 10859: @example
10860: 100 100 t-rex draw
10861: @end example
1.23 crook 10862:
1.78 anton 10863: @noindent
10864: where @code{t-rex} is an object or object pointer, created with e.g.
10865: @code{graphical : t-rex}.
1.23 crook 10866:
1.78 anton 10867: @cindex abstract class
10868: How do we create a graphical object? With the present definitions,
10869: we cannot create a useful graphical object. The class
10870: @code{graphical} describes graphical objects in general, but not
10871: any concrete graphical object type (C++ users would call it an
10872: @emph{abstract class}); e.g., there is no method for the selector
10873: @code{draw} in the class @code{graphical}.
1.23 crook 10874:
1.78 anton 10875: For concrete graphical objects, we define child classes of the
10876: class @code{graphical}, e.g.:
1.23 crook 10877:
1.78 anton 10878: @example
10879: graphical class circle \ "graphical" is the parent class
10880: cell var circle-radius
10881: how:
10882: : draw ( x y -- )
10883: circle-radius @@ draw-circle ;
1.23 crook 10884:
1.139 pazsan 10885: : init ( n-radius -- )
1.78 anton 10886: circle-radius ! ;
10887: class;
10888: @end example
1.1 anton 10889:
1.78 anton 10890: Here we define a class @code{circle} as a child of @code{graphical},
10891: with a field @code{circle-radius}; it defines new methods for the
10892: selectors @code{draw} and @code{init} (@code{init} is defined in
10893: @code{object}, the parent class of @code{graphical}).
1.1 anton 10894:
1.78 anton 10895: Now we can create a circle in the dictionary with:
1.1 anton 10896:
1.78 anton 10897: @example
10898: 50 circle : my-circle
10899: @end example
1.21 crook 10900:
1.78 anton 10901: @noindent
10902: @code{:} invokes @code{init}, thus initializing the field
10903: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10904: with:
1.1 anton 10905:
1.78 anton 10906: @example
10907: 100 100 my-circle draw
10908: @end example
1.1 anton 10909:
1.78 anton 10910: @cindex selector invocation, restrictions
10911: @cindex class definition, restrictions
10912: Note: You can only invoke a selector if the receiving object belongs to
10913: the class where the selector was defined or one of its descendents;
10914: e.g., you can invoke @code{draw} only for objects belonging to
10915: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10916: mechanism will check if you try to invoke a selector that is not
10917: defined in this class hierarchy, so you'll get an error at compilation
10918: time.
1.1 anton 10919:
10920:
1.78 anton 10921: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10922: @subsubsection The @file{oof.fs} base class
10923: @cindex @file{oof.fs} base class
1.1 anton 10924:
1.78 anton 10925: When you define a class, you have to specify a parent class. So how do
10926: you start defining classes? There is one class available from the start:
10927: @code{object}. You have to use it as ancestor for all classes. It is the
10928: only class that has no parent. Classes are also objects, except that
10929: they don't have instance variables; class manipulation such as
10930: inheritance or changing definitions of a class is handled through
10931: selectors of the class @code{object}.
1.1 anton 10932:
1.78 anton 10933: @code{object} provides a number of selectors:
1.1 anton 10934:
1.78 anton 10935: @itemize @bullet
10936: @item
10937: @code{class} for subclassing, @code{definitions} to add definitions
10938: later on, and @code{class?} to get type informations (is the class a
10939: subclass of the class passed on the stack?).
1.1 anton 10940:
1.78 anton 10941: doc---object-class
10942: doc---object-definitions
10943: doc---object-class?
1.1 anton 10944:
10945:
1.26 crook 10946: @item
1.78 anton 10947: @code{init} and @code{dispose} as constructor and destructor of the
10948: object. @code{init} is invocated after the object's memory is allocated,
10949: while @code{dispose} also handles deallocation. Thus if you redefine
10950: @code{dispose}, you have to call the parent's dispose with @code{super
10951: dispose}, too.
10952:
10953: doc---object-init
10954: doc---object-dispose
10955:
1.1 anton 10956:
1.26 crook 10957: @item
1.78 anton 10958: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10959: @code{[]} to create named and unnamed objects and object arrays or
10960: object pointers.
10961:
10962: doc---object-new
10963: doc---object-new[]
10964: doc---object-:
10965: doc---object-ptr
10966: doc---object-asptr
10967: doc---object-[]
10968:
1.1 anton 10969:
1.26 crook 10970: @item
1.78 anton 10971: @code{::} and @code{super} for explicit scoping. You should use explicit
10972: scoping only for super classes or classes with the same set of instance
10973: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10974:
1.78 anton 10975: doc---object-::
10976: doc---object-super
1.21 crook 10977:
10978:
1.26 crook 10979: @item
1.78 anton 10980: @code{self} to get the address of the object
1.21 crook 10981:
1.78 anton 10982: doc---object-self
1.21 crook 10983:
10984:
1.78 anton 10985: @item
10986: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10987: pointers and instance defers.
1.21 crook 10988:
1.78 anton 10989: doc---object-bind
10990: doc---object-bound
10991: doc---object-link
10992: doc---object-is
1.21 crook 10993:
10994:
1.78 anton 10995: @item
10996: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10997: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10998:
1.78 anton 10999: doc---object-'
11000: doc---object-postpone
1.21 crook 11001:
11002:
1.78 anton 11003: @item
11004: @code{with} and @code{endwith} to select the active object from the
11005: stack, and enable its scope. Using @code{with} and @code{endwith}
11006: also allows you to create code using selector @code{postpone} without being
11007: trapped by the state-smart objects.
1.21 crook 11008:
1.78 anton 11009: doc---object-with
11010: doc---object-endwith
1.21 crook 11011:
11012:
1.78 anton 11013: @end itemize
1.21 crook 11014:
1.78 anton 11015: @node Class Declaration, Class Implementation, The OOF base class, OOF
11016: @subsubsection Class Declaration
11017: @cindex class declaration
1.21 crook 11018:
1.78 anton 11019: @itemize @bullet
11020: @item
11021: Instance variables
1.21 crook 11022:
1.78 anton 11023: doc---oof-var
1.21 crook 11024:
11025:
1.78 anton 11026: @item
11027: Object pointers
1.21 crook 11028:
1.78 anton 11029: doc---oof-ptr
11030: doc---oof-asptr
1.21 crook 11031:
11032:
1.78 anton 11033: @item
11034: Instance defers
1.21 crook 11035:
1.78 anton 11036: doc---oof-defer
1.21 crook 11037:
11038:
1.78 anton 11039: @item
11040: Method selectors
1.21 crook 11041:
1.78 anton 11042: doc---oof-early
11043: doc---oof-method
1.21 crook 11044:
11045:
1.78 anton 11046: @item
11047: Class-wide variables
1.21 crook 11048:
1.78 anton 11049: doc---oof-static
1.21 crook 11050:
11051:
1.78 anton 11052: @item
11053: End declaration
1.1 anton 11054:
1.78 anton 11055: doc---oof-how:
11056: doc---oof-class;
1.21 crook 11057:
11058:
1.78 anton 11059: @end itemize
1.21 crook 11060:
1.78 anton 11061: @c -------------------------------------------------------------
11062: @node Class Implementation, , Class Declaration, OOF
11063: @subsubsection Class Implementation
11064: @cindex class implementation
1.21 crook 11065:
1.78 anton 11066: @c -------------------------------------------------------------
11067: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11068: @subsection The @file{mini-oof.fs} model
11069: @cindex mini-oof
1.21 crook 11070:
1.78 anton 11071: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11072: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11073: and reduces to the bare minimum of features. This is based on a posting
11074: of Bernd Paysan in comp.lang.forth.
1.21 crook 11075:
1.78 anton 11076: @menu
11077: * Basic Mini-OOF Usage::
11078: * Mini-OOF Example::
11079: * Mini-OOF Implementation::
11080: @end menu
1.21 crook 11081:
1.78 anton 11082: @c -------------------------------------------------------------
11083: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11084: @subsubsection Basic @file{mini-oof.fs} Usage
11085: @cindex mini-oof usage
1.21 crook 11086:
1.78 anton 11087: There is a base class (@code{class}, which allocates one cell for the
11088: object pointer) plus seven other words: to define a method, a variable,
11089: a class; to end a class, to resolve binding, to allocate an object and
11090: to compile a class method.
11091: @comment TODO better description of the last one
1.26 crook 11092:
1.21 crook 11093:
1.78 anton 11094: doc-object
11095: doc-method
11096: doc-var
11097: doc-class
11098: doc-end-class
11099: doc-defines
11100: doc-new
11101: doc-::
1.21 crook 11102:
11103:
11104:
1.78 anton 11105: @c -------------------------------------------------------------
11106: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11107: @subsubsection Mini-OOF Example
11108: @cindex mini-oof example
1.1 anton 11109:
1.78 anton 11110: A short example shows how to use this package. This example, in slightly
11111: extended form, is supplied as @file{moof-exm.fs}
11112: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11113:
1.26 crook 11114: @example
1.78 anton 11115: object class
11116: method init
11117: method draw
11118: end-class graphical
1.26 crook 11119: @end example
1.20 pazsan 11120:
1.78 anton 11121: This code defines a class @code{graphical} with an
11122: operation @code{draw}. We can perform the operation
11123: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11124:
1.26 crook 11125: @example
1.78 anton 11126: 100 100 t-rex draw
1.26 crook 11127: @end example
1.12 anton 11128:
1.78 anton 11129: where @code{t-rex} is an object or object pointer, created with e.g.
11130: @code{graphical new Constant t-rex}.
1.12 anton 11131:
1.78 anton 11132: For concrete graphical objects, we define child classes of the
11133: class @code{graphical}, e.g.:
1.12 anton 11134:
1.26 crook 11135: @example
11136: graphical class
1.78 anton 11137: cell var circle-radius
11138: end-class circle \ "graphical" is the parent class
1.12 anton 11139:
1.78 anton 11140: :noname ( x y -- )
11141: circle-radius @@ draw-circle ; circle defines draw
11142: :noname ( r -- )
11143: circle-radius ! ; circle defines init
11144: @end example
1.12 anton 11145:
1.78 anton 11146: There is no implicit init method, so we have to define one. The creation
11147: code of the object now has to call init explicitely.
1.21 crook 11148:
1.78 anton 11149: @example
11150: circle new Constant my-circle
11151: 50 my-circle init
1.12 anton 11152: @end example
11153:
1.78 anton 11154: It is also possible to add a function to create named objects with
11155: automatic call of @code{init}, given that all objects have @code{init}
11156: on the same place:
1.38 anton 11157:
1.78 anton 11158: @example
11159: : new: ( .. o "name" -- )
11160: new dup Constant init ;
11161: 80 circle new: large-circle
11162: @end example
1.12 anton 11163:
1.78 anton 11164: We can draw this new circle at (100,100) with:
1.12 anton 11165:
1.78 anton 11166: @example
11167: 100 100 my-circle draw
11168: @end example
1.12 anton 11169:
1.78 anton 11170: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11171: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11172:
1.78 anton 11173: Object-oriented systems with late binding typically use a
11174: ``vtable''-approach: the first variable in each object is a pointer to a
11175: table, which contains the methods as function pointers. The vtable
11176: may also contain other information.
1.12 anton 11177:
1.79 anton 11178: So first, let's declare selectors:
1.37 anton 11179:
11180: @example
1.79 anton 11181: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11182: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11183: @end example
1.37 anton 11184:
1.79 anton 11185: During selector declaration, the number of selectors and instance
11186: variables is on the stack (in address units). @code{method} creates one
11187: selector and increments the selector number. To execute a selector, it
1.78 anton 11188: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11189: executes the method @i{xt} stored there. Each selector takes the object
11190: it is invoked with as top of stack parameter; it passes the parameters
11191: (including the object) unchanged to the appropriate method which should
1.78 anton 11192: consume that object.
1.37 anton 11193:
1.78 anton 11194: Now, we also have to declare instance variables
1.37 anton 11195:
1.78 anton 11196: @example
1.79 anton 11197: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11198: DOES> ( o -- addr ) @@ + ;
1.37 anton 11199: @end example
11200:
1.78 anton 11201: As before, a word is created with the current offset. Instance
11202: variables can have different sizes (cells, floats, doubles, chars), so
11203: all we do is take the size and add it to the offset. If your machine
11204: has alignment restrictions, put the proper @code{aligned} or
11205: @code{faligned} before the variable, to adjust the variable
11206: offset. That's why it is on the top of stack.
1.37 anton 11207:
1.78 anton 11208: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11209:
1.78 anton 11210: @example
11211: Create object 1 cells , 2 cells ,
1.79 anton 11212: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11213: @end example
1.12 anton 11214:
1.78 anton 11215: For inheritance, the vtable of the parent object has to be
11216: copied when a new, derived class is declared. This gives all the
11217: methods of the parent class, which can be overridden, though.
1.12 anton 11218:
1.78 anton 11219: @example
1.79 anton 11220: : end-class ( class selectors vars "name" -- )
1.78 anton 11221: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11222: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11223: @end example
1.12 anton 11224:
1.78 anton 11225: The first line creates the vtable, initialized with
11226: @code{noop}s. The second line is the inheritance mechanism, it
11227: copies the xts from the parent vtable.
1.12 anton 11228:
1.78 anton 11229: We still have no way to define new methods, let's do that now:
1.12 anton 11230:
1.26 crook 11231: @example
1.79 anton 11232: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11233: @end example
1.12 anton 11234:
1.78 anton 11235: To allocate a new object, we need a word, too:
1.12 anton 11236:
1.78 anton 11237: @example
11238: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11239: @end example
11240:
1.78 anton 11241: Sometimes derived classes want to access the method of the
11242: parent object. There are two ways to achieve this with Mini-OOF:
11243: first, you could use named words, and second, you could look up the
11244: vtable of the parent object.
1.12 anton 11245:
1.78 anton 11246: @example
11247: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11248: @end example
1.12 anton 11249:
11250:
1.78 anton 11251: Nothing can be more confusing than a good example, so here is
11252: one. First let's declare a text object (called
11253: @code{button}), that stores text and position:
1.12 anton 11254:
1.78 anton 11255: @example
11256: object class
11257: cell var text
11258: cell var len
11259: cell var x
11260: cell var y
11261: method init
11262: method draw
11263: end-class button
11264: @end example
1.12 anton 11265:
1.78 anton 11266: @noindent
11267: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11268:
1.26 crook 11269: @example
1.78 anton 11270: :noname ( o -- )
11271: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11272: button defines draw
11273: :noname ( addr u o -- )
11274: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11275: button defines init
1.26 crook 11276: @end example
1.12 anton 11277:
1.78 anton 11278: @noindent
11279: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11280: new data and no new selectors:
1.78 anton 11281:
11282: @example
11283: button class
11284: end-class bold-button
1.12 anton 11285:
1.78 anton 11286: : bold 27 emit ." [1m" ;
11287: : normal 27 emit ." [0m" ;
11288: @end example
1.1 anton 11289:
1.78 anton 11290: @noindent
11291: The class @code{bold-button} has a different draw method to
11292: @code{button}, but the new method is defined in terms of the draw method
11293: for @code{button}:
1.20 pazsan 11294:
1.78 anton 11295: @example
11296: :noname bold [ button :: draw ] normal ; bold-button defines draw
11297: @end example
1.21 crook 11298:
1.78 anton 11299: @noindent
1.79 anton 11300: Finally, create two objects and apply selectors:
1.21 crook 11301:
1.26 crook 11302: @example
1.78 anton 11303: button new Constant foo
11304: s" thin foo" foo init
11305: page
11306: foo draw
11307: bold-button new Constant bar
11308: s" fat bar" bar init
11309: 1 bar y !
11310: bar draw
1.26 crook 11311: @end example
1.21 crook 11312:
11313:
1.78 anton 11314: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11315: @subsection Comparison with other object models
11316: @cindex comparison of object models
11317: @cindex object models, comparison
11318:
11319: Many object-oriented Forth extensions have been proposed (@cite{A survey
11320: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11321: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11322: relation of the object models described here to two well-known and two
11323: closely-related (by the use of method maps) models. Andras Zsoter
11324: helped us with this section.
11325:
11326: @cindex Neon model
11327: The most popular model currently seems to be the Neon model (see
11328: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11329: 1997) by Andrew McKewan) but this model has a number of limitations
11330: @footnote{A longer version of this critique can be
11331: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11332: Dimensions, May 1997) by Anton Ertl.}:
11333:
11334: @itemize @bullet
11335: @item
11336: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11337: to pass objects on the stack.
1.21 crook 11338:
1.78 anton 11339: @item
11340: It requires that the selector parses the input stream (at
1.79 anton 11341: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11342: hard to find.
1.21 crook 11343:
1.78 anton 11344: @item
1.79 anton 11345: It allows using every selector on every object; this eliminates the
11346: need for interfaces, but makes it harder to create efficient
11347: implementations.
1.78 anton 11348: @end itemize
1.21 crook 11349:
1.78 anton 11350: @cindex Pountain's object-oriented model
11351: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11352: Press, London, 1987) by Dick Pountain. However, it is not really about
11353: object-oriented programming, because it hardly deals with late
11354: binding. Instead, it focuses on features like information hiding and
11355: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11356:
1.78 anton 11357: @cindex Zsoter's object-oriented model
1.79 anton 11358: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11359: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11360: describes a model that makes heavy use of an active object (like
11361: @code{this} in @file{objects.fs}): The active object is not only used
11362: for accessing all fields, but also specifies the receiving object of
11363: every selector invocation; you have to change the active object
11364: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11365: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11366: the method entry point is unnecessary with Zsoter's model, because the
11367: receiving object is the active object already. On the other hand, the
11368: explicit change is absolutely necessary in that model, because otherwise
11369: no one could ever change the active object. An ANS Forth implementation
11370: of this model is available through
11371: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11372:
1.78 anton 11373: @cindex @file{oof.fs}, differences to other models
11374: The @file{oof.fs} model combines information hiding and overloading
11375: resolution (by keeping names in various word lists) with object-oriented
11376: programming. It sets the active object implicitly on method entry, but
11377: also allows explicit changing (with @code{>o...o>} or with
11378: @code{with...endwith}). It uses parsing and state-smart objects and
11379: classes for resolving overloading and for early binding: the object or
11380: class parses the selector and determines the method from this. If the
11381: selector is not parsed by an object or class, it performs a call to the
11382: selector for the active object (late binding), like Zsoter's model.
11383: Fields are always accessed through the active object. The big
11384: disadvantage of this model is the parsing and the state-smartness, which
11385: reduces extensibility and increases the opportunities for subtle bugs;
11386: essentially, you are only safe if you never tick or @code{postpone} an
11387: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11388:
1.78 anton 11389: @cindex @file{mini-oof.fs}, differences to other models
11390: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11391: version of the @file{objects.fs} model, but syntactically it is a
11392: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11393:
11394:
1.78 anton 11395: @c -------------------------------------------------------------
1.150 anton 11396: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11397: @section Programming Tools
11398: @cindex programming tools
1.21 crook 11399:
1.78 anton 11400: @c !! move this and assembler down below OO stuff.
1.21 crook 11401:
1.78 anton 11402: @menu
1.150 anton 11403: * Examining:: Data and Code.
11404: * Forgetting words:: Usually before reloading.
1.78 anton 11405: * Debugging:: Simple and quick.
11406: * Assertions:: Making your programs self-checking.
11407: * Singlestep Debugger:: Executing your program word by word.
11408: @end menu
1.21 crook 11409:
1.78 anton 11410: @node Examining, Forgetting words, Programming Tools, Programming Tools
11411: @subsection Examining data and code
11412: @cindex examining data and code
11413: @cindex data examination
11414: @cindex code examination
1.44 crook 11415:
1.78 anton 11416: The following words inspect the stack non-destructively:
1.21 crook 11417:
1.78 anton 11418: doc-.s
11419: doc-f.s
1.44 crook 11420:
1.78 anton 11421: There is a word @code{.r} but it does @i{not} display the return stack!
11422: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11423:
1.78 anton 11424: doc-depth
11425: doc-fdepth
11426: doc-clearstack
1.124 anton 11427: doc-clearstacks
1.21 crook 11428:
1.78 anton 11429: The following words inspect memory.
1.21 crook 11430:
1.78 anton 11431: doc-?
11432: doc-dump
1.21 crook 11433:
1.78 anton 11434: And finally, @code{see} allows to inspect code:
1.21 crook 11435:
1.78 anton 11436: doc-see
11437: doc-xt-see
1.111 anton 11438: doc-simple-see
11439: doc-simple-see-range
1.21 crook 11440:
1.78 anton 11441: @node Forgetting words, Debugging, Examining, Programming Tools
11442: @subsection Forgetting words
11443: @cindex words, forgetting
11444: @cindex forgeting words
1.21 crook 11445:
1.78 anton 11446: @c anton: other, maybe better places for this subsection: Defining Words;
11447: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11448:
1.78 anton 11449: Forth allows you to forget words (and everything that was alloted in the
11450: dictonary after them) in a LIFO manner.
1.21 crook 11451:
1.78 anton 11452: doc-marker
1.21 crook 11453:
1.78 anton 11454: The most common use of this feature is during progam development: when
11455: you change a source file, forget all the words it defined and load it
11456: again (since you also forget everything defined after the source file
11457: was loaded, you have to reload that, too). Note that effects like
11458: storing to variables and destroyed system words are not undone when you
11459: forget words. With a system like Gforth, that is fast enough at
11460: starting up and compiling, I find it more convenient to exit and restart
11461: Gforth, as this gives me a clean slate.
1.21 crook 11462:
1.78 anton 11463: Here's an example of using @code{marker} at the start of a source file
11464: that you are debugging; it ensures that you only ever have one copy of
11465: the file's definitions compiled at any time:
1.21 crook 11466:
1.78 anton 11467: @example
11468: [IFDEF] my-code
11469: my-code
11470: [ENDIF]
1.26 crook 11471:
1.78 anton 11472: marker my-code
11473: init-included-files
1.21 crook 11474:
1.78 anton 11475: \ .. definitions start here
11476: \ .
11477: \ .
11478: \ end
11479: @end example
1.21 crook 11480:
1.26 crook 11481:
1.78 anton 11482: @node Debugging, Assertions, Forgetting words, Programming Tools
11483: @subsection Debugging
11484: @cindex debugging
1.21 crook 11485:
1.78 anton 11486: Languages with a slow edit/compile/link/test development loop tend to
11487: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11488:
1.78 anton 11489: A much better (faster) way in fast-compiling languages is to add
11490: printing code at well-selected places, let the program run, look at
11491: the output, see where things went wrong, add more printing code, etc.,
11492: until the bug is found.
1.21 crook 11493:
1.78 anton 11494: The simple debugging aids provided in @file{debugs.fs}
11495: are meant to support this style of debugging.
1.21 crook 11496:
1.78 anton 11497: The word @code{~~} prints debugging information (by default the source
11498: location and the stack contents). It is easy to insert. If you use Emacs
11499: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11500: query-replace them with nothing). The deferred words
1.101 anton 11501: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11502: @code{~~}. The default source location output format works well with
11503: Emacs' compilation mode, so you can step through the program at the
11504: source level using @kbd{C-x `} (the advantage over a stepping debugger
11505: is that you can step in any direction and you know where the crash has
11506: happened or where the strange data has occurred).
1.21 crook 11507:
1.78 anton 11508: doc-~~
11509: doc-printdebugdata
1.101 anton 11510: doc-.debugline
1.21 crook 11511:
1.106 anton 11512: @cindex filenames in @code{~~} output
11513: @code{~~} (and assertions) will usually print the wrong file name if a
11514: marker is executed in the same file after their occurance. They will
11515: print @samp{*somewhere*} as file name if a marker is executed in the
11516: same file before their occurance.
11517:
11518:
1.78 anton 11519: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11520: @subsection Assertions
11521: @cindex assertions
1.21 crook 11522:
1.78 anton 11523: It is a good idea to make your programs self-checking, especially if you
11524: make an assumption that may become invalid during maintenance (for
11525: example, that a certain field of a data structure is never zero). Gforth
11526: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11527:
11528: @example
1.78 anton 11529: assert( @i{flag} )
1.26 crook 11530: @end example
11531:
1.78 anton 11532: The code between @code{assert(} and @code{)} should compute a flag, that
11533: should be true if everything is alright and false otherwise. It should
11534: not change anything else on the stack. The overall stack effect of the
11535: assertion is @code{( -- )}. E.g.
1.21 crook 11536:
1.26 crook 11537: @example
1.78 anton 11538: assert( 1 1 + 2 = ) \ what we learn in school
11539: assert( dup 0<> ) \ assert that the top of stack is not zero
11540: assert( false ) \ this code should not be reached
1.21 crook 11541: @end example
11542:
1.78 anton 11543: The need for assertions is different at different times. During
11544: debugging, we want more checking, in production we sometimes care more
11545: for speed. Therefore, assertions can be turned off, i.e., the assertion
11546: becomes a comment. Depending on the importance of an assertion and the
11547: time it takes to check it, you may want to turn off some assertions and
11548: keep others turned on. Gforth provides several levels of assertions for
11549: this purpose:
11550:
11551:
11552: doc-assert0(
11553: doc-assert1(
11554: doc-assert2(
11555: doc-assert3(
11556: doc-assert(
11557: doc-)
1.21 crook 11558:
11559:
1.78 anton 11560: The variable @code{assert-level} specifies the highest assertions that
11561: are turned on. I.e., at the default @code{assert-level} of one,
11562: @code{assert0(} and @code{assert1(} assertions perform checking, while
11563: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11564:
1.78 anton 11565: The value of @code{assert-level} is evaluated at compile-time, not at
11566: run-time. Therefore you cannot turn assertions on or off at run-time;
11567: you have to set the @code{assert-level} appropriately before compiling a
11568: piece of code. You can compile different pieces of code at different
11569: @code{assert-level}s (e.g., a trusted library at level 1 and
11570: newly-written code at level 3).
1.26 crook 11571:
11572:
1.78 anton 11573: doc-assert-level
1.26 crook 11574:
11575:
1.78 anton 11576: If an assertion fails, a message compatible with Emacs' compilation mode
11577: is produced and the execution is aborted (currently with @code{ABORT"}.
11578: If there is interest, we will introduce a special throw code. But if you
11579: intend to @code{catch} a specific condition, using @code{throw} is
11580: probably more appropriate than an assertion).
1.106 anton 11581:
11582: @cindex filenames in assertion output
11583: Assertions (and @code{~~}) will usually print the wrong file name if a
11584: marker is executed in the same file after their occurance. They will
11585: print @samp{*somewhere*} as file name if a marker is executed in the
11586: same file before their occurance.
1.44 crook 11587:
1.78 anton 11588: Definitions in ANS Forth for these assertion words are provided
11589: in @file{compat/assert.fs}.
1.26 crook 11590:
1.44 crook 11591:
1.78 anton 11592: @node Singlestep Debugger, , Assertions, Programming Tools
11593: @subsection Singlestep Debugger
11594: @cindex singlestep Debugger
11595: @cindex debugging Singlestep
1.44 crook 11596:
1.112 anton 11597: The singlestep debugger does not work in this release.
11598:
1.78 anton 11599: When you create a new word there's often the need to check whether it
11600: behaves correctly or not. You can do this by typing @code{dbg
11601: badword}. A debug session might look like this:
1.26 crook 11602:
1.78 anton 11603: @example
11604: : badword 0 DO i . LOOP ; ok
11605: 2 dbg badword
11606: : badword
11607: Scanning code...
1.44 crook 11608:
1.78 anton 11609: Nesting debugger ready!
1.44 crook 11610:
1.78 anton 11611: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11612: 400D4740 8049F68 DO -> [ 0 ]
11613: 400D4744 804A0C8 i -> [ 1 ] 00000
11614: 400D4748 400C5E60 . -> 0 [ 0 ]
11615: 400D474C 8049D0C LOOP -> [ 0 ]
11616: 400D4744 804A0C8 i -> [ 1 ] 00001
11617: 400D4748 400C5E60 . -> 1 [ 0 ]
11618: 400D474C 8049D0C LOOP -> [ 0 ]
11619: 400D4758 804B384 ; -> ok
11620: @end example
1.21 crook 11621:
1.78 anton 11622: Each line displayed is one step. You always have to hit return to
11623: execute the next word that is displayed. If you don't want to execute
11624: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11625: an overview what keys are available:
1.44 crook 11626:
1.78 anton 11627: @table @i
1.44 crook 11628:
1.78 anton 11629: @item @key{RET}
11630: Next; Execute the next word.
1.21 crook 11631:
1.78 anton 11632: @item n
11633: Nest; Single step through next word.
1.44 crook 11634:
1.78 anton 11635: @item u
11636: Unnest; Stop debugging and execute rest of word. If we got to this word
11637: with nest, continue debugging with the calling word.
1.44 crook 11638:
1.78 anton 11639: @item d
11640: Done; Stop debugging and execute rest.
1.21 crook 11641:
1.78 anton 11642: @item s
11643: Stop; Abort immediately.
1.44 crook 11644:
1.78 anton 11645: @end table
1.44 crook 11646:
1.78 anton 11647: Debugging large application with this mechanism is very difficult, because
11648: you have to nest very deeply into the program before the interesting part
11649: begins. This takes a lot of time.
1.26 crook 11650:
1.78 anton 11651: To do it more directly put a @code{BREAK:} command into your source code.
11652: When program execution reaches @code{BREAK:} the single step debugger is
11653: invoked and you have all the features described above.
1.44 crook 11654:
1.78 anton 11655: If you have more than one part to debug it is useful to know where the
11656: program has stopped at the moment. You can do this by the
11657: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11658: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11659:
1.26 crook 11660:
1.78 anton 11661: doc-dbg
11662: doc-break:
11663: doc-break"
1.44 crook 11664:
1.150 anton 11665: @c ------------------------------------------------------------
11666: @node C Interface, Assembler and Code Words, Programming Tools, Words
11667: @section C Interface
11668: @cindex C interface
11669: @cindex foreign language interface
11670: @cindex interface to C functions
11671:
11672: Note that the C interface is not yet complete; a better way of
11673: declaring C functions is planned, as well as a way of declaring
11674: structs, unions, and their fields.
11675:
11676: @menu
11677: * Calling C Functions::
11678: * Declaring C Functions::
11679: * Callbacks::
11680: @end menu
11681:
1.151 ! pazsan 11682: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 11683: @subsection Calling C functions
11684:
1.151 ! pazsan 11685: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 11686: can call it as follows: You push the arguments on the stack(s), and
11687: then call the word for the C function. The arguments have to be
11688: pushed in the same order as the arguments appear in the C
11689: documentation (i.e., the first argument is deepest on the stack).
11690: Integer and pointer arguments have to be pushed on the data stack,
11691: floating-point arguments on the FP stack; these arguments are consumed
11692: by calling the C function.
11693:
11694: On returning from the C function, the return value, if any, is pushed
11695: on the appropriate stack: an integer return value is pushed on the
11696: data stack, an FP return value on the FP stack, and a void return
11697: value results in not pushing anything. Note that most C functions
11698: have a return value, even if that is often not used in C; in Forth,
11699: you have to @code{drop} this return value explicitly if you do not use
11700: it.
11701:
11702: By default, an integer argument or return value corresponds to a
11703: single cell, and a floating-point argument or return value corresponds
11704: to a Forth float value; the C interface performs the appropriate
11705: conversions where necessary, on a best-effort basis (in some cases,
11706: there may be some loss).
11707:
11708: As an example, consider the POSIX function @code{lseek()}:
11709:
11710: @example
11711: off_t lseek(int fd, off_t offset, int whence);
11712: @end example
11713:
11714: This function takes three integer arguments, and returns an integer
11715: argument, so a Forth call for setting the current file offset to the
11716: start of the file could look like this:
11717:
11718: @example
11719: fd @@ 0 SEEK_SET lseek -1 = if
11720: ... \ error handling
11721: then
11722: @end example
11723:
11724: You might be worried that an @code{off_t} does not fit into a cell, so
11725: you could not pass larger offsets to lseek, and might get only a part
11726: of the return values. In that case, you should declare the function
11727: to use double-cells for the off_t argument and return value (no matter
11728: how large or small the off_t type actually is), and maybe give the
11729: resulting Forth word a different name, like @code{dlseek}; the result
11730: could be called like this:
11731:
11732: @example
11733: fd @@ 0. SEEK_SET dlseek -1. d= if
11734: ... \ error handling
11735: then
11736: @end example
11737:
11738: Passing and returning structs or unions is currently not supported by
11739: our interface@footnote{If you know the calling convention of your C
11740: compiler, you usually can call such functions in some way, but that
11741: way is usually not portable between platforms, and sometimes not even
11742: between C compilers.}.
11743:
11744: Calling functions with a variable number of arguments (e.g.,
11745: @code{printf()}) is currently only supported by having you declare one
11746: function-calling word for each argument pattern, and calling the
11747: appropriate word for the desired pattern.
11748:
1.151 ! pazsan 11749: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
1.150 anton 11750: @subsection Declaring C Functions
11751:
11752: Before you can call @code{lseek} or @code{dlseek}, you have to declare
11753: it. You have to look up in your system what the concrete type for the
11754: abstract type @code{off_t} is; let's assume it is @code{long}. Then
11755: the declarations for these words are:
11756:
11757: @example
11758: library libc libc.so.6
11759: libc lseek int long int (long) lseek ( fd noffset whence -- noffset2 )
11760: libc dlseek int dlong int (dlong) lseek ( fd doffset whence -- doffset2 )
11761: @end example
11762:
11763: The first line defines a Forth word @code{libc} for accessing the C
11764: functions in the shared library @file{libc.so.6} (the name of the
11765: shared library depends on the library and the OS; this example is the
11766: standard C library (containing most of the standard C and Unix
11767: functions) for GNU/Linux systems since about 1998).
11768:
11769: The next two lines define two Forth words for the same C function
11770: @code{lseek()}; the middle line defines @code{lseek ( n1 n2 n3 -- n
11771: )}, and the last line defines @code{dlseek ( n1 d2 n3 -- d)}
11772:
11773: !!!
11774:
11775:
11776: As you can see, the declarations are relatively platform-dependent
11777: (e.g., on one platform @code{off_t} may be a @code{long}, whereas on
11778: another platform it may be a @code{long long}; actually, in this case
11779: you can have this difference even on the same platform), while the
11780: resulting function-calling words are platform-independent, and calls
11781: to them are portable.
11782:
11783: At some point in the future this interface will be superseded by a
11784: more convenient one with fewer portability issues. But the resulting
11785: words for the C function will still have the same interface, so will
11786: not need to change the calls.
11787:
11788:
11789: @node Callbacks, , Declaring C Functions, C Interface
11790: @subsection Callbacks
11791:
1.44 crook 11792:
1.26 crook 11793:
1.78 anton 11794: @c -------------------------------------------------------------
1.150 anton 11795: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 11796: @section Assembler and Code Words
11797: @cindex assembler
11798: @cindex code words
1.44 crook 11799:
1.78 anton 11800: @menu
11801: * Code and ;code::
11802: * Common Assembler:: Assembler Syntax
11803: * Common Disassembler::
11804: * 386 Assembler:: Deviations and special cases
11805: * Alpha Assembler:: Deviations and special cases
11806: * MIPS assembler:: Deviations and special cases
11807: * Other assemblers:: How to write them
11808: @end menu
1.21 crook 11809:
1.78 anton 11810: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11811: @subsection @code{Code} and @code{;code}
1.26 crook 11812:
1.78 anton 11813: Gforth provides some words for defining primitives (words written in
11814: machine code), and for defining the machine-code equivalent of
11815: @code{DOES>}-based defining words. However, the machine-independent
11816: nature of Gforth poses a few problems: First of all, Gforth runs on
11817: several architectures, so it can provide no standard assembler. What's
11818: worse is that the register allocation not only depends on the processor,
11819: but also on the @code{gcc} version and options used.
1.44 crook 11820:
1.78 anton 11821: The words that Gforth offers encapsulate some system dependences (e.g.,
11822: the header structure), so a system-independent assembler may be used in
11823: Gforth. If you do not have an assembler, you can compile machine code
11824: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11825: because these words emit stuff in @i{data} space; it works because
11826: Gforth has unified code/data spaces. Assembler isn't likely to be
11827: portable anyway.}.
1.21 crook 11828:
1.44 crook 11829:
1.78 anton 11830: doc-assembler
11831: doc-init-asm
11832: doc-code
11833: doc-end-code
11834: doc-;code
11835: doc-flush-icache
1.44 crook 11836:
1.21 crook 11837:
1.78 anton 11838: If @code{flush-icache} does not work correctly, @code{code} words
11839: etc. will not work (reliably), either.
1.44 crook 11840:
1.78 anton 11841: The typical usage of these @code{code} words can be shown most easily by
11842: analogy to the equivalent high-level defining words:
1.44 crook 11843:
1.78 anton 11844: @example
11845: : foo code foo
11846: <high-level Forth words> <assembler>
11847: ; end-code
11848:
11849: : bar : bar
11850: <high-level Forth words> <high-level Forth words>
11851: CREATE CREATE
11852: <high-level Forth words> <high-level Forth words>
11853: DOES> ;code
11854: <high-level Forth words> <assembler>
11855: ; end-code
11856: @end example
1.21 crook 11857:
1.78 anton 11858: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11859:
1.78 anton 11860: @cindex registers of the inner interpreter
11861: In the assembly code you will want to refer to the inner interpreter's
11862: registers (e.g., the data stack pointer) and you may want to use other
11863: registers for temporary storage. Unfortunately, the register allocation
11864: is installation-dependent.
1.44 crook 11865:
1.78 anton 11866: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11867: (return stack pointer) may be in different places in @code{gforth} and
11868: @code{gforth-fast}, or different installations. This means that you
11869: cannot write a @code{NEXT} routine that works reliably on both versions
11870: or different installations; so for doing @code{NEXT}, I recommend
11871: jumping to @code{' noop >code-address}, which contains nothing but a
11872: @code{NEXT}.
1.21 crook 11873:
1.78 anton 11874: For general accesses to the inner interpreter's registers, the easiest
11875: solution is to use explicit register declarations (@pxref{Explicit Reg
11876: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11877: all of the inner interpreter's registers: You have to compile Gforth
11878: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11879: the appropriate declarations must be present in the @code{machine.h}
11880: file (see @code{mips.h} for an example; you can find a full list of all
11881: declarable register symbols with @code{grep register engine.c}). If you
11882: give explicit registers to all variables that are declared at the
11883: beginning of @code{engine()}, you should be able to use the other
11884: caller-saved registers for temporary storage. Alternatively, you can use
11885: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11886: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11887: reserve a register (however, this restriction on register allocation may
11888: slow Gforth significantly).
1.44 crook 11889:
1.78 anton 11890: If this solution is not viable (e.g., because @code{gcc} does not allow
11891: you to explicitly declare all the registers you need), you have to find
11892: out by looking at the code where the inner interpreter's registers
11893: reside and which registers can be used for temporary storage. You can
11894: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11895:
1.78 anton 11896: In any case, it is good practice to abstract your assembly code from the
11897: actual register allocation. E.g., if the data stack pointer resides in
11898: register @code{$17}, create an alias for this register called @code{sp},
11899: and use that in your assembly code.
1.21 crook 11900:
1.78 anton 11901: @cindex code words, portable
11902: Another option for implementing normal and defining words efficiently
11903: is to add the desired functionality to the source of Gforth. For normal
11904: words you just have to edit @file{primitives} (@pxref{Automatic
11905: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11906: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11907: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11908:
1.78 anton 11909: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11910: @subsection Common Assembler
1.44 crook 11911:
1.78 anton 11912: The assemblers in Gforth generally use a postfix syntax, i.e., the
11913: instruction name follows the operands.
1.21 crook 11914:
1.78 anton 11915: The operands are passed in the usual order (the same that is used in the
11916: manual of the architecture). Since they all are Forth words, they have
11917: to be separated by spaces; you can also use Forth words to compute the
11918: operands.
1.44 crook 11919:
1.78 anton 11920: The instruction names usually end with a @code{,}. This makes it easier
11921: to visually separate instructions if you put several of them on one
11922: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11923:
1.78 anton 11924: Registers are usually specified by number; e.g., (decimal) @code{11}
11925: specifies registers R11 and F11 on the Alpha architecture (which one,
11926: depends on the instruction). The usual names are also available, e.g.,
11927: @code{s2} for R11 on Alpha.
1.21 crook 11928:
1.78 anton 11929: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11930: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11931: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11932: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11933: conditions are specified in a way specific to each assembler.
1.1 anton 11934:
1.78 anton 11935: Note that the register assignments of the Gforth engine can change
11936: between Gforth versions, or even between different compilations of the
11937: same Gforth version (e.g., if you use a different GCC version). So if
11938: you want to refer to Gforth's registers (e.g., the stack pointer or
11939: TOS), I recommend defining your own words for refering to these
11940: registers, and using them later on; then you can easily adapt to a
11941: changed register assignment. The stability of the register assignment
11942: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11943:
1.100 anton 11944: The most common use of these registers is to dispatch to the next word
11945: (the @code{next} routine). A portable way to do this is to jump to
11946: @code{' noop >code-address} (of course, this is less efficient than
11947: integrating the @code{next} code and scheduling it well).
1.1 anton 11948:
1.96 anton 11949: Another difference between Gforth version is that the top of stack is
11950: kept in memory in @code{gforth} and, on most platforms, in a register in
11951: @code{gforth-fast}.
11952:
1.78 anton 11953: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11954: @subsection Common Disassembler
1.127 anton 11955: @cindex disassembler, general
11956: @cindex gdb disassembler
1.1 anton 11957:
1.78 anton 11958: You can disassemble a @code{code} word with @code{see}
11959: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11960:
1.127 anton 11961: doc-discode
1.44 crook 11962:
1.127 anton 11963: There are two kinds of disassembler for Gforth: The Forth disassembler
11964: (available on some CPUs) and the gdb disassembler (available on
11965: platforms with @command{gdb} and @command{mktemp}). If both are
11966: available, the Forth disassembler is used by default. If you prefer
11967: the gdb disassembler, say
11968:
11969: @example
11970: ' disasm-gdb is discode
11971: @end example
11972:
11973: If neither is available, @code{discode} performs @code{dump}.
11974:
11975: The Forth disassembler generally produces output that can be fed into the
1.78 anton 11976: assembler (i.e., same syntax, etc.). It also includes additional
11977: information in comments. In particular, the address of the instruction
11978: is given in a comment before the instruction.
1.1 anton 11979:
1.127 anton 11980: The gdb disassembler produces output in the same format as the gdb
11981: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11982: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11983: the 386 and AMD64 architectures).
11984:
1.78 anton 11985: @code{See} may display more or less than the actual code of the word,
11986: because the recognition of the end of the code is unreliable. You can
1.127 anton 11987: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 11988: the code word is not immediately followed by a named word. If you have
1.116 anton 11989: something else there, you can follow the word with @code{align latest ,}
1.78 anton 11990: to ensure that the end is recognized.
1.21 crook 11991:
1.78 anton 11992: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11993: @subsection 386 Assembler
1.44 crook 11994:
1.78 anton 11995: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11996: available under GPL, and originally part of bigFORTH.
1.21 crook 11997:
1.78 anton 11998: The 386 disassembler included in Gforth was written by Andrew McKewan
11999: and is in the public domain.
1.21 crook 12000:
1.91 anton 12001: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12002:
1.78 anton 12003: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12004:
1.78 anton 12005: The assembler includes all instruction of the Athlon, i.e. 486 core
12006: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12007: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12008: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12009:
1.78 anton 12010: There are several prefixes to switch between different operation sizes,
12011: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12012: double-word accesses. Addressing modes can be switched with @code{.wa}
12013: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12014: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12015:
1.78 anton 12016: For floating point operations, the prefixes are @code{.fs} (IEEE
12017: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12018: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12019:
1.78 anton 12020: The MMX opcodes don't have size prefixes, they are spelled out like in
12021: the Intel assembler. Instead of move from and to memory, there are
12022: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12023:
1.78 anton 12024: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12025: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12026: e.g., @code{3 #}. Here are some examples of addressing modes in various
12027: syntaxes:
1.21 crook 12028:
1.26 crook 12029: @example
1.91 anton 12030: Gforth Intel (NASM) AT&T (gas) Name
12031: .w ax ax %ax register (16 bit)
12032: ax eax %eax register (32 bit)
12033: 3 # offset 3 $3 immediate
12034: 1000 #) byte ptr 1000 1000 displacement
12035: bx ) [ebx] (%ebx) base
12036: 100 di d) 100[edi] 100(%edi) base+displacement
12037: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12038: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12039: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12040: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12041: @end example
12042:
12043: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12044: @code{DI)} to enforce 32-bit displacement fields (useful for
12045: later patching).
1.21 crook 12046:
1.78 anton 12047: Some example of instructions are:
1.1 anton 12048:
12049: @example
1.78 anton 12050: ax bx mov \ move ebx,eax
12051: 3 # ax mov \ mov eax,3
1.137 pazsan 12052: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12053: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12054: .w ax bx mov \ mov bx,ax
1.1 anton 12055: @end example
12056:
1.78 anton 12057: The following forms are supported for binary instructions:
1.1 anton 12058:
12059: @example
1.78 anton 12060: <reg> <reg> <inst>
12061: <n> # <reg> <inst>
12062: <mem> <reg> <inst>
12063: <reg> <mem> <inst>
1.136 pazsan 12064: <n> # <mem> <inst>
1.1 anton 12065: @end example
12066:
1.136 pazsan 12067: The shift/rotate syntax is:
1.1 anton 12068:
1.26 crook 12069: @example
1.78 anton 12070: <reg/mem> 1 # shl \ shortens to shift without immediate
12071: <reg/mem> 4 # shl
12072: <reg/mem> cl shl
1.26 crook 12073: @end example
1.1 anton 12074:
1.78 anton 12075: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12076: the byte version.
1.1 anton 12077:
1.78 anton 12078: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12079: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12080: pc < >= <= >}. (Note that most of these words shadow some Forth words
12081: when @code{assembler} is in front of @code{forth} in the search path,
12082: e.g., in @code{code} words). Currently the control structure words use
12083: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12084: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12085:
1.78 anton 12086: Here is an example of a @code{code} word (assumes that the stack pointer
12087: is in esi and the TOS is in ebx):
1.21 crook 12088:
1.26 crook 12089: @example
1.78 anton 12090: code my+ ( n1 n2 -- n )
12091: 4 si D) bx add
12092: 4 # si add
12093: Next
12094: end-code
1.26 crook 12095: @end example
1.21 crook 12096:
1.78 anton 12097: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12098: @subsection Alpha Assembler
1.21 crook 12099:
1.78 anton 12100: The Alpha assembler and disassembler were originally written by Bernd
12101: Thallner.
1.26 crook 12102:
1.78 anton 12103: The register names @code{a0}--@code{a5} are not available to avoid
12104: shadowing hex numbers.
1.2 jwilke 12105:
1.78 anton 12106: Immediate forms of arithmetic instructions are distinguished by a
12107: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12108: does not count as arithmetic instruction).
1.2 jwilke 12109:
1.78 anton 12110: You have to specify all operands to an instruction, even those that
12111: other assemblers consider optional, e.g., the destination register for
12112: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12113:
1.78 anton 12114: You can specify conditions for @code{if,} by removing the first @code{b}
12115: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12116:
1.26 crook 12117: @example
1.78 anton 12118: 11 fgt if, \ if F11>0e
12119: ...
12120: endif,
1.26 crook 12121: @end example
1.2 jwilke 12122:
1.78 anton 12123: @code{fbgt,} gives @code{fgt}.
12124:
12125: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
12126: @subsection MIPS assembler
1.2 jwilke 12127:
1.78 anton 12128: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12129:
1.78 anton 12130: Currently the assembler and disassembler only cover the MIPS-I
12131: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12132:
1.78 anton 12133: The register names @code{$a0}--@code{$a3} are not available to avoid
12134: shadowing hex numbers.
1.2 jwilke 12135:
1.78 anton 12136: Because there is no way to distinguish registers from immediate values,
12137: you have to explicitly use the immediate forms of instructions, i.e.,
12138: @code{addiu,}, not just @code{addu,} (@command{as} does this
12139: implicitly).
1.2 jwilke 12140:
1.78 anton 12141: If the architecture manual specifies several formats for the instruction
12142: (e.g., for @code{jalr,}), you usually have to use the one with more
12143: arguments (i.e., two for @code{jalr,}). When in doubt, see
12144: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12145:
1.78 anton 12146: Branches and jumps in the MIPS architecture have a delay slot. You have
12147: to fill it yourself (the simplest way is to use @code{nop,}), the
12148: assembler does not do it for you (unlike @command{as}). Even
12149: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12150: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12151: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12152:
1.78 anton 12153: Note that you must not put branches, jumps, or @code{li,} into the delay
12154: slot: @code{li,} may expand to several instructions, and control flow
12155: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12156:
1.78 anton 12157: For branches the argument specifying the target is a relative address;
12158: You have to add the address of the delay slot to get the absolute
12159: address.
1.1 anton 12160:
1.78 anton 12161: The MIPS architecture also has load delay slots and restrictions on
12162: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12163: yourself to satisfy these restrictions, the assembler does not do it for
12164: you.
1.1 anton 12165:
1.78 anton 12166: You can specify the conditions for @code{if,} etc. by taking a
12167: conditional branch and leaving away the @code{b} at the start and the
12168: @code{,} at the end. E.g.,
1.1 anton 12169:
1.26 crook 12170: @example
1.78 anton 12171: 4 5 eq if,
12172: ... \ do something if $4 equals $5
12173: then,
1.26 crook 12174: @end example
1.1 anton 12175:
1.78 anton 12176: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12177: @subsection Other assemblers
12178:
12179: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12180: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12181: an assembler already. If you are writing them from scratch, please use
12182: a similar syntax style as the one we use (i.e., postfix, commas at the
12183: end of the instruction names, @pxref{Common Assembler}); make the output
12184: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12185: similar to the style we used.
12186:
12187: Hints on implementation: The most important part is to have a good test
12188: suite that contains all instructions. Once you have that, the rest is
12189: easy. For actual coding you can take a look at
12190: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12191: the assembler and disassembler, avoiding redundancy and some potential
12192: bugs. You can also look at that file (and @pxref{Advanced does> usage
12193: example}) to get ideas how to factor a disassembler.
12194:
12195: Start with the disassembler, because it's easier to reuse data from the
12196: disassembler for the assembler than the other way round.
1.1 anton 12197:
1.78 anton 12198: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12199: how simple it can be.
1.1 anton 12200:
1.78 anton 12201: @c -------------------------------------------------------------
12202: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12203: @section Threading Words
12204: @cindex threading words
1.1 anton 12205:
1.78 anton 12206: @cindex code address
12207: These words provide access to code addresses and other threading stuff
12208: in Gforth (and, possibly, other interpretive Forths). It more or less
12209: abstracts away the differences between direct and indirect threading
12210: (and, for direct threading, the machine dependences). However, at
12211: present this wordset is still incomplete. It is also pretty low-level;
12212: some day it will hopefully be made unnecessary by an internals wordset
12213: that abstracts implementation details away completely.
1.1 anton 12214:
1.78 anton 12215: The terminology used here stems from indirect threaded Forth systems; in
12216: such a system, the XT of a word is represented by the CFA (code field
12217: address) of a word; the CFA points to a cell that contains the code
12218: address. The code address is the address of some machine code that
12219: performs the run-time action of invoking the word (e.g., the
12220: @code{dovar:} routine pushes the address of the body of the word (a
12221: variable) on the stack
12222: ).
1.1 anton 12223:
1.78 anton 12224: @cindex code address
12225: @cindex code field address
12226: In an indirect threaded Forth, you can get the code address of @i{name}
12227: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12228: >code-address}, independent of the threading method.
1.1 anton 12229:
1.78 anton 12230: doc-threading-method
12231: doc->code-address
12232: doc-code-address!
1.1 anton 12233:
1.78 anton 12234: @cindex @code{does>}-handler
12235: @cindex @code{does>}-code
12236: For a word defined with @code{DOES>}, the code address usually points to
12237: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12238: routine (in Gforth on some platforms, it can also point to the dodoes
12239: routine itself). What you are typically interested in, though, is
12240: whether a word is a @code{DOES>}-defined word, and what Forth code it
12241: executes; @code{>does-code} tells you that.
1.1 anton 12242:
1.78 anton 12243: doc->does-code
1.1 anton 12244:
1.78 anton 12245: To create a @code{DOES>}-defined word with the following basic words,
12246: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12247: @code{/does-handler} aus behind you have to place your executable Forth
12248: code. Finally you have to create a word and modify its behaviour with
12249: @code{does-handler!}.
1.1 anton 12250:
1.78 anton 12251: doc-does-code!
12252: doc-does-handler!
12253: doc-/does-handler
1.1 anton 12254:
1.78 anton 12255: The code addresses produced by various defining words are produced by
12256: the following words:
1.1 anton 12257:
1.78 anton 12258: doc-docol:
12259: doc-docon:
12260: doc-dovar:
12261: doc-douser:
12262: doc-dodefer:
12263: doc-dofield:
1.1 anton 12264:
1.99 anton 12265: @cindex definer
12266: The following two words generalize @code{>code-address},
12267: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12268:
12269: doc->definer
12270: doc-definer!
12271:
1.26 crook 12272: @c -------------------------------------------------------------
1.78 anton 12273: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12274: @section Passing Commands to the Operating System
12275: @cindex operating system - passing commands
12276: @cindex shell commands
12277:
12278: Gforth allows you to pass an arbitrary string to the host operating
12279: system shell (if such a thing exists) for execution.
12280:
12281: doc-sh
12282: doc-system
12283: doc-$?
1.23 crook 12284: doc-getenv
1.44 crook 12285:
1.26 crook 12286: @c -------------------------------------------------------------
1.47 crook 12287: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12288: @section Keeping track of Time
12289: @cindex time-related words
12290:
12291: doc-ms
12292: doc-time&date
1.79 anton 12293: doc-utime
12294: doc-cputime
1.47 crook 12295:
12296:
12297: @c -------------------------------------------------------------
12298: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12299: @section Miscellaneous Words
12300: @cindex miscellaneous words
12301:
1.29 crook 12302: @comment TODO find homes for these
12303:
1.26 crook 12304: These section lists the ANS Forth words that are not documented
1.21 crook 12305: elsewhere in this manual. Ultimately, they all need proper homes.
12306:
1.68 anton 12307: doc-quit
1.44 crook 12308:
1.26 crook 12309: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12310: (@pxref{ANS conformance}):
1.21 crook 12311:
12312: @code{EDITOR}
12313: @code{EMIT?}
12314: @code{FORGET}
12315:
1.24 anton 12316: @c ******************************************************************
12317: @node Error messages, Tools, Words, Top
12318: @chapter Error messages
12319: @cindex error messages
12320: @cindex backtrace
12321:
12322: A typical Gforth error message looks like this:
12323:
12324: @example
1.86 anton 12325: in file included from \evaluated string/:-1
1.24 anton 12326: in file included from ./yyy.fs:1
12327: ./xxx.fs:4: Invalid memory address
1.134 anton 12328: >>>bar<<<
1.79 anton 12329: Backtrace:
1.25 anton 12330: $400E664C @@
12331: $400E6664 foo
1.24 anton 12332: @end example
12333:
12334: The message identifying the error is @code{Invalid memory address}. The
12335: error happened when text-interpreting line 4 of the file
12336: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12337: word on the line where the error happened, is pointed out (with
1.134 anton 12338: @code{>>>} and @code{<<<}).
1.24 anton 12339:
12340: The file containing the error was included in line 1 of @file{./yyy.fs},
12341: and @file{yyy.fs} was included from a non-file (in this case, by giving
12342: @file{yyy.fs} as command-line parameter to Gforth).
12343:
12344: At the end of the error message you find a return stack dump that can be
12345: interpreted as a backtrace (possibly empty). On top you find the top of
12346: the return stack when the @code{throw} happened, and at the bottom you
12347: find the return stack entry just above the return stack of the topmost
12348: text interpreter.
12349:
12350: To the right of most return stack entries you see a guess for the word
12351: that pushed that return stack entry as its return address. This gives a
12352: backtrace. In our case we see that @code{bar} called @code{foo}, and
12353: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12354: address} exception).
12355:
12356: Note that the backtrace is not perfect: We don't know which return stack
12357: entries are return addresses (so we may get false positives); and in
12358: some cases (e.g., for @code{abort"}) we cannot determine from the return
12359: address the word that pushed the return address, so for some return
12360: addresses you see no names in the return stack dump.
1.25 anton 12361:
12362: @cindex @code{catch} and backtraces
12363: The return stack dump represents the return stack at the time when a
12364: specific @code{throw} was executed. In programs that make use of
12365: @code{catch}, it is not necessarily clear which @code{throw} should be
12366: used for the return stack dump (e.g., consider one @code{throw} that
12367: indicates an error, which is caught, and during recovery another error
1.42 anton 12368: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12369: presents the return stack dump for the first @code{throw} after the last
12370: executed (not returned-to) @code{catch}; this works well in the usual
12371: case.
12372:
12373: @cindex @code{gforth-fast} and backtraces
12374: @cindex @code{gforth-fast}, difference from @code{gforth}
12375: @cindex backtraces with @code{gforth-fast}
12376: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12377: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12378: from primitives (e.g., invalid memory address, stack empty etc.);
12379: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12380: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12381: exception caused by a primitive in @code{gforth-fast}, you will
12382: typically see no return stack dump at all; however, if the exception is
12383: caught by @code{catch} (e.g., for restoring some state), and then
12384: @code{throw}n again, the return stack dump will be for the first such
12385: @code{throw}.
1.2 jwilke 12386:
1.5 anton 12387: @c ******************************************************************
1.24 anton 12388: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12389: @chapter Tools
12390:
12391: @menu
12392: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12393: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12394: @end menu
12395:
12396: See also @ref{Emacs and Gforth}.
12397:
1.126 pazsan 12398: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12399: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12400: @cindex @file{ans-report.fs}
12401: @cindex report the words used in your program
12402: @cindex words used in your program
12403:
12404: If you want to label a Forth program as ANS Forth Program, you must
12405: document which wordsets the program uses; for extension wordsets, it is
12406: helpful to list the words the program requires from these wordsets
12407: (because Forth systems are allowed to provide only some words of them).
12408:
12409: The @file{ans-report.fs} tool makes it easy for you to determine which
12410: words from which wordset and which non-ANS words your application
12411: uses. You simply have to include @file{ans-report.fs} before loading the
12412: program you want to check. After loading your program, you can get the
12413: report with @code{print-ans-report}. A typical use is to run this as
12414: batch job like this:
12415: @example
12416: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12417: @end example
12418:
12419: The output looks like this (for @file{compat/control.fs}):
12420: @example
12421: The program uses the following words
12422: from CORE :
12423: : POSTPONE THEN ; immediate ?dup IF 0=
12424: from BLOCK-EXT :
12425: \
12426: from FILE :
12427: (
12428: @end example
12429:
12430: @subsection Caveats
12431:
12432: Note that @file{ans-report.fs} just checks which words are used, not whether
12433: they are used in an ANS Forth conforming way!
12434:
12435: Some words are defined in several wordsets in the
12436: standard. @file{ans-report.fs} reports them for only one of the
12437: wordsets, and not necessarily the one you expect. It depends on usage
12438: which wordset is the right one to specify. E.g., if you only use the
12439: compilation semantics of @code{S"}, it is a Core word; if you also use
12440: its interpretation semantics, it is a File word.
1.124 anton 12441:
12442:
1.127 anton 12443: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12444: @section Stack depth changes during interpretation
12445: @cindex @file{depth-changes.fs}
12446: @cindex depth changes during interpretation
12447: @cindex stack depth changes during interpretation
12448: @cindex items on the stack after interpretation
12449:
12450: Sometimes you notice that, after loading a file, there are items left
12451: on the stack. The tool @file{depth-changes.fs} helps you find out
12452: quickly where in the file these stack items are coming from.
12453:
12454: The simplest way of using @file{depth-changes.fs} is to include it
12455: before the file(s) you want to check, e.g.:
12456:
12457: @example
12458: gforth depth-changes.fs my-file.fs
12459: @end example
12460:
12461: This will compare the stack depths of the data and FP stack at every
12462: empty line (in interpretation state) against these depths at the last
12463: empty line (in interpretation state). If the depths are not equal,
12464: the position in the file and the stack contents are printed with
12465: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12466: change has occured in the paragraph of non-empty lines before the
12467: indicated line. It is a good idea to leave an empty line at the end
12468: of the file, so the last paragraph is checked, too.
12469:
12470: Checking only at empty lines usually works well, but sometimes you
12471: have big blocks of non-empty lines (e.g., when building a big table),
12472: and you want to know where in this block the stack depth changed. You
12473: can check all interpreted lines with
12474:
12475: @example
12476: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12477: @end example
12478:
12479: This checks the stack depth at every end-of-line. So the depth change
12480: occured in the line reported by the @code{~~} (not in the line
12481: before).
12482:
12483: Note that, while this offers better accuracy in indicating where the
12484: stack depth changes, it will often report many intentional stack depth
12485: changes (e.g., when an interpreted computation stretches across
12486: several lines). You can suppress the checking of some lines by
12487: putting backslashes at the end of these lines (not followed by white
12488: space), and using
12489:
12490: @example
12491: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12492: @end example
1.1 anton 12493:
12494: @c ******************************************************************
1.65 anton 12495: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12496: @chapter ANS conformance
12497: @cindex ANS conformance of Gforth
12498:
12499: To the best of our knowledge, Gforth is an
12500:
12501: ANS Forth System
12502: @itemize @bullet
12503: @item providing the Core Extensions word set
12504: @item providing the Block word set
12505: @item providing the Block Extensions word set
12506: @item providing the Double-Number word set
12507: @item providing the Double-Number Extensions word set
12508: @item providing the Exception word set
12509: @item providing the Exception Extensions word set
12510: @item providing the Facility word set
1.40 anton 12511: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12512: @item providing the File Access word set
12513: @item providing the File Access Extensions word set
12514: @item providing the Floating-Point word set
12515: @item providing the Floating-Point Extensions word set
12516: @item providing the Locals word set
12517: @item providing the Locals Extensions word set
12518: @item providing the Memory-Allocation word set
12519: @item providing the Memory-Allocation Extensions word set (that one's easy)
12520: @item providing the Programming-Tools word set
12521: @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
12522: @item providing the Search-Order word set
12523: @item providing the Search-Order Extensions word set
12524: @item providing the String word set
12525: @item providing the String Extensions word set (another easy one)
12526: @end itemize
12527:
1.118 anton 12528: Gforth has the following environmental restrictions:
12529:
12530: @cindex environmental restrictions
12531: @itemize @bullet
12532: @item
12533: While processing the OS command line, if an exception is not caught,
12534: Gforth exits with a non-zero exit code instyead of performing QUIT.
12535:
12536: @item
12537: When an @code{throw} is performed after a @code{query}, Gforth does not
12538: allways restore the input source specification in effect at the
12539: corresponding catch.
12540:
12541: @end itemize
12542:
12543:
1.1 anton 12544: @cindex system documentation
12545: In addition, ANS Forth systems are required to document certain
12546: implementation choices. This chapter tries to meet these
12547: requirements. In many cases it gives a way to ask the system for the
12548: information instead of providing the information directly, in
12549: particular, if the information depends on the processor, the operating
12550: system or the installation options chosen, or if they are likely to
12551: change during the maintenance of Gforth.
12552:
12553: @comment The framework for the rest has been taken from pfe.
12554:
12555: @menu
12556: * The Core Words::
12557: * The optional Block word set::
12558: * The optional Double Number word set::
12559: * The optional Exception word set::
12560: * The optional Facility word set::
12561: * The optional File-Access word set::
12562: * The optional Floating-Point word set::
12563: * The optional Locals word set::
12564: * The optional Memory-Allocation word set::
12565: * The optional Programming-Tools word set::
12566: * The optional Search-Order word set::
12567: @end menu
12568:
12569:
12570: @c =====================================================================
12571: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12572: @comment node-name, next, previous, up
12573: @section The Core Words
12574: @c =====================================================================
12575: @cindex core words, system documentation
12576: @cindex system documentation, core words
12577:
12578: @menu
12579: * core-idef:: Implementation Defined Options
12580: * core-ambcond:: Ambiguous Conditions
12581: * core-other:: Other System Documentation
12582: @end menu
12583:
12584: @c ---------------------------------------------------------------------
12585: @node core-idef, core-ambcond, The Core Words, The Core Words
12586: @subsection Implementation Defined Options
12587: @c ---------------------------------------------------------------------
12588: @cindex core words, implementation-defined options
12589: @cindex implementation-defined options, core words
12590:
12591:
12592: @table @i
12593: @item (Cell) aligned addresses:
12594: @cindex cell-aligned addresses
12595: @cindex aligned addresses
12596: processor-dependent. Gforth's alignment words perform natural alignment
12597: (e.g., an address aligned for a datum of size 8 is divisible by
12598: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12599:
12600: @item @code{EMIT} and non-graphic characters:
12601: @cindex @code{EMIT} and non-graphic characters
12602: @cindex non-graphic characters and @code{EMIT}
12603: The character is output using the C library function (actually, macro)
12604: @code{putc}.
12605:
12606: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12607: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12608: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12609: @cindex @code{ACCEPT}, editing
12610: @cindex @code{EXPECT}, editing
12611: This is modeled on the GNU readline library (@pxref{Readline
12612: Interaction, , Command Line Editing, readline, The GNU Readline
12613: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12614: producing a full word completion every time you type it (instead of
1.28 crook 12615: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12616:
12617: @item character set:
12618: @cindex character set
12619: The character set of your computer and display device. Gforth is
12620: 8-bit-clean (but some other component in your system may make trouble).
12621:
12622: @item Character-aligned address requirements:
12623: @cindex character-aligned address requirements
12624: installation-dependent. Currently a character is represented by a C
12625: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12626: (Comments on that requested).
12627:
12628: @item character-set extensions and matching of names:
12629: @cindex character-set extensions and matching of names
1.26 crook 12630: @cindex case-sensitivity for name lookup
12631: @cindex name lookup, case-sensitivity
12632: @cindex locale and case-sensitivity
1.21 crook 12633: Any character except the ASCII NUL character can be used in a
1.1 anton 12634: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12635: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12636: function is probably influenced by the locale. E.g., the @code{C} locale
12637: does not know about accents and umlauts, so they are matched
12638: case-sensitively in that locale. For portability reasons it is best to
12639: write programs such that they work in the @code{C} locale. Then one can
12640: use libraries written by a Polish programmer (who might use words
12641: containing ISO Latin-2 encoded characters) and by a French programmer
12642: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12643: funny results for some of the words (which ones, depends on the font you
12644: are using)). Also, the locale you prefer may not be available in other
12645: operating systems. Hopefully, Unicode will solve these problems one day.
12646:
12647: @item conditions under which control characters match a space delimiter:
12648: @cindex space delimiters
12649: @cindex control characters as delimiters
1.117 anton 12650: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12651: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12652: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12653: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12654: interpreter (aka text interpreter) by default, treats all white-space
12655: characters as delimiters.
12656:
1.26 crook 12657: @item format of the control-flow stack:
12658: @cindex control-flow stack, format
12659: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12660: stack item in cells is given by the constant @code{cs-item-size}. At the
12661: time of this writing, an item consists of a (pointer to a) locals list
12662: (third), an address in the code (second), and a tag for identifying the
12663: item (TOS). The following tags are used: @code{defstart},
12664: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12665: @code{scopestart}.
12666:
12667: @item conversion of digits > 35
12668: @cindex digits > 35
12669: The characters @code{[\]^_'} are the digits with the decimal value
12670: 36@minus{}41. There is no way to input many of the larger digits.
12671:
12672: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12673: @cindex @code{EXPECT}, display after end of input
12674: @cindex @code{ACCEPT}, display after end of input
12675: The cursor is moved to the end of the entered string. If the input is
12676: terminated using the @kbd{Return} key, a space is typed.
12677:
12678: @item exception abort sequence of @code{ABORT"}:
12679: @cindex exception abort sequence of @code{ABORT"}
12680: @cindex @code{ABORT"}, exception abort sequence
12681: The error string is stored into the variable @code{"error} and a
12682: @code{-2 throw} is performed.
12683:
12684: @item input line terminator:
12685: @cindex input line terminator
12686: @cindex line terminator on input
1.26 crook 12687: @cindex newline character on input
1.1 anton 12688: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12689: lines. One of these characters is typically produced when you type the
12690: @kbd{Enter} or @kbd{Return} key.
12691:
12692: @item maximum size of a counted string:
12693: @cindex maximum size of a counted string
12694: @cindex counted string, maximum size
12695: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12696: on all platforms, but this may change.
1.1 anton 12697:
12698: @item maximum size of a parsed string:
12699: @cindex maximum size of a parsed string
12700: @cindex parsed string, maximum size
12701: Given by the constant @code{/line}. Currently 255 characters.
12702:
12703: @item maximum size of a definition name, in characters:
12704: @cindex maximum size of a definition name, in characters
12705: @cindex name, maximum length
1.113 anton 12706: MAXU/8
1.1 anton 12707:
12708: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12709: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12710: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12711: MAXU/8
1.1 anton 12712:
12713: @item method of selecting the user input device:
12714: @cindex user input device, method of selecting
12715: The user input device is the standard input. There is currently no way to
12716: change it from within Gforth. However, the input can typically be
12717: redirected in the command line that starts Gforth.
12718:
12719: @item method of selecting the user output device:
12720: @cindex user output device, method of selecting
12721: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12722: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12723: output when the user output device is a terminal, otherwise the output
12724: is buffered.
1.1 anton 12725:
12726: @item methods of dictionary compilation:
12727: What are we expected to document here?
12728:
12729: @item number of bits in one address unit:
12730: @cindex number of bits in one address unit
12731: @cindex address unit, size in bits
12732: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12733: platforms.
1.1 anton 12734:
12735: @item number representation and arithmetic:
12736: @cindex number representation and arithmetic
1.79 anton 12737: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12738:
12739: @item ranges for integer types:
12740: @cindex ranges for integer types
12741: @cindex integer types, ranges
12742: Installation-dependent. Make environmental queries for @code{MAX-N},
12743: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12744: unsigned (and positive) types is 0. The lower bound for signed types on
12745: two's complement and one's complement machines machines can be computed
12746: by adding 1 to the upper bound.
12747:
12748: @item read-only data space regions:
12749: @cindex read-only data space regions
12750: @cindex data-space, read-only regions
12751: The whole Forth data space is writable.
12752:
12753: @item size of buffer at @code{WORD}:
12754: @cindex size of buffer at @code{WORD}
12755: @cindex @code{WORD} buffer size
12756: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12757: shared with the pictured numeric output string. If overwriting
12758: @code{PAD} is acceptable, it is as large as the remaining dictionary
12759: space, although only as much can be sensibly used as fits in a counted
12760: string.
12761:
12762: @item size of one cell in address units:
12763: @cindex cell size
12764: @code{1 cells .}.
12765:
12766: @item size of one character in address units:
12767: @cindex char size
1.79 anton 12768: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12769:
12770: @item size of the keyboard terminal buffer:
12771: @cindex size of the keyboard terminal buffer
12772: @cindex terminal buffer, size
12773: Varies. You can determine the size at a specific time using @code{lp@@
12774: tib - .}. It is shared with the locals stack and TIBs of files that
12775: include the current file. You can change the amount of space for TIBs
12776: and locals stack at Gforth startup with the command line option
12777: @code{-l}.
12778:
12779: @item size of the pictured numeric output buffer:
12780: @cindex size of the pictured numeric output buffer
12781: @cindex pictured numeric output buffer, size
12782: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12783: shared with @code{WORD}.
12784:
12785: @item size of the scratch area returned by @code{PAD}:
12786: @cindex size of the scratch area returned by @code{PAD}
12787: @cindex @code{PAD} size
12788: The remainder of dictionary space. @code{unused pad here - - .}.
12789:
12790: @item system case-sensitivity characteristics:
12791: @cindex case-sensitivity characteristics
1.26 crook 12792: Dictionary searches are case-insensitive (except in
1.1 anton 12793: @code{TABLE}s). However, as explained above under @i{character-set
12794: extensions}, the matching for non-ASCII characters is determined by the
12795: locale you are using. In the default @code{C} locale all non-ASCII
12796: characters are matched case-sensitively.
12797:
12798: @item system prompt:
12799: @cindex system prompt
12800: @cindex prompt
12801: @code{ ok} in interpret state, @code{ compiled} in compile state.
12802:
12803: @item division rounding:
12804: @cindex division rounding
12805: installation dependent. @code{s" floored" environment? drop .}. We leave
12806: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12807: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12808:
12809: @item values of @code{STATE} when true:
12810: @cindex @code{STATE} values
12811: -1.
12812:
12813: @item values returned after arithmetic overflow:
12814: On two's complement machines, arithmetic is performed modulo
12815: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12816: arithmetic (with appropriate mapping for signed types). Division by zero
12817: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12818: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12819:
12820: @item whether the current definition can be found after @t{DOES>}:
12821: @cindex @t{DOES>}, visibility of current definition
12822: No.
12823:
12824: @end table
12825:
12826: @c ---------------------------------------------------------------------
12827: @node core-ambcond, core-other, core-idef, The Core Words
12828: @subsection Ambiguous conditions
12829: @c ---------------------------------------------------------------------
12830: @cindex core words, ambiguous conditions
12831: @cindex ambiguous conditions, core words
12832:
12833: @table @i
12834:
12835: @item a name is neither a word nor a number:
12836: @cindex name not found
1.26 crook 12837: @cindex undefined word
1.80 anton 12838: @code{-13 throw} (Undefined word).
1.1 anton 12839:
12840: @item a definition name exceeds the maximum length allowed:
1.26 crook 12841: @cindex word name too long
1.1 anton 12842: @code{-19 throw} (Word name too long)
12843:
12844: @item addressing a region not inside the various data spaces of the forth system:
12845: @cindex Invalid memory address
1.32 anton 12846: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12847: typically readable. Accessing other addresses gives results dependent on
12848: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12849: address).
12850:
12851: @item argument type incompatible with parameter:
1.26 crook 12852: @cindex argument type mismatch
1.1 anton 12853: This is usually not caught. Some words perform checks, e.g., the control
12854: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12855: mismatch).
12856:
12857: @item attempting to obtain the execution token of a word with undefined execution semantics:
12858: @cindex Interpreting a compile-only word, for @code{'} etc.
12859: @cindex execution token of words with undefined execution semantics
12860: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12861: get an execution token for @code{compile-only-error} (which performs a
12862: @code{-14 throw} when executed).
12863:
12864: @item dividing by zero:
12865: @cindex dividing by zero
12866: @cindex floating point unidentified fault, integer division
1.80 anton 12867: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12868: zero); on other systems, this typically results in a @code{-55 throw}
12869: (Floating-point unidentified fault).
1.1 anton 12870:
12871: @item insufficient data stack or return stack space:
12872: @cindex insufficient data stack or return stack space
12873: @cindex stack overflow
1.26 crook 12874: @cindex address alignment exception, stack overflow
1.1 anton 12875: @cindex Invalid memory address, stack overflow
12876: Depending on the operating system, the installation, and the invocation
12877: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12878: it is not checked. If it is checked, you typically get a @code{-3 throw}
12879: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12880: throw} (Invalid memory address) (depending on the platform and how you
12881: achieved the overflow) as soon as the overflow happens. If it is not
12882: checked, overflows typically result in mysterious illegal memory
12883: accesses, producing @code{-9 throw} (Invalid memory address) or
12884: @code{-23 throw} (Address alignment exception); they might also destroy
12885: the internal data structure of @code{ALLOCATE} and friends, resulting in
12886: various errors in these words.
1.1 anton 12887:
12888: @item insufficient space for loop control parameters:
12889: @cindex insufficient space for loop control parameters
1.80 anton 12890: Like other return stack overflows.
1.1 anton 12891:
12892: @item insufficient space in the dictionary:
12893: @cindex insufficient space in the dictionary
12894: @cindex dictionary overflow
1.12 anton 12895: If you try to allot (either directly with @code{allot}, or indirectly
12896: with @code{,}, @code{create} etc.) more memory than available in the
12897: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12898: to access memory beyond the end of the dictionary, the results are
12899: similar to stack overflows.
1.1 anton 12900:
12901: @item interpreting a word with undefined interpretation semantics:
12902: @cindex interpreting a word with undefined interpretation semantics
12903: @cindex Interpreting a compile-only word
12904: For some words, we have defined interpretation semantics. For the
12905: others: @code{-14 throw} (Interpreting a compile-only word).
12906:
12907: @item modifying the contents of the input buffer or a string literal:
12908: @cindex modifying the contents of the input buffer or a string literal
12909: These are located in writable memory and can be modified.
12910:
12911: @item overflow of the pictured numeric output string:
12912: @cindex overflow of the pictured numeric output string
12913: @cindex pictured numeric output string, overflow
1.24 anton 12914: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12915:
12916: @item parsed string overflow:
12917: @cindex parsed string overflow
12918: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12919:
12920: @item producing a result out of range:
12921: @cindex result out of range
12922: On two's complement machines, arithmetic is performed modulo
12923: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12924: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12925: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12926: throw} (floating point unidentified fault). @code{convert} and
12927: @code{>number} currently overflow silently.
1.1 anton 12928:
12929: @item reading from an empty data or return stack:
12930: @cindex stack empty
12931: @cindex stack underflow
1.24 anton 12932: @cindex return stack underflow
1.1 anton 12933: The data stack is checked by the outer (aka text) interpreter after
12934: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12935: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12936: depending on operating system, installation, and invocation. If they are
12937: caught by a check, they typically result in @code{-4 throw} (Stack
12938: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12939: (Invalid memory address), depending on the platform and which stack
12940: underflows and by how much. Note that even if the system uses checking
12941: (through the MMU), your program may have to underflow by a significant
12942: number of stack items to trigger the reaction (the reason for this is
12943: that the MMU, and therefore the checking, works with a page-size
12944: granularity). If there is no checking, the symptoms resulting from an
12945: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12946: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12947: (Invalid memory address) and Illegal Instruction (typically @code{-260
12948: throw}).
1.1 anton 12949:
12950: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12951: @cindex unexpected end of the input buffer
12952: @cindex zero-length string as a name
12953: @cindex Attempt to use zero-length string as a name
12954: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12955: use zero-length string as a name). Words like @code{'} probably will not
12956: find what they search. Note that it is possible to create zero-length
12957: names with @code{nextname} (should it not?).
12958:
12959: @item @code{>IN} greater than input buffer:
12960: @cindex @code{>IN} greater than input buffer
12961: The next invocation of a parsing word returns a string with length 0.
12962:
12963: @item @code{RECURSE} appears after @code{DOES>}:
12964: @cindex @code{RECURSE} appears after @code{DOES>}
12965: Compiles a recursive call to the defining word, not to the defined word.
12966:
12967: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12968: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12969: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12970: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12971: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12972: the end of the file was reached), its source-id may be
12973: reused. Therefore, restoring an input source specification referencing a
12974: closed file may lead to unpredictable results instead of a @code{-12
12975: THROW}.
12976:
12977: In the future, Gforth may be able to restore input source specifications
12978: from other than the current input source.
12979:
12980: @item data space containing definitions gets de-allocated:
12981: @cindex data space containing definitions gets de-allocated
12982: Deallocation with @code{allot} is not checked. This typically results in
12983: memory access faults or execution of illegal instructions.
12984:
12985: @item data space read/write with incorrect alignment:
12986: @cindex data space read/write with incorrect alignment
12987: @cindex alignment faults
1.26 crook 12988: @cindex address alignment exception
1.1 anton 12989: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12990: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12991: alignment turned on, incorrect alignment results in a @code{-9 throw}
12992: (Invalid memory address). There are reportedly some processors with
1.12 anton 12993: alignment restrictions that do not report violations.
1.1 anton 12994:
12995: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12996: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12997: Like other alignment errors.
12998:
12999: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13000: Like other stack underflows.
13001:
13002: @item loop control parameters not available:
13003: @cindex loop control parameters not available
13004: Not checked. The counted loop words simply assume that the top of return
13005: stack items are loop control parameters and behave accordingly.
13006:
13007: @item most recent definition does not have a name (@code{IMMEDIATE}):
13008: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13009: @cindex last word was headerless
13010: @code{abort" last word was headerless"}.
13011:
13012: @item name not defined by @code{VALUE} used by @code{TO}:
13013: @cindex name not defined by @code{VALUE} used by @code{TO}
13014: @cindex @code{TO} on non-@code{VALUE}s
13015: @cindex Invalid name argument, @code{TO}
13016: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13017: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13018:
13019: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13020: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13021: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13022: @code{-13 throw} (Undefined word)
13023:
13024: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13025: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13026: Gforth behaves as if they were of the same type. I.e., you can predict
13027: the behaviour by interpreting all parameters as, e.g., signed.
13028:
13029: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13030: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13031: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13032: compilation semantics of @code{TO}.
13033:
13034: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13035: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13036: @cindex @code{WORD}, string overflow
13037: Not checked. The string will be ok, but the count will, of course,
13038: contain only the least significant bits of the length.
13039:
13040: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13041: @cindex @code{LSHIFT}, large shift counts
13042: @cindex @code{RSHIFT}, large shift counts
13043: Processor-dependent. Typical behaviours are returning 0 and using only
13044: the low bits of the shift count.
13045:
13046: @item word not defined via @code{CREATE}:
13047: @cindex @code{>BODY} of non-@code{CREATE}d words
13048: @code{>BODY} produces the PFA of the word no matter how it was defined.
13049:
13050: @cindex @code{DOES>} of non-@code{CREATE}d words
13051: @code{DOES>} changes the execution semantics of the last defined word no
13052: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13053: @code{CREATE , DOES>}.
13054:
13055: @item words improperly used outside @code{<#} and @code{#>}:
13056: Not checked. As usual, you can expect memory faults.
13057:
13058: @end table
13059:
13060:
13061: @c ---------------------------------------------------------------------
13062: @node core-other, , core-ambcond, The Core Words
13063: @subsection Other system documentation
13064: @c ---------------------------------------------------------------------
13065: @cindex other system documentation, core words
13066: @cindex core words, other system documentation
13067:
13068: @table @i
13069: @item nonstandard words using @code{PAD}:
13070: @cindex @code{PAD} use by nonstandard words
13071: None.
13072:
13073: @item operator's terminal facilities available:
13074: @cindex operator's terminal facilities available
1.80 anton 13075: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13076: and you can give commands to Gforth interactively. The actual facilities
13077: available depend on how you invoke Gforth.
13078:
13079: @item program data space available:
13080: @cindex program data space available
13081: @cindex data space available
13082: @code{UNUSED .} gives the remaining dictionary space. The total
13083: dictionary space can be specified with the @code{-m} switch
13084: (@pxref{Invoking Gforth}) when Gforth starts up.
13085:
13086: @item return stack space available:
13087: @cindex return stack space available
13088: You can compute the total return stack space in cells with
13089: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13090: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13091:
13092: @item stack space available:
13093: @cindex stack space available
13094: You can compute the total data stack space in cells with
13095: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13096: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13097:
13098: @item system dictionary space required, in address units:
13099: @cindex system dictionary space required, in address units
13100: Type @code{here forthstart - .} after startup. At the time of this
13101: writing, this gives 80080 (bytes) on a 32-bit system.
13102: @end table
13103:
13104:
13105: @c =====================================================================
13106: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13107: @section The optional Block word set
13108: @c =====================================================================
13109: @cindex system documentation, block words
13110: @cindex block words, system documentation
13111:
13112: @menu
13113: * block-idef:: Implementation Defined Options
13114: * block-ambcond:: Ambiguous Conditions
13115: * block-other:: Other System Documentation
13116: @end menu
13117:
13118:
13119: @c ---------------------------------------------------------------------
13120: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13121: @subsection Implementation Defined Options
13122: @c ---------------------------------------------------------------------
13123: @cindex implementation-defined options, block words
13124: @cindex block words, implementation-defined options
13125:
13126: @table @i
13127: @item the format for display by @code{LIST}:
13128: @cindex @code{LIST} display format
13129: First the screen number is displayed, then 16 lines of 64 characters,
13130: each line preceded by the line number.
13131:
13132: @item the length of a line affected by @code{\}:
13133: @cindex length of a line affected by @code{\}
13134: @cindex @code{\}, line length in blocks
13135: 64 characters.
13136: @end table
13137:
13138:
13139: @c ---------------------------------------------------------------------
13140: @node block-ambcond, block-other, block-idef, The optional Block word set
13141: @subsection Ambiguous conditions
13142: @c ---------------------------------------------------------------------
13143: @cindex block words, ambiguous conditions
13144: @cindex ambiguous conditions, block words
13145:
13146: @table @i
13147: @item correct block read was not possible:
13148: @cindex block read not possible
13149: Typically results in a @code{throw} of some OS-derived value (between
13150: -512 and -2048). If the blocks file was just not long enough, blanks are
13151: supplied for the missing portion.
13152:
13153: @item I/O exception in block transfer:
13154: @cindex I/O exception in block transfer
13155: @cindex block transfer, I/O exception
13156: Typically results in a @code{throw} of some OS-derived value (between
13157: -512 and -2048).
13158:
13159: @item invalid block number:
13160: @cindex invalid block number
13161: @cindex block number invalid
13162: @code{-35 throw} (Invalid block number)
13163:
13164: @item a program directly alters the contents of @code{BLK}:
13165: @cindex @code{BLK}, altering @code{BLK}
13166: The input stream is switched to that other block, at the same
13167: position. If the storing to @code{BLK} happens when interpreting
13168: non-block input, the system will get quite confused when the block ends.
13169:
13170: @item no current block buffer for @code{UPDATE}:
13171: @cindex @code{UPDATE}, no current block buffer
13172: @code{UPDATE} has no effect.
13173:
13174: @end table
13175:
13176: @c ---------------------------------------------------------------------
13177: @node block-other, , block-ambcond, The optional Block word set
13178: @subsection Other system documentation
13179: @c ---------------------------------------------------------------------
13180: @cindex other system documentation, block words
13181: @cindex block words, other system documentation
13182:
13183: @table @i
13184: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13185: No restrictions (yet).
13186:
13187: @item the number of blocks available for source and data:
13188: depends on your disk space.
13189:
13190: @end table
13191:
13192:
13193: @c =====================================================================
13194: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13195: @section The optional Double Number word set
13196: @c =====================================================================
13197: @cindex system documentation, double words
13198: @cindex double words, system documentation
13199:
13200: @menu
13201: * double-ambcond:: Ambiguous Conditions
13202: @end menu
13203:
13204:
13205: @c ---------------------------------------------------------------------
13206: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13207: @subsection Ambiguous conditions
13208: @c ---------------------------------------------------------------------
13209: @cindex double words, ambiguous conditions
13210: @cindex ambiguous conditions, double words
13211:
13212: @table @i
1.29 crook 13213: @item @i{d} outside of range of @i{n} in @code{D>S}:
13214: @cindex @code{D>S}, @i{d} out of range of @i{n}
13215: The least significant cell of @i{d} is produced.
1.1 anton 13216:
13217: @end table
13218:
13219:
13220: @c =====================================================================
13221: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13222: @section The optional Exception word set
13223: @c =====================================================================
13224: @cindex system documentation, exception words
13225: @cindex exception words, system documentation
13226:
13227: @menu
13228: * exception-idef:: Implementation Defined Options
13229: @end menu
13230:
13231:
13232: @c ---------------------------------------------------------------------
13233: @node exception-idef, , The optional Exception word set, The optional Exception word set
13234: @subsection Implementation Defined Options
13235: @c ---------------------------------------------------------------------
13236: @cindex implementation-defined options, exception words
13237: @cindex exception words, implementation-defined options
13238:
13239: @table @i
13240: @item @code{THROW}-codes used in the system:
13241: @cindex @code{THROW}-codes used in the system
13242: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13243: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13244: codes -512@minus{}-2047 are used for OS errors (for file and memory
13245: allocation operations). The mapping from OS error numbers to throw codes
13246: is -512@minus{}@code{errno}. One side effect of this mapping is that
13247: undefined OS errors produce a message with a strange number; e.g.,
13248: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13249: @end table
13250:
13251: @c =====================================================================
13252: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13253: @section The optional Facility word set
13254: @c =====================================================================
13255: @cindex system documentation, facility words
13256: @cindex facility words, system documentation
13257:
13258: @menu
13259: * facility-idef:: Implementation Defined Options
13260: * facility-ambcond:: Ambiguous Conditions
13261: @end menu
13262:
13263:
13264: @c ---------------------------------------------------------------------
13265: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13266: @subsection Implementation Defined Options
13267: @c ---------------------------------------------------------------------
13268: @cindex implementation-defined options, facility words
13269: @cindex facility words, implementation-defined options
13270:
13271: @table @i
13272: @item encoding of keyboard events (@code{EKEY}):
13273: @cindex keyboard events, encoding in @code{EKEY}
13274: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13275: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13276: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13277: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13278: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13279: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13280:
1.1 anton 13281:
13282: @item duration of a system clock tick:
13283: @cindex duration of a system clock tick
13284: @cindex clock tick duration
13285: System dependent. With respect to @code{MS}, the time is specified in
13286: microseconds. How well the OS and the hardware implement this, is
13287: another question.
13288:
13289: @item repeatability to be expected from the execution of @code{MS}:
13290: @cindex repeatability to be expected from the execution of @code{MS}
13291: @cindex @code{MS}, repeatability to be expected
13292: System dependent. On Unix, a lot depends on load. If the system is
13293: lightly loaded, and the delay is short enough that Gforth does not get
13294: swapped out, the performance should be acceptable. Under MS-DOS and
13295: other single-tasking systems, it should be good.
13296:
13297: @end table
13298:
13299:
13300: @c ---------------------------------------------------------------------
13301: @node facility-ambcond, , facility-idef, The optional Facility word set
13302: @subsection Ambiguous conditions
13303: @c ---------------------------------------------------------------------
13304: @cindex facility words, ambiguous conditions
13305: @cindex ambiguous conditions, facility words
13306:
13307: @table @i
13308: @item @code{AT-XY} can't be performed on user output device:
13309: @cindex @code{AT-XY} can't be performed on user output device
13310: Largely terminal dependent. No range checks are done on the arguments.
13311: No errors are reported. You may see some garbage appearing, you may see
13312: simply nothing happen.
13313:
13314: @end table
13315:
13316:
13317: @c =====================================================================
13318: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13319: @section The optional File-Access word set
13320: @c =====================================================================
13321: @cindex system documentation, file words
13322: @cindex file words, system documentation
13323:
13324: @menu
13325: * file-idef:: Implementation Defined Options
13326: * file-ambcond:: Ambiguous Conditions
13327: @end menu
13328:
13329: @c ---------------------------------------------------------------------
13330: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13331: @subsection Implementation Defined Options
13332: @c ---------------------------------------------------------------------
13333: @cindex implementation-defined options, file words
13334: @cindex file words, implementation-defined options
13335:
13336: @table @i
13337: @item file access methods used:
13338: @cindex file access methods used
13339: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13340: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13341: @code{wb}): The file is cleared, if it exists, and created, if it does
13342: not (with both @code{open-file} and @code{create-file}). Under Unix
13343: @code{create-file} creates a file with 666 permissions modified by your
13344: umask.
13345:
13346: @item file exceptions:
13347: @cindex file exceptions
13348: The file words do not raise exceptions (except, perhaps, memory access
13349: faults when you pass illegal addresses or file-ids).
13350:
13351: @item file line terminator:
13352: @cindex file line terminator
13353: System-dependent. Gforth uses C's newline character as line
13354: terminator. What the actual character code(s) of this are is
13355: system-dependent.
13356:
13357: @item file name format:
13358: @cindex file name format
13359: System dependent. Gforth just uses the file name format of your OS.
13360:
13361: @item information returned by @code{FILE-STATUS}:
13362: @cindex @code{FILE-STATUS}, returned information
13363: @code{FILE-STATUS} returns the most powerful file access mode allowed
13364: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13365: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13366: along with the returned mode.
13367:
13368: @item input file state after an exception when including source:
13369: @cindex exception when including source
13370: All files that are left via the exception are closed.
13371:
1.29 crook 13372: @item @i{ior} values and meaning:
13373: @cindex @i{ior} values and meaning
1.68 anton 13374: @cindex @i{wior} values and meaning
1.29 crook 13375: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13376: intended as throw codes. They typically are in the range
13377: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13378: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13379:
13380: @item maximum depth of file input nesting:
13381: @cindex maximum depth of file input nesting
13382: @cindex file input nesting, maximum depth
13383: limited by the amount of return stack, locals/TIB stack, and the number
13384: of open files available. This should not give you troubles.
13385:
13386: @item maximum size of input line:
13387: @cindex maximum size of input line
13388: @cindex input line size, maximum
13389: @code{/line}. Currently 255.
13390:
13391: @item methods of mapping block ranges to files:
13392: @cindex mapping block ranges to files
13393: @cindex files containing blocks
13394: @cindex blocks in files
13395: By default, blocks are accessed in the file @file{blocks.fb} in the
13396: current working directory. The file can be switched with @code{USE}.
13397:
13398: @item number of string buffers provided by @code{S"}:
13399: @cindex @code{S"}, number of string buffers
13400: 1
13401:
13402: @item size of string buffer used by @code{S"}:
13403: @cindex @code{S"}, size of string buffer
13404: @code{/line}. currently 255.
13405:
13406: @end table
13407:
13408: @c ---------------------------------------------------------------------
13409: @node file-ambcond, , file-idef, The optional File-Access word set
13410: @subsection Ambiguous conditions
13411: @c ---------------------------------------------------------------------
13412: @cindex file words, ambiguous conditions
13413: @cindex ambiguous conditions, file words
13414:
13415: @table @i
13416: @item attempting to position a file outside its boundaries:
13417: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13418: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13419: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13420:
13421: @item attempting to read from file positions not yet written:
13422: @cindex reading from file positions not yet written
13423: End-of-file, i.e., zero characters are read and no error is reported.
13424:
1.29 crook 13425: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13426: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13427: An appropriate exception may be thrown, but a memory fault or other
13428: problem is more probable.
13429:
1.29 crook 13430: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13431: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13432: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13433: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13434: thrown.
13435:
13436: @item named file cannot be opened (@code{INCLUDED}):
13437: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13438: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13439:
13440: @item requesting an unmapped block number:
13441: @cindex unmapped block numbers
13442: There are no unmapped legal block numbers. On some operating systems,
13443: writing a block with a large number may overflow the file system and
13444: have an error message as consequence.
13445:
13446: @item using @code{source-id} when @code{blk} is non-zero:
13447: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13448: @code{source-id} performs its function. Typically it will give the id of
13449: the source which loaded the block. (Better ideas?)
13450:
13451: @end table
13452:
13453:
13454: @c =====================================================================
13455: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13456: @section The optional Floating-Point word set
13457: @c =====================================================================
13458: @cindex system documentation, floating-point words
13459: @cindex floating-point words, system documentation
13460:
13461: @menu
13462: * floating-idef:: Implementation Defined Options
13463: * floating-ambcond:: Ambiguous Conditions
13464: @end menu
13465:
13466:
13467: @c ---------------------------------------------------------------------
13468: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13469: @subsection Implementation Defined Options
13470: @c ---------------------------------------------------------------------
13471: @cindex implementation-defined options, floating-point words
13472: @cindex floating-point words, implementation-defined options
13473:
13474: @table @i
13475: @item format and range of floating point numbers:
13476: @cindex format and range of floating point numbers
13477: @cindex floating point numbers, format and range
13478: System-dependent; the @code{double} type of C.
13479:
1.29 crook 13480: @item results of @code{REPRESENT} when @i{float} is out of range:
13481: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13482: System dependent; @code{REPRESENT} is implemented using the C library
13483: function @code{ecvt()} and inherits its behaviour in this respect.
13484:
13485: @item rounding or truncation of floating-point numbers:
13486: @cindex rounding of floating-point numbers
13487: @cindex truncation of floating-point numbers
13488: @cindex floating-point numbers, rounding or truncation
13489: System dependent; the rounding behaviour is inherited from the hosting C
13490: compiler. IEEE-FP-based (i.e., most) systems by default round to
13491: nearest, and break ties by rounding to even (i.e., such that the last
13492: bit of the mantissa is 0).
13493:
13494: @item size of floating-point stack:
13495: @cindex floating-point stack size
13496: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13497: the floating-point stack (in floats). You can specify this on startup
13498: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13499:
13500: @item width of floating-point stack:
13501: @cindex floating-point stack width
13502: @code{1 floats}.
13503:
13504: @end table
13505:
13506:
13507: @c ---------------------------------------------------------------------
13508: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13509: @subsection Ambiguous conditions
13510: @c ---------------------------------------------------------------------
13511: @cindex floating-point words, ambiguous conditions
13512: @cindex ambiguous conditions, floating-point words
13513:
13514: @table @i
13515: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13516: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13517: System-dependent. Typically results in a @code{-23 THROW} like other
13518: alignment violations.
13519:
13520: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13521: @cindex @code{f@@} used with an address that is not float aligned
13522: @cindex @code{f!} used with an address that is not float aligned
13523: System-dependent. Typically results in a @code{-23 THROW} like other
13524: alignment violations.
13525:
13526: @item floating-point result out of range:
13527: @cindex floating-point result out of range
1.80 anton 13528: System-dependent. Can result in a @code{-43 throw} (floating point
13529: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13530: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13531: unidentified fault), or can produce a special value representing, e.g.,
13532: Infinity.
13533:
13534: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13535: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13536: System-dependent. Typically results in an alignment fault like other
13537: alignment violations.
13538:
1.35 anton 13539: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13540: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13541: The floating-point number is converted into decimal nonetheless.
13542:
13543: @item Both arguments are equal to zero (@code{FATAN2}):
13544: @cindex @code{FATAN2}, both arguments are equal to zero
13545: System-dependent. @code{FATAN2} is implemented using the C library
13546: function @code{atan2()}.
13547:
1.29 crook 13548: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13549: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13550: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13551: because of small errors and the tan will be a very large (or very small)
13552: but finite number.
13553:
1.29 crook 13554: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13555: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13556: The result is rounded to the nearest float.
13557:
13558: @item dividing by zero:
13559: @cindex dividing by zero, floating-point
13560: @cindex floating-point dividing by zero
13561: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13562: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13563: (floating point divide by zero) or @code{-55 throw} (Floating-point
13564: unidentified fault).
1.1 anton 13565:
13566: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13567: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13568: System dependent. On IEEE-FP based systems the number is converted into
13569: an infinity.
13570:
1.29 crook 13571: @item @i{float}<1 (@code{FACOSH}):
13572: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13573: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13574: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13575:
1.29 crook 13576: @item @i{float}=<-1 (@code{FLNP1}):
13577: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13578: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13579: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13580: negative infinity for @i{float}=-1).
1.1 anton 13581:
1.29 crook 13582: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13583: @cindex @code{FLN}, @i{float}=<0
13584: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13585: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13586: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13587: negative infinity for @i{float}=0).
1.1 anton 13588:
1.29 crook 13589: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13590: @cindex @code{FASINH}, @i{float}<0
13591: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13592: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13593: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13594: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13595: C library?).
1.1 anton 13596:
1.29 crook 13597: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13598: @cindex @code{FACOS}, |@i{float}|>1
13599: @cindex @code{FASIN}, |@i{float}|>1
13600: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13601: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13602: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13603:
1.29 crook 13604: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13605: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13606: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13607: Platform-dependent; typically, some double number is produced and no
13608: error is reported.
1.1 anton 13609:
13610: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13611: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13612: @code{Precision} characters of the numeric output area are used. If
13613: @code{precision} is too high, these words will smash the data or code
13614: close to @code{here}.
1.1 anton 13615: @end table
13616:
13617: @c =====================================================================
13618: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13619: @section The optional Locals word set
13620: @c =====================================================================
13621: @cindex system documentation, locals words
13622: @cindex locals words, system documentation
13623:
13624: @menu
13625: * locals-idef:: Implementation Defined Options
13626: * locals-ambcond:: Ambiguous Conditions
13627: @end menu
13628:
13629:
13630: @c ---------------------------------------------------------------------
13631: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13632: @subsection Implementation Defined Options
13633: @c ---------------------------------------------------------------------
13634: @cindex implementation-defined options, locals words
13635: @cindex locals words, implementation-defined options
13636:
13637: @table @i
13638: @item maximum number of locals in a definition:
13639: @cindex maximum number of locals in a definition
13640: @cindex locals, maximum number in a definition
13641: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13642: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13643: characters. The number of locals in a definition is bounded by the size
13644: of locals-buffer, which contains the names of the locals.
13645:
13646: @end table
13647:
13648:
13649: @c ---------------------------------------------------------------------
13650: @node locals-ambcond, , locals-idef, The optional Locals word set
13651: @subsection Ambiguous conditions
13652: @c ---------------------------------------------------------------------
13653: @cindex locals words, ambiguous conditions
13654: @cindex ambiguous conditions, locals words
13655:
13656: @table @i
13657: @item executing a named local in interpretation state:
13658: @cindex local in interpretation state
13659: @cindex Interpreting a compile-only word, for a local
13660: Locals have no interpretation semantics. If you try to perform the
13661: interpretation semantics, you will get a @code{-14 throw} somewhere
13662: (Interpreting a compile-only word). If you perform the compilation
13663: semantics, the locals access will be compiled (irrespective of state).
13664:
1.29 crook 13665: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13666: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13667: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13668: @cindex Invalid name argument, @code{TO}
13669: @code{-32 throw} (Invalid name argument)
13670:
13671: @end table
13672:
13673:
13674: @c =====================================================================
13675: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13676: @section The optional Memory-Allocation word set
13677: @c =====================================================================
13678: @cindex system documentation, memory-allocation words
13679: @cindex memory-allocation words, system documentation
13680:
13681: @menu
13682: * memory-idef:: Implementation Defined Options
13683: @end menu
13684:
13685:
13686: @c ---------------------------------------------------------------------
13687: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13688: @subsection Implementation Defined Options
13689: @c ---------------------------------------------------------------------
13690: @cindex implementation-defined options, memory-allocation words
13691: @cindex memory-allocation words, implementation-defined options
13692:
13693: @table @i
1.29 crook 13694: @item values and meaning of @i{ior}:
13695: @cindex @i{ior} values and meaning
13696: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13697: intended as throw codes. They typically are in the range
13698: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13699: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13700:
13701: @end table
13702:
13703: @c =====================================================================
13704: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13705: @section The optional Programming-Tools word set
13706: @c =====================================================================
13707: @cindex system documentation, programming-tools words
13708: @cindex programming-tools words, system documentation
13709:
13710: @menu
13711: * programming-idef:: Implementation Defined Options
13712: * programming-ambcond:: Ambiguous Conditions
13713: @end menu
13714:
13715:
13716: @c ---------------------------------------------------------------------
13717: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13718: @subsection Implementation Defined Options
13719: @c ---------------------------------------------------------------------
13720: @cindex implementation-defined options, programming-tools words
13721: @cindex programming-tools words, implementation-defined options
13722:
13723: @table @i
13724: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13725: @cindex @code{;CODE} ending sequence
13726: @cindex @code{CODE} ending sequence
13727: @code{END-CODE}
13728:
13729: @item manner of processing input following @code{;CODE} and @code{CODE}:
13730: @cindex @code{;CODE}, processing input
13731: @cindex @code{CODE}, processing input
13732: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13733: the input is processed by the text interpreter, (starting) in interpret
13734: state.
13735:
13736: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13737: @cindex @code{ASSEMBLER}, search order capability
13738: The ANS Forth search order word set.
13739:
13740: @item source and format of display by @code{SEE}:
13741: @cindex @code{SEE}, source and format of output
1.80 anton 13742: The source for @code{see} is the executable code used by the inner
1.1 anton 13743: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13744: (and on some platforms, assembly code for primitives) as well as
13745: possible.
1.1 anton 13746:
13747: @end table
13748:
13749: @c ---------------------------------------------------------------------
13750: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13751: @subsection Ambiguous conditions
13752: @c ---------------------------------------------------------------------
13753: @cindex programming-tools words, ambiguous conditions
13754: @cindex ambiguous conditions, programming-tools words
13755:
13756: @table @i
13757:
1.21 crook 13758: @item deleting the compilation word list (@code{FORGET}):
13759: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13760: Not implemented (yet).
13761:
1.29 crook 13762: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13763: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13764: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13765: @cindex control-flow stack underflow
13766: This typically results in an @code{abort"} with a descriptive error
13767: message (may change into a @code{-22 throw} (Control structure mismatch)
13768: in the future). You may also get a memory access error. If you are
13769: unlucky, this ambiguous condition is not caught.
13770:
1.29 crook 13771: @item @i{name} can't be found (@code{FORGET}):
13772: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13773: Not implemented (yet).
13774:
1.29 crook 13775: @item @i{name} not defined via @code{CREATE}:
13776: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13777: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13778: the execution semantics of the last defined word no matter how it was
13779: defined.
13780:
13781: @item @code{POSTPONE} applied to @code{[IF]}:
13782: @cindex @code{POSTPONE} applied to @code{[IF]}
13783: @cindex @code{[IF]} and @code{POSTPONE}
13784: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13785: equivalent to @code{[IF]}.
13786:
13787: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13788: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13789: Continue in the same state of conditional compilation in the next outer
13790: input source. Currently there is no warning to the user about this.
13791:
13792: @item removing a needed definition (@code{FORGET}):
13793: @cindex @code{FORGET}, removing a needed definition
13794: Not implemented (yet).
13795:
13796: @end table
13797:
13798:
13799: @c =====================================================================
13800: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13801: @section The optional Search-Order word set
13802: @c =====================================================================
13803: @cindex system documentation, search-order words
13804: @cindex search-order words, system documentation
13805:
13806: @menu
13807: * search-idef:: Implementation Defined Options
13808: * search-ambcond:: Ambiguous Conditions
13809: @end menu
13810:
13811:
13812: @c ---------------------------------------------------------------------
13813: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13814: @subsection Implementation Defined Options
13815: @c ---------------------------------------------------------------------
13816: @cindex implementation-defined options, search-order words
13817: @cindex search-order words, implementation-defined options
13818:
13819: @table @i
13820: @item maximum number of word lists in search order:
13821: @cindex maximum number of word lists in search order
13822: @cindex search order, maximum depth
13823: @code{s" wordlists" environment? drop .}. Currently 16.
13824:
13825: @item minimum search order:
13826: @cindex minimum search order
13827: @cindex search order, minimum
13828: @code{root root}.
13829:
13830: @end table
13831:
13832: @c ---------------------------------------------------------------------
13833: @node search-ambcond, , search-idef, The optional Search-Order word set
13834: @subsection Ambiguous conditions
13835: @c ---------------------------------------------------------------------
13836: @cindex search-order words, ambiguous conditions
13837: @cindex ambiguous conditions, search-order words
13838:
13839: @table @i
1.21 crook 13840: @item changing the compilation word list (during compilation):
13841: @cindex changing the compilation word list (during compilation)
13842: @cindex compilation word list, change before definition ends
13843: The word is entered into the word list that was the compilation word list
1.1 anton 13844: at the start of the definition. Any changes to the name field (e.g.,
13845: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13846: are applied to the latest defined word (as reported by @code{latest} or
13847: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13848:
13849: @item search order empty (@code{previous}):
13850: @cindex @code{previous}, search order empty
1.26 crook 13851: @cindex vocstack empty, @code{previous}
1.1 anton 13852: @code{abort" Vocstack empty"}.
13853:
13854: @item too many word lists in search order (@code{also}):
13855: @cindex @code{also}, too many word lists in search order
1.26 crook 13856: @cindex vocstack full, @code{also}
1.1 anton 13857: @code{abort" Vocstack full"}.
13858:
13859: @end table
13860:
13861: @c ***************************************************************
1.65 anton 13862: @node Standard vs Extensions, Model, ANS conformance, Top
13863: @chapter Should I use Gforth extensions?
13864: @cindex Gforth extensions
13865:
13866: As you read through the rest of this manual, you will see documentation
13867: for @i{Standard} words, and documentation for some appealing Gforth
13868: @i{extensions}. You might ask yourself the question: @i{``Should I
13869: restrict myself to the standard, or should I use the extensions?''}
13870:
13871: The answer depends on the goals you have for the program you are working
13872: on:
13873:
13874: @itemize @bullet
13875:
13876: @item Is it just for yourself or do you want to share it with others?
13877:
13878: @item
13879: If you want to share it, do the others all use Gforth?
13880:
13881: @item
13882: If it is just for yourself, do you want to restrict yourself to Gforth?
13883:
13884: @end itemize
13885:
13886: If restricting the program to Gforth is ok, then there is no reason not
13887: to use extensions. It is still a good idea to keep to the standard
13888: where it is easy, in case you want to reuse these parts in another
13889: program that you want to be portable.
13890:
13891: If you want to be able to port the program to other Forth systems, there
13892: are the following points to consider:
13893:
13894: @itemize @bullet
13895:
13896: @item
13897: Most Forth systems that are being maintained support the ANS Forth
13898: standard. So if your program complies with the standard, it will be
13899: portable among many systems.
13900:
13901: @item
13902: A number of the Gforth extensions can be implemented in ANS Forth using
13903: public-domain files provided in the @file{compat/} directory. These are
13904: mentioned in the text in passing. There is no reason not to use these
13905: extensions, your program will still be ANS Forth compliant; just include
13906: the appropriate compat files with your program.
13907:
13908: @item
13909: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13910: analyse your program and determine what non-Standard words it relies
13911: upon. However, it does not check whether you use standard words in a
13912: non-standard way.
13913:
13914: @item
13915: Some techniques are not standardized by ANS Forth, and are hard or
13916: impossible to implement in a standard way, but can be implemented in
13917: most Forth systems easily, and usually in similar ways (e.g., accessing
13918: word headers). Forth has a rich historical precedent for programmers
13919: taking advantage of implementation-dependent features of their tools
13920: (for example, relying on a knowledge of the dictionary
13921: structure). Sometimes these techniques are necessary to extract every
13922: last bit of performance from the hardware, sometimes they are just a
13923: programming shorthand.
13924:
13925: @item
13926: Does using a Gforth extension save more work than the porting this part
13927: to other Forth systems (if any) will cost?
13928:
13929: @item
13930: Is the additional functionality worth the reduction in portability and
13931: the additional porting problems?
13932:
13933: @end itemize
13934:
13935: In order to perform these consideratios, you need to know what's
13936: standard and what's not. This manual generally states if something is
1.81 anton 13937: non-standard, but the authoritative source is the
13938: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13939: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13940: into the thought processes of the technical committee.
13941:
13942: Note also that portability between Forth systems is not the only
13943: portability issue; there is also the issue of portability between
13944: different platforms (processor/OS combinations).
13945:
13946: @c ***************************************************************
13947: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13948: @chapter Model
13949:
13950: This chapter has yet to be written. It will contain information, on
13951: which internal structures you can rely.
13952:
13953: @c ***************************************************************
13954: @node Integrating Gforth, Emacs and Gforth, Model, Top
13955: @chapter Integrating Gforth into C programs
13956:
13957: This is not yet implemented.
13958:
13959: Several people like to use Forth as scripting language for applications
13960: that are otherwise written in C, C++, or some other language.
13961:
13962: The Forth system ATLAST provides facilities for embedding it into
13963: applications; unfortunately it has several disadvantages: most
13964: importantly, it is not based on ANS Forth, and it is apparently dead
13965: (i.e., not developed further and not supported). The facilities
1.21 crook 13966: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13967: making the switch should not be hard.
13968:
13969: We also tried to design the interface such that it can easily be
13970: implemented by other Forth systems, so that we may one day arrive at a
13971: standardized interface. Such a standard interface would allow you to
13972: replace the Forth system without having to rewrite C code.
13973:
13974: You embed the Gforth interpreter by linking with the library
13975: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13976: global symbols in this library that belong to the interface, have the
13977: prefix @code{forth_}. (Global symbols that are used internally have the
13978: prefix @code{gforth_}).
13979:
13980: You can include the declarations of Forth types and the functions and
13981: variables of the interface with @code{#include <forth.h>}.
13982:
13983: Types.
13984:
13985: Variables.
13986:
13987: Data and FP Stack pointer. Area sizes.
13988:
13989: functions.
13990:
13991: forth_init(imagefile)
13992: forth_evaluate(string) exceptions?
13993: forth_goto(address) (or forth_execute(xt)?)
13994: forth_continue() (a corountining mechanism)
13995:
13996: Adding primitives.
13997:
13998: No checking.
13999:
14000: Signals?
14001:
14002: Accessing the Stacks
14003:
1.26 crook 14004: @c ******************************************************************
1.1 anton 14005: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14006: @chapter Emacs and Gforth
14007: @cindex Emacs and Gforth
14008:
14009: @cindex @file{gforth.el}
14010: @cindex @file{forth.el}
14011: @cindex Rydqvist, Goran
1.107 dvdkhlng 14012: @cindex Kuehling, David
1.1 anton 14013: @cindex comment editing commands
14014: @cindex @code{\}, editing with Emacs
14015: @cindex debug tracer editing commands
14016: @cindex @code{~~}, removal with Emacs
14017: @cindex Forth mode in Emacs
1.107 dvdkhlng 14018:
1.1 anton 14019: Gforth comes with @file{gforth.el}, an improved version of
14020: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14021: improvements are:
14022:
14023: @itemize @bullet
14024: @item
1.107 dvdkhlng 14025: A better handling of indentation.
14026: @item
14027: A custom hilighting engine for Forth-code.
1.26 crook 14028: @item
14029: Comment paragraph filling (@kbd{M-q})
14030: @item
14031: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14032: @item
14033: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14034: @item
14035: Support of the @code{info-lookup} feature for looking up the
14036: documentation of a word.
1.107 dvdkhlng 14037: @item
14038: Support for reading and writing blocks files.
1.26 crook 14039: @end itemize
14040:
1.107 dvdkhlng 14041: To get a basic description of these features, enter Forth mode and
14042: type @kbd{C-h m}.
1.1 anton 14043:
14044: @cindex source location of error or debugging output in Emacs
14045: @cindex error output, finding the source location in Emacs
14046: @cindex debugging output, finding the source location in Emacs
14047: In addition, Gforth supports Emacs quite well: The source code locations
14048: given in error messages, debugging output (from @code{~~}) and failed
14049: assertion messages are in the right format for Emacs' compilation mode
14050: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14051: Manual}) so the source location corresponding to an error or other
14052: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14053: @kbd{C-c C-c} for the error under the cursor).
14054:
1.107 dvdkhlng 14055: @cindex viewing the documentation of a word in Emacs
14056: @cindex context-sensitive help
14057: Moreover, for words documented in this manual, you can look up the
14058: glossary entry quickly by using @kbd{C-h TAB}
14059: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14060: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14061: later and does not work for words containing @code{:}.
14062:
14063: @menu
14064: * Installing gforth.el:: Making Emacs aware of Forth.
14065: * Emacs Tags:: Viewing the source of a word in Emacs.
14066: * Hilighting:: Making Forth code look prettier.
14067: * Auto-Indentation:: Customizing auto-indentation.
14068: * Blocks Files:: Reading and writing blocks files.
14069: @end menu
14070:
14071: @c ----------------------------------
1.109 anton 14072: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14073: @section Installing gforth.el
14074: @cindex @file{.emacs}
14075: @cindex @file{gforth.el}, installation
14076: To make the features from @file{gforth.el} available in Emacs, add
14077: the following lines to your @file{.emacs} file:
14078:
14079: @example
14080: (autoload 'forth-mode "gforth.el")
14081: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14082: auto-mode-alist))
14083: (autoload 'forth-block-mode "gforth.el")
14084: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14085: auto-mode-alist))
14086: (add-hook 'forth-mode-hook (function (lambda ()
14087: ;; customize variables here:
14088: (setq forth-indent-level 4)
14089: (setq forth-minor-indent-level 2)
14090: (setq forth-hilight-level 3)
14091: ;;; ...
14092: )))
14093: @end example
14094:
14095: @c ----------------------------------
14096: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14097: @section Emacs Tags
1.1 anton 14098: @cindex @file{TAGS} file
14099: @cindex @file{etags.fs}
14100: @cindex viewing the source of a word in Emacs
1.43 anton 14101: @cindex @code{require}, placement in files
14102: @cindex @code{include}, placement in files
1.107 dvdkhlng 14103: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14104: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14105: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14106: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14107: several tags files at the same time (e.g., one for the Gforth sources
14108: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14109: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14110: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14111: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14112: with @file{etags.fs}, you should avoid putting definitions both before
14113: and after @code{require} etc., otherwise you will see the same file
14114: visited several times by commands like @code{tags-search}.
1.1 anton 14115:
1.107 dvdkhlng 14116: @c ----------------------------------
14117: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14118: @section Hilighting
14119: @cindex hilighting Forth code in Emacs
14120: @cindex highlighting Forth code in Emacs
14121: @file{gforth.el} comes with a custom source hilighting engine. When
14122: you open a file in @code{forth-mode}, it will be completely parsed,
14123: assigning faces to keywords, comments, strings etc. While you edit
14124: the file, modified regions get parsed and updated on-the-fly.
14125:
14126: Use the variable `forth-hilight-level' to change the level of
14127: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14128: you set the hilighting level to 0, the parser will still work in the
14129: background, collecting information about whether regions of text are
14130: ``compiled'' or ``interpreted''. Those information are required for
14131: auto-indentation to work properly. Set `forth-disable-parser' to
14132: non-nil if your computer is too slow to handle parsing. This will
14133: have an impact on the smartness of the auto-indentation engine,
14134: though.
14135:
14136: Sometimes Forth sources define new features that should be hilighted,
14137: new control structures, defining-words etc. You can use the variable
14138: `forth-custom-words' to make @code{forth-mode} hilight additional
14139: words and constructs. See the docstring of `forth-words' for details
14140: (in Emacs, type @kbd{C-h v forth-words}).
14141:
14142: `forth-custom-words' is meant to be customized in your
14143: @file{.emacs} file. To customize hilighing in a file-specific manner,
14144: set `forth-local-words' in a local-variables section at the end of
14145: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14146:
14147: Example:
14148: @example
14149: 0 [IF]
14150: Local Variables:
14151: forth-local-words:
14152: ((("t:") definition-starter (font-lock-keyword-face . 1)
14153: "[ \t\n]" t name (font-lock-function-name-face . 3))
14154: ((";t") definition-ender (font-lock-keyword-face . 1)))
14155: End:
14156: [THEN]
14157: @end example
14158:
14159: @c ----------------------------------
14160: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14161: @section Auto-Indentation
14162: @cindex auto-indentation of Forth code in Emacs
14163: @cindex indentation of Forth code in Emacs
14164: @code{forth-mode} automatically tries to indent lines in a smart way,
14165: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14166:
14167: Simple customization can be achieved by setting
14168: `forth-indent-level' and `forth-minor-indent-level' in your
14169: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14170: per default by multiples of 4 columns. To use the more traditional
14171: 3-column indentation, add the following lines to your @file{.emacs}:
14172:
14173: @example
14174: (add-hook 'forth-mode-hook (function (lambda ()
14175: ;; customize variables here:
14176: (setq forth-indent-level 3)
14177: (setq forth-minor-indent-level 1)
14178: )))
14179: @end example
14180:
14181: If you want indentation to recognize non-default words, customize it
14182: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14183: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14184: v forth-indent-words}).
14185:
14186: To customize indentation in a file-specific manner, set
14187: `forth-local-indent-words' in a local-variables section at the end of
14188: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14189: Emacs Manual}).
14190:
14191: Example:
14192: @example
14193: 0 [IF]
14194: Local Variables:
14195: forth-local-indent-words:
14196: ((("t:") (0 . 2) (0 . 2))
14197: ((";t") (-2 . 0) (0 . -2)))
14198: End:
14199: [THEN]
14200: @end example
14201:
14202: @c ----------------------------------
1.109 anton 14203: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14204: @section Blocks Files
14205: @cindex blocks files, use with Emacs
14206: @code{forth-mode} Autodetects blocks files by checking whether the
14207: length of the first line exceeds 1023 characters. It then tries to
14208: convert the file into normal text format. When you save the file, it
14209: will be written to disk as normal stream-source file.
14210:
14211: If you want to write blocks files, use @code{forth-blocks-mode}. It
14212: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14213:
1.107 dvdkhlng 14214: @itemize @bullet
14215: @item
14216: Files are written to disk in blocks file format.
14217: @item
14218: Screen numbers are displayed in the mode line (enumerated beginning
14219: with the value of `forth-block-base')
14220: @item
14221: Warnings are displayed when lines exceed 64 characters.
14222: @item
14223: The beginning of the currently edited block is marked with an
14224: overlay-arrow.
14225: @end itemize
1.41 anton 14226:
1.107 dvdkhlng 14227: There are some restrictions you should be aware of. When you open a
14228: blocks file that contains tabulator or newline characters, these
14229: characters will be translated into spaces when the file is written
14230: back to disk. If tabs or newlines are encountered during blocks file
14231: reading, an error is output to the echo area. So have a look at the
14232: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14233:
1.107 dvdkhlng 14234: Please consult the docstring of @code{forth-blocks-mode} for more
14235: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14236:
1.26 crook 14237: @c ******************************************************************
1.1 anton 14238: @node Image Files, Engine, Emacs and Gforth, Top
14239: @chapter Image Files
1.26 crook 14240: @cindex image file
14241: @cindex @file{.fi} files
1.1 anton 14242: @cindex precompiled Forth code
14243: @cindex dictionary in persistent form
14244: @cindex persistent form of dictionary
14245:
14246: An image file is a file containing an image of the Forth dictionary,
14247: i.e., compiled Forth code and data residing in the dictionary. By
14248: convention, we use the extension @code{.fi} for image files.
14249:
14250: @menu
1.18 anton 14251: * Image Licensing Issues:: Distribution terms for images.
14252: * Image File Background:: Why have image files?
1.67 anton 14253: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14254: * Data-Relocatable Image Files:: are better.
1.67 anton 14255: * Fully Relocatable Image Files:: better yet.
1.18 anton 14256: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14257: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14258: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14259: @end menu
14260:
1.18 anton 14261: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14262: @section Image Licensing Issues
14263: @cindex license for images
14264: @cindex image license
14265:
14266: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14267: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14268: original image; i.e., according to copyright law it is a derived work of
14269: the original image.
14270:
14271: Since Gforth is distributed under the GNU GPL, the newly created image
14272: falls under the GNU GPL, too. In particular, this means that if you
14273: distribute the image, you have to make all of the sources for the image
1.113 anton 14274: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14275: GNU General Public License (Section 3)}.
14276:
14277: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14278: contains only code compiled from the sources you gave it; if none of
14279: these sources is under the GPL, the terms discussed above do not apply
14280: to the image. However, if your image needs an engine (a gforth binary)
14281: that is under the GPL, you should make sure that you distribute both in
14282: a way that is at most a @emph{mere aggregation}, if you don't want the
14283: terms of the GPL to apply to the image.
14284:
14285: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14286: @section Image File Background
14287: @cindex image file background
14288:
1.80 anton 14289: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14290: definitions written in Forth. Since the Forth compiler itself belongs to
14291: those definitions, it is not possible to start the system with the
1.80 anton 14292: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14293: code as an image file in nearly executable form. When Gforth starts up,
14294: a C routine loads the image file into memory, optionally relocates the
14295: addresses, then sets up the memory (stacks etc.) according to
14296: information in the image file, and (finally) starts executing Forth
14297: code.
1.1 anton 14298:
14299: The image file variants represent different compromises between the
14300: goals of making it easy to generate image files and making them
14301: portable.
14302:
14303: @cindex relocation at run-time
1.26 crook 14304: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14305: run-time. This avoids many of the complications discussed below (image
14306: files are data relocatable without further ado), but costs performance
14307: (one addition per memory access).
14308:
14309: @cindex relocation at load-time
1.26 crook 14310: By contrast, the Gforth loader performs relocation at image load time. The
14311: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14312: appropriate code-field addresses (or code addresses in the case of
14313: direct threading).
14314:
14315: There are three kinds of image files, with different degrees of
14316: relocatability: non-relocatable, data-relocatable, and fully relocatable
14317: image files.
14318:
14319: @cindex image file loader
14320: @cindex relocating loader
14321: @cindex loader for image files
14322: These image file variants have several restrictions in common; they are
14323: caused by the design of the image file loader:
14324:
14325: @itemize @bullet
14326: @item
14327: There is only one segment; in particular, this means, that an image file
14328: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14329: them). The contents of the stacks are not represented, either.
1.1 anton 14330:
14331: @item
14332: The only kinds of relocation supported are: adding the same offset to
14333: all cells that represent data addresses; and replacing special tokens
14334: with code addresses or with pieces of machine code.
14335:
14336: If any complex computations involving addresses are performed, the
14337: results cannot be represented in the image file. Several applications that
14338: use such computations come to mind:
14339: @itemize @minus
14340: @item
14341: Hashing addresses (or data structures which contain addresses) for table
14342: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14343: purpose, you will have no problem, because the hash tables are
14344: recomputed automatically when the system is started. If you use your own
14345: hash tables, you will have to do something similar.
14346:
14347: @item
14348: There's a cute implementation of doubly-linked lists that uses
14349: @code{XOR}ed addresses. You could represent such lists as singly-linked
14350: in the image file, and restore the doubly-linked representation on
14351: startup.@footnote{In my opinion, though, you should think thrice before
14352: using a doubly-linked list (whatever implementation).}
14353:
14354: @item
14355: The code addresses of run-time routines like @code{docol:} cannot be
14356: represented in the image file (because their tokens would be replaced by
14357: machine code in direct threaded implementations). As a workaround,
14358: compute these addresses at run-time with @code{>code-address} from the
14359: executions tokens of appropriate words (see the definitions of
1.80 anton 14360: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14361:
14362: @item
14363: On many architectures addresses are represented in machine code in some
14364: shifted or mangled form. You cannot put @code{CODE} words that contain
14365: absolute addresses in this form in a relocatable image file. Workarounds
14366: are representing the address in some relative form (e.g., relative to
14367: the CFA, which is present in some register), or loading the address from
14368: a place where it is stored in a non-mangled form.
14369: @end itemize
14370: @end itemize
14371:
14372: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14373: @section Non-Relocatable Image Files
14374: @cindex non-relocatable image files
1.26 crook 14375: @cindex image file, non-relocatable
1.1 anton 14376:
14377: These files are simple memory dumps of the dictionary. They are specific
14378: to the executable (i.e., @file{gforth} file) they were created
14379: with. What's worse, they are specific to the place on which the
14380: dictionary resided when the image was created. Now, there is no
14381: guarantee that the dictionary will reside at the same place the next
14382: time you start Gforth, so there's no guarantee that a non-relocatable
14383: image will work the next time (Gforth will complain instead of crashing,
14384: though).
14385:
14386: You can create a non-relocatable image file with
14387:
1.44 crook 14388:
1.1 anton 14389: doc-savesystem
14390:
1.44 crook 14391:
1.1 anton 14392: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14393: @section Data-Relocatable Image Files
14394: @cindex data-relocatable image files
1.26 crook 14395: @cindex image file, data-relocatable
1.1 anton 14396:
14397: These files contain relocatable data addresses, but fixed code addresses
14398: (instead of tokens). They are specific to the executable (i.e.,
14399: @file{gforth} file) they were created with. For direct threading on some
14400: architectures (e.g., the i386), data-relocatable images do not work. You
14401: get a data-relocatable image, if you use @file{gforthmi} with a
14402: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14403: Relocatable Image Files}).
14404:
14405: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14406: @section Fully Relocatable Image Files
14407: @cindex fully relocatable image files
1.26 crook 14408: @cindex image file, fully relocatable
1.1 anton 14409:
14410: @cindex @file{kern*.fi}, relocatability
14411: @cindex @file{gforth.fi}, relocatability
14412: These image files have relocatable data addresses, and tokens for code
14413: addresses. They can be used with different binaries (e.g., with and
14414: without debugging) on the same machine, and even across machines with
14415: the same data formats (byte order, cell size, floating point
14416: format). However, they are usually specific to the version of Gforth
14417: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14418: are fully relocatable.
14419:
14420: There are two ways to create a fully relocatable image file:
14421:
14422: @menu
1.29 crook 14423: * gforthmi:: The normal way
1.1 anton 14424: * cross.fs:: The hard way
14425: @end menu
14426:
14427: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14428: @subsection @file{gforthmi}
14429: @cindex @file{comp-i.fs}
14430: @cindex @file{gforthmi}
14431:
14432: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14433: image @i{file} that contains everything you would load by invoking
14434: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14435: @example
1.29 crook 14436: gforthmi @i{file} @i{options}
1.1 anton 14437: @end example
14438:
14439: E.g., if you want to create an image @file{asm.fi} that has the file
14440: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14441: like this:
14442:
14443: @example
14444: gforthmi asm.fi asm.fs
14445: @end example
14446:
1.27 crook 14447: @file{gforthmi} is implemented as a sh script and works like this: It
14448: produces two non-relocatable images for different addresses and then
14449: compares them. Its output reflects this: first you see the output (if
1.62 crook 14450: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14451: files, then you see the output of the comparing program: It displays the
14452: offset used for data addresses and the offset used for code addresses;
1.1 anton 14453: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14454: image files, it displays a line like this:
1.1 anton 14455:
14456: @example
14457: 78DC BFFFFA50 BFFFFA40
14458: @end example
14459:
14460: This means that at offset $78dc from @code{forthstart}, one input image
14461: contains $bffffa50, and the other contains $bffffa40. Since these cells
14462: cannot be represented correctly in the output image, you should examine
14463: these places in the dictionary and verify that these cells are dead
14464: (i.e., not read before they are written).
1.39 anton 14465:
14466: @cindex --application, @code{gforthmi} option
14467: If you insert the option @code{--application} in front of the image file
14468: name, you will get an image that uses the @code{--appl-image} option
14469: instead of the @code{--image-file} option (@pxref{Invoking
14470: Gforth}). When you execute such an image on Unix (by typing the image
14471: name as command), the Gforth engine will pass all options to the image
14472: instead of trying to interpret them as engine options.
1.1 anton 14473:
1.27 crook 14474: If you type @file{gforthmi} with no arguments, it prints some usage
14475: instructions.
14476:
1.1 anton 14477: @cindex @code{savesystem} during @file{gforthmi}
14478: @cindex @code{bye} during @file{gforthmi}
14479: @cindex doubly indirect threaded code
1.44 crook 14480: @cindex environment variables
14481: @cindex @code{GFORTHD} -- environment variable
14482: @cindex @code{GFORTH} -- environment variable
1.1 anton 14483: @cindex @code{gforth-ditc}
1.29 crook 14484: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14485: words @code{savesystem} and @code{bye} must be visible. A special doubly
14486: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14487: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14488: this executable through the environment variable @code{GFORTHD}
14489: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14490: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14491: data-relocatable image (because there is no code address offset). The
14492: normal @file{gforth} executable is used for creating the relocatable
14493: image; you can pass the exact filename of this executable through the
14494: environment variable @code{GFORTH}.
1.1 anton 14495:
14496: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14497: @subsection @file{cross.fs}
14498: @cindex @file{cross.fs}
14499: @cindex cross-compiler
14500: @cindex metacompiler
1.47 crook 14501: @cindex target compiler
1.1 anton 14502:
14503: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14504: programming language (@pxref{Cross Compiler}).
1.1 anton 14505:
1.47 crook 14506: @code{cross} allows you to create image files for machines with
1.1 anton 14507: different data sizes and data formats than the one used for generating
14508: the image file. You can also use it to create an application image that
14509: does not contain a Forth compiler. These features are bought with
14510: restrictions and inconveniences in programming. E.g., addresses have to
14511: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14512: order to make the code relocatable.
14513:
14514:
14515: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14516: @section Stack and Dictionary Sizes
14517: @cindex image file, stack and dictionary sizes
14518: @cindex dictionary size default
14519: @cindex stack size default
14520:
14521: If you invoke Gforth with a command line flag for the size
14522: (@pxref{Invoking Gforth}), the size you specify is stored in the
14523: dictionary. If you save the dictionary with @code{savesystem} or create
14524: an image with @file{gforthmi}, this size will become the default
14525: for the resulting image file. E.g., the following will create a
1.21 crook 14526: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14527:
14528: @example
14529: gforthmi gforth.fi -m 1M
14530: @end example
14531:
14532: In other words, if you want to set the default size for the dictionary
14533: and the stacks of an image, just invoke @file{gforthmi} with the
14534: appropriate options when creating the image.
14535:
14536: @cindex stack size, cache-friendly
14537: Note: For cache-friendly behaviour (i.e., good performance), you should
14538: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14539: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14540: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14541:
14542: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14543: @section Running Image Files
14544: @cindex running image files
14545: @cindex invoking image files
14546: @cindex image file invocation
14547:
14548: @cindex -i, invoke image file
14549: @cindex --image file, invoke image file
1.29 crook 14550: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14551: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14552: @example
1.29 crook 14553: gforth -i @i{image}
1.1 anton 14554: @end example
14555:
14556: @cindex executable image file
1.26 crook 14557: @cindex image file, executable
1.1 anton 14558: If your operating system supports starting scripts with a line of the
14559: form @code{#! ...}, you just have to type the image file name to start
14560: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14561: just a convention). I.e., to run Gforth with the image file @i{image},
14562: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14563: This works because every @code{.fi} file starts with a line of this
14564: format:
14565:
14566: @example
14567: #! /usr/local/bin/gforth-0.4.0 -i
14568: @end example
14569:
14570: The file and pathname for the Gforth engine specified on this line is
14571: the specific Gforth executable that it was built against; i.e. the value
14572: of the environment variable @code{GFORTH} at the time that
14573: @file{gforthmi} was executed.
1.1 anton 14574:
1.27 crook 14575: You can make use of the same shell capability to make a Forth source
14576: file into an executable. For example, if you place this text in a file:
1.26 crook 14577:
14578: @example
14579: #! /usr/local/bin/gforth
14580:
14581: ." Hello, world" CR
14582: bye
14583: @end example
14584:
14585: @noindent
1.27 crook 14586: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14587: directly from the command line. The sequence @code{#!} is used in two
14588: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14589: system@footnote{The Unix kernel actually recognises two types of files:
14590: executable files and files of data, where the data is processed by an
14591: interpreter that is specified on the ``interpreter line'' -- the first
14592: line of the file, starting with the sequence #!. There may be a small
14593: limit (e.g., 32) on the number of characters that may be specified on
14594: the interpreter line.} secondly it is treated as a comment character by
14595: Gforth. Because of the second usage, a space is required between
1.80 anton 14596: @code{#!} and the path to the executable (moreover, some Unixes
14597: require the sequence @code{#! /}).
1.27 crook 14598:
14599: The disadvantage of this latter technique, compared with using
1.80 anton 14600: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14601: compiled on-the-fly, each time the program is invoked.
1.26 crook 14602:
1.1 anton 14603: doc-#!
14604:
1.44 crook 14605:
1.1 anton 14606: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14607: @section Modifying the Startup Sequence
14608: @cindex startup sequence for image file
14609: @cindex image file initialization sequence
14610: @cindex initialization sequence of image file
14611:
1.120 anton 14612: You can add your own initialization to the startup sequence of an image
14613: through the deferred word @code{'cold}. @code{'cold} is invoked just
14614: before the image-specific command line processing (i.e., loading files
14615: and evaluating (@code{-e}) strings) starts.
1.1 anton 14616:
14617: A sequence for adding your initialization usually looks like this:
14618:
14619: @example
14620: :noname
14621: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14622: ... \ your stuff
14623: ; IS 'cold
14624: @end example
14625:
14626: @cindex turnkey image files
1.26 crook 14627: @cindex image file, turnkey applications
1.1 anton 14628: You can make a turnkey image by letting @code{'cold} execute a word
14629: (your turnkey application) that never returns; instead, it exits Gforth
14630: via @code{bye} or @code{throw}.
14631:
1.121 anton 14632: You can access the (image-specific) command-line arguments through
14633: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14634: arguments}).
1.1 anton 14635:
1.26 crook 14636: If @code{'cold} exits normally, Gforth processes the command-line
14637: arguments as files to be loaded and strings to be evaluated. Therefore,
14638: @code{'cold} should remove the arguments it has used in this case.
14639:
14640: doc-'cold
1.44 crook 14641:
1.1 anton 14642: @c ******************************************************************
1.113 anton 14643: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14644: @chapter Engine
14645: @cindex engine
14646: @cindex virtual machine
14647:
1.26 crook 14648: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14649: may be helpful for finding your way in the Gforth sources.
14650:
1.109 anton 14651: The ideas in this section have also been published in the following
14652: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14653: Forth-Tagung '93; M. Anton Ertl,
14654: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14655: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14656: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14657: Threaded code variations and optimizations (extended version)}},
14658: Forth-Tagung '02.
1.1 anton 14659:
14660: @menu
14661: * Portability::
14662: * Threading::
14663: * Primitives::
14664: * Performance::
14665: @end menu
14666:
14667: @node Portability, Threading, Engine, Engine
14668: @section Portability
14669: @cindex engine portability
14670:
1.26 crook 14671: An important goal of the Gforth Project is availability across a wide
14672: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14673: achieved this goal by manually coding the engine in assembly language
14674: for several then-popular processors. This approach is very
14675: labor-intensive and the results are short-lived due to progress in
14676: computer architecture.
1.1 anton 14677:
14678: @cindex C, using C for the engine
14679: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14680: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14681: particularly popular for UNIX-based Forths due to the large variety of
14682: architectures of UNIX machines. Unfortunately an implementation in C
14683: does not mix well with the goals of efficiency and with using
14684: traditional techniques: Indirect or direct threading cannot be expressed
14685: in C, and switch threading, the fastest technique available in C, is
14686: significantly slower. Another problem with C is that it is very
14687: cumbersome to express double integer arithmetic.
14688:
14689: @cindex GNU C for the engine
14690: @cindex long long
14691: Fortunately, there is a portable language that does not have these
14692: limitations: GNU C, the version of C processed by the GNU C compiler
14693: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14694: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14695: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14696: threading possible, its @code{long long} type (@pxref{Long Long, ,
14697: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14698: double numbers on many systems. GNU C is freely available on all
1.1 anton 14699: important (and many unimportant) UNIX machines, VMS, 80386s running
14700: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14701: on all these machines.
14702:
14703: Writing in a portable language has the reputation of producing code that
14704: is slower than assembly. For our Forth engine we repeatedly looked at
14705: the code produced by the compiler and eliminated most compiler-induced
14706: inefficiencies by appropriate changes in the source code.
14707:
14708: @cindex explicit register declarations
14709: @cindex --enable-force-reg, configuration flag
14710: @cindex -DFORCE_REG
14711: However, register allocation cannot be portably influenced by the
14712: programmer, leading to some inefficiencies on register-starved
14713: machines. We use explicit register declarations (@pxref{Explicit Reg
14714: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14715: improve the speed on some machines. They are turned on by using the
14716: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14717: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14718: machine, but also on the compiler version: On some machines some
14719: compiler versions produce incorrect code when certain explicit register
14720: declarations are used. So by default @code{-DFORCE_REG} is not used.
14721:
14722: @node Threading, Primitives, Portability, Engine
14723: @section Threading
14724: @cindex inner interpreter implementation
14725: @cindex threaded code implementation
14726:
14727: @cindex labels as values
14728: GNU C's labels as values extension (available since @code{gcc-2.0},
14729: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14730: makes it possible to take the address of @i{label} by writing
14731: @code{&&@i{label}}. This address can then be used in a statement like
14732: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14733: @code{goto x}.
14734:
1.26 crook 14735: @cindex @code{NEXT}, indirect threaded
1.1 anton 14736: @cindex indirect threaded inner interpreter
14737: @cindex inner interpreter, indirect threaded
1.26 crook 14738: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14739: @example
14740: cfa = *ip++;
14741: ca = *cfa;
14742: goto *ca;
14743: @end example
14744: @cindex instruction pointer
14745: For those unfamiliar with the names: @code{ip} is the Forth instruction
14746: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14747: execution token and points to the code field of the next word to be
14748: executed; The @code{ca} (code address) fetched from there points to some
14749: executable code, e.g., a primitive or the colon definition handler
14750: @code{docol}.
14751:
1.26 crook 14752: @cindex @code{NEXT}, direct threaded
1.1 anton 14753: @cindex direct threaded inner interpreter
14754: @cindex inner interpreter, direct threaded
14755: Direct threading is even simpler:
14756: @example
14757: ca = *ip++;
14758: goto *ca;
14759: @end example
14760:
14761: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14762: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14763:
14764: @menu
14765: * Scheduling::
14766: * Direct or Indirect Threaded?::
1.109 anton 14767: * Dynamic Superinstructions::
1.1 anton 14768: * DOES>::
14769: @end menu
14770:
14771: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14772: @subsection Scheduling
14773: @cindex inner interpreter optimization
14774:
14775: There is a little complication: Pipelined and superscalar processors,
14776: i.e., RISC and some modern CISC machines can process independent
14777: instructions while waiting for the results of an instruction. The
14778: compiler usually reorders (schedules) the instructions in a way that
14779: achieves good usage of these delay slots. However, on our first tries
14780: the compiler did not do well on scheduling primitives. E.g., for
14781: @code{+} implemented as
14782: @example
14783: n=sp[0]+sp[1];
14784: sp++;
14785: sp[0]=n;
14786: NEXT;
14787: @end example
1.81 anton 14788: the @code{NEXT} comes strictly after the other code, i.e., there is
14789: nearly no scheduling. After a little thought the problem becomes clear:
14790: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14791: addresses (and the version of @code{gcc} we used would not know it even
14792: if it was possible), so it could not move the load of the cfa above the
14793: store to the TOS. Indeed the pointers could be the same, if code on or
14794: very near the top of stack were executed. In the interest of speed we
14795: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14796: in scheduling: @code{NEXT} is divided into several parts:
14797: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14798: like:
1.1 anton 14799: @example
1.81 anton 14800: NEXT_P0;
1.1 anton 14801: n=sp[0]+sp[1];
14802: sp++;
14803: NEXT_P1;
14804: sp[0]=n;
14805: NEXT_P2;
14806: @end example
14807:
1.81 anton 14808: There are various schemes that distribute the different operations of
14809: NEXT between these parts in several ways; in general, different schemes
14810: perform best on different processors. We use a scheme for most
14811: architectures that performs well for most processors of this
1.109 anton 14812: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14813: the scheme on installation time.
14814:
1.1 anton 14815:
1.109 anton 14816: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14817: @subsection Direct or Indirect Threaded?
14818: @cindex threading, direct or indirect?
14819:
1.109 anton 14820: Threaded forth code consists of references to primitives (simple machine
14821: code routines like @code{+}) and to non-primitives (e.g., colon
14822: definitions, variables, constants); for a specific class of
14823: non-primitives (e.g., variables) there is one code routine (e.g.,
14824: @code{dovar}), but each variable needs a separate reference to its data.
14825:
14826: Traditionally Forth has been implemented as indirect threaded code,
14827: because this allows to use only one cell to reference a non-primitive
14828: (basically you point to the data, and find the code address there).
14829:
14830: @cindex primitive-centric threaded code
14831: However, threaded code in Gforth (since 0.6.0) uses two cells for
14832: non-primitives, one for the code address, and one for the data address;
14833: the data pointer is an immediate argument for the virtual machine
14834: instruction represented by the code address. We call this
14835: @emph{primitive-centric} threaded code, because all code addresses point
14836: to simple primitives. E.g., for a variable, the code address is for
14837: @code{lit} (also used for integer literals like @code{99}).
14838:
14839: Primitive-centric threaded code allows us to use (faster) direct
14840: threading as dispatch method, completely portably (direct threaded code
14841: in Gforth before 0.6.0 required architecture-specific code). It also
14842: eliminates the performance problems related to I-cache consistency that
14843: 386 implementations have with direct threaded code, and allows
14844: additional optimizations.
14845:
14846: @cindex hybrid direct/indirect threaded code
14847: There is a catch, however: the @var{xt} parameter of @code{execute} can
14848: occupy only one cell, so how do we pass non-primitives with their code
14849: @emph{and} data addresses to them? Our answer is to use indirect
14850: threaded dispatch for @code{execute} and other words that use a
14851: single-cell xt. So, normal threaded code in colon definitions uses
14852: direct threading, and @code{execute} and similar words, which dispatch
14853: to xts on the data stack, use indirect threaded code. We call this
14854: @emph{hybrid direct/indirect} threaded code.
14855:
14856: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14857: @cindex gforth engine
14858: @cindex gforth-fast engine
14859: The engines @command{gforth} and @command{gforth-fast} use hybrid
14860: direct/indirect threaded code. This means that with these engines you
14861: cannot use @code{,} to compile an xt. Instead, you have to use
14862: @code{compile,}.
14863:
14864: @cindex gforth-itc engine
1.115 anton 14865: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14866: This engine uses plain old indirect threaded code. It still compiles in
14867: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14868: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14869: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14870: and execute @code{' , is compile,}. Your program can check if it is
14871: running on a hybrid direct/indirect threaded engine or a pure indirect
14872: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14873:
14874:
14875: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14876: @subsection Dynamic Superinstructions
14877: @cindex Dynamic superinstructions with replication
14878: @cindex Superinstructions
14879: @cindex Replication
14880:
14881: The engines @command{gforth} and @command{gforth-fast} use another
14882: optimization: Dynamic superinstructions with replication. As an
14883: example, consider the following colon definition:
14884:
14885: @example
14886: : squared ( n1 -- n2 )
14887: dup * ;
14888: @end example
14889:
14890: Gforth compiles this into the threaded code sequence
14891:
14892: @example
14893: dup
14894: *
14895: ;s
14896: @end example
14897:
14898: In normal direct threaded code there is a code address occupying one
14899: cell for each of these primitives. Each code address points to a
14900: machine code routine, and the interpreter jumps to this machine code in
14901: order to execute the primitive. The routines for these three
14902: primitives are (in @command{gforth-fast} on the 386):
14903:
14904: @example
14905: Code dup
14906: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14907: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14908: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14909: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14910: end-code
14911: Code *
14912: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14913: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14914: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14915: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14916: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14917: end-code
14918: Code ;s
14919: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14920: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14921: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14922: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14923: end-code
14924: @end example
14925:
14926: With dynamic superinstructions and replication the compiler does not
14927: just lay down the threaded code, but also copies the machine code
14928: fragments, usually without the jump at the end.
14929:
14930: @example
14931: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14932: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14933: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14934: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14935: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14936: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14937: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14938: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14939: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14940: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14941: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14942: @end example
14943:
14944: Only when a threaded-code control-flow change happens (e.g., in
14945: @code{;s}), the jump is appended. This optimization eliminates many of
14946: these jumps and makes the rest much more predictable. The speedup
14947: depends on the processor and the application; on the Athlon and Pentium
14948: III this optimization typically produces a speedup by a factor of 2.
14949:
14950: The code addresses in the direct-threaded code are set to point to the
14951: appropriate points in the copied machine code, in this example like
14952: this:
1.1 anton 14953:
1.109 anton 14954: @example
14955: primitive code address
14956: dup $4057D27D
14957: * $4057D286
14958: ;s $4057D292
14959: @end example
14960:
14961: Thus there can be threaded-code jumps to any place in this piece of
14962: code. This also simplifies decompilation quite a bit.
14963:
14964: @cindex --no-dynamic command-line option
14965: @cindex --no-super command-line option
14966: You can disable this optimization with @option{--no-dynamic}. You can
14967: use the copying without eliminating the jumps (i.e., dynamic
14968: replication, but without superinstructions) with @option{--no-super};
14969: this gives the branch prediction benefit alone; the effect on
1.110 anton 14970: performance depends on the CPU; on the Athlon and Pentium III the
14971: speedup is a little less than for dynamic superinstructions with
14972: replication.
14973:
14974: @cindex patching threaded code
14975: One use of these options is if you want to patch the threaded code.
14976: With superinstructions, many of the dispatch jumps are eliminated, so
14977: patching often has no effect. These options preserve all the dispatch
14978: jumps.
1.109 anton 14979:
14980: @cindex --dynamic command-line option
1.110 anton 14981: On some machines dynamic superinstructions are disabled by default,
14982: because it is unsafe on these machines. However, if you feel
14983: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14984:
14985: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14986: @subsection DOES>
14987: @cindex @code{DOES>} implementation
14988:
1.26 crook 14989: @cindex @code{dodoes} routine
14990: @cindex @code{DOES>}-code
1.1 anton 14991: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14992: the chunk of code executed by every word defined by a
1.109 anton 14993: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14994: this is only needed if the xt of the word is @code{execute}d. The main
14995: problem here is: How to find the Forth code to be executed, i.e. the
14996: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14997: solutions:
1.1 anton 14998:
1.21 crook 14999: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15000: @code{DOES>}-code address is stored in the cell after the code address
15001: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15002: illegal in the Forth-79 and all later standards, because in fig-Forth
15003: this address lies in the body (which is illegal in these
15004: standards). However, by making the code field larger for all words this
15005: solution becomes legal again. We use this approach. Leaving a cell
15006: unused in most words is a bit wasteful, but on the machines we are
15007: targeting this is hardly a problem.
15008:
1.1 anton 15009:
15010: @node Primitives, Performance, Threading, Engine
15011: @section Primitives
15012: @cindex primitives, implementation
15013: @cindex virtual machine instructions, implementation
15014:
15015: @menu
15016: * Automatic Generation::
15017: * TOS Optimization::
15018: * Produced code::
15019: @end menu
15020:
15021: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15022: @subsection Automatic Generation
15023: @cindex primitives, automatic generation
15024:
15025: @cindex @file{prims2x.fs}
1.109 anton 15026:
1.1 anton 15027: Since the primitives are implemented in a portable language, there is no
15028: longer any need to minimize the number of primitives. On the contrary,
15029: having many primitives has an advantage: speed. In order to reduce the
15030: number of errors in primitives and to make programming them easier, we
1.109 anton 15031: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15032: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15033: generates most (and sometimes all) of the C code for a primitive from
15034: the stack effect notation. The source for a primitive has the following
15035: form:
1.1 anton 15036:
15037: @cindex primitive source format
15038: @format
1.58 anton 15039: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15040: [@code{""}@i{glossary entry}@code{""}]
15041: @i{C code}
1.1 anton 15042: [@code{:}
1.29 crook 15043: @i{Forth code}]
1.1 anton 15044: @end format
15045:
15046: The items in brackets are optional. The category and glossary fields
15047: are there for generating the documentation, the Forth code is there
15048: for manual implementations on machines without GNU C. E.g., the source
15049: for the primitive @code{+} is:
15050: @example
1.58 anton 15051: + ( n1 n2 -- n ) core plus
1.1 anton 15052: n = n1+n2;
15053: @end example
15054:
15055: This looks like a specification, but in fact @code{n = n1+n2} is C
15056: code. Our primitive generation tool extracts a lot of information from
15057: the stack effect notations@footnote{We use a one-stack notation, even
15058: though we have separate data and floating-point stacks; The separate
15059: notation can be generated easily from the unified notation.}: The number
15060: of items popped from and pushed on the stack, their type, and by what
15061: name they are referred to in the C code. It then generates a C code
15062: prelude and postlude for each primitive. The final C code for @code{+}
15063: looks like this:
15064:
15065: @example
1.46 pazsan 15066: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15067: /* */ /* documentation */
1.81 anton 15068: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15069: @{
15070: DEF_CA /* definition of variable ca (indirect threading) */
15071: Cell n1; /* definitions of variables */
15072: Cell n2;
15073: Cell n;
1.81 anton 15074: NEXT_P0; /* NEXT part 0 */
1.1 anton 15075: n1 = (Cell) sp[1]; /* input */
15076: n2 = (Cell) TOS;
15077: sp += 1; /* stack adjustment */
15078: @{
15079: n = n1+n2; /* C code taken from the source */
15080: @}
15081: NEXT_P1; /* NEXT part 1 */
15082: TOS = (Cell)n; /* output */
15083: NEXT_P2; /* NEXT part 2 */
15084: @}
15085: @end example
15086:
15087: This looks long and inefficient, but the GNU C compiler optimizes quite
15088: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15089: HP RISC machines: Defining the @code{n}s does not produce any code, and
15090: using them as intermediate storage also adds no cost.
15091:
1.26 crook 15092: There are also other optimizations that are not illustrated by this
15093: example: assignments between simple variables are usually for free (copy
1.1 anton 15094: propagation). If one of the stack items is not used by the primitive
15095: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15096: (dead code elimination). On the other hand, there are some things that
15097: the compiler does not do, therefore they are performed by
15098: @file{prims2x.fs}: The compiler does not optimize code away that stores
15099: a stack item to the place where it just came from (e.g., @code{over}).
15100:
15101: While programming a primitive is usually easy, there are a few cases
15102: where the programmer has to take the actions of the generator into
15103: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15104: fall through to @code{NEXT}.
1.109 anton 15105:
15106: For more information
1.1 anton 15107:
15108: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15109: @subsection TOS Optimization
15110: @cindex TOS optimization for primitives
15111: @cindex primitives, keeping the TOS in a register
15112:
15113: An important optimization for stack machine emulators, e.g., Forth
15114: engines, is keeping one or more of the top stack items in
1.29 crook 15115: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15116: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15117: @itemize @bullet
15118: @item
1.29 crook 15119: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15120: due to fewer loads from and stores to the stack.
1.29 crook 15121: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15122: @i{y<n}, due to additional moves between registers.
1.1 anton 15123: @end itemize
15124:
15125: @cindex -DUSE_TOS
15126: @cindex -DUSE_NO_TOS
15127: In particular, keeping one item in a register is never a disadvantage,
15128: if there are enough registers. Keeping two items in registers is a
15129: disadvantage for frequent words like @code{?branch}, constants,
15130: variables, literals and @code{i}. Therefore our generator only produces
15131: code that keeps zero or one items in registers. The generated C code
15132: covers both cases; the selection between these alternatives is made at
15133: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15134: code for @code{+} is just a simple variable name in the one-item case,
15135: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15136: GNU C compiler tries to keep simple variables like @code{TOS} in
15137: registers, and it usually succeeds, if there are enough registers.
15138:
15139: @cindex -DUSE_FTOS
15140: @cindex -DUSE_NO_FTOS
15141: The primitive generator performs the TOS optimization for the
15142: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15143: operations the benefit of this optimization is even larger:
15144: floating-point operations take quite long on most processors, but can be
15145: performed in parallel with other operations as long as their results are
15146: not used. If the FP-TOS is kept in a register, this works. If
15147: it is kept on the stack, i.e., in memory, the store into memory has to
15148: wait for the result of the floating-point operation, lengthening the
15149: execution time of the primitive considerably.
15150:
15151: The TOS optimization makes the automatic generation of primitives a
15152: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15153: @code{TOS} is not sufficient. There are some special cases to
15154: consider:
15155: @itemize @bullet
15156: @item In the case of @code{dup ( w -- w w )} the generator must not
15157: eliminate the store to the original location of the item on the stack,
15158: if the TOS optimization is turned on.
15159: @item Primitives with stack effects of the form @code{--}
1.29 crook 15160: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15161: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15162: must load the TOS from the stack at the end. But for the null stack
15163: effect @code{--} no stores or loads should be generated.
15164: @end itemize
15165:
15166: @node Produced code, , TOS Optimization, Primitives
15167: @subsection Produced code
15168: @cindex primitives, assembly code listing
15169:
15170: @cindex @file{engine.s}
15171: To see what assembly code is produced for the primitives on your machine
15172: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15173: look at the resulting file @file{engine.s}. Alternatively, you can also
15174: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15175:
15176: @node Performance, , Primitives, Engine
15177: @section Performance
15178: @cindex performance of some Forth interpreters
15179: @cindex engine performance
15180: @cindex benchmarking Forth systems
15181: @cindex Gforth performance
15182:
15183: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15184: impossible to write a significantly faster threaded-code engine.
1.1 anton 15185:
15186: On register-starved machines like the 386 architecture processors
15187: improvements are possible, because @code{gcc} does not utilize the
15188: registers as well as a human, even with explicit register declarations;
15189: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15190: and hand-tuned it for the 486; this system is 1.19 times faster on the
15191: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15192: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15193: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15194: registers fit in real registers (and we can even afford to use the TOS
15195: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15196: earlier results. And dynamic superinstructions provide another speedup
15197: (but only around a factor 1.2 on the 486).
1.1 anton 15198:
15199: @cindex Win32Forth performance
15200: @cindex NT Forth performance
15201: @cindex eforth performance
15202: @cindex ThisForth performance
15203: @cindex PFE performance
15204: @cindex TILE performance
1.81 anton 15205: The potential advantage of assembly language implementations is not
1.112 anton 15206: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15207: (direct threaded, compiled with @code{gcc-2.95.1} and
15208: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15209: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15210: (with and without peephole (aka pinhole) optimization of the threaded
15211: code); all these systems were written in assembly language. We also
15212: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15213: with @code{gcc-2.6.3} with the default configuration for Linux:
15214: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15215: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15216: employs peephole optimization of the threaded code) and TILE (compiled
15217: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15218: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15219: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15220: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15221: then extended it to run the benchmarks, added the peephole optimizer,
15222: ran the benchmarks and reported the results.
1.40 anton 15223:
1.1 anton 15224: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15225: matrix multiplication come from the Stanford integer benchmarks and have
15226: been translated into Forth by Martin Fraeman; we used the versions
15227: included in the TILE Forth package, but with bigger data set sizes; and
15228: a recursive Fibonacci number computation for benchmarking calling
15229: performance. The following table shows the time taken for the benchmarks
15230: scaled by the time taken by Gforth (in other words, it shows the speedup
15231: factor that Gforth achieved over the other systems).
15232:
15233: @example
1.112 anton 15234: relative Win32- NT eforth This-
15235: time Gforth Forth Forth eforth +opt PFE Forth TILE
15236: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15237: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15238: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15239: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15240: @end example
15241:
1.26 crook 15242: You may be quite surprised by the good performance of Gforth when
15243: compared with systems written in assembly language. One important reason
15244: for the disappointing performance of these other systems is probably
15245: that they are not written optimally for the 486 (e.g., they use the
15246: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15247: but costly method for relocating the Forth image: like @code{cforth}, it
15248: computes the actual addresses at run time, resulting in two address
15249: computations per @code{NEXT} (@pxref{Image File Background}).
15250:
1.1 anton 15251: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15252: explained with the self-imposed restriction of the latter systems to
15253: standard C, which makes efficient threading impossible (however, the
1.4 anton 15254: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15255: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15256: Moreover, current C compilers have a hard time optimizing other aspects
15257: of the ThisForth and the TILE source.
15258:
1.26 crook 15259: The performance of Gforth on 386 architecture processors varies widely
15260: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15261: allocate any of the virtual machine registers into real machine
15262: registers by itself and would not work correctly with explicit register
1.112 anton 15263: declarations, giving a significantly slower engine (on a 486DX2/66
15264: running the Sieve) than the one measured above.
1.1 anton 15265:
1.26 crook 15266: Note that there have been several releases of Win32Forth since the
15267: release presented here, so the results presented above may have little
1.40 anton 15268: predictive value for the performance of Win32Forth today (results for
15269: the current release on an i486DX2/66 are welcome).
1.1 anton 15270:
15271: @cindex @file{Benchres}
1.66 anton 15272: In
15273: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15274: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15275: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15276: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15277: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15278: than the version used here. You can find a newer version of these
15279: measurements at
1.47 crook 15280: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15281: find numbers for Gforth on various machines in @file{Benchres}.
15282:
1.26 crook 15283: @c ******************************************************************
1.113 anton 15284: @c @node Binding to System Library, Cross Compiler, Engine, Top
15285: @c @chapter Binding to System Library
1.13 pazsan 15286:
1.113 anton 15287: @c ****************************************************************
15288: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15289: @chapter Cross Compiler
1.47 crook 15290: @cindex @file{cross.fs}
15291: @cindex cross-compiler
15292: @cindex metacompiler
15293: @cindex target compiler
1.13 pazsan 15294:
1.46 pazsan 15295: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15296: mostly written in Forth, including crucial parts like the outer
15297: interpreter and compiler, it needs compiled Forth code to get
15298: started. The cross compiler allows to create new images for other
15299: architectures, even running under another Forth system.
1.13 pazsan 15300:
15301: @menu
1.67 anton 15302: * Using the Cross Compiler::
15303: * How the Cross Compiler Works::
1.13 pazsan 15304: @end menu
15305:
1.21 crook 15306: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15307: @section Using the Cross Compiler
1.46 pazsan 15308:
15309: The cross compiler uses a language that resembles Forth, but isn't. The
15310: main difference is that you can execute Forth code after definition,
15311: while you usually can't execute the code compiled by cross, because the
15312: code you are compiling is typically for a different computer than the
15313: one you are compiling on.
15314:
1.81 anton 15315: @c anton: This chapter is somewhat different from waht I would expect: I
15316: @c would expect an explanation of the cross language and how to create an
15317: @c application image with it. The section explains some aspects of
15318: @c creating a Gforth kernel.
15319:
1.46 pazsan 15320: The Makefile is already set up to allow you to create kernels for new
15321: architectures with a simple make command. The generic kernels using the
15322: GCC compiled virtual machine are created in the normal build process
15323: with @code{make}. To create a embedded Gforth executable for e.g. the
15324: 8086 processor (running on a DOS machine), type
15325:
15326: @example
15327: make kernl-8086.fi
15328: @end example
15329:
15330: This will use the machine description from the @file{arch/8086}
15331: directory to create a new kernel. A machine file may look like that:
15332:
15333: @example
15334: \ Parameter for target systems 06oct92py
15335:
15336: 4 Constant cell \ cell size in bytes
15337: 2 Constant cell<< \ cell shift to bytes
15338: 5 Constant cell>bit \ cell shift to bits
15339: 8 Constant bits/char \ bits per character
15340: 8 Constant bits/byte \ bits per byte [default: 8]
15341: 8 Constant float \ bytes per float
15342: 8 Constant /maxalign \ maximum alignment in bytes
15343: false Constant bigendian \ byte order
15344: ( true=big, false=little )
15345:
15346: include machpc.fs \ feature list
15347: @end example
15348:
15349: This part is obligatory for the cross compiler itself, the feature list
15350: is used by the kernel to conditionally compile some features in and out,
15351: depending on whether the target supports these features.
15352:
15353: There are some optional features, if you define your own primitives,
15354: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15355: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15356: @code{prims-include} includes primitives, and @code{>boot} prepares for
15357: booting.
15358:
15359: @example
15360: : asm-include ." Include assembler" cr
15361: s" arch/8086/asm.fs" included ;
15362:
15363: : prims-include ." Include primitives" cr
15364: s" arch/8086/prim.fs" included ;
15365:
15366: : >boot ." Prepare booting" cr
15367: s" ' boot >body into-forth 1+ !" evaluate ;
15368: @end example
15369:
15370: These words are used as sort of macro during the cross compilation in
1.81 anton 15371: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15372: be possible --- but more complicated --- to write a new kernel project
15373: file, too.
15374:
15375: @file{kernel/main.fs} expects the machine description file name on the
15376: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15377: @code{mach-file} leaves a counted string on the stack, or
15378: @code{machine-file} leaves an address, count pair of the filename on the
15379: stack.
15380:
15381: The feature list is typically controlled using @code{SetValue}, generic
15382: files that are used by several projects can use @code{DefaultValue}
15383: instead. Both functions work like @code{Value}, when the value isn't
15384: defined, but @code{SetValue} works like @code{to} if the value is
15385: defined, and @code{DefaultValue} doesn't set anything, if the value is
15386: defined.
15387:
15388: @example
15389: \ generic mach file for pc gforth 03sep97jaw
15390:
15391: true DefaultValue NIL \ relocating
15392:
15393: >ENVIRON
15394:
15395: true DefaultValue file \ controls the presence of the
15396: \ file access wordset
15397: true DefaultValue OS \ flag to indicate a operating system
15398:
15399: true DefaultValue prims \ true: primitives are c-code
15400:
15401: true DefaultValue floating \ floating point wordset is present
15402:
15403: true DefaultValue glocals \ gforth locals are present
15404: \ will be loaded
15405: true DefaultValue dcomps \ double number comparisons
15406:
15407: true DefaultValue hash \ hashing primitives are loaded/present
15408:
15409: true DefaultValue xconds \ used together with glocals,
15410: \ special conditionals supporting gforths'
15411: \ local variables
15412: true DefaultValue header \ save a header information
15413:
15414: true DefaultValue backtrace \ enables backtrace code
15415:
15416: false DefaultValue ec
15417: false DefaultValue crlf
15418:
15419: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15420:
15421: &16 KB DefaultValue stack-size
15422: &15 KB &512 + DefaultValue fstack-size
15423: &15 KB DefaultValue rstack-size
15424: &14 KB &512 + DefaultValue lstack-size
15425: @end example
1.13 pazsan 15426:
1.48 anton 15427: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15428: @section How the Cross Compiler Works
1.13 pazsan 15429:
15430: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15431: @appendix Bugs
1.1 anton 15432: @cindex bug reporting
15433:
1.21 crook 15434: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15435:
1.103 anton 15436: If you find a bug, please submit a bug report through
15437: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15438:
15439: @itemize @bullet
15440: @item
1.81 anton 15441: A program (or a sequence of keyboard commands) that reproduces the bug.
15442: @item
15443: A description of what you think constitutes the buggy behaviour.
15444: @item
1.21 crook 15445: The Gforth version used (it is announced at the start of an
15446: interactive Gforth session).
15447: @item
15448: The machine and operating system (on Unix
15449: systems @code{uname -a} will report this information).
15450: @item
1.81 anton 15451: The installation options (you can find the configure options at the
15452: start of @file{config.status}) and configuration (@code{configure}
15453: output or @file{config.cache}).
1.21 crook 15454: @item
15455: A complete list of changes (if any) you (or your installer) have made to the
15456: Gforth sources.
15457: @end itemize
1.1 anton 15458:
15459: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15460: to Report Bugs, gcc.info, GNU C Manual}.
15461:
15462:
1.21 crook 15463: @node Origin, Forth-related information, Bugs, Top
15464: @appendix Authors and Ancestors of Gforth
1.1 anton 15465:
15466: @section Authors and Contributors
15467: @cindex authors of Gforth
15468: @cindex contributors to Gforth
15469:
15470: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15471: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15472: lot to the manual. Assemblers and disassemblers were contributed by
15473: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15474: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15475: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15476: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15477: support for calling C libraries. Helpful comments also came from Paul
15478: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15479: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15480: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15481: Gforth-0.2.1 there were also helpful comments from many others; thank
15482: you all, sorry for not listing you here (but digging through my mailbox
15483: to extract your names is on my to-do list).
1.1 anton 15484:
15485: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15486: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15487: was developed across the Internet, and its authors did not meet
1.20 pazsan 15488: physically for the first 4 years of development.
1.1 anton 15489:
15490: @section Pedigree
1.26 crook 15491: @cindex pedigree of Gforth
1.1 anton 15492:
1.81 anton 15493: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15494: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15495:
1.20 pazsan 15496: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15497: 32 bit native code version of VolksForth for the Atari ST, written
15498: mostly by Dietrich Weineck.
15499:
1.81 anton 15500: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15501: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 15502: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 15503:
1.147 anton 15504: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15505: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 15506:
15507: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15508: 1979. Robert Selzer and Bill Ragsdale developed the original
15509: implementation of fig-Forth for the 6502 based on microForth.
15510:
15511: The principal architect of microForth was Dean Sanderson. microForth was
15512: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15513: the 1802, and subsequently implemented on the 8080, the 6800 and the
15514: Z80.
15515:
15516: All earlier Forth systems were custom-made, usually by Charles Moore,
15517: who discovered (as he puts it) Forth during the late 60s. The first full
15518: Forth existed in 1971.
15519:
1.81 anton 15520: A part of the information in this section comes from
15521: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15522: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 15523: Charles H. Moore, presented at the HOPL-II conference and preprinted
15524: in SIGPLAN Notices 28(3), 1993. You can find more historical and
15525: genealogical information about Forth there. For a more general (and
15526: graphical) Forth family tree look see
15527: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15528: Forth Family Tree and Timeline}.
1.1 anton 15529:
1.81 anton 15530: @c ------------------------------------------------------------------
1.113 anton 15531: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15532: @appendix Other Forth-related information
15533: @cindex Forth-related information
15534:
1.81 anton 15535: @c anton: I threw most of this stuff out, because it can be found through
15536: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15537:
15538: @cindex comp.lang.forth
15539: @cindex frequently asked questions
1.81 anton 15540: There is an active news group (comp.lang.forth) discussing Forth
15541: (including Gforth) and Forth-related issues. Its
15542: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15543: (frequently asked questions and their answers) contains a lot of
15544: information on Forth. You should read it before posting to
15545: comp.lang.forth.
1.21 crook 15546:
1.81 anton 15547: The ANS Forth standard is most usable in its
15548: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15549:
1.113 anton 15550: @c ---------------------------------------------------
15551: @node Licenses, Word Index, Forth-related information, Top
15552: @appendix Licenses
15553:
15554: @menu
15555: * GNU Free Documentation License:: License for copying this manual.
15556: * Copying:: GPL (for copying this software).
15557: @end menu
15558:
15559: @include fdl.texi
15560:
15561: @include gpl.texi
15562:
15563:
15564:
1.81 anton 15565: @c ------------------------------------------------------------------
1.113 anton 15566: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15567: @unnumbered Word Index
15568:
1.26 crook 15569: This index is a list of Forth words that have ``glossary'' entries
15570: within this manual. Each word is listed with its stack effect and
15571: wordset.
1.1 anton 15572:
15573: @printindex fn
15574:
1.81 anton 15575: @c anton: the name index seems superfluous given the word and concept indices.
15576:
15577: @c @node Name Index, Concept Index, Word Index, Top
15578: @c @unnumbered Name Index
1.41 anton 15579:
1.81 anton 15580: @c This index is a list of Forth words that have ``glossary'' entries
15581: @c within this manual.
1.41 anton 15582:
1.81 anton 15583: @c @printindex ky
1.41 anton 15584:
1.113 anton 15585: @c -------------------------------------------------------
1.81 anton 15586: @node Concept Index, , Word Index, Top
1.1 anton 15587: @unnumbered Concept and Word Index
15588:
1.26 crook 15589: Not all entries listed in this index are present verbatim in the
15590: text. This index also duplicates, in abbreviated form, all of the words
15591: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15592:
15593: @printindex cp
15594:
15595: @bye
1.81 anton 15596:
15597:
1.1 anton 15598:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>