Annotation of gforth/doc/gforth.ds, revision 1.113
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
! 59: This manual is for Gforth
! 60: (version @value{VERSION}, @value{UPDATED}),
! 61: a fast and portable implementation of the ANS Forth language
1.29 crook 62:
1.113 ! anton 63: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.29 crook 64:
1.113 ! anton 65: @quotation
! 66: Permission is granted to copy, distribute and/or modify this document
! 67: under the terms of the GNU Free Documentation License, Version 1.1 or
! 68: any later version published by the Free Software Foundation; with no
! 69: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
! 70: and with the Back-Cover Texts as in (a) below. A copy of the
! 71: license is included in the section entitled ``GNU Free Documentation
! 72: License.''
! 73:
! 74: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
! 75: this GNU Manual, like GNU software. Copies published by the Free
! 76: Software Foundation raise funds for GNU development.''
! 77: @end quotation
! 78: @end copying
1.10 anton 79:
1.113 ! anton 80: @dircategory Software development
! 81: @direntry
! 82: * Gforth: (gforth). A fast interpreter for the Forth language.
! 83: @end direntry
! 84: @c The Texinfo manual also recommends doing this, but for Gforth it may
! 85: @c not make much sense
! 86: @c @dircategory Individual utilities
! 87: @c @direntry
! 88: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
! 89: @c @end direntry
1.1 anton 90:
91: @titlepage
1.113 ! anton 92: @title Gforth
! 93: @subtitle for version @value{VERSION}, @value{UPDATED}
! 94: @author Neal Crook
! 95: @author Anton Ertl
! 96: @author Bernd Paysan
! 97: @author Jens Wilke
1.1 anton 98: @page
99: @vskip 0pt plus 1filll
1.113 ! anton 100: @insertcopying
! 101: @end titlepage
1.1 anton 102:
1.113 ! anton 103: @contents
1.1 anton 104:
1.113 ! anton 105: @ifnottex
! 106: @node Top, Goals, (dir), (dir)
! 107: @top Gforth
1.1 anton 108:
1.113 ! anton 109: @insertcopying
1.49 anton 110: @end ifnottex
1.1 anton 111:
112: @menu
1.26 crook 113: * Goals:: About the Gforth Project
1.29 crook 114: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 115: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 116: * Introduction:: An introduction to ANS Forth
1.1 anton 117: * Words:: Forth words available in Gforth
1.24 anton 118: * Error messages:: How to interpret them
1.1 anton 119: * Tools:: Programming tools
120: * ANS conformance:: Implementation-defined options etc.
1.65 anton 121: * Standard vs Extensions:: Should I use extensions?
1.1 anton 122: * Model:: The abstract machine of Gforth
123: * Integrating Gforth:: Forth as scripting language for applications
124: * Emacs and Gforth:: The Gforth Mode
125: * Image Files:: @code{.fi} files contain compiled code
126: * Engine:: The inner interpreter and the primitives
1.13 pazsan 127: * Cross Compiler:: The Cross Compiler
1.1 anton 128: * Bugs:: How to report them
129: * Origin:: Authors and ancestors of Gforth
1.21 crook 130: * Forth-related information:: Books and places to look on the WWW
1.113 ! anton 131: * Licenses::
1.1 anton 132: * Word Index:: An item for each Forth word
133: * Concept Index:: A menu covering many topics
1.12 anton 134:
1.91 anton 135: @detailmenu
136: --- The Detailed Node Listing ---
1.12 anton 137:
1.29 crook 138: Gforth Environment
139:
1.32 anton 140: * Invoking Gforth:: Getting in
141: * Leaving Gforth:: Getting out
142: * Command-line editing::
1.48 anton 143: * Environment variables:: that affect how Gforth starts up
1.32 anton 144: * Gforth Files:: What gets installed and where
1.112 anton 145: * Gforth in pipes::
1.48 anton 146: * Startup speed:: When 35ms is not fast enough ...
147:
148: Forth Tutorial
149:
150: * Starting Gforth Tutorial::
151: * Syntax Tutorial::
152: * Crash Course Tutorial::
153: * Stack Tutorial::
154: * Arithmetics Tutorial::
155: * Stack Manipulation Tutorial::
156: * Using files for Forth code Tutorial::
157: * Comments Tutorial::
158: * Colon Definitions Tutorial::
159: * Decompilation Tutorial::
160: * Stack-Effect Comments Tutorial::
161: * Types Tutorial::
162: * Factoring Tutorial::
163: * Designing the stack effect Tutorial::
164: * Local Variables Tutorial::
165: * Conditional execution Tutorial::
166: * Flags and Comparisons Tutorial::
167: * General Loops Tutorial::
168: * Counted loops Tutorial::
169: * Recursion Tutorial::
170: * Leaving definitions or loops Tutorial::
171: * Return Stack Tutorial::
172: * Memory Tutorial::
173: * Characters and Strings Tutorial::
174: * Alignment Tutorial::
1.87 anton 175: * Files Tutorial::
1.48 anton 176: * Interpretation and Compilation Semantics and Immediacy Tutorial::
177: * Execution Tokens Tutorial::
178: * Exceptions Tutorial::
179: * Defining Words Tutorial::
180: * Arrays and Records Tutorial::
181: * POSTPONE Tutorial::
182: * Literal Tutorial::
183: * Advanced macros Tutorial::
184: * Compilation Tokens Tutorial::
185: * Wordlists and Search Order Tutorial::
1.29 crook 186:
1.24 anton 187: An Introduction to ANS Forth
188:
1.67 anton 189: * Introducing the Text Interpreter::
190: * Stacks and Postfix notation::
191: * Your first definition::
192: * How does that work?::
193: * Forth is written in Forth::
194: * Review - elements of a Forth system::
195: * Where to go next::
196: * Exercises::
1.24 anton 197:
1.12 anton 198: Forth Words
199:
200: * Notation::
1.65 anton 201: * Case insensitivity::
202: * Comments::
203: * Boolean Flags::
1.12 anton 204: * Arithmetic::
205: * Stack Manipulation::
206: * Memory::
207: * Control Structures::
208: * Defining Words::
1.65 anton 209: * Interpretation and Compilation Semantics::
1.47 crook 210: * Tokens for Words::
1.81 anton 211: * Compiling words::
1.65 anton 212: * The Text Interpreter::
1.111 anton 213: * The Input Stream::
1.65 anton 214: * Word Lists::
215: * Environmental Queries::
1.12 anton 216: * Files::
217: * Blocks::
218: * Other I/O::
1.78 anton 219: * Locals::
220: * Structures::
221: * Object-oriented Forth::
1.12 anton 222: * Programming Tools::
223: * Assembler and Code Words::
224: * Threading Words::
1.65 anton 225: * Passing Commands to the OS::
226: * Keeping track of Time::
227: * Miscellaneous Words::
1.12 anton 228:
229: Arithmetic
230:
231: * Single precision::
1.67 anton 232: * Double precision:: Double-cell integer arithmetic
1.12 anton 233: * Bitwise operations::
1.67 anton 234: * Numeric comparison::
1.32 anton 235: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 236: * Floating Point::
237:
238: Stack Manipulation
239:
240: * Data stack::
241: * Floating point stack::
242: * Return stack::
243: * Locals stack::
244: * Stack pointer manipulation::
245:
246: Memory
247:
1.32 anton 248: * Memory model::
249: * Dictionary allocation::
250: * Heap Allocation::
251: * Memory Access::
252: * Address arithmetic::
253: * Memory Blocks::
1.12 anton 254:
255: Control Structures
256:
1.41 anton 257: * Selection:: IF ... ELSE ... ENDIF
258: * Simple Loops:: BEGIN ...
1.32 anton 259: * Counted Loops:: DO
1.67 anton 260: * Arbitrary control structures::
261: * Calls and returns::
1.12 anton 262: * Exception Handling::
263:
264: Defining Words
265:
1.67 anton 266: * CREATE::
1.44 crook 267: * Variables:: Variables and user variables
1.67 anton 268: * Constants::
1.44 crook 269: * Values:: Initialised variables
1.67 anton 270: * Colon Definitions::
1.44 crook 271: * Anonymous Definitions:: Definitions without names
1.71 anton 272: * Supplying names:: Passing definition names as strings
1.67 anton 273: * User-defined Defining Words::
1.44 crook 274: * Deferred words:: Allow forward references
1.67 anton 275: * Aliases::
1.47 crook 276:
1.63 anton 277: User-defined Defining Words
278:
279: * CREATE..DOES> applications::
280: * CREATE..DOES> details::
281: * Advanced does> usage example::
1.91 anton 282: * @code{Const-does>}::
1.63 anton 283:
1.47 crook 284: Interpretation and Compilation Semantics
285:
1.67 anton 286: * Combined words::
1.12 anton 287:
1.71 anton 288: Tokens for Words
289:
290: * Execution token:: represents execution/interpretation semantics
291: * Compilation token:: represents compilation semantics
292: * Name token:: represents named words
293:
1.82 anton 294: Compiling words
295:
296: * Literals:: Compiling data values
297: * Macros:: Compiling words
298:
1.21 crook 299: The Text Interpreter
300:
1.67 anton 301: * Input Sources::
302: * Number Conversion::
303: * Interpret/Compile states::
304: * Interpreter Directives::
1.21 crook 305:
1.26 crook 306: Word Lists
307:
1.75 anton 308: * Vocabularies::
1.67 anton 309: * Why use word lists?::
1.75 anton 310: * Word list example::
1.26 crook 311:
312: Files
313:
1.48 anton 314: * Forth source files::
315: * General files::
316: * Search Paths::
317:
318: Search Paths
319:
1.75 anton 320: * Source Search Paths::
1.26 crook 321: * General Search Paths::
322:
323: Other I/O
324:
1.32 anton 325: * Simple numeric output:: Predefined formats
326: * Formatted numeric output:: Formatted (pictured) output
327: * String Formats:: How Forth stores strings in memory
1.67 anton 328: * Displaying characters and strings:: Other stuff
1.32 anton 329: * Input:: Input
1.112 anton 330: * Pipes:: How to create your own pipes
1.26 crook 331:
332: Locals
333:
334: * Gforth locals::
335: * ANS Forth locals::
336:
337: Gforth locals
338:
339: * Where are locals visible by name?::
340: * How long do locals live?::
1.78 anton 341: * Locals programming style::
342: * Locals implementation::
1.26 crook 343:
1.12 anton 344: Structures
345:
346: * Why explicit structure support?::
347: * Structure Usage::
348: * Structure Naming Convention::
349: * Structure Implementation::
350: * Structure Glossary::
351:
352: Object-oriented Forth
353:
1.48 anton 354: * Why object-oriented programming?::
355: * Object-Oriented Terminology::
356: * Objects::
357: * OOF::
358: * Mini-OOF::
1.23 crook 359: * Comparison with other object models::
1.12 anton 360:
1.24 anton 361: The @file{objects.fs} model
1.12 anton 362:
363: * Properties of the Objects model::
364: * Basic Objects Usage::
1.41 anton 365: * The Objects base class::
1.12 anton 366: * Creating objects::
367: * Object-Oriented Programming Style::
368: * Class Binding::
369: * Method conveniences::
370: * Classes and Scoping::
1.41 anton 371: * Dividing classes::
1.12 anton 372: * Object Interfaces::
373: * Objects Implementation::
374: * Objects Glossary::
375:
1.24 anton 376: The @file{oof.fs} model
1.12 anton 377:
1.67 anton 378: * Properties of the OOF model::
379: * Basic OOF Usage::
380: * The OOF base class::
381: * Class Declaration::
382: * Class Implementation::
1.12 anton 383:
1.24 anton 384: The @file{mini-oof.fs} model
1.23 crook 385:
1.48 anton 386: * Basic Mini-OOF Usage::
387: * Mini-OOF Example::
388: * Mini-OOF Implementation::
1.23 crook 389:
1.78 anton 390: Programming Tools
391:
392: * Examining::
393: * Forgetting words::
394: * Debugging:: Simple and quick.
395: * Assertions:: Making your programs self-checking.
396: * Singlestep Debugger:: Executing your program word by word.
397:
398: Assembler and Code Words
399:
400: * Code and ;code::
401: * Common Assembler:: Assembler Syntax
402: * Common Disassembler::
403: * 386 Assembler:: Deviations and special cases
404: * Alpha Assembler:: Deviations and special cases
405: * MIPS assembler:: Deviations and special cases
406: * Other assemblers:: How to write them
407:
1.12 anton 408: Tools
409:
410: * ANS Report:: Report the words used, sorted by wordset.
411:
412: ANS conformance
413:
414: * The Core Words::
415: * The optional Block word set::
416: * The optional Double Number word set::
417: * The optional Exception word set::
418: * The optional Facility word set::
419: * The optional File-Access word set::
420: * The optional Floating-Point word set::
421: * The optional Locals word set::
422: * The optional Memory-Allocation word set::
423: * The optional Programming-Tools word set::
424: * The optional Search-Order word set::
425:
426: The Core Words
427:
428: * core-idef:: Implementation Defined Options
429: * core-ambcond:: Ambiguous Conditions
430: * core-other:: Other System Documentation
431:
432: The optional Block word set
433:
434: * block-idef:: Implementation Defined Options
435: * block-ambcond:: Ambiguous Conditions
436: * block-other:: Other System Documentation
437:
438: The optional Double Number word set
439:
440: * double-ambcond:: Ambiguous Conditions
441:
442: The optional Exception word set
443:
444: * exception-idef:: Implementation Defined Options
445:
446: The optional Facility word set
447:
448: * facility-idef:: Implementation Defined Options
449: * facility-ambcond:: Ambiguous Conditions
450:
451: The optional File-Access word set
452:
453: * file-idef:: Implementation Defined Options
454: * file-ambcond:: Ambiguous Conditions
455:
456: The optional Floating-Point word set
457:
458: * floating-idef:: Implementation Defined Options
459: * floating-ambcond:: Ambiguous Conditions
460:
461: The optional Locals word set
462:
463: * locals-idef:: Implementation Defined Options
464: * locals-ambcond:: Ambiguous Conditions
465:
466: The optional Memory-Allocation word set
467:
468: * memory-idef:: Implementation Defined Options
469:
470: The optional Programming-Tools word set
471:
472: * programming-idef:: Implementation Defined Options
473: * programming-ambcond:: Ambiguous Conditions
474:
475: The optional Search-Order word set
476:
477: * search-idef:: Implementation Defined Options
478: * search-ambcond:: Ambiguous Conditions
479:
1.109 anton 480: Emacs and Gforth
481:
482: * Installing gforth.el:: Making Emacs aware of Forth.
483: * Emacs Tags:: Viewing the source of a word in Emacs.
484: * Hilighting:: Making Forth code look prettier.
485: * Auto-Indentation:: Customizing auto-indentation.
486: * Blocks Files:: Reading and writing blocks files.
487:
1.12 anton 488: Image Files
489:
1.24 anton 490: * Image Licensing Issues:: Distribution terms for images.
491: * Image File Background:: Why have image files?
1.67 anton 492: * Non-Relocatable Image Files:: don't always work.
1.24 anton 493: * Data-Relocatable Image Files:: are better.
1.67 anton 494: * Fully Relocatable Image Files:: better yet.
1.24 anton 495: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 496: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 497: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 498:
499: Fully Relocatable Image Files
500:
1.27 crook 501: * gforthmi:: The normal way
1.12 anton 502: * cross.fs:: The hard way
503:
504: Engine
505:
506: * Portability::
507: * Threading::
508: * Primitives::
509: * Performance::
510:
511: Threading
512:
513: * Scheduling::
514: * Direct or Indirect Threaded?::
1.109 anton 515: * Dynamic Superinstructions::
1.12 anton 516: * DOES>::
517:
518: Primitives
519:
520: * Automatic Generation::
521: * TOS Optimization::
522: * Produced code::
1.13 pazsan 523:
524: Cross Compiler
525:
1.67 anton 526: * Using the Cross Compiler::
527: * How the Cross Compiler Works::
1.13 pazsan 528:
1.113 ! anton 529: Licenses
! 530:
! 531: * GNU Free Documentation License:: License for copying this manual.
! 532: * Copying:: GPL (for copying this software).
! 533:
1.24 anton 534: @end detailmenu
1.1 anton 535: @end menu
536:
1.113 ! anton 537: @c ----------------------------------------------------------
1.1 anton 538: @iftex
539: @unnumbered Preface
540: @cindex Preface
1.21 crook 541: This manual documents Gforth. Some introductory material is provided for
542: readers who are unfamiliar with Forth or who are migrating to Gforth
543: from other Forth compilers. However, this manual is primarily a
544: reference manual.
1.1 anton 545: @end iftex
546:
1.28 crook 547: @comment TODO much more blurb here.
1.26 crook 548:
549: @c ******************************************************************
1.113 ! anton 550: @node Goals, Gforth Environment, Top, Top
1.26 crook 551: @comment node-name, next, previous, up
552: @chapter Goals of Gforth
553: @cindex goals of the Gforth project
554: The goal of the Gforth Project is to develop a standard model for
555: ANS Forth. This can be split into several subgoals:
556:
557: @itemize @bullet
558: @item
559: Gforth should conform to the ANS Forth Standard.
560: @item
561: It should be a model, i.e. it should define all the
562: implementation-dependent things.
563: @item
564: It should become standard, i.e. widely accepted and used. This goal
565: is the most difficult one.
566: @end itemize
567:
568: To achieve these goals Gforth should be
569: @itemize @bullet
570: @item
571: Similar to previous models (fig-Forth, F83)
572: @item
573: Powerful. It should provide for all the things that are considered
574: necessary today and even some that are not yet considered necessary.
575: @item
576: Efficient. It should not get the reputation of being exceptionally
577: slow.
578: @item
579: Free.
580: @item
581: Available on many machines/easy to port.
582: @end itemize
583:
584: Have we achieved these goals? Gforth conforms to the ANS Forth
585: standard. It may be considered a model, but we have not yet documented
586: which parts of the model are stable and which parts we are likely to
587: change. It certainly has not yet become a de facto standard, but it
588: appears to be quite popular. It has some similarities to and some
589: differences from previous models. It has some powerful features, but not
590: yet everything that we envisioned. We certainly have achieved our
1.65 anton 591: execution speed goals (@pxref{Performance})@footnote{However, in 1998
592: the bar was raised when the major commercial Forth vendors switched to
593: native code compilers.}. It is free and available on many machines.
1.29 crook 594:
1.26 crook 595: @c ******************************************************************
1.48 anton 596: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 597: @chapter Gforth Environment
598: @cindex Gforth environment
1.21 crook 599:
1.45 crook 600: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 601: material in this chapter.
1.21 crook 602:
603: @menu
1.29 crook 604: * Invoking Gforth:: Getting in
605: * Leaving Gforth:: Getting out
606: * Command-line editing::
1.48 anton 607: * Environment variables:: that affect how Gforth starts up
1.29 crook 608: * Gforth Files:: What gets installed and where
1.112 anton 609: * Gforth in pipes::
1.48 anton 610: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 611: @end menu
612:
1.49 anton 613: For related information about the creation of images see @ref{Image Files}.
1.29 crook 614:
1.21 crook 615: @comment ----------------------------------------------
1.48 anton 616: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 617: @section Invoking Gforth
618: @cindex invoking Gforth
619: @cindex running Gforth
620: @cindex command-line options
621: @cindex options on the command line
622: @cindex flags on the command line
1.21 crook 623:
1.30 anton 624: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 625: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 626: will usually just say @code{gforth} -- this automatically loads the
627: default image file @file{gforth.fi}. In many other cases the default
628: Gforth image will be invoked like this:
1.21 crook 629: @example
1.30 anton 630: gforth [file | -e forth-code] ...
1.21 crook 631: @end example
1.29 crook 632: @noindent
633: This interprets the contents of the files and the Forth code in the order they
634: are given.
1.21 crook 635:
1.109 anton 636: In addition to the @command{gforth} engine, there is also an engine
637: called @command{gforth-fast}, which is faster, but gives less
638: informative error messages (@pxref{Error messages}) and may catch some
639: stack underflows later or not at all. You should use it for debugged,
640: performance-critical programs.
641:
642: Moreover, there is an engine called @command{gforth-itc}, which is
643: useful in some backwards-compatibility situations (@pxref{Direct or
644: Indirect Threaded?}).
1.30 anton 645:
1.29 crook 646: In general, the command line looks like this:
1.21 crook 647:
648: @example
1.30 anton 649: gforth[-fast] [engine options] [image options]
1.21 crook 650: @end example
651:
1.30 anton 652: The engine options must come before the rest of the command
1.29 crook 653: line. They are:
1.26 crook 654:
1.29 crook 655: @table @code
656: @cindex -i, command-line option
657: @cindex --image-file, command-line option
658: @item --image-file @i{file}
659: @itemx -i @i{file}
660: Loads the Forth image @i{file} instead of the default
661: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 662:
1.39 anton 663: @cindex --appl-image, command-line option
664: @item --appl-image @i{file}
665: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 666: to the image (instead of processing them as engine options). This is
667: useful for building executable application images on Unix, built with
1.39 anton 668: @code{gforthmi --application ...}.
669:
1.29 crook 670: @cindex --path, command-line option
671: @cindex -p, command-line option
672: @item --path @i{path}
673: @itemx -p @i{path}
674: Uses @i{path} for searching the image file and Forth source code files
675: instead of the default in the environment variable @code{GFORTHPATH} or
676: the path specified at installation time (e.g.,
677: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
678: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 679:
1.29 crook 680: @cindex --dictionary-size, command-line option
681: @cindex -m, command-line option
682: @cindex @i{size} parameters for command-line options
683: @cindex size of the dictionary and the stacks
684: @item --dictionary-size @i{size}
685: @itemx -m @i{size}
686: Allocate @i{size} space for the Forth dictionary space instead of
687: using the default specified in the image (typically 256K). The
688: @i{size} specification for this and subsequent options consists of
689: an integer and a unit (e.g.,
690: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
691: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
692: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
693: @code{e} is used.
1.21 crook 694:
1.29 crook 695: @cindex --data-stack-size, command-line option
696: @cindex -d, command-line option
697: @item --data-stack-size @i{size}
698: @itemx -d @i{size}
699: Allocate @i{size} space for the data stack instead of using the
700: default specified in the image (typically 16K).
1.21 crook 701:
1.29 crook 702: @cindex --return-stack-size, command-line option
703: @cindex -r, command-line option
704: @item --return-stack-size @i{size}
705: @itemx -r @i{size}
706: Allocate @i{size} space for the return stack instead of using the
707: default specified in the image (typically 15K).
1.21 crook 708:
1.29 crook 709: @cindex --fp-stack-size, command-line option
710: @cindex -f, command-line option
711: @item --fp-stack-size @i{size}
712: @itemx -f @i{size}
713: Allocate @i{size} space for the floating point stack instead of
714: using the default specified in the image (typically 15.5K). In this case
715: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 716:
1.48 anton 717: @cindex --locals-stack-size, command-line option
718: @cindex -l, command-line option
719: @item --locals-stack-size @i{size}
720: @itemx -l @i{size}
721: Allocate @i{size} space for the locals stack instead of using the
722: default specified in the image (typically 14.5K).
723:
724: @cindex -h, command-line option
725: @cindex --help, command-line option
726: @item --help
727: @itemx -h
728: Print a message about the command-line options
729:
730: @cindex -v, command-line option
731: @cindex --version, command-line option
732: @item --version
733: @itemx -v
734: Print version and exit
735:
736: @cindex --debug, command-line option
737: @item --debug
738: Print some information useful for debugging on startup.
739:
740: @cindex --offset-image, command-line option
741: @item --offset-image
742: Start the dictionary at a slightly different position than would be used
743: otherwise (useful for creating data-relocatable images,
744: @pxref{Data-Relocatable Image Files}).
745:
746: @cindex --no-offset-im, command-line option
747: @item --no-offset-im
748: Start the dictionary at the normal position.
749:
750: @cindex --clear-dictionary, command-line option
751: @item --clear-dictionary
752: Initialize all bytes in the dictionary to 0 before loading the image
753: (@pxref{Data-Relocatable Image Files}).
754:
755: @cindex --die-on-signal, command-line-option
756: @item --die-on-signal
757: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
758: or the segmentation violation SIGSEGV) by translating it into a Forth
759: @code{THROW}. With this option, Gforth exits if it receives such a
760: signal. This option is useful when the engine and/or the image might be
761: severely broken (such that it causes another signal before recovering
762: from the first); this option avoids endless loops in such cases.
1.109 anton 763:
764: @item --no-dynamic
765: @item --dynamic
766: Disable or enable dynamic superinstructions with replication
767: (@pxref{Dynamic Superinstructions}).
768:
769: @item --no-super
1.110 anton 770: Disable dynamic superinstructions, use just dynamic replication; this is
771: useful if you want to patch threaded code (@pxref{Dynamic
772: Superinstructions}).
1.109 anton 773:
1.48 anton 774: @end table
775:
776: @cindex loading files at startup
777: @cindex executing code on startup
778: @cindex batch processing with Gforth
779: As explained above, the image-specific command-line arguments for the
780: default image @file{gforth.fi} consist of a sequence of filenames and
781: @code{-e @var{forth-code}} options that are interpreted in the sequence
782: in which they are given. The @code{-e @var{forth-code}} or
783: @code{--evaluate @var{forth-code}} option evaluates the Forth
784: code. This option takes only one argument; if you want to evaluate more
785: Forth words, you have to quote them or use @code{-e} several times. To exit
786: after processing the command line (instead of entering interactive mode)
787: append @code{-e bye} to the command line.
788:
789: @cindex versions, invoking other versions of Gforth
790: If you have several versions of Gforth installed, @code{gforth} will
791: invoke the version that was installed last. @code{gforth-@i{version}}
792: invokes a specific version. If your environment contains the variable
793: @code{GFORTHPATH}, you may want to override it by using the
794: @code{--path} option.
795:
796: Not yet implemented:
797: On startup the system first executes the system initialization file
798: (unless the option @code{--no-init-file} is given; note that the system
799: resulting from using this option may not be ANS Forth conformant). Then
800: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 801: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 802: then in @file{~}, then in the normal path (see above).
803:
804:
805:
806: @comment ----------------------------------------------
807: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
808: @section Leaving Gforth
809: @cindex Gforth - leaving
810: @cindex leaving Gforth
811:
812: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
813: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
814: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 815: data are discarded. For ways of saving the state of the system before
816: leaving Gforth see @ref{Image Files}.
1.48 anton 817:
818: doc-bye
819:
820:
821: @comment ----------------------------------------------
1.65 anton 822: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 823: @section Command-line editing
824: @cindex command-line editing
825:
826: Gforth maintains a history file that records every line that you type to
827: the text interpreter. This file is preserved between sessions, and is
828: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
829: repeatedly you can recall successively older commands from this (or
830: previous) session(s). The full list of command-line editing facilities is:
831:
832: @itemize @bullet
833: @item
834: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
835: commands from the history buffer.
836: @item
837: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
838: from the history buffer.
839: @item
840: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
841: @item
842: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
843: @item
844: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
845: closing up the line.
846: @item
847: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
848: @item
849: @kbd{Ctrl-a} to move the cursor to the start of the line.
850: @item
851: @kbd{Ctrl-e} to move the cursor to the end of the line.
852: @item
853: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
854: line.
855: @item
856: @key{TAB} to step through all possible full-word completions of the word
857: currently being typed.
858: @item
1.65 anton 859: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
860: using @code{bye}).
861: @item
862: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
863: character under the cursor.
1.48 anton 864: @end itemize
865:
866: When editing, displayable characters are inserted to the left of the
867: cursor position; the line is always in ``insert'' (as opposed to
868: ``overstrike'') mode.
869:
870: @cindex history file
871: @cindex @file{.gforth-history}
872: On Unix systems, the history file is @file{~/.gforth-history} by
873: default@footnote{i.e. it is stored in the user's home directory.}. You
874: can find out the name and location of your history file using:
875:
876: @example
877: history-file type \ Unix-class systems
878:
879: history-file type \ Other systems
880: history-dir type
881: @end example
882:
883: If you enter long definitions by hand, you can use a text editor to
884: paste them out of the history file into a Forth source file for reuse at
885: a later time.
886:
887: Gforth never trims the size of the history file, so you should do this
888: periodically, if necessary.
889:
890: @comment this is all defined in history.fs
891: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
892: @comment chosen?
893:
894:
895: @comment ----------------------------------------------
1.65 anton 896: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 897: @section Environment variables
898: @cindex environment variables
899:
900: Gforth uses these environment variables:
901:
902: @itemize @bullet
903: @item
904: @cindex @code{GFORTHHIST} -- environment variable
905: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
906: open/create the history file, @file{.gforth-history}. Default:
907: @code{$HOME}.
908:
909: @item
910: @cindex @code{GFORTHPATH} -- environment variable
911: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
912: for Forth source-code files.
913:
914: @item
915: @cindex @code{GFORTH} -- environment variable
1.49 anton 916: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 917:
918: @item
919: @cindex @code{GFORTHD} -- environment variable
1.62 crook 920: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 921:
922: @item
923: @cindex @code{TMP}, @code{TEMP} - environment variable
924: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
925: location for the history file.
926: @end itemize
927:
928: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
929: @comment mentioning these.
930:
931: All the Gforth environment variables default to sensible values if they
932: are not set.
933:
934:
935: @comment ----------------------------------------------
1.112 anton 936: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 937: @section Gforth files
938: @cindex Gforth files
939:
940: When you install Gforth on a Unix system, it installs files in these
941: locations by default:
942:
943: @itemize @bullet
944: @item
945: @file{/usr/local/bin/gforth}
946: @item
947: @file{/usr/local/bin/gforthmi}
948: @item
949: @file{/usr/local/man/man1/gforth.1} - man page.
950: @item
951: @file{/usr/local/info} - the Info version of this manual.
952: @item
953: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
954: @item
955: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
956: @item
957: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
958: @item
959: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
960: @end itemize
961:
962: You can select different places for installation by using
963: @code{configure} options (listed with @code{configure --help}).
964:
965: @comment ----------------------------------------------
1.112 anton 966: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
967: @section Gforth in pipes
968: @cindex pipes, Gforth as part of
969:
970: Gforth can be used in pipes created elsewhere (described here). It can
971: also create pipes on its own (@pxref{Pipes}).
972:
973: @cindex input from pipes
974: If you pipe into Gforth, your program should read with @code{read-file}
975: or @code{read-line} from @code{stdin} (@pxref{General files}).
976: @code{Key} does not recognize the end of input. Words like
977: @code{accept} echo the input and are therefore usually not useful for
978: reading from a pipe. You have to invoke the Forth program with an OS
979: command-line option, as you have no chance to use the Forth command line
980: (the text interpreter would try to interpret the pipe input).
981:
982: @cindex output in pipes
983: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
984:
985: @cindex silent exiting from Gforth
986: When you write to a pipe that has been closed at the other end, Gforth
987: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
988: into the exception @code{broken-pipe-error}. If your application does
989: not catch that exception, the system catches it and exits, usually
990: silently (unless you were working on the Forth command line; then it
991: prints an error message and exits). This is usually the desired
992: behaviour.
993:
994: If you do not like this behaviour, you have to catch the exception
995: yourself, and react to it.
996:
997: Here's an example of an invocation of Gforth that is usable in a pipe:
998:
999: @example
1000: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1001: type repeat ; foo bye"
1002: @end example
1003:
1004: This example just copies the input verbatim to the output. A very
1005: simple pipe containing this example looks like this:
1006:
1007: @example
1008: cat startup.fs |
1009: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1010: type repeat ; foo bye"|
1011: head
1012: @end example
1013:
1014: @cindex stderr and pipes
1015: Pipes involving Gforth's @code{stderr} output do not work.
1016:
1017: @comment ----------------------------------------------
1018: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1019: @section Startup speed
1020: @cindex Startup speed
1021: @cindex speed, startup
1022:
1023: If Gforth is used for CGI scripts or in shell scripts, its startup
1024: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1025: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1026: system time.
1027:
1028: If startup speed is a problem, you may consider the following ways to
1029: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1030: (for example, by using Fast-CGI).
1.48 anton 1031:
1.112 anton 1032: An easy step that influences Gforth startup speed is the use of the
1033: @option{--no-dynamic} option; this decreases image loading speed, but
1034: increases compile-time and run-time.
1035:
1036: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1037: building it with @code{XLDFLAGS=-static}. This requires more memory for
1038: the code and will therefore slow down the first invocation, but
1039: subsequent invocations avoid the dynamic linking overhead. Another
1040: disadvantage is that Gforth won't profit from library upgrades. As a
1041: result, @code{gforth-static -e bye} takes about 17.1ms user and
1042: 8.2ms system time.
1043:
1044: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1045: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1046: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1047: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1048: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1049: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1050: address for the dictionary, for whatever reason; so you better provide a
1051: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1052: bye} takes about 15.3ms user and 7.5ms system time.
1053:
1054: The final step is to disable dictionary hashing in Gforth. Gforth
1055: builds the hash table on startup, which takes much of the startup
1056: overhead. You can do this by commenting out the @code{include hash.fs}
1057: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1058: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1059: The disadvantages are that functionality like @code{table} and
1060: @code{ekey} is missing and that text interpretation (e.g., compiling)
1061: now takes much longer. So, you should only use this method if there is
1062: no significant text interpretation to perform (the script should be
1.62 crook 1063: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1064: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1065:
1066: @c ******************************************************************
1067: @node Tutorial, Introduction, Gforth Environment, Top
1068: @chapter Forth Tutorial
1069: @cindex Tutorial
1070: @cindex Forth Tutorial
1071:
1.67 anton 1072: @c Topics from nac's Introduction that could be mentioned:
1073: @c press <ret> after each line
1074: @c Prompt
1075: @c numbers vs. words in dictionary on text interpretation
1076: @c what happens on redefinition
1077: @c parsing words (in particular, defining words)
1078:
1.83 anton 1079: The difference of this chapter from the Introduction
1080: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1081: be used while sitting in front of a computer, and covers much more
1082: material, but does not explain how the Forth system works.
1083:
1.62 crook 1084: This tutorial can be used with any ANS-compliant Forth; any
1085: Gforth-specific features are marked as such and you can skip them if you
1086: work with another Forth. This tutorial does not explain all features of
1087: Forth, just enough to get you started and give you some ideas about the
1088: facilities available in Forth. Read the rest of the manual and the
1089: standard when you are through this.
1.48 anton 1090:
1091: The intended way to use this tutorial is that you work through it while
1092: sitting in front of the console, take a look at the examples and predict
1093: what they will do, then try them out; if the outcome is not as expected,
1094: find out why (e.g., by trying out variations of the example), so you
1095: understand what's going on. There are also some assignments that you
1096: should solve.
1097:
1098: This tutorial assumes that you have programmed before and know what,
1099: e.g., a loop is.
1100:
1101: @c !! explain compat library
1102:
1103: @menu
1104: * Starting Gforth Tutorial::
1105: * Syntax Tutorial::
1106: * Crash Course Tutorial::
1107: * Stack Tutorial::
1108: * Arithmetics Tutorial::
1109: * Stack Manipulation Tutorial::
1110: * Using files for Forth code Tutorial::
1111: * Comments Tutorial::
1112: * Colon Definitions Tutorial::
1113: * Decompilation Tutorial::
1114: * Stack-Effect Comments Tutorial::
1115: * Types Tutorial::
1116: * Factoring Tutorial::
1117: * Designing the stack effect Tutorial::
1118: * Local Variables Tutorial::
1119: * Conditional execution Tutorial::
1120: * Flags and Comparisons Tutorial::
1121: * General Loops Tutorial::
1122: * Counted loops Tutorial::
1123: * Recursion Tutorial::
1124: * Leaving definitions or loops Tutorial::
1125: * Return Stack Tutorial::
1126: * Memory Tutorial::
1127: * Characters and Strings Tutorial::
1128: * Alignment Tutorial::
1.87 anton 1129: * Files Tutorial::
1.48 anton 1130: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1131: * Execution Tokens Tutorial::
1132: * Exceptions Tutorial::
1133: * Defining Words Tutorial::
1134: * Arrays and Records Tutorial::
1135: * POSTPONE Tutorial::
1136: * Literal Tutorial::
1137: * Advanced macros Tutorial::
1138: * Compilation Tokens Tutorial::
1139: * Wordlists and Search Order Tutorial::
1140: @end menu
1141:
1142: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1143: @section Starting Gforth
1.66 anton 1144: @cindex starting Gforth tutorial
1.48 anton 1145: You can start Gforth by typing its name:
1146:
1147: @example
1148: gforth
1149: @end example
1150:
1151: That puts you into interactive mode; you can leave Gforth by typing
1152: @code{bye}. While in Gforth, you can edit the command line and access
1153: the command line history with cursor keys, similar to bash.
1154:
1155:
1156: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1157: @section Syntax
1.66 anton 1158: @cindex syntax tutorial
1.48 anton 1159:
1160: A @dfn{word} is a sequence of arbitrary characters (expcept white
1161: space). Words are separated by white space. E.g., each of the
1162: following lines contains exactly one word:
1163:
1164: @example
1165: word
1166: !@@#$%^&*()
1167: 1234567890
1168: 5!a
1169: @end example
1170:
1171: A frequent beginner's error is to leave away necessary white space,
1172: resulting in an error like @samp{Undefined word}; so if you see such an
1173: error, check if you have put spaces wherever necessary.
1174:
1175: @example
1176: ." hello, world" \ correct
1177: ."hello, world" \ gives an "Undefined word" error
1178: @end example
1179:
1.65 anton 1180: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1181: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1182: your system is case-sensitive, you may have to type all the examples
1183: given here in upper case.
1184:
1185:
1186: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1187: @section Crash Course
1188:
1189: Type
1190:
1191: @example
1192: 0 0 !
1193: here execute
1194: ' catch >body 20 erase abort
1195: ' (quit) >body 20 erase
1196: @end example
1197:
1198: The last two examples are guaranteed to destroy parts of Gforth (and
1199: most other systems), so you better leave Gforth afterwards (if it has
1200: not finished by itself). On some systems you may have to kill gforth
1201: from outside (e.g., in Unix with @code{kill}).
1202:
1203: Now that you know how to produce crashes (and that there's not much to
1204: them), let's learn how to produce meaningful programs.
1205:
1206:
1207: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1208: @section Stack
1.66 anton 1209: @cindex stack tutorial
1.48 anton 1210:
1211: The most obvious feature of Forth is the stack. When you type in a
1212: number, it is pushed on the stack. You can display the content of the
1213: stack with @code{.s}.
1214:
1215: @example
1216: 1 2 .s
1217: 3 .s
1218: @end example
1219:
1220: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1221: appear in @code{.s} output as they appeared in the input.
1222:
1223: You can print the top of stack element with @code{.}.
1224:
1225: @example
1226: 1 2 3 . . .
1227: @end example
1228:
1229: In general, words consume their stack arguments (@code{.s} is an
1230: exception).
1231:
1232: @assignment
1233: What does the stack contain after @code{5 6 7 .}?
1234: @endassignment
1235:
1236:
1237: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1238: @section Arithmetics
1.66 anton 1239: @cindex arithmetics tutorial
1.48 anton 1240:
1241: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1242: operate on the top two stack items:
1243:
1244: @example
1.67 anton 1245: 2 2 .s
1246: + .s
1247: .
1.48 anton 1248: 2 1 - .
1249: 7 3 mod .
1250: @end example
1251:
1252: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1253: as in the corresponding infix expression (this is generally the case in
1254: Forth).
1255:
1256: Parentheses are superfluous (and not available), because the order of
1257: the words unambiguously determines the order of evaluation and the
1258: operands:
1259:
1260: @example
1261: 3 4 + 5 * .
1262: 3 4 5 * + .
1263: @end example
1264:
1265: @assignment
1266: What are the infix expressions corresponding to the Forth code above?
1267: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1268: known as Postfix or RPN (Reverse Polish Notation).}.
1269: @endassignment
1270:
1271: To change the sign, use @code{negate}:
1272:
1273: @example
1274: 2 negate .
1275: @end example
1276:
1277: @assignment
1278: Convert -(-3)*4-5 to Forth.
1279: @endassignment
1280:
1281: @code{/mod} performs both @code{/} and @code{mod}.
1282:
1283: @example
1284: 7 3 /mod . .
1285: @end example
1286:
1.66 anton 1287: Reference: @ref{Arithmetic}.
1288:
1289:
1.48 anton 1290: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1291: @section Stack Manipulation
1.66 anton 1292: @cindex stack manipulation tutorial
1.48 anton 1293:
1294: Stack manipulation words rearrange the data on the stack.
1295:
1296: @example
1297: 1 .s drop .s
1298: 1 .s dup .s drop drop .s
1299: 1 2 .s over .s drop drop drop
1300: 1 2 .s swap .s drop drop
1301: 1 2 3 .s rot .s drop drop drop
1302: @end example
1303:
1304: These are the most important stack manipulation words. There are also
1305: variants that manipulate twice as many stack items:
1306:
1307: @example
1308: 1 2 3 4 .s 2swap .s 2drop 2drop
1309: @end example
1310:
1311: Two more stack manipulation words are:
1312:
1313: @example
1314: 1 2 .s nip .s drop
1315: 1 2 .s tuck .s 2drop drop
1316: @end example
1317:
1318: @assignment
1319: Replace @code{nip} and @code{tuck} with combinations of other stack
1320: manipulation words.
1321:
1322: @example
1323: Given: How do you get:
1324: 1 2 3 3 2 1
1325: 1 2 3 1 2 3 2
1326: 1 2 3 1 2 3 3
1327: 1 2 3 1 3 3
1328: 1 2 3 2 1 3
1329: 1 2 3 4 4 3 2 1
1330: 1 2 3 1 2 3 1 2 3
1331: 1 2 3 4 1 2 3 4 1 2
1332: 1 2 3
1333: 1 2 3 1 2 3 4
1334: 1 2 3 1 3
1335: @end example
1336: @endassignment
1337:
1338: @example
1339: 5 dup * .
1340: @end example
1341:
1342: @assignment
1343: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1344: Write a piece of Forth code that expects two numbers on the stack
1345: (@var{a} and @var{b}, with @var{b} on top) and computes
1346: @code{(a-b)(a+1)}.
1347: @endassignment
1348:
1.66 anton 1349: Reference: @ref{Stack Manipulation}.
1350:
1351:
1.48 anton 1352: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1353: @section Using files for Forth code
1.66 anton 1354: @cindex loading Forth code, tutorial
1355: @cindex files containing Forth code, tutorial
1.48 anton 1356:
1357: While working at the Forth command line is convenient for one-line
1358: examples and short one-off code, you probably want to store your source
1359: code in files for convenient editing and persistence. You can use your
1360: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1361: Gforth}) to create @var{file.fs} and use
1.48 anton 1362:
1363: @example
1.102 anton 1364: s" @var{file.fs}" included
1.48 anton 1365: @end example
1366:
1367: to load it into your Forth system. The file name extension I use for
1368: Forth files is @samp{.fs}.
1369:
1370: You can easily start Gforth with some files loaded like this:
1371:
1372: @example
1.102 anton 1373: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1374: @end example
1375:
1376: If an error occurs during loading these files, Gforth terminates,
1377: whereas an error during @code{INCLUDED} within Gforth usually gives you
1378: a Gforth command line. Starting the Forth system every time gives you a
1379: clean start every time, without interference from the results of earlier
1380: tries.
1381:
1382: I often put all the tests in a file, then load the code and run the
1383: tests with
1384:
1385: @example
1.102 anton 1386: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1387: @end example
1388:
1389: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1390: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1391: restart this command without ado.
1392:
1393: The advantage of this approach is that the tests can be repeated easily
1394: every time the program ist changed, making it easy to catch bugs
1395: introduced by the change.
1396:
1.66 anton 1397: Reference: @ref{Forth source files}.
1398:
1.48 anton 1399:
1400: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1401: @section Comments
1.66 anton 1402: @cindex comments tutorial
1.48 anton 1403:
1404: @example
1405: \ That's a comment; it ends at the end of the line
1406: ( Another comment; it ends here: ) .s
1407: @end example
1408:
1409: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1410: separated with white space from the following text.
1411:
1412: @example
1413: \This gives an "Undefined word" error
1414: @end example
1415:
1416: The first @code{)} ends a comment started with @code{(}, so you cannot
1417: nest @code{(}-comments; and you cannot comment out text containing a
1418: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1419: avoid @code{)} in word names.}.
1420:
1421: I use @code{\}-comments for descriptive text and for commenting out code
1422: of one or more line; I use @code{(}-comments for describing the stack
1423: effect, the stack contents, or for commenting out sub-line pieces of
1424: code.
1425:
1426: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1427: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1428: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1429: with @kbd{M-q}.
1430:
1.66 anton 1431: Reference: @ref{Comments}.
1432:
1.48 anton 1433:
1434: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1435: @section Colon Definitions
1.66 anton 1436: @cindex colon definitions, tutorial
1437: @cindex definitions, tutorial
1438: @cindex procedures, tutorial
1439: @cindex functions, tutorial
1.48 anton 1440:
1441: are similar to procedures and functions in other programming languages.
1442:
1443: @example
1444: : squared ( n -- n^2 )
1445: dup * ;
1446: 5 squared .
1447: 7 squared .
1448: @end example
1449:
1450: @code{:} starts the colon definition; its name is @code{squared}. The
1451: following comment describes its stack effect. The words @code{dup *}
1452: are not executed, but compiled into the definition. @code{;} ends the
1453: colon definition.
1454:
1455: The newly-defined word can be used like any other word, including using
1456: it in other definitions:
1457:
1458: @example
1459: : cubed ( n -- n^3 )
1460: dup squared * ;
1461: -5 cubed .
1462: : fourth-power ( n -- n^4 )
1463: squared squared ;
1464: 3 fourth-power .
1465: @end example
1466:
1467: @assignment
1468: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1469: @code{/mod} in terms of other Forth words, and check if they work (hint:
1470: test your tests on the originals first). Don't let the
1471: @samp{redefined}-Messages spook you, they are just warnings.
1472: @endassignment
1473:
1.66 anton 1474: Reference: @ref{Colon Definitions}.
1475:
1.48 anton 1476:
1477: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1478: @section Decompilation
1.66 anton 1479: @cindex decompilation tutorial
1480: @cindex see tutorial
1.48 anton 1481:
1482: You can decompile colon definitions with @code{see}:
1483:
1484: @example
1485: see squared
1486: see cubed
1487: @end example
1488:
1489: In Gforth @code{see} shows you a reconstruction of the source code from
1490: the executable code. Informations that were present in the source, but
1491: not in the executable code, are lost (e.g., comments).
1492:
1.65 anton 1493: You can also decompile the predefined words:
1494:
1495: @example
1496: see .
1497: see +
1498: @end example
1499:
1500:
1.48 anton 1501: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1502: @section Stack-Effect Comments
1.66 anton 1503: @cindex stack-effect comments, tutorial
1504: @cindex --, tutorial
1.48 anton 1505: By convention the comment after the name of a definition describes the
1506: stack effect: The part in from of the @samp{--} describes the state of
1507: the stack before the execution of the definition, i.e., the parameters
1508: that are passed into the colon definition; the part behind the @samp{--}
1509: is the state of the stack after the execution of the definition, i.e.,
1510: the results of the definition. The stack comment only shows the top
1511: stack items that the definition accesses and/or changes.
1512:
1513: You should put a correct stack effect on every definition, even if it is
1514: just @code{( -- )}. You should also add some descriptive comment to
1515: more complicated words (I usually do this in the lines following
1516: @code{:}). If you don't do this, your code becomes unreadable (because
1517: you have to work through every definition before you can undertsand
1518: any).
1519:
1520: @assignment
1521: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1522: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1523: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1524: are done, you can compare your stack effects to those in this manual
1.48 anton 1525: (@pxref{Word Index}).
1526: @endassignment
1527:
1528: Sometimes programmers put comments at various places in colon
1529: definitions that describe the contents of the stack at that place (stack
1530: comments); i.e., they are like the first part of a stack-effect
1531: comment. E.g.,
1532:
1533: @example
1534: : cubed ( n -- n^3 )
1535: dup squared ( n n^2 ) * ;
1536: @end example
1537:
1538: In this case the stack comment is pretty superfluous, because the word
1539: is simple enough. If you think it would be a good idea to add such a
1540: comment to increase readability, you should also consider factoring the
1541: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1542: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1543: however, if you decide not to refactor it, then having such a comment is
1544: better than not having it.
1545:
1546: The names of the stack items in stack-effect and stack comments in the
1547: standard, in this manual, and in many programs specify the type through
1548: a type prefix, similar to Fortran and Hungarian notation. The most
1549: frequent prefixes are:
1550:
1551: @table @code
1552: @item n
1553: signed integer
1554: @item u
1555: unsigned integer
1556: @item c
1557: character
1558: @item f
1559: Boolean flags, i.e. @code{false} or @code{true}.
1560: @item a-addr,a-
1561: Cell-aligned address
1562: @item c-addr,c-
1563: Char-aligned address (note that a Char may have two bytes in Windows NT)
1564: @item xt
1565: Execution token, same size as Cell
1566: @item w,x
1567: Cell, can contain an integer or an address. It usually takes 32, 64 or
1568: 16 bits (depending on your platform and Forth system). A cell is more
1569: commonly known as machine word, but the term @emph{word} already means
1570: something different in Forth.
1571: @item d
1572: signed double-cell integer
1573: @item ud
1574: unsigned double-cell integer
1575: @item r
1576: Float (on the FP stack)
1577: @end table
1578:
1579: You can find a more complete list in @ref{Notation}.
1580:
1581: @assignment
1582: Write stack-effect comments for all definitions you have written up to
1583: now.
1584: @endassignment
1585:
1586:
1587: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1588: @section Types
1.66 anton 1589: @cindex types tutorial
1.48 anton 1590:
1591: In Forth the names of the operations are not overloaded; so similar
1592: operations on different types need different names; e.g., @code{+} adds
1593: integers, and you have to use @code{f+} to add floating-point numbers.
1594: The following prefixes are often used for related operations on
1595: different types:
1596:
1597: @table @code
1598: @item (none)
1599: signed integer
1600: @item u
1601: unsigned integer
1602: @item c
1603: character
1604: @item d
1605: signed double-cell integer
1606: @item ud, du
1607: unsigned double-cell integer
1608: @item 2
1609: two cells (not-necessarily double-cell numbers)
1610: @item m, um
1611: mixed single-cell and double-cell operations
1612: @item f
1613: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1614: and @samp{r} represents FP numbers).
1.48 anton 1615: @end table
1616:
1617: If there are no differences between the signed and the unsigned variant
1618: (e.g., for @code{+}), there is only the prefix-less variant.
1619:
1620: Forth does not perform type checking, neither at compile time, nor at
1621: run time. If you use the wrong oeration, the data are interpreted
1622: incorrectly:
1623:
1624: @example
1625: -1 u.
1626: @end example
1627:
1628: If you have only experience with type-checked languages until now, and
1629: have heard how important type-checking is, don't panic! In my
1630: experience (and that of other Forthers), type errors in Forth code are
1631: usually easy to find (once you get used to it), the increased vigilance
1632: of the programmer tends to catch some harder errors in addition to most
1633: type errors, and you never have to work around the type system, so in
1634: most situations the lack of type-checking seems to be a win (projects to
1635: add type checking to Forth have not caught on).
1636:
1637:
1638: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1639: @section Factoring
1.66 anton 1640: @cindex factoring tutorial
1.48 anton 1641:
1642: If you try to write longer definitions, you will soon find it hard to
1643: keep track of the stack contents. Therefore, good Forth programmers
1644: tend to write only short definitions (e.g., three lines). The art of
1645: finding meaningful short definitions is known as factoring (as in
1646: factoring polynomials).
1647:
1648: Well-factored programs offer additional advantages: smaller, more
1649: general words, are easier to test and debug and can be reused more and
1650: better than larger, specialized words.
1651:
1652: So, if you run into difficulties with stack management, when writing
1653: code, try to define meaningful factors for the word, and define the word
1654: in terms of those. Even if a factor contains only two words, it is
1655: often helpful.
1656:
1.65 anton 1657: Good factoring is not easy, and it takes some practice to get the knack
1658: for it; but even experienced Forth programmers often don't find the
1659: right solution right away, but only when rewriting the program. So, if
1660: you don't come up with a good solution immediately, keep trying, don't
1661: despair.
1.48 anton 1662:
1663: @c example !!
1664:
1665:
1666: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1667: @section Designing the stack effect
1.66 anton 1668: @cindex Stack effect design, tutorial
1669: @cindex design of stack effects, tutorial
1.48 anton 1670:
1671: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1672: function; and since there is only one result, you don't have to deal with
1.48 anton 1673: the order of results, either.
1674:
1675: In Forth (and other stack-based languages, e.g., Postscript) the
1676: parameter and result order of a definition is important and should be
1677: designed well. The general guideline is to design the stack effect such
1678: that the word is simple to use in most cases, even if that complicates
1679: the implementation of the word. Some concrete rules are:
1680:
1681: @itemize @bullet
1682:
1683: @item
1684: Words consume all of their parameters (e.g., @code{.}).
1685:
1686: @item
1687: If there is a convention on the order of parameters (e.g., from
1688: mathematics or another programming language), stick with it (e.g.,
1689: @code{-}).
1690:
1691: @item
1692: If one parameter usually requires only a short computation (e.g., it is
1693: a constant), pass it on the top of the stack. Conversely, parameters
1694: that usually require a long sequence of code to compute should be passed
1695: as the bottom (i.e., first) parameter. This makes the code easier to
1696: read, because reader does not need to keep track of the bottom item
1697: through a long sequence of code (or, alternatively, through stack
1.49 anton 1698: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1699: address on top of the stack because it is usually simpler to compute
1700: than the stored value (often the address is just a variable).
1701:
1702: @item
1703: Similarly, results that are usually consumed quickly should be returned
1704: on the top of stack, whereas a result that is often used in long
1705: computations should be passed as bottom result. E.g., the file words
1706: like @code{open-file} return the error code on the top of stack, because
1707: it is usually consumed quickly by @code{throw}; moreover, the error code
1708: has to be checked before doing anything with the other results.
1709:
1710: @end itemize
1711:
1712: These rules are just general guidelines, don't lose sight of the overall
1713: goal to make the words easy to use. E.g., if the convention rule
1714: conflicts with the computation-length rule, you might decide in favour
1715: of the convention if the word will be used rarely, and in favour of the
1716: computation-length rule if the word will be used frequently (because
1717: with frequent use the cost of breaking the computation-length rule would
1718: be quite high, and frequent use makes it easier to remember an
1719: unconventional order).
1720:
1721: @c example !! structure package
1722:
1.65 anton 1723:
1.48 anton 1724: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1725: @section Local Variables
1.66 anton 1726: @cindex local variables, tutorial
1.48 anton 1727:
1728: You can define local variables (@emph{locals}) in a colon definition:
1729:
1730: @example
1731: : swap @{ a b -- b a @}
1732: b a ;
1733: 1 2 swap .s 2drop
1734: @end example
1735:
1736: (If your Forth system does not support this syntax, include
1737: @file{compat/anslocals.fs} first).
1738:
1739: In this example @code{@{ a b -- b a @}} is the locals definition; it
1740: takes two cells from the stack, puts the top of stack in @code{b} and
1741: the next stack element in @code{a}. @code{--} starts a comment ending
1742: with @code{@}}. After the locals definition, using the name of the
1743: local will push its value on the stack. You can leave the comment
1744: part (@code{-- b a}) away:
1745:
1746: @example
1747: : swap ( x1 x2 -- x2 x1 )
1748: @{ a b @} b a ;
1749: @end example
1750:
1751: In Gforth you can have several locals definitions, anywhere in a colon
1752: definition; in contrast, in a standard program you can have only one
1753: locals definition per colon definition, and that locals definition must
1754: be outside any controll structure.
1755:
1756: With locals you can write slightly longer definitions without running
1757: into stack trouble. However, I recommend trying to write colon
1758: definitions without locals for exercise purposes to help you gain the
1759: essential factoring skills.
1760:
1761: @assignment
1762: Rewrite your definitions until now with locals
1763: @endassignment
1764:
1.66 anton 1765: Reference: @ref{Locals}.
1766:
1.48 anton 1767:
1768: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1769: @section Conditional execution
1.66 anton 1770: @cindex conditionals, tutorial
1771: @cindex if, tutorial
1.48 anton 1772:
1773: In Forth you can use control structures only inside colon definitions.
1774: An @code{if}-structure looks like this:
1775:
1776: @example
1777: : abs ( n1 -- +n2 )
1778: dup 0 < if
1779: negate
1780: endif ;
1781: 5 abs .
1782: -5 abs .
1783: @end example
1784:
1785: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1786: the following code is performed, otherwise execution continues after the
1.51 pazsan 1787: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1788: elements and prioduces a flag:
1789:
1790: @example
1791: 1 2 < .
1792: 2 1 < .
1793: 1 1 < .
1794: @end example
1795:
1796: Actually the standard name for @code{endif} is @code{then}. This
1797: tutorial presents the examples using @code{endif}, because this is often
1798: less confusing for people familiar with other programming languages
1799: where @code{then} has a different meaning. If your system does not have
1800: @code{endif}, define it with
1801:
1802: @example
1803: : endif postpone then ; immediate
1804: @end example
1805:
1806: You can optionally use an @code{else}-part:
1807:
1808: @example
1809: : min ( n1 n2 -- n )
1810: 2dup < if
1811: drop
1812: else
1813: nip
1814: endif ;
1815: 2 3 min .
1816: 3 2 min .
1817: @end example
1818:
1819: @assignment
1820: Write @code{min} without @code{else}-part (hint: what's the definition
1821: of @code{nip}?).
1822: @endassignment
1823:
1.66 anton 1824: Reference: @ref{Selection}.
1825:
1.48 anton 1826:
1827: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1828: @section Flags and Comparisons
1.66 anton 1829: @cindex flags tutorial
1830: @cindex comparison tutorial
1.48 anton 1831:
1832: In a false-flag all bits are clear (0 when interpreted as integer). In
1833: a canonical true-flag all bits are set (-1 as a twos-complement signed
1834: integer); in many contexts (e.g., @code{if}) any non-zero value is
1835: treated as true flag.
1836:
1837: @example
1838: false .
1839: true .
1840: true hex u. decimal
1841: @end example
1842:
1843: Comparison words produce canonical flags:
1844:
1845: @example
1846: 1 1 = .
1847: 1 0= .
1848: 0 1 < .
1849: 0 0 < .
1850: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1851: -1 1 < .
1852: @end example
1853:
1.66 anton 1854: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1855: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1856: these combinations are standard (for details see the standard,
1857: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1858:
1859: You can use @code{and or xor invert} can be used as operations on
1860: canonical flags. Actually they are bitwise operations:
1861:
1862: @example
1863: 1 2 and .
1864: 1 2 or .
1865: 1 3 xor .
1866: 1 invert .
1867: @end example
1868:
1869: You can convert a zero/non-zero flag into a canonical flag with
1870: @code{0<>} (and complement it on the way with @code{0=}).
1871:
1872: @example
1873: 1 0= .
1874: 1 0<> .
1875: @end example
1876:
1.65 anton 1877: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1878: operation of the Boolean operations to avoid @code{if}s:
1879:
1880: @example
1881: : foo ( n1 -- n2 )
1882: 0= if
1883: 14
1884: else
1885: 0
1886: endif ;
1887: 0 foo .
1888: 1 foo .
1889:
1890: : foo ( n1 -- n2 )
1891: 0= 14 and ;
1892: 0 foo .
1893: 1 foo .
1894: @end example
1895:
1896: @assignment
1897: Write @code{min} without @code{if}.
1898: @endassignment
1899:
1.66 anton 1900: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1901: @ref{Bitwise operations}.
1902:
1.48 anton 1903:
1904: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1905: @section General Loops
1.66 anton 1906: @cindex loops, indefinite, tutorial
1.48 anton 1907:
1908: The endless loop is the most simple one:
1909:
1910: @example
1911: : endless ( -- )
1912: 0 begin
1913: dup . 1+
1914: again ;
1915: endless
1916: @end example
1917:
1918: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
1919: does nothing at run-time, @code{again} jumps back to @code{begin}.
1920:
1921: A loop with one exit at any place looks like this:
1922:
1923: @example
1924: : log2 ( +n1 -- n2 )
1925: \ logarithmus dualis of n1>0, rounded down to the next integer
1926: assert( dup 0> )
1927: 2/ 0 begin
1928: over 0> while
1929: 1+ swap 2/ swap
1930: repeat
1931: nip ;
1932: 7 log2 .
1933: 8 log2 .
1934: @end example
1935:
1936: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 1937: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 1938: continues behind the @code{while}. @code{Repeat} jumps back to
1939: @code{begin}, just like @code{again}.
1940:
1941: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 1942: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 1943: one bit (arithmetic shift right):
1944:
1945: @example
1946: -5 2 / .
1947: -5 2/ .
1948: @end example
1949:
1950: @code{assert(} is no standard word, but you can get it on systems other
1951: then Gforth by including @file{compat/assert.fs}. You can see what it
1952: does by trying
1953:
1954: @example
1955: 0 log2 .
1956: @end example
1957:
1958: Here's a loop with an exit at the end:
1959:
1960: @example
1961: : log2 ( +n1 -- n2 )
1962: \ logarithmus dualis of n1>0, rounded down to the next integer
1963: assert( dup 0 > )
1964: -1 begin
1965: 1+ swap 2/ swap
1966: over 0 <=
1967: until
1968: nip ;
1969: @end example
1970:
1971: @code{Until} consumes a flag; if it is non-zero, execution continues at
1972: the @code{begin}, otherwise after the @code{until}.
1973:
1974: @assignment
1975: Write a definition for computing the greatest common divisor.
1976: @endassignment
1977:
1.66 anton 1978: Reference: @ref{Simple Loops}.
1979:
1.48 anton 1980:
1981: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
1982: @section Counted loops
1.66 anton 1983: @cindex loops, counted, tutorial
1.48 anton 1984:
1985: @example
1986: : ^ ( n1 u -- n )
1987: \ n = the uth power of u1
1988: 1 swap 0 u+do
1989: over *
1990: loop
1991: nip ;
1992: 3 2 ^ .
1993: 4 3 ^ .
1994: @end example
1995:
1996: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
1997: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
1998: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
1999: times (or not at all, if @code{u3-u4<0}).
2000:
2001: You can see the stack effect design rules at work in the stack effect of
2002: the loop start words: Since the start value of the loop is more
2003: frequently constant than the end value, the start value is passed on
2004: the top-of-stack.
2005:
2006: You can access the counter of a counted loop with @code{i}:
2007:
2008: @example
2009: : fac ( u -- u! )
2010: 1 swap 1+ 1 u+do
2011: i *
2012: loop ;
2013: 5 fac .
2014: 7 fac .
2015: @end example
2016:
2017: There is also @code{+do}, which expects signed numbers (important for
2018: deciding whether to enter the loop).
2019:
2020: @assignment
2021: Write a definition for computing the nth Fibonacci number.
2022: @endassignment
2023:
1.65 anton 2024: You can also use increments other than 1:
2025:
2026: @example
2027: : up2 ( n1 n2 -- )
2028: +do
2029: i .
2030: 2 +loop ;
2031: 10 0 up2
2032:
2033: : down2 ( n1 n2 -- )
2034: -do
2035: i .
2036: 2 -loop ;
2037: 0 10 down2
2038: @end example
1.48 anton 2039:
1.66 anton 2040: Reference: @ref{Counted Loops}.
2041:
1.48 anton 2042:
2043: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2044: @section Recursion
1.66 anton 2045: @cindex recursion tutorial
1.48 anton 2046:
2047: Usually the name of a definition is not visible in the definition; but
2048: earlier definitions are usually visible:
2049:
2050: @example
2051: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2052: : / ( n1 n2 -- n )
2053: dup 0= if
2054: -10 throw \ report division by zero
2055: endif
2056: / \ old version
2057: ;
2058: 1 0 /
2059: @end example
2060:
2061: For recursive definitions you can use @code{recursive} (non-standard) or
2062: @code{recurse}:
2063:
2064: @example
2065: : fac1 ( n -- n! ) recursive
2066: dup 0> if
2067: dup 1- fac1 *
2068: else
2069: drop 1
2070: endif ;
2071: 7 fac1 .
2072:
2073: : fac2 ( n -- n! )
2074: dup 0> if
2075: dup 1- recurse *
2076: else
2077: drop 1
2078: endif ;
2079: 8 fac2 .
2080: @end example
2081:
2082: @assignment
2083: Write a recursive definition for computing the nth Fibonacci number.
2084: @endassignment
2085:
1.66 anton 2086: Reference (including indirect recursion): @xref{Calls and returns}.
2087:
1.48 anton 2088:
2089: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2090: @section Leaving definitions or loops
1.66 anton 2091: @cindex leaving definitions, tutorial
2092: @cindex leaving loops, tutorial
1.48 anton 2093:
2094: @code{EXIT} exits the current definition right away. For every counted
2095: loop that is left in this way, an @code{UNLOOP} has to be performed
2096: before the @code{EXIT}:
2097:
2098: @c !! real examples
2099: @example
2100: : ...
2101: ... u+do
2102: ... if
2103: ... unloop exit
2104: endif
2105: ...
2106: loop
2107: ... ;
2108: @end example
2109:
2110: @code{LEAVE} leaves the innermost counted loop right away:
2111:
2112: @example
2113: : ...
2114: ... u+do
2115: ... if
2116: ... leave
2117: endif
2118: ...
2119: loop
2120: ... ;
2121: @end example
2122:
1.65 anton 2123: @c !! example
1.48 anton 2124:
1.66 anton 2125: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2126:
2127:
1.48 anton 2128: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2129: @section Return Stack
1.66 anton 2130: @cindex return stack tutorial
1.48 anton 2131:
2132: In addition to the data stack Forth also has a second stack, the return
2133: stack; most Forth systems store the return addresses of procedure calls
2134: there (thus its name). Programmers can also use this stack:
2135:
2136: @example
2137: : foo ( n1 n2 -- )
2138: .s
2139: >r .s
1.50 anton 2140: r@@ .
1.48 anton 2141: >r .s
1.50 anton 2142: r@@ .
1.48 anton 2143: r> .
1.50 anton 2144: r@@ .
1.48 anton 2145: r> . ;
2146: 1 2 foo
2147: @end example
2148:
2149: @code{>r} takes an element from the data stack and pushes it onto the
2150: return stack; conversely, @code{r>} moves an elementm from the return to
2151: the data stack; @code{r@@} pushes a copy of the top of the return stack
2152: on the return stack.
2153:
2154: Forth programmers usually use the return stack for storing data
2155: temporarily, if using the data stack alone would be too complex, and
2156: factoring and locals are not an option:
2157:
2158: @example
2159: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2160: rot >r rot r> ;
2161: @end example
2162:
2163: The return address of the definition and the loop control parameters of
2164: counted loops usually reside on the return stack, so you have to take
2165: all items, that you have pushed on the return stack in a colon
2166: definition or counted loop, from the return stack before the definition
2167: or loop ends. You cannot access items that you pushed on the return
2168: stack outside some definition or loop within the definition of loop.
2169:
2170: If you miscount the return stack items, this usually ends in a crash:
2171:
2172: @example
2173: : crash ( n -- )
2174: >r ;
2175: 5 crash
2176: @end example
2177:
2178: You cannot mix using locals and using the return stack (according to the
2179: standard; Gforth has no problem). However, they solve the same
2180: problems, so this shouldn't be an issue.
2181:
2182: @assignment
2183: Can you rewrite any of the definitions you wrote until now in a better
2184: way using the return stack?
2185: @endassignment
2186:
1.66 anton 2187: Reference: @ref{Return stack}.
2188:
1.48 anton 2189:
2190: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2191: @section Memory
1.66 anton 2192: @cindex memory access/allocation tutorial
1.48 anton 2193:
2194: You can create a global variable @code{v} with
2195:
2196: @example
2197: variable v ( -- addr )
2198: @end example
2199:
2200: @code{v} pushes the address of a cell in memory on the stack. This cell
2201: was reserved by @code{variable}. You can use @code{!} (store) to store
2202: values into this cell and @code{@@} (fetch) to load the value from the
2203: stack into memory:
2204:
2205: @example
2206: v .
2207: 5 v ! .s
1.50 anton 2208: v @@ .
1.48 anton 2209: @end example
2210:
1.65 anton 2211: You can see a raw dump of memory with @code{dump}:
2212:
2213: @example
2214: v 1 cells .s dump
2215: @end example
2216:
2217: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2218: generally, address units (aus)) that @code{n1 cells} occupy. You can
2219: also reserve more memory:
1.48 anton 2220:
2221: @example
2222: create v2 20 cells allot
1.65 anton 2223: v2 20 cells dump
1.48 anton 2224: @end example
2225:
1.65 anton 2226: creates a word @code{v2} and reserves 20 uninitialized cells; the
2227: address pushed by @code{v2} points to the start of these 20 cells. You
2228: can use address arithmetic to access these cells:
1.48 anton 2229:
2230: @example
2231: 3 v2 5 cells + !
1.65 anton 2232: v2 20 cells dump
1.48 anton 2233: @end example
2234:
2235: You can reserve and initialize memory with @code{,}:
2236:
2237: @example
2238: create v3
2239: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2240: v3 @@ .
2241: v3 cell+ @@ .
2242: v3 2 cells + @@ .
1.65 anton 2243: v3 5 cells dump
1.48 anton 2244: @end example
2245:
2246: @assignment
2247: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2248: @code{u} cells, with the first of these cells at @code{addr}, the next
2249: one at @code{addr cell+} etc.
2250: @endassignment
2251:
2252: You can also reserve memory without creating a new word:
2253:
2254: @example
1.60 anton 2255: here 10 cells allot .
2256: here .
1.48 anton 2257: @end example
2258:
2259: @code{Here} pushes the start address of the memory area. You should
2260: store it somewhere, or you will have a hard time finding the memory area
2261: again.
2262:
2263: @code{Allot} manages dictionary memory. The dictionary memory contains
2264: the system's data structures for words etc. on Gforth and most other
2265: Forth systems. It is managed like a stack: You can free the memory that
2266: you have just @code{allot}ed with
2267:
2268: @example
2269: -10 cells allot
1.60 anton 2270: here .
1.48 anton 2271: @end example
2272:
2273: Note that you cannot do this if you have created a new word in the
2274: meantime (because then your @code{allot}ed memory is no longer on the
2275: top of the dictionary ``stack'').
2276:
2277: Alternatively, you can use @code{allocate} and @code{free} which allow
2278: freeing memory in any order:
2279:
2280: @example
2281: 10 cells allocate throw .s
2282: 20 cells allocate throw .s
2283: swap
2284: free throw
2285: free throw
2286: @end example
2287:
2288: The @code{throw}s deal with errors (e.g., out of memory).
2289:
1.65 anton 2290: And there is also a
2291: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2292: garbage collector}, which eliminates the need to @code{free} memory
2293: explicitly.
1.48 anton 2294:
1.66 anton 2295: Reference: @ref{Memory}.
2296:
1.48 anton 2297:
2298: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2299: @section Characters and Strings
1.66 anton 2300: @cindex strings tutorial
2301: @cindex characters tutorial
1.48 anton 2302:
2303: On the stack characters take up a cell, like numbers. In memory they
2304: have their own size (one 8-bit byte on most systems), and therefore
2305: require their own words for memory access:
2306:
2307: @example
2308: create v4
2309: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2310: v4 4 chars + c@@ .
1.65 anton 2311: v4 5 chars dump
1.48 anton 2312: @end example
2313:
2314: The preferred representation of strings on the stack is @code{addr
2315: u-count}, where @code{addr} is the address of the first character and
2316: @code{u-count} is the number of characters in the string.
2317:
2318: @example
2319: v4 5 type
2320: @end example
2321:
2322: You get a string constant with
2323:
2324: @example
2325: s" hello, world" .s
2326: type
2327: @end example
2328:
2329: Make sure you have a space between @code{s"} and the string; @code{s"}
2330: is a normal Forth word and must be delimited with white space (try what
2331: happens when you remove the space).
2332:
2333: However, this interpretive use of @code{s"} is quite restricted: the
2334: string exists only until the next call of @code{s"} (some Forth systems
2335: keep more than one of these strings, but usually they still have a
1.62 crook 2336: limited lifetime).
1.48 anton 2337:
2338: @example
2339: s" hello," s" world" .s
2340: type
2341: type
2342: @end example
2343:
1.62 crook 2344: You can also use @code{s"} in a definition, and the resulting
2345: strings then live forever (well, for as long as the definition):
1.48 anton 2346:
2347: @example
2348: : foo s" hello," s" world" ;
2349: foo .s
2350: type
2351: type
2352: @end example
2353:
2354: @assignment
2355: @code{Emit ( c -- )} types @code{c} as character (not a number).
2356: Implement @code{type ( addr u -- )}.
2357: @endassignment
2358:
1.66 anton 2359: Reference: @ref{Memory Blocks}.
2360:
2361:
1.84 pazsan 2362: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2363: @section Alignment
1.66 anton 2364: @cindex alignment tutorial
2365: @cindex memory alignment tutorial
1.48 anton 2366:
2367: On many processors cells have to be aligned in memory, if you want to
2368: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2369: not require alignment, access to aligned cells is faster).
1.48 anton 2370:
2371: @code{Create} aligns @code{here} (i.e., the place where the next
2372: allocation will occur, and that the @code{create}d word points to).
2373: Likewise, the memory produced by @code{allocate} starts at an aligned
2374: address. Adding a number of @code{cells} to an aligned address produces
2375: another aligned address.
2376:
2377: However, address arithmetic involving @code{char+} and @code{chars} can
2378: create an address that is not cell-aligned. @code{Aligned ( addr --
2379: a-addr )} produces the next aligned address:
2380:
2381: @example
1.50 anton 2382: v3 char+ aligned .s @@ .
2383: v3 char+ .s @@ .
1.48 anton 2384: @end example
2385:
2386: Similarly, @code{align} advances @code{here} to the next aligned
2387: address:
2388:
2389: @example
2390: create v5 97 c,
2391: here .
2392: align here .
2393: 1000 ,
2394: @end example
2395:
2396: Note that you should use aligned addresses even if your processor does
2397: not require them, if you want your program to be portable.
2398:
1.66 anton 2399: Reference: @ref{Address arithmetic}.
2400:
1.48 anton 2401:
1.84 pazsan 2402: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2403: @section Files
2404: @cindex files tutorial
2405:
2406: This section gives a short introduction into how to use files inside
2407: Forth. It's broken up into five easy steps:
2408:
2409: @enumerate 1
2410: @item Opened an ASCII text file for input
2411: @item Opened a file for output
2412: @item Read input file until string matched (or some other condition matched)
2413: @item Wrote some lines from input ( modified or not) to output
2414: @item Closed the files.
2415: @end enumerate
2416:
2417: @subsection Open file for input
2418:
2419: @example
2420: s" foo.in" r/o open-file throw Value fd-in
2421: @end example
2422:
2423: @subsection Create file for output
2424:
2425: @example
2426: s" foo.out" w/o create-file throw Value fd-out
2427: @end example
2428:
2429: The available file modes are r/o for read-only access, r/w for
2430: read-write access, and w/o for write-only access. You could open both
2431: files with r/w, too, if you like. All file words return error codes; for
2432: most applications, it's best to pass there error codes with @code{throw}
2433: to the outer error handler.
2434:
2435: If you want words for opening and assigning, define them as follows:
2436:
2437: @example
2438: 0 Value fd-in
2439: 0 Value fd-out
2440: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2441: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2442: @end example
2443:
2444: Usage example:
2445:
2446: @example
2447: s" foo.in" open-input
2448: s" foo.out" open-output
2449: @end example
2450:
2451: @subsection Scan file for a particular line
2452:
2453: @example
2454: 256 Constant max-line
2455: Create line-buffer max-line 2 + allot
2456:
2457: : scan-file ( addr u -- )
2458: begin
2459: line-buffer max-line fd-in read-line throw
2460: while
2461: >r 2dup line-buffer r> compare 0=
2462: until
2463: else
2464: drop
2465: then
2466: 2drop ;
2467: @end example
2468:
2469: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2470: the buffer at addr, and returns the number of bytes read, a flag that is
2471: false when the end of file is reached, and an error code.
1.84 pazsan 2472:
2473: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2474: returns zero if both strings are equal. It returns a positive number if
2475: the first string is lexically greater, a negative if the second string
2476: is lexically greater.
2477:
2478: We haven't seen this loop here; it has two exits. Since the @code{while}
2479: exits with the number of bytes read on the stack, we have to clean up
2480: that separately; that's after the @code{else}.
2481:
2482: Usage example:
2483:
2484: @example
2485: s" The text I search is here" scan-file
2486: @end example
2487:
2488: @subsection Copy input to output
2489:
2490: @example
2491: : copy-file ( -- )
2492: begin
2493: line-buffer max-line fd-in read-line throw
2494: while
2495: line-buffer swap fd-out write-file throw
2496: repeat ;
2497: @end example
2498:
2499: @subsection Close files
2500:
2501: @example
2502: fd-in close-file throw
2503: fd-out close-file throw
2504: @end example
2505:
2506: Likewise, you can put that into definitions, too:
2507:
2508: @example
2509: : close-input ( -- ) fd-in close-file throw ;
2510: : close-output ( -- ) fd-out close-file throw ;
2511: @end example
2512:
2513: @assignment
2514: How could you modify @code{copy-file} so that it copies until a second line is
2515: matched? Can you write a program that extracts a section of a text file,
2516: given the line that starts and the line that terminates that section?
2517: @endassignment
2518:
2519: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2520: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2521: @cindex semantics tutorial
2522: @cindex interpretation semantics tutorial
2523: @cindex compilation semantics tutorial
2524: @cindex immediate, tutorial
1.48 anton 2525:
2526: When a word is compiled, it behaves differently from being interpreted.
2527: E.g., consider @code{+}:
2528:
2529: @example
2530: 1 2 + .
2531: : foo + ;
2532: @end example
2533:
2534: These two behaviours are known as compilation and interpretation
2535: semantics. For normal words (e.g., @code{+}), the compilation semantics
2536: is to append the interpretation semantics to the currently defined word
2537: (@code{foo} in the example above). I.e., when @code{foo} is executed
2538: later, the interpretation semantics of @code{+} (i.e., adding two
2539: numbers) will be performed.
2540:
2541: However, there are words with non-default compilation semantics, e.g.,
2542: the control-flow words like @code{if}. You can use @code{immediate} to
2543: change the compilation semantics of the last defined word to be equal to
2544: the interpretation semantics:
2545:
2546: @example
2547: : [FOO] ( -- )
2548: 5 . ; immediate
2549:
2550: [FOO]
2551: : bar ( -- )
2552: [FOO] ;
2553: bar
2554: see bar
2555: @end example
2556:
2557: Two conventions to mark words with non-default compilation semnatics are
2558: names with brackets (more frequently used) and to write them all in
2559: upper case (less frequently used).
2560:
2561: In Gforth (and many other systems) you can also remove the
2562: interpretation semantics with @code{compile-only} (the compilation
2563: semantics is derived from the original interpretation semantics):
2564:
2565: @example
2566: : flip ( -- )
2567: 6 . ; compile-only \ but not immediate
2568: flip
2569:
2570: : flop ( -- )
2571: flip ;
2572: flop
2573: @end example
2574:
2575: In this example the interpretation semantics of @code{flop} is equal to
2576: the original interpretation semantics of @code{flip}.
2577:
2578: The text interpreter has two states: in interpret state, it performs the
2579: interpretation semantics of words it encounters; in compile state, it
2580: performs the compilation semantics of these words.
2581:
2582: Among other things, @code{:} switches into compile state, and @code{;}
2583: switches back to interpret state. They contain the factors @code{]}
2584: (switch to compile state) and @code{[} (switch to interpret state), that
2585: do nothing but switch the state.
2586:
2587: @example
2588: : xxx ( -- )
2589: [ 5 . ]
2590: ;
2591:
2592: xxx
2593: see xxx
2594: @end example
2595:
2596: These brackets are also the source of the naming convention mentioned
2597: above.
2598:
1.66 anton 2599: Reference: @ref{Interpretation and Compilation Semantics}.
2600:
1.48 anton 2601:
2602: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2603: @section Execution Tokens
1.66 anton 2604: @cindex execution tokens tutorial
2605: @cindex XT tutorial
1.48 anton 2606:
2607: @code{' word} gives you the execution token (XT) of a word. The XT is a
2608: cell representing the interpretation semantics of a word. You can
2609: execute this semantics with @code{execute}:
2610:
2611: @example
2612: ' + .s
2613: 1 2 rot execute .
2614: @end example
2615:
2616: The XT is similar to a function pointer in C. However, parameter
2617: passing through the stack makes it a little more flexible:
2618:
2619: @example
2620: : map-array ( ... addr u xt -- ... )
1.50 anton 2621: \ executes xt ( ... x -- ... ) for every element of the array starting
2622: \ at addr and containing u elements
1.48 anton 2623: @{ xt @}
2624: cells over + swap ?do
1.50 anton 2625: i @@ xt execute
1.48 anton 2626: 1 cells +loop ;
2627:
2628: create a 3 , 4 , 2 , -1 , 4 ,
2629: a 5 ' . map-array .s
2630: 0 a 5 ' + map-array .
2631: s" max-n" environment? drop .s
2632: a 5 ' min map-array .
2633: @end example
2634:
2635: You can use map-array with the XTs of words that consume one element
2636: more than they produce. In theory you can also use it with other XTs,
2637: but the stack effect then depends on the size of the array, which is
2638: hard to understand.
2639:
1.51 pazsan 2640: Since XTs are cell-sized, you can store them in memory and manipulate
2641: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2642: word with @code{compile,}:
2643:
2644: @example
2645: : foo1 ( n1 n2 -- n )
2646: [ ' + compile, ] ;
2647: see foo
2648: @end example
2649:
2650: This is non-standard, because @code{compile,} has no compilation
2651: semantics in the standard, but it works in good Forth systems. For the
2652: broken ones, use
2653:
2654: @example
2655: : [compile,] compile, ; immediate
2656:
2657: : foo1 ( n1 n2 -- n )
2658: [ ' + ] [compile,] ;
2659: see foo
2660: @end example
2661:
2662: @code{'} is a word with default compilation semantics; it parses the
2663: next word when its interpretation semantics are executed, not during
2664: compilation:
2665:
2666: @example
2667: : foo ( -- xt )
2668: ' ;
2669: see foo
2670: : bar ( ... "word" -- ... )
2671: ' execute ;
2672: see bar
1.60 anton 2673: 1 2 bar + .
1.48 anton 2674: @end example
2675:
2676: You often want to parse a word during compilation and compile its XT so
2677: it will be pushed on the stack at run-time. @code{[']} does this:
2678:
2679: @example
2680: : xt-+ ( -- xt )
2681: ['] + ;
2682: see xt-+
2683: 1 2 xt-+ execute .
2684: @end example
2685:
2686: Many programmers tend to see @code{'} and the word it parses as one
2687: unit, and expect it to behave like @code{[']} when compiled, and are
2688: confused by the actual behaviour. If you are, just remember that the
2689: Forth system just takes @code{'} as one unit and has no idea that it is
2690: a parsing word (attempts to convenience programmers in this issue have
2691: usually resulted in even worse pitfalls, see
1.66 anton 2692: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2693: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2694:
2695: Note that the state of the interpreter does not come into play when
1.51 pazsan 2696: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2697: compile state, it still gives you the interpretation semantics. And
2698: whatever that state is, @code{execute} performs the semantics
1.66 anton 2699: represented by the XT (i.e., for XTs produced with @code{'} the
2700: interpretation semantics).
2701:
2702: Reference: @ref{Tokens for Words}.
1.48 anton 2703:
2704:
2705: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2706: @section Exceptions
1.66 anton 2707: @cindex exceptions tutorial
1.48 anton 2708:
2709: @code{throw ( n -- )} causes an exception unless n is zero.
2710:
2711: @example
2712: 100 throw .s
2713: 0 throw .s
2714: @end example
2715:
2716: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2717: it catches exceptions and pushes the number of the exception on the
2718: stack (or 0, if the xt executed without exception). If there was an
2719: exception, the stacks have the same depth as when entering @code{catch}:
2720:
2721: @example
2722: .s
2723: 3 0 ' / catch .s
2724: 3 2 ' / catch .s
2725: @end example
2726:
2727: @assignment
2728: Try the same with @code{execute} instead of @code{catch}.
2729: @endassignment
2730:
2731: @code{Throw} always jumps to the dynamically next enclosing
2732: @code{catch}, even if it has to leave several call levels to achieve
2733: this:
2734:
2735: @example
2736: : foo 100 throw ;
2737: : foo1 foo ." after foo" ;
1.51 pazsan 2738: : bar ['] foo1 catch ;
1.60 anton 2739: bar .
1.48 anton 2740: @end example
2741:
2742: It is often important to restore a value upon leaving a definition, even
2743: if the definition is left through an exception. You can ensure this
2744: like this:
2745:
2746: @example
2747: : ...
2748: save-x
1.51 pazsan 2749: ['] word-changing-x catch ( ... n )
1.48 anton 2750: restore-x
2751: ( ... n ) throw ;
2752: @end example
2753:
1.55 anton 2754: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2755: @code{try ... recover ... endtry}. If the code between @code{try} and
2756: @code{recover} has an exception, the stack depths are restored, the
2757: exception number is pushed on the stack, and the code between
2758: @code{recover} and @code{endtry} is performed. E.g., the definition for
2759: @code{catch} is
2760:
2761: @example
2762: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2763: try
2764: execute 0
2765: recover
2766: nip
2767: endtry ;
2768: @end example
2769:
2770: The equivalent to the restoration code above is
2771:
2772: @example
2773: : ...
2774: save-x
2775: try
1.92 anton 2776: word-changing-x 0
2777: recover endtry
1.48 anton 2778: restore-x
2779: throw ;
2780: @end example
2781:
1.92 anton 2782: This works if @code{word-changing-x} does not change the stack depth,
2783: otherwise you should add some code between @code{recover} and
2784: @code{endtry} to balance the stack.
1.48 anton 2785:
1.66 anton 2786: Reference: @ref{Exception Handling}.
2787:
1.48 anton 2788:
2789: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2790: @section Defining Words
1.66 anton 2791: @cindex defining words tutorial
2792: @cindex does> tutorial
2793: @cindex create...does> tutorial
2794:
2795: @c before semantics?
1.48 anton 2796:
2797: @code{:}, @code{create}, and @code{variable} are definition words: They
2798: define other words. @code{Constant} is another definition word:
2799:
2800: @example
2801: 5 constant foo
2802: foo .
2803: @end example
2804:
2805: You can also use the prefixes @code{2} (double-cell) and @code{f}
2806: (floating point) with @code{variable} and @code{constant}.
2807:
2808: You can also define your own defining words. E.g.:
2809:
2810: @example
2811: : variable ( "name" -- )
2812: create 0 , ;
2813: @end example
2814:
2815: You can also define defining words that create words that do something
2816: other than just producing their address:
2817:
2818: @example
2819: : constant ( n "name" -- )
2820: create ,
2821: does> ( -- n )
1.50 anton 2822: ( addr ) @@ ;
1.48 anton 2823:
2824: 5 constant foo
2825: foo .
2826: @end example
2827:
2828: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2829: @code{does>} replaces @code{;}, but it also does something else: It
2830: changes the last defined word such that it pushes the address of the
2831: body of the word and then performs the code after the @code{does>}
2832: whenever it is called.
2833:
2834: In the example above, @code{constant} uses @code{,} to store 5 into the
2835: body of @code{foo}. When @code{foo} executes, it pushes the address of
2836: the body onto the stack, then (in the code after the @code{does>})
2837: fetches the 5 from there.
2838:
2839: The stack comment near the @code{does>} reflects the stack effect of the
2840: defined word, not the stack effect of the code after the @code{does>}
2841: (the difference is that the code expects the address of the body that
2842: the stack comment does not show).
2843:
2844: You can use these definition words to do factoring in cases that involve
2845: (other) definition words. E.g., a field offset is always added to an
2846: address. Instead of defining
2847:
2848: @example
2849: 2 cells constant offset-field1
2850: @end example
2851:
2852: and using this like
2853:
2854: @example
2855: ( addr ) offset-field1 +
2856: @end example
2857:
2858: you can define a definition word
2859:
2860: @example
2861: : simple-field ( n "name" -- )
2862: create ,
2863: does> ( n1 -- n1+n )
1.50 anton 2864: ( addr ) @@ + ;
1.48 anton 2865: @end example
1.21 crook 2866:
1.48 anton 2867: Definition and use of field offsets now look like this:
1.21 crook 2868:
1.48 anton 2869: @example
2870: 2 cells simple-field field1
1.60 anton 2871: create mystruct 4 cells allot
2872: mystruct .s field1 .s drop
1.48 anton 2873: @end example
1.21 crook 2874:
1.48 anton 2875: If you want to do something with the word without performing the code
2876: after the @code{does>}, you can access the body of a @code{create}d word
2877: with @code{>body ( xt -- addr )}:
1.21 crook 2878:
1.48 anton 2879: @example
2880: : value ( n "name" -- )
2881: create ,
2882: does> ( -- n1 )
1.50 anton 2883: @@ ;
1.48 anton 2884: : to ( n "name" -- )
2885: ' >body ! ;
1.21 crook 2886:
1.48 anton 2887: 5 value foo
2888: foo .
2889: 7 to foo
2890: foo .
2891: @end example
1.21 crook 2892:
1.48 anton 2893: @assignment
2894: Define @code{defer ( "name" -- )}, which creates a word that stores an
2895: XT (at the start the XT of @code{abort}), and upon execution
2896: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2897: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2898: recursion is one application of @code{defer}.
2899: @endassignment
1.29 crook 2900:
1.66 anton 2901: Reference: @ref{User-defined Defining Words}.
2902:
2903:
1.48 anton 2904: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2905: @section Arrays and Records
1.66 anton 2906: @cindex arrays tutorial
2907: @cindex records tutorial
2908: @cindex structs tutorial
1.29 crook 2909:
1.48 anton 2910: Forth has no standard words for defining data structures such as arrays
2911: and records (structs in C terminology), but you can build them yourself
2912: based on address arithmetic. You can also define words for defining
2913: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 2914:
1.48 anton 2915: One of the first projects a Forth newcomer sets out upon when learning
2916: about defining words is an array defining word (possibly for
2917: n-dimensional arrays). Go ahead and do it, I did it, too; you will
2918: learn something from it. However, don't be disappointed when you later
2919: learn that you have little use for these words (inappropriate use would
2920: be even worse). I have not yet found a set of useful array words yet;
2921: the needs are just too diverse, and named, global arrays (the result of
2922: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 2923: consider how to pass them as parameters). Another such project is a set
2924: of words to help dealing with strings.
1.29 crook 2925:
1.48 anton 2926: On the other hand, there is a useful set of record words, and it has
2927: been defined in @file{compat/struct.fs}; these words are predefined in
2928: Gforth. They are explained in depth elsewhere in this manual (see
2929: @pxref{Structures}). The @code{simple-field} example above is
2930: simplified variant of fields in this package.
1.21 crook 2931:
2932:
1.48 anton 2933: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
2934: @section @code{POSTPONE}
1.66 anton 2935: @cindex postpone tutorial
1.21 crook 2936:
1.48 anton 2937: You can compile the compilation semantics (instead of compiling the
2938: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 2939:
1.48 anton 2940: @example
2941: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 2942: POSTPONE + ; immediate
1.48 anton 2943: : foo ( n1 n2 -- n )
2944: MY-+ ;
2945: 1 2 foo .
2946: see foo
2947: @end example
1.21 crook 2948:
1.48 anton 2949: During the definition of @code{foo} the text interpreter performs the
2950: compilation semantics of @code{MY-+}, which performs the compilation
2951: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
2952:
2953: This example also displays separate stack comments for the compilation
2954: semantics and for the stack effect of the compiled code. For words with
2955: default compilation semantics these stack effects are usually not
2956: displayed; the stack effect of the compilation semantics is always
2957: @code{( -- )} for these words, the stack effect for the compiled code is
2958: the stack effect of the interpretation semantics.
2959:
2960: Note that the state of the interpreter does not come into play when
2961: performing the compilation semantics in this way. You can also perform
2962: it interpretively, e.g.:
2963:
2964: @example
2965: : foo2 ( n1 n2 -- n )
2966: [ MY-+ ] ;
2967: 1 2 foo .
2968: see foo
2969: @end example
1.21 crook 2970:
1.48 anton 2971: However, there are some broken Forth systems where this does not always
1.62 crook 2972: work, and therefore this practice was been declared non-standard in
1.48 anton 2973: 1999.
2974: @c !! repair.fs
2975:
2976: Here is another example for using @code{POSTPONE}:
1.44 crook 2977:
1.48 anton 2978: @example
2979: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
2980: POSTPONE negate POSTPONE + ; immediate compile-only
2981: : bar ( n1 n2 -- n )
2982: MY-- ;
2983: 2 1 bar .
2984: see bar
2985: @end example
1.21 crook 2986:
1.48 anton 2987: You can define @code{ENDIF} in this way:
1.21 crook 2988:
1.48 anton 2989: @example
2990: : ENDIF ( Compilation: orig -- )
2991: POSTPONE then ; immediate
2992: @end example
1.21 crook 2993:
1.48 anton 2994: @assignment
2995: Write @code{MY-2DUP} that has compilation semantics equivalent to
2996: @code{2dup}, but compiles @code{over over}.
2997: @endassignment
1.29 crook 2998:
1.66 anton 2999: @c !! @xref{Macros} for reference
3000:
3001:
1.48 anton 3002: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3003: @section @code{Literal}
1.66 anton 3004: @cindex literal tutorial
1.29 crook 3005:
1.48 anton 3006: You cannot @code{POSTPONE} numbers:
1.21 crook 3007:
1.48 anton 3008: @example
3009: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3010: @end example
3011:
1.48 anton 3012: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3013:
1.48 anton 3014: @example
3015: : [FOO] ( compilation: --; run-time: -- n )
3016: 500 POSTPONE literal ; immediate
1.29 crook 3017:
1.60 anton 3018: : flip [FOO] ;
1.48 anton 3019: flip .
3020: see flip
3021: @end example
1.29 crook 3022:
1.48 anton 3023: @code{LITERAL} consumes a number at compile-time (when it's compilation
3024: semantics are executed) and pushes it at run-time (when the code it
3025: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3026: number computed at compile time into the current word:
1.29 crook 3027:
1.48 anton 3028: @example
3029: : bar ( -- n )
3030: [ 2 2 + ] literal ;
3031: see bar
3032: @end example
1.29 crook 3033:
1.48 anton 3034: @assignment
3035: Write @code{]L} which allows writing the example above as @code{: bar (
3036: -- n ) [ 2 2 + ]L ;}
3037: @endassignment
3038:
1.66 anton 3039: @c !! @xref{Macros} for reference
3040:
1.48 anton 3041:
3042: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3043: @section Advanced macros
1.66 anton 3044: @cindex macros, advanced tutorial
3045: @cindex run-time code generation, tutorial
1.48 anton 3046:
1.66 anton 3047: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3048: Execution Tokens}. It frequently performs @code{execute}, a relatively
3049: expensive operation in some Forth implementations. You can use
1.48 anton 3050: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3051: and produce a word that contains the word to be performed directly:
3052:
3053: @c use ]] ... [[
3054: @example
3055: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3056: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3057: \ array beginning at addr and containing u elements
3058: @{ xt @}
3059: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3060: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3061: 1 cells POSTPONE literal POSTPONE +loop ;
3062:
3063: : sum-array ( addr u -- n )
3064: 0 rot rot [ ' + compile-map-array ] ;
3065: see sum-array
3066: a 5 sum-array .
3067: @end example
3068:
3069: You can use the full power of Forth for generating the code; here's an
3070: example where the code is generated in a loop:
3071:
3072: @example
3073: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3074: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3075: POSTPONE tuck POSTPONE @@
1.48 anton 3076: POSTPONE literal POSTPONE * POSTPONE +
3077: POSTPONE swap POSTPONE cell+ ;
3078:
3079: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3080: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3081: 0 postpone literal postpone swap
3082: [ ' compile-vmul-step compile-map-array ]
3083: postpone drop ;
3084: see compile-vmul
3085:
3086: : a-vmul ( addr -- n )
1.51 pazsan 3087: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3088: [ a 5 compile-vmul ] ;
3089: see a-vmul
3090: a a-vmul .
3091: @end example
3092:
3093: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3094: also use @code{map-array} instead (try it now!).
1.48 anton 3095:
3096: You can use this technique for efficient multiplication of large
3097: matrices. In matrix multiplication, you multiply every line of one
3098: matrix with every column of the other matrix. You can generate the code
3099: for one line once, and use it for every column. The only downside of
3100: this technique is that it is cumbersome to recover the memory consumed
3101: by the generated code when you are done (and in more complicated cases
3102: it is not possible portably).
3103:
1.66 anton 3104: @c !! @xref{Macros} for reference
3105:
3106:
1.48 anton 3107: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3108: @section Compilation Tokens
1.66 anton 3109: @cindex compilation tokens, tutorial
3110: @cindex CT, tutorial
1.48 anton 3111:
3112: This section is Gforth-specific. You can skip it.
3113:
3114: @code{' word compile,} compiles the interpretation semantics. For words
3115: with default compilation semantics this is the same as performing the
3116: compilation semantics. To represent the compilation semantics of other
3117: words (e.g., words like @code{if} that have no interpretation
3118: semantics), Gforth has the concept of a compilation token (CT,
3119: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3120: You can perform the compilation semantics represented by a CT with
3121: @code{execute}:
1.29 crook 3122:
1.48 anton 3123: @example
3124: : foo2 ( n1 n2 -- n )
3125: [ comp' + execute ] ;
3126: see foo
3127: @end example
1.29 crook 3128:
1.48 anton 3129: You can compile the compilation semantics represented by a CT with
3130: @code{postpone,}:
1.30 anton 3131:
1.48 anton 3132: @example
3133: : foo3 ( -- )
3134: [ comp' + postpone, ] ;
3135: see foo3
3136: @end example
1.30 anton 3137:
1.51 pazsan 3138: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3139: @code{comp'} is particularly useful for words that have no
3140: interpretation semantics:
1.29 crook 3141:
1.30 anton 3142: @example
1.48 anton 3143: ' if
1.60 anton 3144: comp' if .s 2drop
1.30 anton 3145: @end example
3146:
1.66 anton 3147: Reference: @ref{Tokens for Words}.
3148:
1.29 crook 3149:
1.48 anton 3150: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3151: @section Wordlists and Search Order
1.66 anton 3152: @cindex wordlists tutorial
3153: @cindex search order, tutorial
1.48 anton 3154:
3155: The dictionary is not just a memory area that allows you to allocate
3156: memory with @code{allot}, it also contains the Forth words, arranged in
3157: several wordlists. When searching for a word in a wordlist,
3158: conceptually you start searching at the youngest and proceed towards
3159: older words (in reality most systems nowadays use hash-tables); i.e., if
3160: you define a word with the same name as an older word, the new word
3161: shadows the older word.
3162:
3163: Which wordlists are searched in which order is determined by the search
3164: order. You can display the search order with @code{order}. It displays
3165: first the search order, starting with the wordlist searched first, then
3166: it displays the wordlist that will contain newly defined words.
1.21 crook 3167:
1.48 anton 3168: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3169:
1.48 anton 3170: @example
3171: wordlist constant mywords
3172: @end example
1.21 crook 3173:
1.48 anton 3174: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3175: defined words (the @emph{current} wordlist):
1.21 crook 3176:
1.48 anton 3177: @example
3178: mywords set-current
3179: order
3180: @end example
1.26 crook 3181:
1.48 anton 3182: Gforth does not display a name for the wordlist in @code{mywords}
3183: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3184:
1.48 anton 3185: You can get the current wordlist with @code{get-current ( -- wid)}. If
3186: you want to put something into a specific wordlist without overall
3187: effect on the current wordlist, this typically looks like this:
1.21 crook 3188:
1.48 anton 3189: @example
3190: get-current mywords set-current ( wid )
3191: create someword
3192: ( wid ) set-current
3193: @end example
1.21 crook 3194:
1.48 anton 3195: You can write the search order with @code{set-order ( wid1 .. widn n --
3196: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3197: searched wordlist is topmost.
1.21 crook 3198:
1.48 anton 3199: @example
3200: get-order mywords swap 1+ set-order
3201: order
3202: @end example
1.21 crook 3203:
1.48 anton 3204: Yes, the order of wordlists in the output of @code{order} is reversed
3205: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3206:
1.48 anton 3207: @assignment
3208: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3209: wordlist to the search order. Define @code{previous ( -- )}, which
3210: removes the first searched wordlist from the search order. Experiment
3211: with boundary conditions (you will see some crashes or situations that
3212: are hard or impossible to leave).
3213: @endassignment
1.21 crook 3214:
1.48 anton 3215: The search order is a powerful foundation for providing features similar
3216: to Modula-2 modules and C++ namespaces. However, trying to modularize
3217: programs in this way has disadvantages for debugging and reuse/factoring
3218: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3219: though). These disadvantages are not so clear in other
1.82 anton 3220: languages/programming environments, because these languages are not so
1.48 anton 3221: strong in debugging and reuse.
1.21 crook 3222:
1.66 anton 3223: @c !! example
3224:
3225: Reference: @ref{Word Lists}.
1.21 crook 3226:
1.29 crook 3227: @c ******************************************************************
1.48 anton 3228: @node Introduction, Words, Tutorial, Top
1.29 crook 3229: @comment node-name, next, previous, up
3230: @chapter An Introduction to ANS Forth
3231: @cindex Forth - an introduction
1.21 crook 3232:
1.83 anton 3233: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3234: that it is slower-paced in its examples, but uses them to dive deep into
3235: explaining Forth internals (not covered by the Tutorial). Apart from
3236: that, this chapter covers far less material. It is suitable for reading
3237: without using a computer.
3238:
1.29 crook 3239: The primary purpose of this manual is to document Gforth. However, since
3240: Forth is not a widely-known language and there is a lack of up-to-date
3241: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3242: material. For other sources of Forth-related
3243: information, see @ref{Forth-related information}.
1.21 crook 3244:
1.29 crook 3245: The examples in this section should work on any ANS Forth; the
3246: output shown was produced using Gforth. Each example attempts to
3247: reproduce the exact output that Gforth produces. If you try out the
3248: examples (and you should), what you should type is shown @kbd{like this}
3249: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3250: that, where the example shows @key{RET} it means that you should
1.29 crook 3251: press the ``carriage return'' key. Unfortunately, some output formats for
3252: this manual cannot show the difference between @kbd{this} and
3253: @code{this} which will make trying out the examples harder (but not
3254: impossible).
1.21 crook 3255:
1.29 crook 3256: Forth is an unusual language. It provides an interactive development
3257: environment which includes both an interpreter and compiler. Forth
3258: programming style encourages you to break a problem down into many
3259: @cindex factoring
3260: small fragments (@dfn{factoring}), and then to develop and test each
3261: fragment interactively. Forth advocates assert that breaking the
3262: edit-compile-test cycle used by conventional programming languages can
3263: lead to great productivity improvements.
1.21 crook 3264:
1.29 crook 3265: @menu
1.67 anton 3266: * Introducing the Text Interpreter::
3267: * Stacks and Postfix notation::
3268: * Your first definition::
3269: * How does that work?::
3270: * Forth is written in Forth::
3271: * Review - elements of a Forth system::
3272: * Where to go next::
3273: * Exercises::
1.29 crook 3274: @end menu
1.21 crook 3275:
1.29 crook 3276: @comment ----------------------------------------------
3277: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3278: @section Introducing the Text Interpreter
3279: @cindex text interpreter
3280: @cindex outer interpreter
1.21 crook 3281:
1.30 anton 3282: @c IMO this is too detailed and the pace is too slow for
3283: @c an introduction. If you know German, take a look at
3284: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3285: @c to see how I do it - anton
3286:
1.44 crook 3287: @c nac-> Where I have accepted your comments 100% and modified the text
3288: @c accordingly, I have deleted your comments. Elsewhere I have added a
3289: @c response like this to attempt to rationalise what I have done. Of
3290: @c course, this is a very clumsy mechanism for something that would be
3291: @c done far more efficiently over a beer. Please delete any dialogue
3292: @c you consider closed.
3293:
1.29 crook 3294: When you invoke the Forth image, you will see a startup banner printed
3295: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3296: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3297: its command line interpreter, which is called the @dfn{Text Interpreter}
3298: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3299: about the text interpreter as you read through this chapter, for more
3300: detail @pxref{The Text Interpreter}).
1.21 crook 3301:
1.29 crook 3302: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3303: input. Type a number and press the @key{RET} key:
1.21 crook 3304:
1.26 crook 3305: @example
1.30 anton 3306: @kbd{45@key{RET}} ok
1.26 crook 3307: @end example
1.21 crook 3308:
1.29 crook 3309: Rather than give you a prompt to invite you to input something, the text
3310: interpreter prints a status message @i{after} it has processed a line
3311: of input. The status message in this case (``@code{ ok}'' followed by
3312: carriage-return) indicates that the text interpreter was able to process
3313: all of your input successfully. Now type something illegal:
3314:
3315: @example
1.30 anton 3316: @kbd{qwer341@key{RET}}
1.29 crook 3317: :1: Undefined word
3318: qwer341
3319: ^^^^^^^
3320: $400D2BA8 Bounce
3321: $400DBDA8 no.extensions
3322: @end example
1.23 crook 3323:
1.29 crook 3324: The exact text, other than the ``Undefined word'' may differ slightly on
3325: your system, but the effect is the same; when the text interpreter
3326: detects an error, it discards any remaining text on a line, resets
1.49 anton 3327: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3328: messages}.
1.23 crook 3329:
1.29 crook 3330: The text interpreter waits for you to press carriage-return, and then
3331: processes your input line. Starting at the beginning of the line, it
3332: breaks the line into groups of characters separated by spaces. For each
3333: group of characters in turn, it makes two attempts to do something:
1.23 crook 3334:
1.29 crook 3335: @itemize @bullet
3336: @item
1.44 crook 3337: @cindex name dictionary
1.29 crook 3338: It tries to treat it as a command. It does this by searching a @dfn{name
3339: dictionary}. If the group of characters matches an entry in the name
3340: dictionary, the name dictionary provides the text interpreter with
3341: information that allows the text interpreter perform some actions. In
3342: Forth jargon, we say that the group
3343: @cindex word
3344: @cindex definition
3345: @cindex execution token
3346: @cindex xt
3347: of characters names a @dfn{word}, that the dictionary search returns an
3348: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3349: word, and that the text interpreter executes the xt. Often, the terms
3350: @dfn{word} and @dfn{definition} are used interchangeably.
3351: @item
3352: If the text interpreter fails to find a match in the name dictionary, it
3353: tries to treat the group of characters as a number in the current number
3354: base (when you start up Forth, the current number base is base 10). If
3355: the group of characters legitimately represents a number, the text
3356: interpreter pushes the number onto a stack (we'll learn more about that
3357: in the next section).
3358: @end itemize
1.23 crook 3359:
1.29 crook 3360: If the text interpreter is unable to do either of these things with any
3361: group of characters, it discards the group of characters and the rest of
3362: the line, then prints an error message. If the text interpreter reaches
3363: the end of the line without error, it prints the status message ``@code{ ok}''
3364: followed by carriage-return.
1.21 crook 3365:
1.29 crook 3366: This is the simplest command we can give to the text interpreter:
1.23 crook 3367:
3368: @example
1.30 anton 3369: @key{RET} ok
1.23 crook 3370: @end example
1.21 crook 3371:
1.29 crook 3372: The text interpreter did everything we asked it to do (nothing) without
3373: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3374: command:
1.21 crook 3375:
1.23 crook 3376: @example
1.30 anton 3377: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3378: :1: Undefined word
3379: 12 dup fred dup
3380: ^^^^
3381: $400D2BA8 Bounce
3382: $400DBDA8 no.extensions
1.23 crook 3383: @end example
1.21 crook 3384:
1.29 crook 3385: When you press the carriage-return key, the text interpreter starts to
3386: work its way along the line:
1.21 crook 3387:
1.29 crook 3388: @itemize @bullet
3389: @item
3390: When it gets to the space after the @code{2}, it takes the group of
3391: characters @code{12} and looks them up in the name
3392: dictionary@footnote{We can't tell if it found them or not, but assume
3393: for now that it did not}. There is no match for this group of characters
3394: in the name dictionary, so it tries to treat them as a number. It is
3395: able to do this successfully, so it puts the number, 12, ``on the stack''
3396: (whatever that means).
3397: @item
3398: The text interpreter resumes scanning the line and gets the next group
3399: of characters, @code{dup}. It looks it up in the name dictionary and
3400: (you'll have to take my word for this) finds it, and executes the word
3401: @code{dup} (whatever that means).
3402: @item
3403: Once again, the text interpreter resumes scanning the line and gets the
3404: group of characters @code{fred}. It looks them up in the name
3405: dictionary, but can't find them. It tries to treat them as a number, but
3406: they don't represent any legal number.
3407: @end itemize
1.21 crook 3408:
1.29 crook 3409: At this point, the text interpreter gives up and prints an error
3410: message. The error message shows exactly how far the text interpreter
3411: got in processing the line. In particular, it shows that the text
3412: interpreter made no attempt to do anything with the final character
3413: group, @code{dup}, even though we have good reason to believe that the
3414: text interpreter would have no problem looking that word up and
3415: executing it a second time.
1.21 crook 3416:
3417:
1.29 crook 3418: @comment ----------------------------------------------
3419: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3420: @section Stacks, postfix notation and parameter passing
3421: @cindex text interpreter
3422: @cindex outer interpreter
1.21 crook 3423:
1.29 crook 3424: In procedural programming languages (like C and Pascal), the
3425: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3426: functions or procedures are called with @dfn{explicit parameters}. For
3427: example, in C we might write:
1.21 crook 3428:
1.23 crook 3429: @example
1.29 crook 3430: total = total + new_volume(length,height,depth);
1.23 crook 3431: @end example
1.21 crook 3432:
1.23 crook 3433: @noindent
1.29 crook 3434: where new_volume is a function-call to another piece of code, and total,
3435: length, height and depth are all variables. length, height and depth are
3436: parameters to the function-call.
1.21 crook 3437:
1.29 crook 3438: In Forth, the equivalent of the function or procedure is the
3439: @dfn{definition} and parameters are implicitly passed between
3440: definitions using a shared stack that is visible to the
3441: programmer. Although Forth does support variables, the existence of the
3442: stack means that they are used far less often than in most other
3443: programming languages. When the text interpreter encounters a number, it
3444: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3445: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3446: used for any operation is implied unambiguously by the operation being
3447: performed. The stack used for all integer operations is called the @dfn{data
3448: stack} and, since this is the stack used most commonly, references to
3449: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3450:
1.29 crook 3451: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3452:
1.23 crook 3453: @example
1.30 anton 3454: @kbd{1 2 3@key{RET}} ok
1.23 crook 3455: @end example
1.21 crook 3456:
1.29 crook 3457: Then this instructs the text interpreter to placed three numbers on the
3458: (data) stack. An analogy for the behaviour of the stack is to take a
3459: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3460: the table. The 3 was the last card onto the pile (``last-in'') and if
3461: you take a card off the pile then, unless you're prepared to fiddle a
3462: bit, the card that you take off will be the 3 (``first-out''). The
3463: number that will be first-out of the stack is called the @dfn{top of
3464: stack}, which
3465: @cindex TOS definition
3466: is often abbreviated to @dfn{TOS}.
1.21 crook 3467:
1.29 crook 3468: To understand how parameters are passed in Forth, consider the
3469: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3470: be surprised to learn that this definition performs addition. More
3471: precisely, it adds two number together and produces a result. Where does
3472: it get the two numbers from? It takes the top two numbers off the
3473: stack. Where does it place the result? On the stack. You can act-out the
3474: behaviour of @code{+} with your playing cards like this:
1.21 crook 3475:
3476: @itemize @bullet
3477: @item
1.29 crook 3478: Pick up two cards from the stack on the table
1.21 crook 3479: @item
1.29 crook 3480: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3481: numbers''
1.21 crook 3482: @item
1.29 crook 3483: Decide that the answer is 5
1.21 crook 3484: @item
1.29 crook 3485: Shuffle the two cards back into the pack and find a 5
1.21 crook 3486: @item
1.29 crook 3487: Put a 5 on the remaining ace that's on the table.
1.21 crook 3488: @end itemize
3489:
1.29 crook 3490: If you don't have a pack of cards handy but you do have Forth running,
3491: you can use the definition @code{.s} to show the current state of the stack,
3492: without affecting the stack. Type:
1.21 crook 3493:
3494: @example
1.30 anton 3495: @kbd{clearstack 1 2 3@key{RET}} ok
3496: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3497: @end example
3498:
1.29 crook 3499: The text interpreter looks up the word @code{clearstack} and executes
3500: it; it tidies up the stack and removes any entries that may have been
3501: left on it by earlier examples. The text interpreter pushes each of the
3502: three numbers in turn onto the stack. Finally, the text interpreter
3503: looks up the word @code{.s} and executes it. The effect of executing
3504: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3505: followed by a list of all the items on the stack; the item on the far
3506: right-hand side is the TOS.
1.21 crook 3507:
1.29 crook 3508: You can now type:
1.21 crook 3509:
1.29 crook 3510: @example
1.30 anton 3511: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3512: @end example
1.21 crook 3513:
1.29 crook 3514: @noindent
3515: which is correct; there are now 2 items on the stack and the result of
3516: the addition is 5.
1.23 crook 3517:
1.29 crook 3518: If you're playing with cards, try doing a second addition: pick up the
3519: two cards, work out that their sum is 6, shuffle them into the pack,
3520: look for a 6 and place that on the table. You now have just one item on
3521: the stack. What happens if you try to do a third addition? Pick up the
3522: first card, pick up the second card -- ah! There is no second card. This
3523: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3524: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3525: Underflow or an Invalid Memory Address error).
1.23 crook 3526:
1.29 crook 3527: The opposite situation to a stack underflow is a @dfn{stack overflow},
3528: which simply accepts that there is a finite amount of storage space
3529: reserved for the stack. To stretch the playing card analogy, if you had
3530: enough packs of cards and you piled the cards up on the table, you would
3531: eventually be unable to add another card; you'd hit the ceiling. Gforth
3532: allows you to set the maximum size of the stacks. In general, the only
3533: time that you will get a stack overflow is because a definition has a
3534: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3535:
1.29 crook 3536: There's one final use for the playing card analogy. If you model your
3537: stack using a pack of playing cards, the maximum number of items on
3538: your stack will be 52 (I assume you didn't use the Joker). The maximum
3539: @i{value} of any item on the stack is 13 (the King). In fact, the only
3540: possible numbers are positive integer numbers 1 through 13; you can't
3541: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3542: think about some of the cards, you can accommodate different
3543: numbers. For example, you could think of the Jack as representing 0,
3544: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3545: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3546: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3547:
1.29 crook 3548: In that analogy, the limit was the amount of information that a single
3549: stack entry could hold, and Forth has a similar limit. In Forth, the
3550: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3551: implementation dependent and affects the maximum value that a stack
3552: entry can hold. A Standard Forth provides a cell size of at least
3553: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3554:
1.29 crook 3555: Forth does not do any type checking for you, so you are free to
3556: manipulate and combine stack items in any way you wish. A convenient way
3557: of treating stack items is as 2's complement signed integers, and that
3558: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3559:
1.29 crook 3560: @example
1.30 anton 3561: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3562: @end example
1.21 crook 3563:
1.29 crook 3564: If you use numbers and definitions like @code{+} in order to turn Forth
3565: into a great big pocket calculator, you will realise that it's rather
3566: different from a normal calculator. Rather than typing 2 + 3 = you had
3567: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3568: result). The terminology used to describe this difference is to say that
3569: your calculator uses @dfn{Infix Notation} (parameters and operators are
3570: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3571: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3572:
1.29 crook 3573: Whilst postfix notation might look confusing to begin with, it has
3574: several important advantages:
1.21 crook 3575:
1.23 crook 3576: @itemize @bullet
3577: @item
1.29 crook 3578: it is unambiguous
1.23 crook 3579: @item
1.29 crook 3580: it is more concise
1.23 crook 3581: @item
1.29 crook 3582: it fits naturally with a stack-based system
1.23 crook 3583: @end itemize
1.21 crook 3584:
1.29 crook 3585: To examine these claims in more detail, consider these sums:
1.21 crook 3586:
1.29 crook 3587: @example
3588: 6 + 5 * 4 =
3589: 4 * 5 + 6 =
3590: @end example
1.21 crook 3591:
1.29 crook 3592: If you're just learning maths or your maths is very rusty, you will
3593: probably come up with the answer 44 for the first and 26 for the
3594: second. If you are a bit of a whizz at maths you will remember the
3595: @i{convention} that multiplication takes precendence over addition, and
3596: you'd come up with the answer 26 both times. To explain the answer 26
3597: to someone who got the answer 44, you'd probably rewrite the first sum
3598: like this:
1.21 crook 3599:
1.29 crook 3600: @example
3601: 6 + (5 * 4) =
3602: @end example
1.21 crook 3603:
1.29 crook 3604: If what you really wanted was to perform the addition before the
3605: multiplication, you would have to use parentheses to force it.
1.21 crook 3606:
1.29 crook 3607: If you did the first two sums on a pocket calculator you would probably
3608: get the right answers, unless you were very cautious and entered them using
3609: these keystroke sequences:
1.21 crook 3610:
1.29 crook 3611: 6 + 5 = * 4 =
3612: 4 * 5 = + 6 =
1.21 crook 3613:
1.29 crook 3614: Postfix notation is unambiguous because the order that the operators
3615: are applied is always explicit; that also means that parentheses are
3616: never required. The operators are @i{active} (the act of quoting the
3617: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3618:
1.29 crook 3619: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3620: equivalent ways:
1.26 crook 3621:
3622: @example
1.29 crook 3623: 6 5 4 * + or:
3624: 5 4 * 6 +
1.26 crook 3625: @end example
1.23 crook 3626:
1.29 crook 3627: An important thing that you should notice about this notation is that
3628: the @i{order} of the numbers does not change; if you want to subtract
3629: 2 from 10 you type @code{10 2 -}.
1.1 anton 3630:
1.29 crook 3631: The reason that Forth uses postfix notation is very simple to explain: it
3632: makes the implementation extremely simple, and it follows naturally from
3633: using the stack as a mechanism for passing parameters. Another way of
3634: thinking about this is to realise that all Forth definitions are
3635: @i{active}; they execute as they are encountered by the text
3636: interpreter. The result of this is that the syntax of Forth is trivially
3637: simple.
1.1 anton 3638:
3639:
3640:
1.29 crook 3641: @comment ----------------------------------------------
3642: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3643: @section Your first Forth definition
3644: @cindex first definition
1.1 anton 3645:
1.29 crook 3646: Until now, the examples we've seen have been trivial; we've just been
3647: using Forth as a bigger-than-pocket calculator. Also, each calculation
3648: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3649: again@footnote{That's not quite true. If you press the up-arrow key on
3650: your keyboard you should be able to scroll back to any earlier command,
3651: edit it and re-enter it.} In this section we'll see how to add new
3652: words to Forth's vocabulary.
1.1 anton 3653:
1.29 crook 3654: The easiest way to create a new word is to use a @dfn{colon
3655: definition}. We'll define a few and try them out before worrying too
3656: much about how they work. Try typing in these examples; be careful to
3657: copy the spaces accurately:
1.1 anton 3658:
1.29 crook 3659: @example
3660: : add-two 2 + . ;
3661: : greet ." Hello and welcome" ;
3662: : demo 5 add-two ;
3663: @end example
1.1 anton 3664:
1.29 crook 3665: @noindent
3666: Now try them out:
1.1 anton 3667:
1.29 crook 3668: @example
1.30 anton 3669: @kbd{greet@key{RET}} Hello and welcome ok
3670: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3671: @kbd{4 add-two@key{RET}} 6 ok
3672: @kbd{demo@key{RET}} 7 ok
3673: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3674: @end example
1.1 anton 3675:
1.29 crook 3676: The first new thing that we've introduced here is the pair of words
3677: @code{:} and @code{;}. These are used to start and terminate a new
3678: definition, respectively. The first word after the @code{:} is the name
3679: for the new definition.
1.1 anton 3680:
1.29 crook 3681: As you can see from the examples, a definition is built up of words that
3682: have already been defined; Forth makes no distinction between
3683: definitions that existed when you started the system up, and those that
3684: you define yourself.
1.1 anton 3685:
1.29 crook 3686: The examples also introduce the words @code{.} (dot), @code{."}
3687: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3688: the stack and displays it. It's like @code{.s} except that it only
3689: displays the top item of the stack and it is destructive; after it has
3690: executed, the number is no longer on the stack. There is always one
3691: space printed after the number, and no spaces before it. Dot-quote
3692: defines a string (a sequence of characters) that will be printed when
3693: the word is executed. The string can contain any printable characters
3694: except @code{"}. A @code{"} has a special function; it is not a Forth
3695: word but it acts as a delimiter (the way that delimiters work is
3696: described in the next section). Finally, @code{dup} duplicates the value
3697: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3698:
1.29 crook 3699: We already know that the text interpreter searches through the
3700: dictionary to locate names. If you've followed the examples earlier, you
3701: will already have a definition called @code{add-two}. Lets try modifying
3702: it by typing in a new definition:
1.1 anton 3703:
1.29 crook 3704: @example
1.30 anton 3705: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3706: @end example
1.5 anton 3707:
1.29 crook 3708: Forth recognised that we were defining a word that already exists, and
3709: printed a message to warn us of that fact. Let's try out the new
3710: definition:
1.5 anton 3711:
1.29 crook 3712: @example
1.30 anton 3713: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3714: @end example
1.1 anton 3715:
1.29 crook 3716: @noindent
3717: All that we've actually done here, though, is to create a new
3718: definition, with a particular name. The fact that there was already a
3719: definition with the same name did not make any difference to the way
3720: that the new definition was created (except that Forth printed a warning
3721: message). The old definition of add-two still exists (try @code{demo}
3722: again to see that this is true). Any new definition will use the new
3723: definition of @code{add-two}, but old definitions continue to use the
3724: version that already existed at the time that they were @code{compiled}.
1.1 anton 3725:
1.29 crook 3726: Before you go on to the next section, try defining and redefining some
3727: words of your own.
1.1 anton 3728:
1.29 crook 3729: @comment ----------------------------------------------
3730: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3731: @section How does that work?
3732: @cindex parsing words
1.1 anton 3733:
1.30 anton 3734: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3735:
3736: @c Is it a good idea to talk about the interpretation semantics of a
3737: @c number? We don't have an xt to go along with it. - anton
3738:
3739: @c Now that I have eliminated execution semantics, I wonder if it would not
3740: @c be better to keep them (or add run-time semantics), to make it easier to
3741: @c explain what compilation semantics usually does. - anton
3742:
1.44 crook 3743: @c nac-> I removed the term ``default compilation sematics'' from the
3744: @c introductory chapter. Removing ``execution semantics'' was making
3745: @c everything simpler to explain, then I think the use of this term made
3746: @c everything more complex again. I replaced it with ``default
3747: @c semantics'' (which is used elsewhere in the manual) by which I mean
3748: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3749: @c flag set''.
3750:
3751: @c anton: I have eliminated default semantics (except in one place where it
3752: @c means "default interpretation and compilation semantics"), because it
3753: @c makes no sense in the presence of combined words. I reverted to
3754: @c "execution semantics" where necessary.
3755:
3756: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3757: @c section (and, unusually for me, I think I even made it shorter!). See
3758: @c what you think -- I know I have not addressed your primary concern
3759: @c that it is too heavy-going for an introduction. From what I understood
3760: @c of your course notes it looks as though they might be a good framework.
3761: @c Things that I've tried to capture here are some things that came as a
3762: @c great revelation here when I first understood them. Also, I like the
3763: @c fact that a very simple code example shows up almost all of the issues
3764: @c that you need to understand to see how Forth works. That's unique and
3765: @c worthwhile to emphasise.
3766:
1.83 anton 3767: @c anton: I think it's a good idea to present the details, especially those
3768: @c that you found to be a revelation, and probably the tutorial tries to be
3769: @c too superficial and does not get some of the things across that make
3770: @c Forth special. I do believe that most of the time these things should
3771: @c be discussed at the end of a section or in separate sections instead of
3772: @c in the middle of a section (e.g., the stuff you added in "User-defined
3773: @c defining words" leads in a completely different direction from the rest
3774: @c of the section).
3775:
1.29 crook 3776: Now we're going to take another look at the definition of @code{add-two}
3777: from the previous section. From our knowledge of the way that the text
3778: interpreter works, we would have expected this result when we tried to
3779: define @code{add-two}:
1.21 crook 3780:
1.29 crook 3781: @example
1.44 crook 3782: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 3783: ^^^^^^^
3784: Error: Undefined word
3785: @end example
1.28 crook 3786:
1.29 crook 3787: The reason that this didn't happen is bound up in the way that @code{:}
3788: works. The word @code{:} does two special things. The first special
3789: thing that it does prevents the text interpreter from ever seeing the
3790: characters @code{add-two}. The text interpreter uses a variable called
3791: @cindex modifying >IN
1.44 crook 3792: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3793: input line. When it encounters the word @code{:} it behaves in exactly
3794: the same way as it does for any other word; it looks it up in the name
3795: dictionary, finds its xt and executes it. When @code{:} executes, it
3796: looks at the input buffer, finds the word @code{add-two} and advances the
3797: value of @code{>IN} to point past it. It then does some other stuff
3798: associated with creating the new definition (including creating an entry
3799: for @code{add-two} in the name dictionary). When the execution of @code{:}
3800: completes, control returns to the text interpreter, which is oblivious
3801: to the fact that it has been tricked into ignoring part of the input
3802: line.
1.21 crook 3803:
1.29 crook 3804: @cindex parsing words
3805: Words like @code{:} -- words that advance the value of @code{>IN} and so
3806: prevent the text interpreter from acting on the whole of the input line
3807: -- are called @dfn{parsing words}.
1.21 crook 3808:
1.29 crook 3809: @cindex @code{state} - effect on the text interpreter
3810: @cindex text interpreter - effect of state
3811: The second special thing that @code{:} does is change the value of a
3812: variable called @code{state}, which affects the way that the text
3813: interpreter behaves. When Gforth starts up, @code{state} has the value
3814: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3815: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3816: the text interpreter is said to be @dfn{compiling}.
3817:
3818: In this example, the text interpreter is compiling when it processes the
3819: string ``@code{2 + . ;}''. It still breaks the string down into
3820: character sequences in the same way. However, instead of pushing the
3821: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3822: into the definition of @code{add-two} that will make the number @code{2} get
3823: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3824: the behaviours of @code{+} and @code{.} are also compiled into the
3825: definition.
3826:
3827: One category of words don't get compiled. These so-called @dfn{immediate
3828: words} get executed (performed @i{now}) regardless of whether the text
3829: interpreter is interpreting or compiling. The word @code{;} is an
3830: immediate word. Rather than being compiled into the definition, it
3831: executes. Its effect is to terminate the current definition, which
3832: includes changing the value of @code{state} back to 0.
3833:
3834: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3835: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3836: definition.
1.28 crook 3837:
1.30 anton 3838: In Forth, every word or number can be described in terms of two
1.29 crook 3839: properties:
1.28 crook 3840:
3841: @itemize @bullet
3842: @item
1.29 crook 3843: @cindex interpretation semantics
1.44 crook 3844: Its @dfn{interpretation semantics} describe how it will behave when the
3845: text interpreter encounters it in @dfn{interpret} state. The
3846: interpretation semantics of a word are represented by an @dfn{execution
3847: token}.
1.28 crook 3848: @item
1.29 crook 3849: @cindex compilation semantics
1.44 crook 3850: Its @dfn{compilation semantics} describe how it will behave when the
3851: text interpreter encounters it in @dfn{compile} state. The compilation
3852: semantics of a word are represented in an implementation-dependent way;
3853: Gforth uses a @dfn{compilation token}.
1.29 crook 3854: @end itemize
3855:
3856: @noindent
3857: Numbers are always treated in a fixed way:
3858:
3859: @itemize @bullet
1.28 crook 3860: @item
1.44 crook 3861: When the number is @dfn{interpreted}, its behaviour is to push the
3862: number onto the stack.
1.28 crook 3863: @item
1.30 anton 3864: When the number is @dfn{compiled}, a piece of code is appended to the
3865: current definition that pushes the number when it runs. (In other words,
3866: the compilation semantics of a number are to postpone its interpretation
3867: semantics until the run-time of the definition that it is being compiled
3868: into.)
1.29 crook 3869: @end itemize
3870:
1.44 crook 3871: Words don't behave in such a regular way, but most have @i{default
3872: semantics} which means that they behave like this:
1.29 crook 3873:
3874: @itemize @bullet
1.28 crook 3875: @item
1.30 anton 3876: The @dfn{interpretation semantics} of the word are to do something useful.
3877: @item
1.29 crook 3878: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3879: @dfn{interpretation semantics} to the current definition (so that its
3880: run-time behaviour is to do something useful).
1.28 crook 3881: @end itemize
3882:
1.30 anton 3883: @cindex immediate words
1.44 crook 3884: The actual behaviour of any particular word can be controlled by using
3885: the words @code{immediate} and @code{compile-only} when the word is
3886: defined. These words set flags in the name dictionary entry of the most
3887: recently defined word, and these flags are retrieved by the text
3888: interpreter when it finds the word in the name dictionary.
3889:
3890: A word that is marked as @dfn{immediate} has compilation semantics that
3891: are identical to its interpretation semantics. In other words, it
3892: behaves like this:
1.29 crook 3893:
3894: @itemize @bullet
3895: @item
1.30 anton 3896: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3897: @item
1.30 anton 3898: The @dfn{compilation semantics} of the word are to do something useful
3899: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3900: @end itemize
1.28 crook 3901:
1.44 crook 3902: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3903: performing the interpretation semantics of the word directly; an attempt
3904: to do so will generate an error. It is never necessary to use
3905: @code{compile-only} (and it is not even part of ANS Forth, though it is
3906: provided by many implementations) but it is good etiquette to apply it
3907: to a word that will not behave correctly (and might have unexpected
3908: side-effects) in interpret state. For example, it is only legal to use
3909: the conditional word @code{IF} within a definition. If you forget this
3910: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3911: @code{compile-only} allows the text interpreter to generate a helpful
3912: error message rather than subjecting you to the consequences of your
3913: folly.
3914:
1.29 crook 3915: This example shows the difference between an immediate and a
3916: non-immediate word:
1.28 crook 3917:
1.29 crook 3918: @example
3919: : show-state state @@ . ;
3920: : show-state-now show-state ; immediate
3921: : word1 show-state ;
3922: : word2 show-state-now ;
1.28 crook 3923: @end example
1.23 crook 3924:
1.29 crook 3925: The word @code{immediate} after the definition of @code{show-state-now}
3926: makes that word an immediate word. These definitions introduce a new
3927: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
3928: variable, and leaves it on the stack. Therefore, the behaviour of
3929: @code{show-state} is to print a number that represents the current value
3930: of @code{state}.
1.28 crook 3931:
1.29 crook 3932: When you execute @code{word1}, it prints the number 0, indicating that
3933: the system is interpreting. When the text interpreter compiled the
3934: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 3935: compilation semantics are to append its interpretation semantics to the
1.29 crook 3936: current definition. When you execute @code{word1}, it performs the
1.30 anton 3937: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 3938: (and therefore @code{show-state}) are executed, the system is
3939: interpreting.
1.28 crook 3940:
1.30 anton 3941: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 3942: you should have seen the number -1 printed, followed by ``@code{
3943: ok}''. When the text interpreter compiled the definition of
3944: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 3945: whose compilation semantics are therefore to perform its interpretation
1.29 crook 3946: semantics. It is executed straight away (even before the text
3947: interpreter has moved on to process another group of characters; the
3948: @code{;} in this example). The effect of executing it are to display the
3949: value of @code{state} @i{at the time that the definition of}
3950: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
3951: system is compiling at this time. If you execute @code{word2} it does
3952: nothing at all.
1.28 crook 3953:
1.29 crook 3954: @cindex @code{."}, how it works
3955: Before leaving the subject of immediate words, consider the behaviour of
3956: @code{."} in the definition of @code{greet}, in the previous
3957: section. This word is both a parsing word and an immediate word. Notice
3958: that there is a space between @code{."} and the start of the text
3959: @code{Hello and welcome}, but that there is no space between the last
3960: letter of @code{welcome} and the @code{"} character. The reason for this
3961: is that @code{."} is a Forth word; it must have a space after it so that
3962: the text interpreter can identify it. The @code{"} is not a Forth word;
3963: it is a @dfn{delimiter}. The examples earlier show that, when the string
3964: is displayed, there is neither a space before the @code{H} nor after the
3965: @code{e}. Since @code{."} is an immediate word, it executes at the time
3966: that @code{greet} is defined. When it executes, its behaviour is to
3967: search forward in the input line looking for the delimiter. When it
3968: finds the delimiter, it updates @code{>IN} to point past the
3969: delimiter. It also compiles some magic code into the definition of
3970: @code{greet}; the xt of a run-time routine that prints a text string. It
3971: compiles the string @code{Hello and welcome} into memory so that it is
3972: available to be printed later. When the text interpreter gains control,
3973: the next word it finds in the input stream is @code{;} and so it
3974: terminates the definition of @code{greet}.
1.28 crook 3975:
3976:
3977: @comment ----------------------------------------------
1.29 crook 3978: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
3979: @section Forth is written in Forth
3980: @cindex structure of Forth programs
3981:
3982: When you start up a Forth compiler, a large number of definitions
3983: already exist. In Forth, you develop a new application using bottom-up
3984: programming techniques to create new definitions that are defined in
3985: terms of existing definitions. As you create each definition you can
3986: test and debug it interactively.
3987:
3988: If you have tried out the examples in this section, you will probably
3989: have typed them in by hand; when you leave Gforth, your definitions will
3990: be lost. You can avoid this by using a text editor to enter Forth source
3991: code into a file, and then loading code from the file using
1.49 anton 3992: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 3993: processed by the text interpreter, just as though you had typed it in by
3994: hand@footnote{Actually, there are some subtle differences -- see
3995: @ref{The Text Interpreter}.}.
3996:
3997: Gforth also supports the traditional Forth alternative to using text
1.49 anton 3998: files for program entry (@pxref{Blocks}).
1.28 crook 3999:
1.29 crook 4000: In common with many, if not most, Forth compilers, most of Gforth is
4001: actually written in Forth. All of the @file{.fs} files in the
4002: installation directory@footnote{For example,
1.30 anton 4003: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4004: study to see examples of Forth programming.
1.28 crook 4005:
1.29 crook 4006: Gforth maintains a history file that records every line that you type to
4007: the text interpreter. This file is preserved between sessions, and is
4008: used to provide a command-line recall facility. If you enter long
4009: definitions by hand, you can use a text editor to paste them out of the
4010: history file into a Forth source file for reuse at a later time
1.49 anton 4011: (for more information @pxref{Command-line editing}).
1.28 crook 4012:
4013:
4014: @comment ----------------------------------------------
1.29 crook 4015: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4016: @section Review - elements of a Forth system
4017: @cindex elements of a Forth system
1.28 crook 4018:
1.29 crook 4019: To summarise this chapter:
1.28 crook 4020:
4021: @itemize @bullet
4022: @item
1.29 crook 4023: Forth programs use @dfn{factoring} to break a problem down into small
4024: fragments called @dfn{words} or @dfn{definitions}.
4025: @item
4026: Forth program development is an interactive process.
4027: @item
4028: The main command loop that accepts input, and controls both
4029: interpretation and compilation, is called the @dfn{text interpreter}
4030: (also known as the @dfn{outer interpreter}).
4031: @item
4032: Forth has a very simple syntax, consisting of words and numbers
4033: separated by spaces or carriage-return characters. Any additional syntax
4034: is imposed by @dfn{parsing words}.
4035: @item
4036: Forth uses a stack to pass parameters between words. As a result, it
4037: uses postfix notation.
4038: @item
4039: To use a word that has previously been defined, the text interpreter
4040: searches for the word in the @dfn{name dictionary}.
4041: @item
1.30 anton 4042: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4043: @item
1.29 crook 4044: The text interpreter uses the value of @code{state} to select between
4045: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4046: semantics} of a word that it encounters.
1.28 crook 4047: @item
1.30 anton 4048: The relationship between the @dfn{interpretation semantics} and
4049: @dfn{compilation semantics} for a word
1.29 crook 4050: depend upon the way in which the word was defined (for example, whether
4051: it is an @dfn{immediate} word).
1.28 crook 4052: @item
1.29 crook 4053: Forth definitions can be implemented in Forth (called @dfn{high-level
4054: definitions}) or in some other way (usually a lower-level language and
4055: as a result often called @dfn{low-level definitions}, @dfn{code
4056: definitions} or @dfn{primitives}).
1.28 crook 4057: @item
1.29 crook 4058: Many Forth systems are implemented mainly in Forth.
1.28 crook 4059: @end itemize
4060:
4061:
1.29 crook 4062: @comment ----------------------------------------------
1.48 anton 4063: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4064: @section Where To Go Next
4065: @cindex where to go next
1.28 crook 4066:
1.29 crook 4067: Amazing as it may seem, if you have read (and understood) this far, you
4068: know almost all the fundamentals about the inner workings of a Forth
4069: system. You certainly know enough to be able to read and understand the
4070: rest of this manual and the ANS Forth document, to learn more about the
4071: facilities that Forth in general and Gforth in particular provide. Even
4072: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4073: However, that's not a good idea just yet... better to try writing some
1.29 crook 4074: programs in Gforth.
1.28 crook 4075:
1.29 crook 4076: Forth has such a rich vocabulary that it can be hard to know where to
4077: start in learning it. This section suggests a few sets of words that are
4078: enough to write small but useful programs. Use the word index in this
4079: document to learn more about each word, then try it out and try to write
4080: small definitions using it. Start by experimenting with these words:
1.28 crook 4081:
4082: @itemize @bullet
4083: @item
1.29 crook 4084: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4085: @item
4086: Comparison: @code{MIN MAX =}
4087: @item
4088: Logic: @code{AND OR XOR NOT}
4089: @item
4090: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4091: @item
1.29 crook 4092: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4093: @item
1.29 crook 4094: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4095: @item
1.29 crook 4096: Defining words: @code{: ; CREATE}
1.28 crook 4097: @item
1.29 crook 4098: Memory allocation words: @code{ALLOT ,}
1.28 crook 4099: @item
1.29 crook 4100: Tools: @code{SEE WORDS .S MARKER}
4101: @end itemize
4102:
4103: When you have mastered those, go on to:
4104:
4105: @itemize @bullet
1.28 crook 4106: @item
1.29 crook 4107: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4108: @item
1.29 crook 4109: Memory access: @code{@@ !}
1.28 crook 4110: @end itemize
1.23 crook 4111:
1.29 crook 4112: When you have mastered these, there's nothing for it but to read through
4113: the whole of this manual and find out what you've missed.
4114:
4115: @comment ----------------------------------------------
1.48 anton 4116: @node Exercises, , Where to go next, Introduction
1.29 crook 4117: @section Exercises
4118: @cindex exercises
4119:
4120: TODO: provide a set of programming excercises linked into the stuff done
4121: already and into other sections of the manual. Provide solutions to all
4122: the exercises in a .fs file in the distribution.
4123:
4124: @c Get some inspiration from Starting Forth and Kelly&Spies.
4125:
4126: @c excercises:
4127: @c 1. take inches and convert to feet and inches.
4128: @c 2. take temperature and convert from fahrenheight to celcius;
4129: @c may need to care about symmetric vs floored??
4130: @c 3. take input line and do character substitution
4131: @c to encipher or decipher
4132: @c 4. as above but work on a file for in and out
4133: @c 5. take input line and convert to pig-latin
4134: @c
4135: @c thing of sets of things to exercise then come up with
4136: @c problems that need those things.
4137:
4138:
1.26 crook 4139: @c ******************************************************************
1.29 crook 4140: @node Words, Error messages, Introduction, Top
1.1 anton 4141: @chapter Forth Words
1.26 crook 4142: @cindex words
1.1 anton 4143:
4144: @menu
4145: * Notation::
1.65 anton 4146: * Case insensitivity::
4147: * Comments::
4148: * Boolean Flags::
1.1 anton 4149: * Arithmetic::
4150: * Stack Manipulation::
1.5 anton 4151: * Memory::
1.1 anton 4152: * Control Structures::
4153: * Defining Words::
1.65 anton 4154: * Interpretation and Compilation Semantics::
1.47 crook 4155: * Tokens for Words::
1.81 anton 4156: * Compiling words::
1.65 anton 4157: * The Text Interpreter::
1.111 anton 4158: * The Input Stream::
1.65 anton 4159: * Word Lists::
4160: * Environmental Queries::
1.12 anton 4161: * Files::
4162: * Blocks::
4163: * Other I/O::
1.78 anton 4164: * Locals::
4165: * Structures::
4166: * Object-oriented Forth::
1.12 anton 4167: * Programming Tools::
4168: * Assembler and Code Words::
4169: * Threading Words::
1.65 anton 4170: * Passing Commands to the OS::
4171: * Keeping track of Time::
4172: * Miscellaneous Words::
1.1 anton 4173: @end menu
4174:
1.65 anton 4175: @node Notation, Case insensitivity, Words, Words
1.1 anton 4176: @section Notation
4177: @cindex notation of glossary entries
4178: @cindex format of glossary entries
4179: @cindex glossary notation format
4180: @cindex word glossary entry format
4181:
4182: The Forth words are described in this section in the glossary notation
1.67 anton 4183: that has become a de-facto standard for Forth texts:
1.1 anton 4184:
4185: @format
1.29 crook 4186: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4187: @end format
1.29 crook 4188: @i{Description}
1.1 anton 4189:
4190: @table @var
4191: @item word
1.28 crook 4192: The name of the word.
1.1 anton 4193:
4194: @item Stack effect
4195: @cindex stack effect
1.29 crook 4196: The stack effect is written in the notation @code{@i{before} --
4197: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4198: stack entries before and after the execution of the word. The rest of
4199: the stack is not touched by the word. The top of stack is rightmost,
4200: i.e., a stack sequence is written as it is typed in. Note that Gforth
4201: uses a separate floating point stack, but a unified stack
1.29 crook 4202: notation. Also, return stack effects are not shown in @i{stack
4203: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4204: the type and/or the function of the item. See below for a discussion of
4205: the types.
4206:
4207: All words have two stack effects: A compile-time stack effect and a
4208: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4209: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4210: this standard behaviour, or the word does other unusual things at
4211: compile time, both stack effects are shown; otherwise only the run-time
4212: stack effect is shown.
4213:
4214: @cindex pronounciation of words
4215: @item pronunciation
4216: How the word is pronounced.
4217:
4218: @cindex wordset
1.67 anton 4219: @cindex environment wordset
1.1 anton 4220: @item wordset
1.21 crook 4221: The ANS Forth standard is divided into several word sets. A standard
4222: system need not support all of them. Therefore, in theory, the fewer
4223: word sets your program uses the more portable it will be. However, we
4224: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4225: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4226: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4227: describes words that will work in future releases of Gforth;
4228: @code{gforth-internal} words are more volatile. Environmental query
4229: strings are also displayed like words; you can recognize them by the
1.21 crook 4230: @code{environment} in the word set field.
1.1 anton 4231:
4232: @item Description
4233: A description of the behaviour of the word.
4234: @end table
4235:
4236: @cindex types of stack items
4237: @cindex stack item types
4238: The type of a stack item is specified by the character(s) the name
4239: starts with:
4240:
4241: @table @code
4242: @item f
4243: @cindex @code{f}, stack item type
4244: Boolean flags, i.e. @code{false} or @code{true}.
4245: @item c
4246: @cindex @code{c}, stack item type
4247: Char
4248: @item w
4249: @cindex @code{w}, stack item type
4250: Cell, can contain an integer or an address
4251: @item n
4252: @cindex @code{n}, stack item type
4253: signed integer
4254: @item u
4255: @cindex @code{u}, stack item type
4256: unsigned integer
4257: @item d
4258: @cindex @code{d}, stack item type
4259: double sized signed integer
4260: @item ud
4261: @cindex @code{ud}, stack item type
4262: double sized unsigned integer
4263: @item r
4264: @cindex @code{r}, stack item type
4265: Float (on the FP stack)
1.21 crook 4266: @item a-
1.1 anton 4267: @cindex @code{a_}, stack item type
4268: Cell-aligned address
1.21 crook 4269: @item c-
1.1 anton 4270: @cindex @code{c_}, stack item type
4271: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4272: @item f-
1.1 anton 4273: @cindex @code{f_}, stack item type
4274: Float-aligned address
1.21 crook 4275: @item df-
1.1 anton 4276: @cindex @code{df_}, stack item type
4277: Address aligned for IEEE double precision float
1.21 crook 4278: @item sf-
1.1 anton 4279: @cindex @code{sf_}, stack item type
4280: Address aligned for IEEE single precision float
4281: @item xt
4282: @cindex @code{xt}, stack item type
4283: Execution token, same size as Cell
4284: @item wid
4285: @cindex @code{wid}, stack item type
1.21 crook 4286: Word list ID, same size as Cell
1.68 anton 4287: @item ior, wior
4288: @cindex ior type description
4289: @cindex wior type description
4290: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4291: @item f83name
4292: @cindex @code{f83name}, stack item type
4293: Pointer to a name structure
4294: @item "
4295: @cindex @code{"}, stack item type
1.12 anton 4296: string in the input stream (not on the stack). The terminating character
4297: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4298: quotes.
4299: @end table
4300:
1.65 anton 4301: @comment ----------------------------------------------
4302: @node Case insensitivity, Comments, Notation, Words
4303: @section Case insensitivity
4304: @cindex case sensitivity
4305: @cindex upper and lower case
4306:
4307: Gforth is case-insensitive; you can enter definitions and invoke
4308: Standard words using upper, lower or mixed case (however,
4309: @pxref{core-idef, Implementation-defined options, Implementation-defined
4310: options}).
4311:
4312: ANS Forth only @i{requires} implementations to recognise Standard words
4313: when they are typed entirely in upper case. Therefore, a Standard
4314: program must use upper case for all Standard words. You can use whatever
4315: case you like for words that you define, but in a Standard program you
4316: have to use the words in the same case that you defined them.
4317:
4318: Gforth supports case sensitivity through @code{table}s (case-sensitive
4319: wordlists, @pxref{Word Lists}).
4320:
4321: Two people have asked how to convert Gforth to be case-sensitive; while
4322: we think this is a bad idea, you can change all wordlists into tables
4323: like this:
4324:
4325: @example
4326: ' table-find forth-wordlist wordlist-map @ !
4327: @end example
4328:
4329: Note that you now have to type the predefined words in the same case
4330: that we defined them, which are varying. You may want to convert them
4331: to your favourite case before doing this operation (I won't explain how,
4332: because if you are even contemplating doing this, you'd better have
4333: enough knowledge of Forth systems to know this already).
4334:
4335: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4336: @section Comments
1.26 crook 4337: @cindex comments
1.21 crook 4338:
1.29 crook 4339: Forth supports two styles of comment; the traditional @i{in-line} comment,
4340: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4341:
1.44 crook 4342:
1.23 crook 4343: doc-(
1.21 crook 4344: doc-\
1.23 crook 4345: doc-\G
1.21 crook 4346:
1.44 crook 4347:
1.21 crook 4348: @node Boolean Flags, Arithmetic, Comments, Words
4349: @section Boolean Flags
1.26 crook 4350: @cindex Boolean flags
1.21 crook 4351:
4352: A Boolean flag is cell-sized. A cell with all bits clear represents the
4353: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4354: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4355: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4356: @c on and off to Memory?
4357: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4358:
1.21 crook 4359: doc-true
4360: doc-false
1.29 crook 4361: doc-on
4362: doc-off
1.21 crook 4363:
1.44 crook 4364:
1.21 crook 4365: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4366: @section Arithmetic
4367: @cindex arithmetic words
4368:
4369: @cindex division with potentially negative operands
4370: Forth arithmetic is not checked, i.e., you will not hear about integer
4371: overflow on addition or multiplication, you may hear about division by
4372: zero if you are lucky. The operator is written after the operands, but
4373: the operands are still in the original order. I.e., the infix @code{2-1}
4374: corresponds to @code{2 1 -}. Forth offers a variety of division
4375: operators. If you perform division with potentially negative operands,
4376: you do not want to use @code{/} or @code{/mod} with its undefined
4377: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4378: former, @pxref{Mixed precision}).
1.26 crook 4379: @comment TODO discuss the different division forms and the std approach
1.1 anton 4380:
4381: @menu
4382: * Single precision::
1.67 anton 4383: * Double precision:: Double-cell integer arithmetic
1.1 anton 4384: * Bitwise operations::
1.67 anton 4385: * Numeric comparison::
1.29 crook 4386: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4387: * Floating Point::
4388: @end menu
4389:
1.67 anton 4390: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4391: @subsection Single precision
4392: @cindex single precision arithmetic words
4393:
1.67 anton 4394: @c !! cell undefined
4395:
4396: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4397: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4398: treat them. For the rules used by the text interpreter for recognising
4399: single-precision integers see @ref{Number Conversion}.
1.21 crook 4400:
1.67 anton 4401: These words are all defined for signed operands, but some of them also
4402: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4403: @code{*}.
1.44 crook 4404:
1.1 anton 4405: doc-+
1.21 crook 4406: doc-1+
1.1 anton 4407: doc--
1.21 crook 4408: doc-1-
1.1 anton 4409: doc-*
4410: doc-/
4411: doc-mod
4412: doc-/mod
4413: doc-negate
4414: doc-abs
4415: doc-min
4416: doc-max
1.27 crook 4417: doc-floored
1.1 anton 4418:
1.44 crook 4419:
1.67 anton 4420: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4421: @subsection Double precision
4422: @cindex double precision arithmetic words
4423:
1.49 anton 4424: For the rules used by the text interpreter for
4425: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4426:
4427: A double precision number is represented by a cell pair, with the most
1.67 anton 4428: significant cell at the TOS. It is trivial to convert an unsigned single
4429: to a double: simply push a @code{0} onto the TOS. Since numbers are
4430: represented by Gforth using 2's complement arithmetic, converting a
4431: signed single to a (signed) double requires sign-extension across the
4432: most significant cell. This can be achieved using @code{s>d}. The moral
4433: of the story is that you cannot convert a number without knowing whether
4434: it represents an unsigned or a signed number.
1.21 crook 4435:
1.67 anton 4436: These words are all defined for signed operands, but some of them also
4437: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4438:
1.21 crook 4439: doc-s>d
1.67 anton 4440: doc-d>s
1.21 crook 4441: doc-d+
4442: doc-d-
4443: doc-dnegate
4444: doc-dabs
4445: doc-dmin
4446: doc-dmax
4447:
1.44 crook 4448:
1.67 anton 4449: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4450: @subsection Bitwise operations
4451: @cindex bitwise operation words
4452:
4453:
4454: doc-and
4455: doc-or
4456: doc-xor
4457: doc-invert
4458: doc-lshift
4459: doc-rshift
4460: doc-2*
4461: doc-d2*
4462: doc-2/
4463: doc-d2/
4464:
4465:
4466: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4467: @subsection Numeric comparison
4468: @cindex numeric comparison words
4469:
1.67 anton 4470: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4471: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4472:
1.28 crook 4473: doc-<
4474: doc-<=
4475: doc-<>
4476: doc-=
4477: doc->
4478: doc->=
4479:
1.21 crook 4480: doc-0<
1.23 crook 4481: doc-0<=
1.21 crook 4482: doc-0<>
4483: doc-0=
1.23 crook 4484: doc-0>
4485: doc-0>=
1.28 crook 4486:
4487: doc-u<
4488: doc-u<=
1.44 crook 4489: @c u<> and u= exist but are the same as <> and =
1.31 anton 4490: @c doc-u<>
4491: @c doc-u=
1.28 crook 4492: doc-u>
4493: doc-u>=
4494:
4495: doc-within
4496:
4497: doc-d<
4498: doc-d<=
4499: doc-d<>
4500: doc-d=
4501: doc-d>
4502: doc-d>=
1.23 crook 4503:
1.21 crook 4504: doc-d0<
1.23 crook 4505: doc-d0<=
4506: doc-d0<>
1.21 crook 4507: doc-d0=
1.23 crook 4508: doc-d0>
4509: doc-d0>=
4510:
1.21 crook 4511: doc-du<
1.28 crook 4512: doc-du<=
1.44 crook 4513: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4514: @c doc-du<>
4515: @c doc-du=
1.28 crook 4516: doc-du>
4517: doc-du>=
1.1 anton 4518:
1.44 crook 4519:
1.21 crook 4520: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4521: @subsection Mixed precision
4522: @cindex mixed precision arithmetic words
4523:
1.44 crook 4524:
1.1 anton 4525: doc-m+
4526: doc-*/
4527: doc-*/mod
4528: doc-m*
4529: doc-um*
4530: doc-m*/
4531: doc-um/mod
4532: doc-fm/mod
4533: doc-sm/rem
4534:
1.44 crook 4535:
1.21 crook 4536: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4537: @subsection Floating Point
4538: @cindex floating point arithmetic words
4539:
1.49 anton 4540: For the rules used by the text interpreter for
4541: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4542:
1.67 anton 4543: Gforth has a separate floating point stack, but the documentation uses
4544: the unified notation.@footnote{It's easy to generate the separate
4545: notation from that by just separating the floating-point numbers out:
4546: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4547: r3 )}.}
1.1 anton 4548:
4549: @cindex floating-point arithmetic, pitfalls
4550: Floating point numbers have a number of unpleasant surprises for the
4551: unwary (e.g., floating point addition is not associative) and even a few
4552: for the wary. You should not use them unless you know what you are doing
4553: or you don't care that the results you get are totally bogus. If you
4554: want to learn about the problems of floating point numbers (and how to
1.66 anton 4555: avoid them), you might start with @cite{David Goldberg,
4556: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4557: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4558: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4559:
1.44 crook 4560:
1.21 crook 4561: doc-d>f
4562: doc-f>d
1.1 anton 4563: doc-f+
4564: doc-f-
4565: doc-f*
4566: doc-f/
4567: doc-fnegate
4568: doc-fabs
4569: doc-fmax
4570: doc-fmin
4571: doc-floor
4572: doc-fround
4573: doc-f**
4574: doc-fsqrt
4575: doc-fexp
4576: doc-fexpm1
4577: doc-fln
4578: doc-flnp1
4579: doc-flog
4580: doc-falog
1.32 anton 4581: doc-f2*
4582: doc-f2/
4583: doc-1/f
4584: doc-precision
4585: doc-set-precision
4586:
4587: @cindex angles in trigonometric operations
4588: @cindex trigonometric operations
4589: Angles in floating point operations are given in radians (a full circle
4590: has 2 pi radians).
4591:
1.1 anton 4592: doc-fsin
4593: doc-fcos
4594: doc-fsincos
4595: doc-ftan
4596: doc-fasin
4597: doc-facos
4598: doc-fatan
4599: doc-fatan2
4600: doc-fsinh
4601: doc-fcosh
4602: doc-ftanh
4603: doc-fasinh
4604: doc-facosh
4605: doc-fatanh
1.21 crook 4606: doc-pi
1.28 crook 4607:
1.32 anton 4608: @cindex equality of floats
4609: @cindex floating-point comparisons
1.31 anton 4610: One particular problem with floating-point arithmetic is that comparison
4611: for equality often fails when you would expect it to succeed. For this
4612: reason approximate equality is often preferred (but you still have to
1.67 anton 4613: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4614: differently from what you might expect. The comparison words are:
1.31 anton 4615:
4616: doc-f~rel
4617: doc-f~abs
1.68 anton 4618: doc-f~
1.31 anton 4619: doc-f=
4620: doc-f<>
4621:
4622: doc-f<
4623: doc-f<=
4624: doc-f>
4625: doc-f>=
4626:
1.21 crook 4627: doc-f0<
1.28 crook 4628: doc-f0<=
4629: doc-f0<>
1.21 crook 4630: doc-f0=
1.28 crook 4631: doc-f0>
4632: doc-f0>=
4633:
1.1 anton 4634:
4635: @node Stack Manipulation, Memory, Arithmetic, Words
4636: @section Stack Manipulation
4637: @cindex stack manipulation words
4638:
4639: @cindex floating-point stack in the standard
1.21 crook 4640: Gforth maintains a number of separate stacks:
4641:
1.29 crook 4642: @cindex data stack
4643: @cindex parameter stack
1.21 crook 4644: @itemize @bullet
4645: @item
1.29 crook 4646: A data stack (also known as the @dfn{parameter stack}) -- for
4647: characters, cells, addresses, and double cells.
1.21 crook 4648:
1.29 crook 4649: @cindex floating-point stack
1.21 crook 4650: @item
1.44 crook 4651: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4652:
1.29 crook 4653: @cindex return stack
1.21 crook 4654: @item
1.44 crook 4655: A return stack -- for holding the return addresses of colon
1.32 anton 4656: definitions and other (non-FP) data.
1.21 crook 4657:
1.29 crook 4658: @cindex locals stack
1.21 crook 4659: @item
1.44 crook 4660: A locals stack -- for holding local variables.
1.21 crook 4661: @end itemize
4662:
1.1 anton 4663: @menu
4664: * Data stack::
4665: * Floating point stack::
4666: * Return stack::
4667: * Locals stack::
4668: * Stack pointer manipulation::
4669: @end menu
4670:
4671: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4672: @subsection Data stack
4673: @cindex data stack manipulation words
4674: @cindex stack manipulations words, data stack
4675:
1.44 crook 4676:
1.1 anton 4677: doc-drop
4678: doc-nip
4679: doc-dup
4680: doc-over
4681: doc-tuck
4682: doc-swap
1.21 crook 4683: doc-pick
1.1 anton 4684: doc-rot
4685: doc--rot
4686: doc-?dup
4687: doc-roll
4688: doc-2drop
4689: doc-2nip
4690: doc-2dup
4691: doc-2over
4692: doc-2tuck
4693: doc-2swap
4694: doc-2rot
4695:
1.44 crook 4696:
1.1 anton 4697: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4698: @subsection Floating point stack
4699: @cindex floating-point stack manipulation words
4700: @cindex stack manipulation words, floating-point stack
4701:
1.32 anton 4702: Whilst every sane Forth has a separate floating-point stack, it is not
4703: strictly required; an ANS Forth system could theoretically keep
4704: floating-point numbers on the data stack. As an additional difficulty,
4705: you don't know how many cells a floating-point number takes. It is
4706: reportedly possible to write words in a way that they work also for a
4707: unified stack model, but we do not recommend trying it. Instead, just
4708: say that your program has an environmental dependency on a separate
4709: floating-point stack.
4710:
4711: doc-floating-stack
4712:
1.1 anton 4713: doc-fdrop
4714: doc-fnip
4715: doc-fdup
4716: doc-fover
4717: doc-ftuck
4718: doc-fswap
1.21 crook 4719: doc-fpick
1.1 anton 4720: doc-frot
4721:
1.44 crook 4722:
1.1 anton 4723: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4724: @subsection Return stack
4725: @cindex return stack manipulation words
4726: @cindex stack manipulation words, return stack
4727:
1.32 anton 4728: @cindex return stack and locals
4729: @cindex locals and return stack
4730: A Forth system is allowed to keep local variables on the
4731: return stack. This is reasonable, as local variables usually eliminate
4732: the need to use the return stack explicitly. So, if you want to produce
4733: a standard compliant program and you are using local variables in a
4734: word, forget about return stack manipulations in that word (refer to the
4735: standard document for the exact rules).
4736:
1.1 anton 4737: doc->r
4738: doc-r>
4739: doc-r@
4740: doc-rdrop
4741: doc-2>r
4742: doc-2r>
4743: doc-2r@
4744: doc-2rdrop
4745:
1.44 crook 4746:
1.1 anton 4747: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4748: @subsection Locals stack
4749:
1.78 anton 4750: Gforth uses an extra locals stack. It is described, along with the
4751: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4752:
1.1 anton 4753: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4754: @subsection Stack pointer manipulation
4755: @cindex stack pointer manipulation words
4756:
1.44 crook 4757: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4758: doc-sp0
1.1 anton 4759: doc-sp@
4760: doc-sp!
1.21 crook 4761: doc-fp0
1.1 anton 4762: doc-fp@
4763: doc-fp!
1.21 crook 4764: doc-rp0
1.1 anton 4765: doc-rp@
4766: doc-rp!
1.21 crook 4767: doc-lp0
1.1 anton 4768: doc-lp@
4769: doc-lp!
4770:
1.44 crook 4771:
1.1 anton 4772: @node Memory, Control Structures, Stack Manipulation, Words
4773: @section Memory
1.26 crook 4774: @cindex memory words
1.1 anton 4775:
1.32 anton 4776: @menu
4777: * Memory model::
4778: * Dictionary allocation::
4779: * Heap Allocation::
4780: * Memory Access::
4781: * Address arithmetic::
4782: * Memory Blocks::
4783: @end menu
4784:
1.67 anton 4785: In addition to the standard Forth memory allocation words, there is also
4786: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4787: garbage collector}.
4788:
1.32 anton 4789: @node Memory model, Dictionary allocation, Memory, Memory
4790: @subsection ANS Forth and Gforth memory models
4791:
4792: @c The ANS Forth description is a mess (e.g., is the heap part of
4793: @c the dictionary?), so let's not stick to closely with it.
4794:
1.67 anton 4795: ANS Forth considers a Forth system as consisting of several address
4796: spaces, of which only @dfn{data space} is managed and accessible with
4797: the memory words. Memory not necessarily in data space includes the
4798: stacks, the code (called code space) and the headers (called name
4799: space). In Gforth everything is in data space, but the code for the
4800: primitives is usually read-only.
1.32 anton 4801:
4802: Data space is divided into a number of areas: The (data space portion of
4803: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4804: refer to the search data structure embodied in word lists and headers,
4805: because it is used for looking up names, just as you would in a
4806: conventional dictionary.}, the heap, and a number of system-allocated
4807: buffers.
4808:
1.68 anton 4809: @cindex address arithmetic restrictions, ANS vs. Gforth
4810: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4811: In ANS Forth data space is also divided into contiguous regions. You
4812: can only use address arithmetic within a contiguous region, not between
4813: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4814: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4815: allocation}).
4816:
4817: Gforth provides one big address space, and address arithmetic can be
4818: performed between any addresses. However, in the dictionary headers or
4819: code are interleaved with data, so almost the only contiguous data space
4820: regions there are those described by ANS Forth as contiguous; but you
4821: can be sure that the dictionary is allocated towards increasing
4822: addresses even between contiguous regions. The memory order of
4823: allocations in the heap is platform-dependent (and possibly different
4824: from one run to the next).
4825:
1.27 crook 4826:
1.32 anton 4827: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4828: @subsection Dictionary allocation
1.27 crook 4829: @cindex reserving data space
4830: @cindex data space - reserving some
4831:
1.32 anton 4832: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4833: you want to deallocate X, you also deallocate everything
4834: allocated after X.
4835:
1.68 anton 4836: @cindex contiguous regions in dictionary allocation
1.32 anton 4837: The allocations using the words below are contiguous and grow the region
4838: towards increasing addresses. Other words that allocate dictionary
4839: memory of any kind (i.e., defining words including @code{:noname}) end
4840: the contiguous region and start a new one.
4841:
4842: In ANS Forth only @code{create}d words are guaranteed to produce an
4843: address that is the start of the following contiguous region. In
4844: particular, the cell allocated by @code{variable} is not guaranteed to
4845: be contiguous with following @code{allot}ed memory.
4846:
4847: You can deallocate memory by using @code{allot} with a negative argument
4848: (with some restrictions, see @code{allot}). For larger deallocations use
4849: @code{marker}.
1.27 crook 4850:
1.29 crook 4851:
1.27 crook 4852: doc-here
4853: doc-unused
4854: doc-allot
4855: doc-c,
1.29 crook 4856: doc-f,
1.27 crook 4857: doc-,
4858: doc-2,
4859:
1.32 anton 4860: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4861: course you should allocate memory in an aligned way, too. I.e., before
4862: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4863: The words below align @code{here} if it is not already. Basically it is
4864: only already aligned for a type, if the last allocation was a multiple
4865: of the size of this type and if @code{here} was aligned for this type
4866: before.
4867:
4868: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4869: ANS Forth (@code{maxalign}ed in Gforth).
4870:
4871: doc-align
4872: doc-falign
4873: doc-sfalign
4874: doc-dfalign
4875: doc-maxalign
4876: doc-cfalign
4877:
4878:
4879: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4880: @subsection Heap allocation
4881: @cindex heap allocation
4882: @cindex dynamic allocation of memory
4883: @cindex memory-allocation word set
4884:
1.68 anton 4885: @cindex contiguous regions and heap allocation
1.32 anton 4886: Heap allocation supports deallocation of allocated memory in any
4887: order. Dictionary allocation is not affected by it (i.e., it does not
4888: end a contiguous region). In Gforth, these words are implemented using
4889: the standard C library calls malloc(), free() and resize().
4890:
1.68 anton 4891: The memory region produced by one invocation of @code{allocate} or
4892: @code{resize} is internally contiguous. There is no contiguity between
4893: such a region and any other region (including others allocated from the
4894: heap).
4895:
1.32 anton 4896: doc-allocate
4897: doc-free
4898: doc-resize
4899:
1.27 crook 4900:
1.32 anton 4901: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4902: @subsection Memory Access
4903: @cindex memory access words
4904:
4905: doc-@
4906: doc-!
4907: doc-+!
4908: doc-c@
4909: doc-c!
4910: doc-2@
4911: doc-2!
4912: doc-f@
4913: doc-f!
4914: doc-sf@
4915: doc-sf!
4916: doc-df@
4917: doc-df!
4918:
1.68 anton 4919:
1.32 anton 4920: @node Address arithmetic, Memory Blocks, Memory Access, Memory
4921: @subsection Address arithmetic
1.1 anton 4922: @cindex address arithmetic words
4923:
1.67 anton 4924: Address arithmetic is the foundation on which you can build data
4925: structures like arrays, records (@pxref{Structures}) and objects
4926: (@pxref{Object-oriented Forth}).
1.32 anton 4927:
1.68 anton 4928: @cindex address unit
4929: @cindex au (address unit)
1.1 anton 4930: ANS Forth does not specify the sizes of the data types. Instead, it
4931: offers a number of words for computing sizes and doing address
1.29 crook 4932: arithmetic. Address arithmetic is performed in terms of address units
4933: (aus); on most systems the address unit is one byte. Note that a
4934: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 4935: platforms where it is a noop, it compiles to nothing).
1.1 anton 4936:
1.67 anton 4937: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
4938: you have the address of a cell, perform @code{1 cells +}, and you will
4939: have the address of the next cell.
4940:
1.68 anton 4941: @cindex contiguous regions and address arithmetic
1.67 anton 4942: In ANS Forth you can perform address arithmetic only within a contiguous
4943: region, i.e., if you have an address into one region, you can only add
4944: and subtract such that the result is still within the region; you can
4945: only subtract or compare addresses from within the same contiguous
4946: region. Reasons: several contiguous regions can be arranged in memory
4947: in any way; on segmented systems addresses may have unusual
4948: representations, such that address arithmetic only works within a
4949: region. Gforth provides a few more guarantees (linear address space,
4950: dictionary grows upwards), but in general I have found it easy to stay
4951: within contiguous regions (exception: computing and comparing to the
4952: address just beyond the end of an array).
4953:
1.1 anton 4954: @cindex alignment of addresses for types
4955: ANS Forth also defines words for aligning addresses for specific
4956: types. Many computers require that accesses to specific data types
4957: must only occur at specific addresses; e.g., that cells may only be
4958: accessed at addresses divisible by 4. Even if a machine allows unaligned
4959: accesses, it can usually perform aligned accesses faster.
4960:
4961: For the performance-conscious: alignment operations are usually only
4962: necessary during the definition of a data structure, not during the
4963: (more frequent) accesses to it.
4964:
4965: ANS Forth defines no words for character-aligning addresses. This is not
4966: an oversight, but reflects the fact that addresses that are not
4967: char-aligned have no use in the standard and therefore will not be
4968: created.
4969:
4970: @cindex @code{CREATE} and alignment
1.29 crook 4971: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 4972: are cell-aligned; in addition, Gforth guarantees that these addresses
4973: are aligned for all purposes.
4974:
1.26 crook 4975: Note that the ANS Forth word @code{char} has nothing to do with address
4976: arithmetic.
1.1 anton 4977:
1.44 crook 4978:
1.1 anton 4979: doc-chars
4980: doc-char+
4981: doc-cells
4982: doc-cell+
4983: doc-cell
4984: doc-aligned
4985: doc-floats
4986: doc-float+
4987: doc-float
4988: doc-faligned
4989: doc-sfloats
4990: doc-sfloat+
4991: doc-sfaligned
4992: doc-dfloats
4993: doc-dfloat+
4994: doc-dfaligned
4995: doc-maxaligned
4996: doc-cfaligned
4997: doc-address-unit-bits
4998:
1.44 crook 4999:
1.32 anton 5000: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5001: @subsection Memory Blocks
5002: @cindex memory block words
1.27 crook 5003: @cindex character strings - moving and copying
5004:
1.49 anton 5005: Memory blocks often represent character strings; For ways of storing
5006: character strings in memory see @ref{String Formats}. For other
5007: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5008:
1.67 anton 5009: A few of these words work on address unit blocks. In that case, you
5010: usually have to insert @code{CHARS} before the word when working on
5011: character strings. Most words work on character blocks, and expect a
5012: char-aligned address.
5013:
5014: When copying characters between overlapping memory regions, use
5015: @code{chars move} or choose carefully between @code{cmove} and
5016: @code{cmove>}.
1.44 crook 5017:
1.1 anton 5018: doc-move
5019: doc-erase
5020: doc-cmove
5021: doc-cmove>
5022: doc-fill
5023: doc-blank
1.21 crook 5024: doc-compare
1.111 anton 5025: doc-str=
5026: doc-str<
5027: doc-string-prefix?
1.21 crook 5028: doc-search
1.27 crook 5029: doc--trailing
5030: doc-/string
1.82 anton 5031: doc-bounds
1.44 crook 5032:
1.111 anton 5033:
1.27 crook 5034: @comment TODO examples
5035:
1.1 anton 5036:
1.26 crook 5037: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5038: @section Control Structures
5039: @cindex control structures
5040:
1.33 anton 5041: Control structures in Forth cannot be used interpretively, only in a
5042: colon definition@footnote{To be precise, they have no interpretation
5043: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5044: not like this limitation, but have not seen a satisfying way around it
5045: yet, although many schemes have been proposed.
1.1 anton 5046:
5047: @menu
1.33 anton 5048: * Selection:: IF ... ELSE ... ENDIF
5049: * Simple Loops:: BEGIN ...
1.29 crook 5050: * Counted Loops:: DO
1.67 anton 5051: * Arbitrary control structures::
5052: * Calls and returns::
1.1 anton 5053: * Exception Handling::
5054: @end menu
5055:
5056: @node Selection, Simple Loops, Control Structures, Control Structures
5057: @subsection Selection
5058: @cindex selection control structures
5059: @cindex control structures for selection
5060:
5061: @cindex @code{IF} control structure
5062: @example
1.29 crook 5063: @i{flag}
1.1 anton 5064: IF
1.29 crook 5065: @i{code}
1.1 anton 5066: ENDIF
5067: @end example
1.21 crook 5068: @noindent
1.33 anton 5069:
1.44 crook 5070: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5071: with any bit set represents truth) @i{code} is executed.
1.33 anton 5072:
1.1 anton 5073: @example
1.29 crook 5074: @i{flag}
1.1 anton 5075: IF
1.29 crook 5076: @i{code1}
1.1 anton 5077: ELSE
1.29 crook 5078: @i{code2}
1.1 anton 5079: ENDIF
5080: @end example
5081:
1.44 crook 5082: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5083: executed.
1.33 anton 5084:
1.1 anton 5085: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5086: standard, and @code{ENDIF} is not, although it is quite popular. We
5087: recommend using @code{ENDIF}, because it is less confusing for people
5088: who also know other languages (and is not prone to reinforcing negative
5089: prejudices against Forth in these people). Adding @code{ENDIF} to a
5090: system that only supplies @code{THEN} is simple:
5091: @example
1.82 anton 5092: : ENDIF POSTPONE then ; immediate
1.1 anton 5093: @end example
5094:
5095: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5096: (adv.)} has the following meanings:
5097: @quotation
5098: ... 2b: following next after in order ... 3d: as a necessary consequence
5099: (if you were there, then you saw them).
5100: @end quotation
5101: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5102: and many other programming languages has the meaning 3d.]
5103:
1.21 crook 5104: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5105: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5106: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5107: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5108: @file{compat/control.fs}.
5109:
5110: @cindex @code{CASE} control structure
5111: @example
1.29 crook 5112: @i{n}
1.1 anton 5113: CASE
1.29 crook 5114: @i{n1} OF @i{code1} ENDOF
5115: @i{n2} OF @i{code2} ENDOF
1.1 anton 5116: @dots{}
1.68 anton 5117: ( n ) @i{default-code} ( n )
1.1 anton 5118: ENDCASE
5119: @end example
5120:
1.68 anton 5121: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5122: @i{ni} matches, the optional @i{default-code} is executed. The optional
5123: default case can be added by simply writing the code after the last
5124: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5125: not consume it.
1.1 anton 5126:
1.69 anton 5127: @progstyle
5128: To keep the code understandable, you should ensure that on all paths
5129: through a selection construct the stack is changed in the same way
5130: (wrt. number and types of stack items consumed and pushed).
5131:
1.1 anton 5132: @node Simple Loops, Counted Loops, Selection, Control Structures
5133: @subsection Simple Loops
5134: @cindex simple loops
5135: @cindex loops without count
5136:
5137: @cindex @code{WHILE} loop
5138: @example
5139: BEGIN
1.29 crook 5140: @i{code1}
5141: @i{flag}
1.1 anton 5142: WHILE
1.29 crook 5143: @i{code2}
1.1 anton 5144: REPEAT
5145: @end example
5146:
1.29 crook 5147: @i{code1} is executed and @i{flag} is computed. If it is true,
5148: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5149: false, execution continues after the @code{REPEAT}.
5150:
5151: @cindex @code{UNTIL} loop
5152: @example
5153: BEGIN
1.29 crook 5154: @i{code}
5155: @i{flag}
1.1 anton 5156: UNTIL
5157: @end example
5158:
1.29 crook 5159: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5160:
1.69 anton 5161: @progstyle
5162: To keep the code understandable, a complete iteration of the loop should
5163: not change the number and types of the items on the stacks.
5164:
1.1 anton 5165: @cindex endless loop
5166: @cindex loops, endless
5167: @example
5168: BEGIN
1.29 crook 5169: @i{code}
1.1 anton 5170: AGAIN
5171: @end example
5172:
5173: This is an endless loop.
5174:
5175: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5176: @subsection Counted Loops
5177: @cindex counted loops
5178: @cindex loops, counted
5179: @cindex @code{DO} loops
5180:
5181: The basic counted loop is:
5182: @example
1.29 crook 5183: @i{limit} @i{start}
1.1 anton 5184: ?DO
1.29 crook 5185: @i{body}
1.1 anton 5186: LOOP
5187: @end example
5188:
1.29 crook 5189: This performs one iteration for every integer, starting from @i{start}
5190: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5191: accessed with @code{i}. For example, the loop:
1.1 anton 5192: @example
5193: 10 0 ?DO
5194: i .
5195: LOOP
5196: @end example
1.21 crook 5197: @noindent
5198: prints @code{0 1 2 3 4 5 6 7 8 9}
5199:
1.1 anton 5200: The index of the innermost loop can be accessed with @code{i}, the index
5201: of the next loop with @code{j}, and the index of the third loop with
5202: @code{k}.
5203:
1.44 crook 5204:
1.1 anton 5205: doc-i
5206: doc-j
5207: doc-k
5208:
1.44 crook 5209:
1.1 anton 5210: The loop control data are kept on the return stack, so there are some
1.21 crook 5211: restrictions on mixing return stack accesses and counted loop words. In
5212: particuler, if you put values on the return stack outside the loop, you
5213: cannot read them inside the loop@footnote{well, not in a way that is
5214: portable.}. If you put values on the return stack within a loop, you
5215: have to remove them before the end of the loop and before accessing the
5216: index of the loop.
1.1 anton 5217:
5218: There are several variations on the counted loop:
5219:
1.21 crook 5220: @itemize @bullet
5221: @item
5222: @code{LEAVE} leaves the innermost counted loop immediately; execution
5223: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5224:
5225: @example
5226: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5227: @end example
5228: prints @code{0 1 2 3}
5229:
1.1 anton 5230:
1.21 crook 5231: @item
5232: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5233: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5234: return stack so @code{EXIT} can get to its return address. For example:
5235:
5236: @example
5237: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5238: @end example
5239: prints @code{0 1 2 3}
5240:
5241:
5242: @item
1.29 crook 5243: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5244: (and @code{LOOP} iterates until they become equal by wrap-around
5245: arithmetic). This behaviour is usually not what you want. Therefore,
5246: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5247: @code{?DO}), which do not enter the loop if @i{start} is greater than
5248: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5249: unsigned loop parameters.
5250:
1.21 crook 5251: @item
5252: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5253: the loop, independent of the loop parameters. Do not use @code{DO}, even
5254: if you know that the loop is entered in any case. Such knowledge tends
5255: to become invalid during maintenance of a program, and then the
5256: @code{DO} will make trouble.
5257:
5258: @item
1.29 crook 5259: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5260: index by @i{n} instead of by 1. The loop is terminated when the border
5261: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5262:
1.21 crook 5263: @example
5264: 4 0 +DO i . 2 +LOOP
5265: @end example
5266: @noindent
5267: prints @code{0 2}
5268:
5269: @example
5270: 4 1 +DO i . 2 +LOOP
5271: @end example
5272: @noindent
5273: prints @code{1 3}
1.1 anton 5274:
1.68 anton 5275: @item
1.1 anton 5276: @cindex negative increment for counted loops
5277: @cindex counted loops with negative increment
1.29 crook 5278: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5279:
1.21 crook 5280: @example
5281: -1 0 ?DO i . -1 +LOOP
5282: @end example
5283: @noindent
5284: prints @code{0 -1}
1.1 anton 5285:
1.21 crook 5286: @example
5287: 0 0 ?DO i . -1 +LOOP
5288: @end example
5289: prints nothing.
1.1 anton 5290:
1.29 crook 5291: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5292: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5293: index by @i{u} each iteration. The loop is terminated when the border
5294: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5295: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5296:
1.21 crook 5297: @example
5298: -2 0 -DO i . 1 -LOOP
5299: @end example
5300: @noindent
5301: prints @code{0 -1}
1.1 anton 5302:
1.21 crook 5303: @example
5304: -1 0 -DO i . 1 -LOOP
5305: @end example
5306: @noindent
5307: prints @code{0}
5308:
5309: @example
5310: 0 0 -DO i . 1 -LOOP
5311: @end example
5312: @noindent
5313: prints nothing.
1.1 anton 5314:
1.21 crook 5315: @end itemize
1.1 anton 5316:
5317: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5318: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5319: for these words that uses only standard words is provided in
5320: @file{compat/loops.fs}.
1.1 anton 5321:
5322:
5323: @cindex @code{FOR} loops
1.26 crook 5324: Another counted loop is:
1.1 anton 5325: @example
1.29 crook 5326: @i{n}
1.1 anton 5327: FOR
1.29 crook 5328: @i{body}
1.1 anton 5329: NEXT
5330: @end example
5331: This is the preferred loop of native code compiler writers who are too
1.26 crook 5332: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5333: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5334: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5335: Forth systems may behave differently, even if they support @code{FOR}
5336: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5337:
5338: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5339: @subsection Arbitrary control structures
5340: @cindex control structures, user-defined
5341:
5342: @cindex control-flow stack
5343: ANS Forth permits and supports using control structures in a non-nested
5344: way. Information about incomplete control structures is stored on the
5345: control-flow stack. This stack may be implemented on the Forth data
5346: stack, and this is what we have done in Gforth.
5347:
5348: @cindex @code{orig}, control-flow stack item
5349: @cindex @code{dest}, control-flow stack item
5350: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5351: entry represents a backward branch target. A few words are the basis for
5352: building any control structure possible (except control structures that
5353: need storage, like calls, coroutines, and backtracking).
5354:
1.44 crook 5355:
1.1 anton 5356: doc-if
5357: doc-ahead
5358: doc-then
5359: doc-begin
5360: doc-until
5361: doc-again
5362: doc-cs-pick
5363: doc-cs-roll
5364:
1.44 crook 5365:
1.21 crook 5366: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5367: manipulate the control-flow stack in a portable way. Without them, you
5368: would need to know how many stack items are occupied by a control-flow
5369: entry (many systems use one cell. In Gforth they currently take three,
5370: but this may change in the future).
5371:
1.1 anton 5372: Some standard control structure words are built from these words:
5373:
1.44 crook 5374:
1.1 anton 5375: doc-else
5376: doc-while
5377: doc-repeat
5378:
1.44 crook 5379:
5380: @noindent
1.1 anton 5381: Gforth adds some more control-structure words:
5382:
1.44 crook 5383:
1.1 anton 5384: doc-endif
5385: doc-?dup-if
5386: doc-?dup-0=-if
5387:
1.44 crook 5388:
5389: @noindent
1.1 anton 5390: Counted loop words constitute a separate group of words:
5391:
1.44 crook 5392:
1.1 anton 5393: doc-?do
5394: doc-+do
5395: doc-u+do
5396: doc--do
5397: doc-u-do
5398: doc-do
5399: doc-for
5400: doc-loop
5401: doc-+loop
5402: doc--loop
5403: doc-next
5404: doc-leave
5405: doc-?leave
5406: doc-unloop
5407: doc-done
5408:
1.44 crook 5409:
1.21 crook 5410: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5411: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5412: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5413: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5414: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5415: resolved (by using one of the loop-ending words or @code{DONE}).
5416:
1.44 crook 5417: @noindent
1.26 crook 5418: Another group of control structure words are:
1.1 anton 5419:
1.44 crook 5420:
1.1 anton 5421: doc-case
5422: doc-endcase
5423: doc-of
5424: doc-endof
5425:
1.44 crook 5426:
1.21 crook 5427: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5428: @code{CS-ROLL}.
1.1 anton 5429:
5430: @subsubsection Programming Style
1.47 crook 5431: @cindex control structures programming style
5432: @cindex programming style, arbitrary control structures
1.1 anton 5433:
5434: In order to ensure readability we recommend that you do not create
5435: arbitrary control structures directly, but define new control structure
5436: words for the control structure you want and use these words in your
1.26 crook 5437: program. For example, instead of writing:
1.1 anton 5438:
5439: @example
1.26 crook 5440: BEGIN
1.1 anton 5441: ...
1.26 crook 5442: IF [ 1 CS-ROLL ]
1.1 anton 5443: ...
1.26 crook 5444: AGAIN THEN
1.1 anton 5445: @end example
5446:
1.21 crook 5447: @noindent
1.1 anton 5448: we recommend defining control structure words, e.g.,
5449:
5450: @example
1.26 crook 5451: : WHILE ( DEST -- ORIG DEST )
5452: POSTPONE IF
5453: 1 CS-ROLL ; immediate
5454:
5455: : REPEAT ( orig dest -- )
5456: POSTPONE AGAIN
5457: POSTPONE THEN ; immediate
1.1 anton 5458: @end example
5459:
1.21 crook 5460: @noindent
1.1 anton 5461: and then using these to create the control structure:
5462:
5463: @example
1.26 crook 5464: BEGIN
1.1 anton 5465: ...
1.26 crook 5466: WHILE
1.1 anton 5467: ...
1.26 crook 5468: REPEAT
1.1 anton 5469: @end example
5470:
5471: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5472: @code{WHILE} are predefined, so in this example it would not be
5473: necessary to define them.
5474:
5475: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5476: @subsection Calls and returns
5477: @cindex calling a definition
5478: @cindex returning from a definition
5479:
1.3 anton 5480: @cindex recursive definitions
5481: A definition can be called simply be writing the name of the definition
1.26 crook 5482: to be called. Normally a definition is invisible during its own
1.3 anton 5483: definition. If you want to write a directly recursive definition, you
1.26 crook 5484: can use @code{recursive} to make the current definition visible, or
5485: @code{recurse} to call the current definition directly.
1.3 anton 5486:
1.44 crook 5487:
1.3 anton 5488: doc-recursive
5489: doc-recurse
5490:
1.44 crook 5491:
1.21 crook 5492: @comment TODO add example of the two recursion methods
1.12 anton 5493: @quotation
5494: @progstyle
5495: I prefer using @code{recursive} to @code{recurse}, because calling the
5496: definition by name is more descriptive (if the name is well-chosen) than
5497: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5498: implementation, it is much better to read (and think) ``now sort the
5499: partitions'' than to read ``now do a recursive call''.
5500: @end quotation
1.3 anton 5501:
1.29 crook 5502: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5503:
5504: @example
1.28 crook 5505: Defer foo
1.3 anton 5506:
5507: : bar ( ... -- ... )
5508: ... foo ... ;
5509:
5510: :noname ( ... -- ... )
5511: ... bar ... ;
5512: IS foo
5513: @end example
5514:
1.44 crook 5515: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5516:
1.26 crook 5517: The current definition returns control to the calling definition when
1.33 anton 5518: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5519:
5520: doc-exit
5521: doc-;s
5522:
1.44 crook 5523:
1.1 anton 5524: @node Exception Handling, , Calls and returns, Control Structures
5525: @subsection Exception Handling
1.26 crook 5526: @cindex exceptions
1.1 anton 5527:
1.68 anton 5528: @c quit is a very bad idea for error handling,
5529: @c because it does not translate into a THROW
5530: @c it also does not belong into this chapter
5531:
5532: If a word detects an error condition that it cannot handle, it can
5533: @code{throw} an exception. In the simplest case, this will terminate
5534: your program, and report an appropriate error.
1.21 crook 5535:
1.68 anton 5536: doc-throw
1.1 anton 5537:
1.69 anton 5538: @code{Throw} consumes a cell-sized error number on the stack. There are
5539: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5540: Gforth (and most other systems) you can use the iors produced by various
5541: words as error numbers (e.g., a typical use of @code{allocate} is
5542: @code{allocate throw}). Gforth also provides the word @code{exception}
5543: to define your own error numbers (with decent error reporting); an ANS
5544: Forth version of this word (but without the error messages) is available
5545: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5546: numbers (anything outside the range -4095..0), but won't get nice error
5547: messages, only numbers. For example, try:
5548:
5549: @example
1.69 anton 5550: -10 throw \ ANS defined
5551: -267 throw \ system defined
5552: s" my error" exception throw \ user defined
5553: 7 throw \ arbitrary number
1.68 anton 5554: @end example
5555:
5556: doc---exception-exception
1.1 anton 5557:
1.69 anton 5558: A common idiom to @code{THROW} a specific error if a flag is true is
5559: this:
5560:
5561: @example
5562: @code{( flag ) 0<> @i{errno} and throw}
5563: @end example
5564:
5565: Your program can provide exception handlers to catch exceptions. An
5566: exception handler can be used to correct the problem, or to clean up
5567: some data structures and just throw the exception to the next exception
5568: handler. Note that @code{throw} jumps to the dynamically innermost
5569: exception handler. The system's exception handler is outermost, and just
5570: prints an error and restarts command-line interpretation (or, in batch
5571: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5572:
1.68 anton 5573: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5574:
1.68 anton 5575: doc-catch
5576:
5577: The most common use of exception handlers is to clean up the state when
5578: an error happens. E.g.,
1.1 anton 5579:
1.26 crook 5580: @example
1.68 anton 5581: base @ >r hex \ actually the hex should be inside foo, or we h
5582: ['] foo catch ( nerror|0 )
5583: r> base !
1.69 anton 5584: ( nerror|0 ) throw \ pass it on
1.26 crook 5585: @end example
1.1 anton 5586:
1.69 anton 5587: A use of @code{catch} for handling the error @code{myerror} might look
5588: like this:
1.44 crook 5589:
1.68 anton 5590: @example
1.69 anton 5591: ['] foo catch
5592: CASE
5593: myerror OF ... ( do something about it ) ENDOF
5594: dup throw \ default: pass other errors on, do nothing on non-errors
5595: ENDCASE
1.68 anton 5596: @end example
1.44 crook 5597:
1.68 anton 5598: Having to wrap the code into a separate word is often cumbersome,
5599: therefore Gforth provides an alternative syntax:
1.1 anton 5600:
5601: @example
1.69 anton 5602: TRY
1.68 anton 5603: @i{code1}
1.69 anton 5604: RECOVER \ optional
1.68 anton 5605: @i{code2} \ optional
1.69 anton 5606: ENDTRY
1.1 anton 5607: @end example
5608:
1.68 anton 5609: This performs @i{Code1}. If @i{code1} completes normally, execution
5610: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5611: reset to the state during @code{try}, the throw value is pushed on the
5612: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5613: through the @code{endtry} into the following code.
1.26 crook 5614:
1.68 anton 5615: doc-try
5616: doc-recover
5617: doc-endtry
1.26 crook 5618:
1.69 anton 5619: The cleanup example from above in this syntax:
1.26 crook 5620:
1.68 anton 5621: @example
1.69 anton 5622: base @ >r TRY
1.68 anton 5623: hex foo \ now the hex is placed correctly
1.69 anton 5624: 0 \ value for throw
1.92 anton 5625: RECOVER ENDTRY
1.68 anton 5626: r> base ! throw
1.1 anton 5627: @end example
5628:
1.69 anton 5629: And here's the error handling example:
1.1 anton 5630:
1.68 anton 5631: @example
1.69 anton 5632: TRY
1.68 anton 5633: foo
1.69 anton 5634: RECOVER
5635: CASE
5636: myerror OF ... ( do something about it ) ENDOF
5637: throw \ pass other errors on
5638: ENDCASE
5639: ENDTRY
1.68 anton 5640: @end example
1.1 anton 5641:
1.69 anton 5642: @progstyle
5643: As usual, you should ensure that the stack depth is statically known at
5644: the end: either after the @code{throw} for passing on errors, or after
5645: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5646: selection construct for handling the error).
5647:
1.68 anton 5648: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5649: and you can provide an error message. @code{Abort} just produces an
5650: ``Aborted'' error.
1.1 anton 5651:
1.68 anton 5652: The problem with these words is that exception handlers cannot
5653: differentiate between different @code{abort"}s; they just look like
5654: @code{-2 throw} to them (the error message cannot be accessed by
5655: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5656: exception handlers.
1.44 crook 5657:
1.68 anton 5658: doc-abort"
1.26 crook 5659: doc-abort
1.29 crook 5660:
5661:
1.44 crook 5662:
1.29 crook 5663: @c -------------------------------------------------------------
1.47 crook 5664: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5665: @section Defining Words
5666: @cindex defining words
5667:
1.47 crook 5668: Defining words are used to extend Forth by creating new entries in the dictionary.
5669:
1.29 crook 5670: @menu
1.67 anton 5671: * CREATE::
1.44 crook 5672: * Variables:: Variables and user variables
1.67 anton 5673: * Constants::
1.44 crook 5674: * Values:: Initialised variables
1.67 anton 5675: * Colon Definitions::
1.44 crook 5676: * Anonymous Definitions:: Definitions without names
1.69 anton 5677: * Supplying names:: Passing definition names as strings
1.67 anton 5678: * User-defined Defining Words::
1.44 crook 5679: * Deferred words:: Allow forward references
1.67 anton 5680: * Aliases::
1.29 crook 5681: @end menu
5682:
1.44 crook 5683: @node CREATE, Variables, Defining Words, Defining Words
5684: @subsection @code{CREATE}
1.29 crook 5685: @cindex simple defining words
5686: @cindex defining words, simple
5687:
5688: Defining words are used to create new entries in the dictionary. The
5689: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5690: this:
5691:
5692: @example
5693: CREATE new-word1
5694: @end example
5695:
1.69 anton 5696: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5697: input stream (@code{new-word1} in our example). It generates a
5698: dictionary entry for @code{new-word1}. When @code{new-word1} is
5699: executed, all that it does is leave an address on the stack. The address
5700: represents the value of the data space pointer (@code{HERE}) at the time
5701: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5702: associating a name with the address of a region of memory.
1.29 crook 5703:
1.34 anton 5704: doc-create
5705:
1.69 anton 5706: Note that in ANS Forth guarantees only for @code{create} that its body
5707: is in dictionary data space (i.e., where @code{here}, @code{allot}
5708: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5709: @code{create}d words can be modified with @code{does>}
5710: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5711: can only be applied to @code{create}d words.
5712:
1.29 crook 5713: By extending this example to reserve some memory in data space, we end
1.69 anton 5714: up with something like a @i{variable}. Here are two different ways to do
5715: it:
1.29 crook 5716:
5717: @example
5718: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5719: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5720: @end example
5721:
5722: The variable can be examined and modified using @code{@@} (``fetch'') and
5723: @code{!} (``store'') like this:
5724:
5725: @example
5726: new-word2 @@ . \ get address, fetch from it and display
5727: 1234 new-word2 ! \ new value, get address, store to it
5728: @end example
5729:
1.44 crook 5730: @cindex arrays
5731: A similar mechanism can be used to create arrays. For example, an
5732: 80-character text input buffer:
1.29 crook 5733:
5734: @example
1.44 crook 5735: CREATE text-buf 80 chars allot
5736:
5737: text-buf 0 chars c@@ \ the 1st character (offset 0)
5738: text-buf 3 chars c@@ \ the 4th character (offset 3)
5739: @end example
1.29 crook 5740:
1.44 crook 5741: You can build arbitrarily complex data structures by allocating
1.49 anton 5742: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5743: learn about some Gforth tools that make it easier,
1.49 anton 5744: @xref{Structures}.
1.44 crook 5745:
5746:
5747: @node Variables, Constants, CREATE, Defining Words
5748: @subsection Variables
5749: @cindex variables
5750:
5751: The previous section showed how a sequence of commands could be used to
5752: generate a variable. As a final refinement, the whole code sequence can
5753: be wrapped up in a defining word (pre-empting the subject of the next
5754: section), making it easier to create new variables:
5755:
5756: @example
5757: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5758: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5759:
5760: myvariableX foo \ variable foo starts off with an unknown value
5761: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5762:
5763: 45 3 * foo ! \ set foo to 135
5764: 1234 joe ! \ set joe to 1234
5765: 3 joe +! \ increment joe by 3.. to 1237
5766: @end example
5767:
5768: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5769: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5770: guarantee that a @code{Variable} is initialised when it is created
5771: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5772: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5773: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5774: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5775: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5776: store a boolean, you can use @code{on} and @code{off} to toggle its
5777: state.
1.29 crook 5778:
1.34 anton 5779: doc-variable
5780: doc-2variable
5781: doc-fvariable
5782:
1.29 crook 5783: @cindex user variables
5784: @cindex user space
5785: The defining word @code{User} behaves in the same way as @code{Variable}.
5786: The difference is that it reserves space in @i{user (data) space} rather
5787: than normal data space. In a Forth system that has a multi-tasker, each
5788: task has its own set of user variables.
5789:
1.34 anton 5790: doc-user
1.67 anton 5791: @c doc-udp
5792: @c doc-uallot
1.34 anton 5793:
1.29 crook 5794: @comment TODO is that stuff about user variables strictly correct? Is it
5795: @comment just terminal tasks that have user variables?
5796: @comment should document tasker.fs (with some examples) elsewhere
5797: @comment in this manual, then expand on user space and user variables.
5798:
1.44 crook 5799: @node Constants, Values, Variables, Defining Words
5800: @subsection Constants
5801: @cindex constants
5802:
5803: @code{Constant} allows you to declare a fixed value and refer to it by
5804: name. For example:
1.29 crook 5805:
5806: @example
5807: 12 Constant INCHES-PER-FOOT
5808: 3E+08 fconstant SPEED-O-LIGHT
5809: @end example
5810:
5811: A @code{Variable} can be both read and written, so its run-time
5812: behaviour is to supply an address through which its current value can be
5813: manipulated. In contrast, the value of a @code{Constant} cannot be
5814: changed once it has been declared@footnote{Well, often it can be -- but
5815: not in a Standard, portable way. It's safer to use a @code{Value} (read
5816: on).} so it's not necessary to supply the address -- it is more
5817: efficient to return the value of the constant directly. That's exactly
5818: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5819: the top of the stack (You can find one
5820: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5821:
1.69 anton 5822: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5823: double and floating-point constants, respectively.
5824:
1.34 anton 5825: doc-constant
5826: doc-2constant
5827: doc-fconstant
5828:
5829: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5830: @c nac-> How could that not be true in an ANS Forth? You can't define a
5831: @c constant, use it and then delete the definition of the constant..
1.69 anton 5832:
5833: @c anton->An ANS Forth system can compile a constant to a literal; On
5834: @c decompilation you would see only the number, just as if it had been used
5835: @c in the first place. The word will stay, of course, but it will only be
5836: @c used by the text interpreter (no run-time duties, except when it is
5837: @c POSTPONEd or somesuch).
5838:
5839: @c nac:
1.44 crook 5840: @c I agree that it's rather deep, but IMO it is an important difference
5841: @c relative to other programming languages.. often it's annoying: it
5842: @c certainly changes my programming style relative to C.
5843:
1.69 anton 5844: @c anton: In what way?
5845:
1.29 crook 5846: Constants in Forth behave differently from their equivalents in other
5847: programming languages. In other languages, a constant (such as an EQU in
5848: assembler or a #define in C) only exists at compile-time; in the
5849: executable program the constant has been translated into an absolute
5850: number and, unless you are using a symbolic debugger, it's impossible to
5851: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5852: an entry in the header space and remains there after the code that uses
5853: it has been defined. In fact, it must remain in the dictionary since it
5854: has run-time duties to perform. For example:
1.29 crook 5855:
5856: @example
5857: 12 Constant INCHES-PER-FOOT
5858: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5859: @end example
5860:
5861: @cindex in-lining of constants
5862: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5863: associated with the constant @code{INCHES-PER-FOOT}. If you use
5864: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5865: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5866: attempt to optimise constants by in-lining them where they are used. You
5867: can force Gforth to in-line a constant like this:
5868:
5869: @example
5870: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5871: @end example
5872:
5873: If you use @code{see} to decompile @i{this} version of
5874: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5875: longer present. To understand how this works, read
5876: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5877:
5878: In-lining constants in this way might improve execution time
5879: fractionally, and can ensure that a constant is now only referenced at
5880: compile-time. However, the definition of the constant still remains in
5881: the dictionary. Some Forth compilers provide a mechanism for controlling
5882: a second dictionary for holding transient words such that this second
5883: dictionary can be deleted later in order to recover memory
5884: space. However, there is no standard way of doing this.
5885:
5886:
1.44 crook 5887: @node Values, Colon Definitions, Constants, Defining Words
5888: @subsection Values
5889: @cindex values
1.34 anton 5890:
1.69 anton 5891: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5892: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5893: (not in ANS Forth) you can access (and change) a @code{value} also with
5894: @code{>body}.
5895:
5896: Here are some
5897: examples:
1.29 crook 5898:
5899: @example
1.69 anton 5900: 12 Value APPLES \ Define APPLES with an initial value of 12
5901: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5902: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5903: APPLES \ puts 35 on the top of the stack.
1.29 crook 5904: @end example
5905:
1.44 crook 5906: doc-value
5907: doc-to
1.29 crook 5908:
1.35 anton 5909:
1.69 anton 5910:
1.44 crook 5911: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
5912: @subsection Colon Definitions
5913: @cindex colon definitions
1.35 anton 5914:
5915: @example
1.44 crook 5916: : name ( ... -- ... )
5917: word1 word2 word3 ;
1.29 crook 5918: @end example
5919:
1.44 crook 5920: @noindent
5921: Creates a word called @code{name} that, upon execution, executes
5922: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 5923:
1.49 anton 5924: The explanation above is somewhat superficial. For simple examples of
5925: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 5926: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 5927: Compilation Semantics}.
1.29 crook 5928:
1.44 crook 5929: doc-:
5930: doc-;
1.1 anton 5931:
1.34 anton 5932:
1.69 anton 5933: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 5934: @subsection Anonymous Definitions
5935: @cindex colon definitions
5936: @cindex defining words without name
1.34 anton 5937:
1.44 crook 5938: Sometimes you want to define an @dfn{anonymous word}; a word without a
5939: name. You can do this with:
1.1 anton 5940:
1.44 crook 5941: doc-:noname
1.1 anton 5942:
1.44 crook 5943: This leaves the execution token for the word on the stack after the
5944: closing @code{;}. Here's an example in which a deferred word is
5945: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 5946:
1.29 crook 5947: @example
1.44 crook 5948: Defer deferred
5949: :noname ( ... -- ... )
5950: ... ;
5951: IS deferred
1.29 crook 5952: @end example
1.26 crook 5953:
1.44 crook 5954: @noindent
5955: Gforth provides an alternative way of doing this, using two separate
5956: words:
1.27 crook 5957:
1.44 crook 5958: doc-noname
5959: @cindex execution token of last defined word
5960: doc-lastxt
1.1 anton 5961:
1.44 crook 5962: @noindent
5963: The previous example can be rewritten using @code{noname} and
5964: @code{lastxt}:
1.1 anton 5965:
1.26 crook 5966: @example
1.44 crook 5967: Defer deferred
5968: noname : ( ... -- ... )
5969: ... ;
5970: lastxt IS deferred
1.26 crook 5971: @end example
1.1 anton 5972:
1.29 crook 5973: @noindent
1.44 crook 5974: @code{noname} works with any defining word, not just @code{:}.
5975:
5976: @code{lastxt} also works when the last word was not defined as
1.71 anton 5977: @code{noname}. It does not work for combined words, though. It also has
5978: the useful property that is is valid as soon as the header for a
5979: definition has been built. Thus:
1.44 crook 5980:
5981: @example
5982: lastxt . : foo [ lastxt . ] ; ' foo .
5983: @end example
1.1 anton 5984:
1.44 crook 5985: @noindent
5986: prints 3 numbers; the last two are the same.
1.26 crook 5987:
1.69 anton 5988: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
5989: @subsection Supplying the name of a defined word
5990: @cindex names for defined words
5991: @cindex defining words, name given in a string
5992:
5993: By default, a defining word takes the name for the defined word from the
5994: input stream. Sometimes you want to supply the name from a string. You
5995: can do this with:
5996:
5997: doc-nextname
5998:
5999: For example:
6000:
6001: @example
6002: s" foo" nextname create
6003: @end example
6004:
6005: @noindent
6006: is equivalent to:
6007:
6008: @example
6009: create foo
6010: @end example
6011:
6012: @noindent
6013: @code{nextname} works with any defining word.
6014:
1.1 anton 6015:
1.69 anton 6016: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6017: @subsection User-defined Defining Words
6018: @cindex user-defined defining words
6019: @cindex defining words, user-defined
1.1 anton 6020:
1.29 crook 6021: You can create a new defining word by wrapping defining-time code around
6022: an existing defining word and putting the sequence in a colon
1.69 anton 6023: definition.
6024:
6025: @c anton: This example is very complex and leads in a quite different
6026: @c direction from the CREATE-DOES> stuff that follows. It should probably
6027: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6028: @c subsection of Defining Words)
6029:
6030: For example, suppose that you have a word @code{stats} that
1.29 crook 6031: gathers statistics about colon definitions given the @i{xt} of the
6032: definition, and you want every colon definition in your application to
6033: make a call to @code{stats}. You can define and use a new version of
6034: @code{:} like this:
6035:
6036: @example
6037: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6038: ... ; \ other code
6039:
6040: : my: : lastxt postpone literal ['] stats compile, ;
6041:
6042: my: foo + - ;
6043: @end example
6044:
6045: When @code{foo} is defined using @code{my:} these steps occur:
6046:
6047: @itemize @bullet
6048: @item
6049: @code{my:} is executed.
6050: @item
6051: The @code{:} within the definition (the one between @code{my:} and
6052: @code{lastxt}) is executed, and does just what it always does; it parses
6053: the input stream for a name, builds a dictionary header for the name
6054: @code{foo} and switches @code{state} from interpret to compile.
6055: @item
6056: The word @code{lastxt} is executed. It puts the @i{xt} for the word that is
6057: being defined -- @code{foo} -- onto the stack.
6058: @item
6059: The code that was produced by @code{postpone literal} is executed; this
6060: causes the value on the stack to be compiled as a literal in the code
6061: area of @code{foo}.
6062: @item
6063: The code @code{['] stats} compiles a literal into the definition of
6064: @code{my:}. When @code{compile,} is executed, that literal -- the
6065: execution token for @code{stats} -- is layed down in the code area of
6066: @code{foo} , following the literal@footnote{Strictly speaking, the
6067: mechanism that @code{compile,} uses to convert an @i{xt} into something
6068: in the code area is implementation-dependent. A threaded implementation
6069: might spit out the execution token directly whilst another
6070: implementation might spit out a native code sequence.}.
6071: @item
6072: At this point, the execution of @code{my:} is complete, and control
6073: returns to the text interpreter. The text interpreter is in compile
6074: state, so subsequent text @code{+ -} is compiled into the definition of
6075: @code{foo} and the @code{;} terminates the definition as always.
6076: @end itemize
6077:
6078: You can use @code{see} to decompile a word that was defined using
6079: @code{my:} and see how it is different from a normal @code{:}
6080: definition. For example:
6081:
6082: @example
6083: : bar + - ; \ like foo but using : rather than my:
6084: see bar
6085: : bar
6086: + - ;
6087: see foo
6088: : foo
6089: 107645672 stats + - ;
6090:
6091: \ use ' stats . to show that 107645672 is the xt for stats
6092: @end example
6093:
6094: You can use techniques like this to make new defining words in terms of
6095: @i{any} existing defining word.
1.1 anton 6096:
6097:
1.29 crook 6098: @cindex defining defining words
1.26 crook 6099: @cindex @code{CREATE} ... @code{DOES>}
6100: If you want the words defined with your defining words to behave
6101: differently from words defined with standard defining words, you can
6102: write your defining word like this:
1.1 anton 6103:
6104: @example
1.26 crook 6105: : def-word ( "name" -- )
1.29 crook 6106: CREATE @i{code1}
1.26 crook 6107: DOES> ( ... -- ... )
1.29 crook 6108: @i{code2} ;
1.26 crook 6109:
6110: def-word name
1.1 anton 6111: @end example
6112:
1.29 crook 6113: @cindex child words
6114: This fragment defines a @dfn{defining word} @code{def-word} and then
6115: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6116: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6117: is not executed at this time. The word @code{name} is sometimes called a
6118: @dfn{child} of @code{def-word}.
6119:
6120: When you execute @code{name}, the address of the body of @code{name} is
6121: put on the data stack and @i{code2} is executed (the address of the body
6122: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6123: @code{CREATE}, i.e., the address a @code{create}d word returns by
6124: default).
6125:
6126: @c anton:
6127: @c www.dictionary.com says:
6128: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6129: @c several generations of absence, usually caused by the chance
6130: @c recombination of genes. 2.An individual or a part that exhibits
6131: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6132: @c of previous behavior after a period of absence.
6133: @c
6134: @c Doesn't seem to fit.
1.29 crook 6135:
1.69 anton 6136: @c @cindex atavism in child words
1.33 anton 6137: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6138: similarly; they all have a common run-time behaviour determined by
6139: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6140: body of the child word. The structure of the data is common to all
6141: children of @code{def-word}, but the data values are specific -- and
6142: private -- to each child word. When a child word is executed, the
6143: address of its private data area is passed as a parameter on TOS to be
6144: used and manipulated@footnote{It is legitimate both to read and write to
6145: this data area.} by @i{code2}.
1.29 crook 6146:
6147: The two fragments of code that make up the defining words act (are
6148: executed) at two completely separate times:
1.1 anton 6149:
1.29 crook 6150: @itemize @bullet
6151: @item
6152: At @i{define time}, the defining word executes @i{code1} to generate a
6153: child word
6154: @item
6155: At @i{child execution time}, when a child word is invoked, @i{code2}
6156: is executed, using parameters (data) that are private and specific to
6157: the child word.
6158: @end itemize
6159:
1.44 crook 6160: Another way of understanding the behaviour of @code{def-word} and
6161: @code{name} is to say that, if you make the following definitions:
1.33 anton 6162: @example
6163: : def-word1 ( "name" -- )
6164: CREATE @i{code1} ;
6165:
6166: : action1 ( ... -- ... )
6167: @i{code2} ;
6168:
6169: def-word1 name1
6170: @end example
6171:
1.44 crook 6172: @noindent
6173: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6174:
1.29 crook 6175: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6176:
1.1 anton 6177: @example
1.29 crook 6178: : CONSTANT ( w "name" -- )
6179: CREATE ,
1.26 crook 6180: DOES> ( -- w )
6181: @@ ;
1.1 anton 6182: @end example
6183:
1.29 crook 6184: @comment There is a beautiful description of how this works and what
6185: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6186: @comment commentary on the Counting Fruits problem.
6187:
6188: When you create a constant with @code{5 CONSTANT five}, a set of
6189: define-time actions take place; first a new word @code{five} is created,
6190: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6191: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6192: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6193: no code of its own; it simply contains a data field and a pointer to the
6194: code that follows @code{DOES>} in its defining word. That makes words
6195: created in this way very compact.
6196:
6197: The final example in this section is intended to remind you that space
6198: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6199: both read and written by a Standard program@footnote{Exercise: use this
6200: example as a starting point for your own implementation of @code{Value}
6201: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6202: @code{[']}.}:
6203:
6204: @example
6205: : foo ( "name" -- )
6206: CREATE -1 ,
6207: DOES> ( -- )
1.33 anton 6208: @@ . ;
1.29 crook 6209:
6210: foo first-word
6211: foo second-word
6212:
6213: 123 ' first-word >BODY !
6214: @end example
6215:
6216: If @code{first-word} had been a @code{CREATE}d word, we could simply
6217: have executed it to get the address of its data field. However, since it
6218: was defined to have @code{DOES>} actions, its execution semantics are to
6219: perform those @code{DOES>} actions. To get the address of its data field
6220: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6221: translate the xt into the address of the data field. When you execute
6222: @code{first-word}, it will display @code{123}. When you execute
6223: @code{second-word} it will display @code{-1}.
1.26 crook 6224:
6225: @cindex stack effect of @code{DOES>}-parts
6226: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6227: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6228: the stack effect of the defined words, not the stack effect of the
6229: following code (the following code expects the address of the body on
6230: the top of stack, which is not reflected in the stack comment). This is
6231: the convention that I use and recommend (it clashes a bit with using
6232: locals declarations for stack effect specification, though).
1.1 anton 6233:
1.53 anton 6234: @menu
6235: * CREATE..DOES> applications::
6236: * CREATE..DOES> details::
1.63 anton 6237: * Advanced does> usage example::
1.91 anton 6238: * @code{Const-does>}::
1.53 anton 6239: @end menu
6240:
6241: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6242: @subsubsection Applications of @code{CREATE..DOES>}
6243: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6244:
1.26 crook 6245: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6246:
1.26 crook 6247: @cindex factoring similar colon definitions
6248: When you see a sequence of code occurring several times, and you can
6249: identify a meaning, you will factor it out as a colon definition. When
6250: you see similar colon definitions, you can factor them using
6251: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6252: that look very similar:
1.1 anton 6253: @example
1.26 crook 6254: : ori, ( reg-target reg-source n -- )
6255: 0 asm-reg-reg-imm ;
6256: : andi, ( reg-target reg-source n -- )
6257: 1 asm-reg-reg-imm ;
1.1 anton 6258: @end example
6259:
1.26 crook 6260: @noindent
6261: This could be factored with:
6262: @example
6263: : reg-reg-imm ( op-code -- )
6264: CREATE ,
6265: DOES> ( reg-target reg-source n -- )
6266: @@ asm-reg-reg-imm ;
6267:
6268: 0 reg-reg-imm ori,
6269: 1 reg-reg-imm andi,
6270: @end example
1.1 anton 6271:
1.26 crook 6272: @cindex currying
6273: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6274: supply a part of the parameters for a word (known as @dfn{currying} in
6275: the functional language community). E.g., @code{+} needs two
6276: parameters. Creating versions of @code{+} with one parameter fixed can
6277: be done like this:
1.82 anton 6278:
1.1 anton 6279: @example
1.82 anton 6280: : curry+ ( n1 "name" -- )
1.26 crook 6281: CREATE ,
6282: DOES> ( n2 -- n1+n2 )
6283: @@ + ;
6284:
6285: 3 curry+ 3+
6286: -2 curry+ 2-
1.1 anton 6287: @end example
6288:
1.91 anton 6289:
1.63 anton 6290: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6291: @subsubsection The gory details of @code{CREATE..DOES>}
6292: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6293:
1.26 crook 6294: doc-does>
1.1 anton 6295:
1.26 crook 6296: @cindex @code{DOES>} in a separate definition
6297: This means that you need not use @code{CREATE} and @code{DOES>} in the
6298: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6299: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6300: @example
6301: : does1
6302: DOES> ( ... -- ... )
1.44 crook 6303: ... ;
6304:
6305: : does2
6306: DOES> ( ... -- ... )
6307: ... ;
6308:
6309: : def-word ( ... -- ... )
6310: create ...
6311: IF
6312: does1
6313: ELSE
6314: does2
6315: ENDIF ;
6316: @end example
6317:
6318: In this example, the selection of whether to use @code{does1} or
1.69 anton 6319: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6320: @code{CREATE}d.
6321:
6322: @cindex @code{DOES>} in interpretation state
6323: In a standard program you can apply a @code{DOES>}-part only if the last
6324: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6325: will override the behaviour of the last word defined in any case. In a
6326: standard program, you can use @code{DOES>} only in a colon
6327: definition. In Gforth, you can also use it in interpretation state, in a
6328: kind of one-shot mode; for example:
6329: @example
6330: CREATE name ( ... -- ... )
6331: @i{initialization}
6332: DOES>
6333: @i{code} ;
6334: @end example
6335:
6336: @noindent
6337: is equivalent to the standard:
6338: @example
6339: :noname
6340: DOES>
6341: @i{code} ;
6342: CREATE name EXECUTE ( ... -- ... )
6343: @i{initialization}
6344: @end example
6345:
1.53 anton 6346: doc->body
6347:
1.91 anton 6348: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6349: @subsubsection Advanced does> usage example
6350:
6351: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6352: for disassembling instructions, that follow a very repetetive scheme:
6353:
6354: @example
6355: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6356: @var{entry-num} cells @var{table} + !
6357: @end example
6358:
6359: Of course, this inspires the idea to factor out the commonalities to
6360: allow a definition like
6361:
6362: @example
6363: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6364: @end example
6365:
6366: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6367: correlated. Moreover, before I wrote the disassembler, there already
6368: existed code that defines instructions like this:
1.63 anton 6369:
6370: @example
6371: @var{entry-num} @var{inst-format} @var{inst-name}
6372: @end example
6373:
6374: This code comes from the assembler and resides in
6375: @file{arch/mips/insts.fs}.
6376:
6377: So I had to define the @var{inst-format} words that performed the scheme
6378: above when executed. At first I chose to use run-time code-generation:
6379:
6380: @example
6381: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6382: :noname Postpone @var{disasm-operands}
6383: name Postpone sliteral Postpone type Postpone ;
6384: swap cells @var{table} + ! ;
6385: @end example
6386:
6387: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6388:
1.63 anton 6389: An alternative would have been to write this using
6390: @code{create}/@code{does>}:
6391:
6392: @example
6393: : @var{inst-format} ( entry-num "name" -- )
6394: here name string, ( entry-num c-addr ) \ parse and save "name"
6395: noname create , ( entry-num )
6396: lastxt swap cells @var{table} + !
6397: does> ( addr w -- )
6398: \ disassemble instruction w at addr
6399: @@ >r
6400: @var{disasm-operands}
6401: r> count type ;
6402: @end example
6403:
6404: Somehow the first solution is simpler, mainly because it's simpler to
6405: shift a string from definition-time to use-time with @code{sliteral}
6406: than with @code{string,} and friends.
6407:
6408: I wrote a lot of words following this scheme and soon thought about
6409: factoring out the commonalities among them. Note that this uses a
6410: two-level defining word, i.e., a word that defines ordinary defining
6411: words.
6412:
6413: This time a solution involving @code{postpone} and friends seemed more
6414: difficult (try it as an exercise), so I decided to use a
6415: @code{create}/@code{does>} word; since I was already at it, I also used
6416: @code{create}/@code{does>} for the lower level (try using
6417: @code{postpone} etc. as an exercise), resulting in the following
6418: definition:
6419:
6420: @example
6421: : define-format ( disasm-xt table-xt -- )
6422: \ define an instruction format that uses disasm-xt for
6423: \ disassembling and enters the defined instructions into table
6424: \ table-xt
6425: create 2,
6426: does> ( u "inst" -- )
6427: \ defines an anonymous word for disassembling instruction inst,
6428: \ and enters it as u-th entry into table-xt
6429: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6430: noname create 2, \ define anonymous word
6431: execute lastxt swap ! \ enter xt of defined word into table-xt
6432: does> ( addr w -- )
6433: \ disassemble instruction w at addr
6434: 2@@ >r ( addr w disasm-xt R: c-addr )
6435: execute ( R: c-addr ) \ disassemble operands
6436: r> count type ; \ print name
6437: @end example
6438:
6439: Note that the tables here (in contrast to above) do the @code{cells +}
6440: by themselves (that's why you have to pass an xt). This word is used in
6441: the following way:
6442:
6443: @example
6444: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6445: @end example
6446:
1.71 anton 6447: As shown above, the defined instruction format is then used like this:
6448:
6449: @example
6450: @var{entry-num} @var{inst-format} @var{inst-name}
6451: @end example
6452:
1.63 anton 6453: In terms of currying, this kind of two-level defining word provides the
6454: parameters in three stages: first @var{disasm-operands} and @var{table},
6455: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6456: the instruction to be disassembled.
6457:
6458: Of course this did not quite fit all the instruction format names used
6459: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6460: the parameters into the right form.
6461:
6462: If you have trouble following this section, don't worry. First, this is
6463: involved and takes time (and probably some playing around) to
6464: understand; second, this is the first two-level
6465: @code{create}/@code{does>} word I have written in seventeen years of
6466: Forth; and if I did not have @file{insts.fs} to start with, I may well
6467: have elected to use just a one-level defining word (with some repeating
6468: of parameters when using the defining word). So it is not necessary to
6469: understand this, but it may improve your understanding of Forth.
1.44 crook 6470:
6471:
1.91 anton 6472: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6473: @subsubsection @code{Const-does>}
6474:
6475: A frequent use of @code{create}...@code{does>} is for transferring some
6476: values from definition-time to run-time. Gforth supports this use with
6477:
6478: doc-const-does>
6479:
6480: A typical use of this word is:
6481:
6482: @example
6483: : curry+ ( n1 "name" -- )
6484: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6485: + ;
6486:
6487: 3 curry+ 3+
6488: @end example
6489:
6490: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6491: definition to run-time.
6492:
6493: The advantages of using @code{const-does>} are:
6494:
6495: @itemize
6496:
6497: @item
6498: You don't have to deal with storing and retrieving the values, i.e.,
6499: your program becomes more writable and readable.
6500:
6501: @item
6502: When using @code{does>}, you have to introduce a @code{@@} that cannot
6503: be optimized away (because you could change the data using
6504: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6505:
6506: @end itemize
6507:
6508: An ANS Forth implementation of @code{const-does>} is available in
6509: @file{compat/const-does.fs}.
6510:
6511:
1.44 crook 6512: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6513: @subsection Deferred words
6514: @cindex deferred words
6515:
6516: The defining word @code{Defer} allows you to define a word by name
6517: without defining its behaviour; the definition of its behaviour is
6518: deferred. Here are two situation where this can be useful:
6519:
6520: @itemize @bullet
6521: @item
6522: Where you want to allow the behaviour of a word to be altered later, and
6523: for all precompiled references to the word to change when its behaviour
6524: is changed.
6525: @item
6526: For mutual recursion; @xref{Calls and returns}.
6527: @end itemize
6528:
6529: In the following example, @code{foo} always invokes the version of
6530: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6531: always invokes the version that prints ``@code{Hello}''. There is no way
6532: of getting @code{foo} to use the later version without re-ordering the
6533: source code and recompiling it.
6534:
6535: @example
6536: : greet ." Good morning" ;
6537: : foo ... greet ... ;
6538: : greet ." Hello" ;
6539: : bar ... greet ... ;
6540: @end example
6541:
6542: This problem can be solved by defining @code{greet} as a @code{Defer}red
6543: word. The behaviour of a @code{Defer}red word can be defined and
6544: redefined at any time by using @code{IS} to associate the xt of a
6545: previously-defined word with it. The previous example becomes:
6546:
6547: @example
1.69 anton 6548: Defer greet ( -- )
1.44 crook 6549: : foo ... greet ... ;
6550: : bar ... greet ... ;
1.69 anton 6551: : greet1 ( -- ) ." Good morning" ;
6552: : greet2 ( -- ) ." Hello" ;
1.44 crook 6553: ' greet2 <IS> greet \ make greet behave like greet2
6554: @end example
6555:
1.69 anton 6556: @progstyle
6557: You should write a stack comment for every deferred word, and put only
6558: XTs into deferred words that conform to this stack effect. Otherwise
6559: it's too difficult to use the deferred word.
6560:
1.44 crook 6561: A deferred word can be used to improve the statistics-gathering example
6562: from @ref{User-defined Defining Words}; rather than edit the
6563: application's source code to change every @code{:} to a @code{my:}, do
6564: this:
6565:
6566: @example
6567: : real: : ; \ retain access to the original
6568: defer : \ redefine as a deferred word
1.69 anton 6569: ' my: <IS> : \ use special version of :
1.44 crook 6570: \
6571: \ load application here
6572: \
1.69 anton 6573: ' real: <IS> : \ go back to the original
1.44 crook 6574: @end example
6575:
6576:
6577: One thing to note is that @code{<IS>} consumes its name when it is
6578: executed. If you want to specify the name at compile time, use
6579: @code{[IS]}:
6580:
6581: @example
6582: : set-greet ( xt -- )
6583: [IS] greet ;
6584:
6585: ' greet1 set-greet
6586: @end example
6587:
1.69 anton 6588: A deferred word can only inherit execution semantics from the xt
6589: (because that is all that an xt can represent -- for more discussion of
6590: this @pxref{Tokens for Words}); by default it will have default
6591: interpretation and compilation semantics deriving from this execution
6592: semantics. However, you can change the interpretation and compilation
6593: semantics of the deferred word in the usual ways:
1.44 crook 6594:
6595: @example
6596: : bar .... ; compile-only
6597: Defer fred immediate
6598: Defer jim
6599:
6600: ' bar <IS> jim \ jim has default semantics
6601: ' bar <IS> fred \ fred is immediate
6602: @end example
6603:
6604: doc-defer
6605: doc-<is>
6606: doc-[is]
6607: doc-is
6608: @comment TODO document these: what's defers [is]
6609: doc-what's
6610: doc-defers
6611:
6612: @c Use @code{words-deferred} to see a list of deferred words.
6613:
6614: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6615: are provided in @file{compat/defer.fs}.
6616:
6617:
1.69 anton 6618: @node Aliases, , Deferred words, Defining Words
1.44 crook 6619: @subsection Aliases
6620: @cindex aliases
1.1 anton 6621:
1.44 crook 6622: The defining word @code{Alias} allows you to define a word by name that
6623: has the same behaviour as some other word. Here are two situation where
6624: this can be useful:
1.1 anton 6625:
1.44 crook 6626: @itemize @bullet
6627: @item
6628: When you want access to a word's definition from a different word list
6629: (for an example of this, see the definition of the @code{Root} word list
6630: in the Gforth source).
6631: @item
6632: When you want to create a synonym; a definition that can be known by
6633: either of two names (for example, @code{THEN} and @code{ENDIF} are
6634: aliases).
6635: @end itemize
1.1 anton 6636:
1.69 anton 6637: Like deferred words, an alias has default compilation and interpretation
6638: semantics at the beginning (not the modifications of the other word),
6639: but you can change them in the usual ways (@code{immediate},
6640: @code{compile-only}). For example:
1.1 anton 6641:
6642: @example
1.44 crook 6643: : foo ... ; immediate
6644:
6645: ' foo Alias bar \ bar is not an immediate word
6646: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6647: @end example
6648:
1.44 crook 6649: Words that are aliases have the same xt, different headers in the
6650: dictionary, and consequently different name tokens (@pxref{Tokens for
6651: Words}) and possibly different immediate flags. An alias can only have
6652: default or immediate compilation semantics; you can define aliases for
6653: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6654:
1.44 crook 6655: doc-alias
1.1 anton 6656:
6657:
1.47 crook 6658: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6659: @section Interpretation and Compilation Semantics
1.26 crook 6660: @cindex semantics, interpretation and compilation
1.1 anton 6661:
1.71 anton 6662: @c !! state and ' are used without explanation
6663: @c example for immediate/compile-only? or is the tutorial enough
6664:
1.26 crook 6665: @cindex interpretation semantics
1.71 anton 6666: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6667: interpreter does when it encounters the word in interpret state. It also
6668: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6669: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6670: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6671: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6672:
1.26 crook 6673: @cindex compilation semantics
1.71 anton 6674: The @dfn{compilation semantics} of a (named) word are what the text
6675: interpreter does when it encounters the word in compile state. It also
6676: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6677: compiles@footnote{In standard terminology, ``appends to the current
6678: definition''.} the compilation semantics of @i{word}.
1.1 anton 6679:
1.26 crook 6680: @cindex execution semantics
6681: The standard also talks about @dfn{execution semantics}. They are used
6682: only for defining the interpretation and compilation semantics of many
6683: words. By default, the interpretation semantics of a word are to
6684: @code{execute} its execution semantics, and the compilation semantics of
6685: a word are to @code{compile,} its execution semantics.@footnote{In
6686: standard terminology: The default interpretation semantics are its
6687: execution semantics; the default compilation semantics are to append its
6688: execution semantics to the execution semantics of the current
6689: definition.}
6690:
1.71 anton 6691: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6692: the text interpreter, ticked, or @code{postpone}d, so they have no
6693: interpretation or compilation semantics. Their behaviour is represented
6694: by their XT (@pxref{Tokens for Words}), and we call it execution
6695: semantics, too.
6696:
1.26 crook 6697: @comment TODO expand, make it co-operate with new sections on text interpreter.
6698:
6699: @cindex immediate words
6700: @cindex compile-only words
6701: You can change the semantics of the most-recently defined word:
6702:
1.44 crook 6703:
1.26 crook 6704: doc-immediate
6705: doc-compile-only
6706: doc-restrict
6707:
1.82 anton 6708: By convention, words with non-default compilation semantics (e.g.,
6709: immediate words) often have names surrounded with brackets (e.g.,
6710: @code{[']}, @pxref{Execution token}).
1.44 crook 6711:
1.26 crook 6712: Note that ticking (@code{'}) a compile-only word gives an error
6713: (``Interpreting a compile-only word'').
1.1 anton 6714:
1.47 crook 6715: @menu
1.67 anton 6716: * Combined words::
1.47 crook 6717: @end menu
1.44 crook 6718:
1.71 anton 6719:
1.48 anton 6720: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6721: @subsection Combined Words
6722: @cindex combined words
6723:
6724: Gforth allows you to define @dfn{combined words} -- words that have an
6725: arbitrary combination of interpretation and compilation semantics.
6726:
1.26 crook 6727: doc-interpret/compile:
1.1 anton 6728:
1.26 crook 6729: This feature was introduced for implementing @code{TO} and @code{S"}. I
6730: recommend that you do not define such words, as cute as they may be:
6731: they make it hard to get at both parts of the word in some contexts.
6732: E.g., assume you want to get an execution token for the compilation
6733: part. Instead, define two words, one that embodies the interpretation
6734: part, and one that embodies the compilation part. Once you have done
6735: that, you can define a combined word with @code{interpret/compile:} for
6736: the convenience of your users.
1.1 anton 6737:
1.26 crook 6738: You might try to use this feature to provide an optimizing
6739: implementation of the default compilation semantics of a word. For
6740: example, by defining:
1.1 anton 6741: @example
1.26 crook 6742: :noname
6743: foo bar ;
6744: :noname
6745: POSTPONE foo POSTPONE bar ;
1.29 crook 6746: interpret/compile: opti-foobar
1.1 anton 6747: @end example
1.26 crook 6748:
1.23 crook 6749: @noindent
1.26 crook 6750: as an optimizing version of:
6751:
1.1 anton 6752: @example
1.26 crook 6753: : foobar
6754: foo bar ;
1.1 anton 6755: @end example
6756:
1.26 crook 6757: Unfortunately, this does not work correctly with @code{[compile]},
6758: because @code{[compile]} assumes that the compilation semantics of all
6759: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6760: opti-foobar} would compile compilation semantics, whereas
6761: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6762:
1.26 crook 6763: @cindex state-smart words (are a bad idea)
1.82 anton 6764: @anchor{state-smartness}
1.29 crook 6765: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6766: by @code{interpret/compile:} (words are state-smart if they check
6767: @code{STATE} during execution). E.g., they would try to code
6768: @code{foobar} like this:
1.1 anton 6769:
1.26 crook 6770: @example
6771: : foobar
6772: STATE @@
6773: IF ( compilation state )
6774: POSTPONE foo POSTPONE bar
6775: ELSE
6776: foo bar
6777: ENDIF ; immediate
6778: @end example
1.1 anton 6779:
1.26 crook 6780: Although this works if @code{foobar} is only processed by the text
6781: interpreter, it does not work in other contexts (like @code{'} or
6782: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6783: for a state-smart word, not for the interpretation semantics of the
6784: original @code{foobar}; when you execute this execution token (directly
6785: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6786: state, the result will not be what you expected (i.e., it will not
6787: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6788: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6789: M. Anton Ertl,
6790: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6791: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6792:
1.26 crook 6793: @cindex defining words with arbitrary semantics combinations
6794: It is also possible to write defining words that define words with
6795: arbitrary combinations of interpretation and compilation semantics. In
6796: general, they look like this:
1.1 anton 6797:
1.26 crook 6798: @example
6799: : def-word
6800: create-interpret/compile
1.29 crook 6801: @i{code1}
1.26 crook 6802: interpretation>
1.29 crook 6803: @i{code2}
1.26 crook 6804: <interpretation
6805: compilation>
1.29 crook 6806: @i{code3}
1.26 crook 6807: <compilation ;
6808: @end example
1.1 anton 6809:
1.29 crook 6810: For a @i{word} defined with @code{def-word}, the interpretation
6811: semantics are to push the address of the body of @i{word} and perform
6812: @i{code2}, and the compilation semantics are to push the address of
6813: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6814: can also be defined like this (except that the defined constants don't
6815: behave correctly when @code{[compile]}d):
1.1 anton 6816:
1.26 crook 6817: @example
6818: : constant ( n "name" -- )
6819: create-interpret/compile
6820: ,
6821: interpretation> ( -- n )
6822: @@
6823: <interpretation
6824: compilation> ( compilation. -- ; run-time. -- n )
6825: @@ postpone literal
6826: <compilation ;
6827: @end example
1.1 anton 6828:
1.44 crook 6829:
1.26 crook 6830: doc-create-interpret/compile
6831: doc-interpretation>
6832: doc-<interpretation
6833: doc-compilation>
6834: doc-<compilation
1.1 anton 6835:
1.44 crook 6836:
1.29 crook 6837: Words defined with @code{interpret/compile:} and
1.26 crook 6838: @code{create-interpret/compile} have an extended header structure that
6839: differs from other words; however, unless you try to access them with
6840: plain address arithmetic, you should not notice this. Words for
6841: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6842: @code{'} @i{word} @code{>body} also gives you the body of a word created
6843: with @code{create-interpret/compile}.
1.1 anton 6844:
1.44 crook 6845:
1.47 crook 6846: @c -------------------------------------------------------------
1.81 anton 6847: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6848: @section Tokens for Words
6849: @cindex tokens for words
6850:
6851: This section describes the creation and use of tokens that represent
6852: words.
6853:
1.71 anton 6854: @menu
6855: * Execution token:: represents execution/interpretation semantics
6856: * Compilation token:: represents compilation semantics
6857: * Name token:: represents named words
6858: @end menu
1.47 crook 6859:
1.71 anton 6860: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6861: @subsection Execution token
1.47 crook 6862:
6863: @cindex xt
6864: @cindex execution token
1.71 anton 6865: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6866: You can use @code{execute} to invoke this behaviour.
1.47 crook 6867:
1.71 anton 6868: @cindex tick (')
6869: You can use @code{'} to get an execution token that represents the
6870: interpretation semantics of a named word:
1.47 crook 6871:
6872: @example
1.97 anton 6873: 5 ' . ( n xt )
6874: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6875: @end example
1.47 crook 6876:
1.71 anton 6877: doc-'
6878:
6879: @code{'} parses at run-time; there is also a word @code{[']} that parses
6880: when it is compiled, and compiles the resulting XT:
6881:
6882: @example
6883: : foo ['] . execute ;
6884: 5 foo
6885: : bar ' execute ; \ by contrast,
6886: 5 bar . \ ' parses "." when bar executes
6887: @end example
6888:
6889: doc-[']
6890:
6891: If you want the execution token of @i{word}, write @code{['] @i{word}}
6892: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6893: @code{'} and @code{[']} behave somewhat unusually by complaining about
6894: compile-only words (because these words have no interpretation
6895: semantics). You might get what you want by using @code{COMP' @i{word}
6896: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6897: token}).
6898:
6899: Another way to get an XT is @code{:noname} or @code{lastxt}
6900: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6901: for the only behaviour the word has (the execution semantics). For
6902: named words, @code{lastxt} produces an XT for the same behaviour it
6903: would produce if the word was defined anonymously.
6904:
6905: @example
6906: :noname ." hello" ;
6907: execute
1.47 crook 6908: @end example
6909:
1.71 anton 6910: An XT occupies one cell and can be manipulated like any other cell.
6911:
1.47 crook 6912: @cindex code field address
6913: @cindex CFA
1.71 anton 6914: In ANS Forth the XT is just an abstract data type (i.e., defined by the
6915: operations that produce or consume it). For old hands: In Gforth, the
6916: XT is implemented as a code field address (CFA).
6917:
6918: doc-execute
6919: doc-perform
6920:
6921: @node Compilation token, Name token, Execution token, Tokens for Words
6922: @subsection Compilation token
1.47 crook 6923:
6924: @cindex compilation token
1.71 anton 6925: @cindex CT (compilation token)
6926: Gforth represents the compilation semantics of a named word by a
1.47 crook 6927: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6928: @i{xt} is an execution token. The compilation semantics represented by
6929: the compilation token can be performed with @code{execute}, which
6930: consumes the whole compilation token, with an additional stack effect
6931: determined by the represented compilation semantics.
6932:
6933: At present, the @i{w} part of a compilation token is an execution token,
6934: and the @i{xt} part represents either @code{execute} or
6935: @code{compile,}@footnote{Depending upon the compilation semantics of the
6936: word. If the word has default compilation semantics, the @i{xt} will
6937: represent @code{compile,}. Otherwise (e.g., for immediate words), the
6938: @i{xt} will represent @code{execute}.}. However, don't rely on that
6939: knowledge, unless necessary; future versions of Gforth may introduce
6940: unusual compilation tokens (e.g., a compilation token that represents
6941: the compilation semantics of a literal).
6942:
1.71 anton 6943: You can perform the compilation semantics represented by the compilation
6944: token with @code{execute}. You can compile the compilation semantics
6945: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
6946: equivalent to @code{postpone @i{word}}.
6947:
6948: doc-[comp']
6949: doc-comp'
6950: doc-postpone,
6951:
6952: @node Name token, , Compilation token, Tokens for Words
6953: @subsection Name token
1.47 crook 6954:
6955: @cindex name token
6956: @cindex name field address
6957: @cindex NFA
1.71 anton 6958: Gforth represents named words by the @dfn{name token}, (@i{nt}). In
1.47 crook 6959: Gforth, the abstract data type @emph{name token} is implemented as a
6960: name field address (NFA).
6961:
6962: doc-find-name
6963: doc-name>int
6964: doc-name?int
6965: doc-name>comp
6966: doc-name>string
1.109 anton 6967: doc-id.
6968: doc-.name
6969: doc-.id
1.47 crook 6970:
1.81 anton 6971: @c ----------------------------------------------------------
6972: @node Compiling words, The Text Interpreter, Tokens for Words, Words
6973: @section Compiling words
6974: @cindex compiling words
6975: @cindex macros
6976:
6977: In contrast to most other languages, Forth has no strict boundary
1.82 anton 6978: between compilation and run-time. E.g., you can run arbitrary code
6979: between defining words (or for computing data used by defining words
6980: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
6981: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
6982: running arbitrary code while compiling a colon definition (exception:
6983: you must not allot dictionary space).
6984:
6985: @menu
6986: * Literals:: Compiling data values
6987: * Macros:: Compiling words
6988: @end menu
6989:
6990: @node Literals, Macros, Compiling words, Compiling words
6991: @subsection Literals
6992: @cindex Literals
6993:
6994: The simplest and most frequent example is to compute a literal during
6995: compilation. E.g., the following definition prints an array of strings,
6996: one string per line:
6997:
6998: @example
6999: : .strings ( addr u -- ) \ gforth
7000: 2* cells bounds U+DO
7001: cr i 2@@ type
7002: 2 cells +LOOP ;
7003: @end example
1.81 anton 7004:
1.82 anton 7005: With a simple-minded compiler like Gforth's, this computes @code{2
7006: cells} on every loop iteration. You can compute this value once and for
7007: all at compile time and compile it into the definition like this:
7008:
7009: @example
7010: : .strings ( addr u -- ) \ gforth
7011: 2* cells bounds U+DO
7012: cr i 2@@ type
7013: [ 2 cells ] literal +LOOP ;
7014: @end example
7015:
7016: @code{[} switches the text interpreter to interpret state (you will get
7017: an @code{ok} prompt if you type this example interactively and insert a
7018: newline between @code{[} and @code{]}), so it performs the
7019: interpretation semantics of @code{2 cells}; this computes a number.
7020: @code{]} switches the text interpreter back into compile state. It then
7021: performs @code{Literal}'s compilation semantics, which are to compile
7022: this number into the current word. You can decompile the word with
7023: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7024:
1.82 anton 7025: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7026: *} in this way.
1.81 anton 7027:
1.82 anton 7028: doc-[
7029: doc-]
1.81 anton 7030: doc-literal
7031: doc-]L
1.82 anton 7032:
7033: There are also words for compiling other data types than single cells as
7034: literals:
7035:
1.81 anton 7036: doc-2literal
7037: doc-fliteral
1.82 anton 7038: doc-sliteral
7039:
7040: @cindex colon-sys, passing data across @code{:}
7041: @cindex @code{:}, passing data across
7042: You might be tempted to pass data from outside a colon definition to the
7043: inside on the data stack. This does not work, because @code{:} puhes a
7044: colon-sys, making stuff below unaccessible. E.g., this does not work:
7045:
7046: @example
7047: 5 : foo literal ; \ error: "unstructured"
7048: @end example
7049:
7050: Instead, you have to pass the value in some other way, e.g., through a
7051: variable:
7052:
7053: @example
7054: variable temp
7055: 5 temp !
7056: : foo [ temp @@ ] literal ;
7057: @end example
7058:
7059:
7060: @node Macros, , Literals, Compiling words
7061: @subsection Macros
7062: @cindex Macros
7063: @cindex compiling compilation semantics
7064:
7065: @code{Literal} and friends compile data values into the current
7066: definition. You can also write words that compile other words into the
7067: current definition. E.g.,
7068:
7069: @example
7070: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7071: POSTPONE + ;
7072:
7073: : foo ( n1 n2 -- n )
7074: [ compile-+ ] ;
7075: 1 2 foo .
7076: @end example
7077:
7078: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7079: What happens in this example? @code{Postpone} compiles the compilation
7080: semantics of @code{+} into @code{compile-+}; later the text interpreter
7081: executes @code{compile-+} and thus the compilation semantics of +, which
7082: compile (the execution semantics of) @code{+} into
7083: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7084: should only be executed in compile state, so this example is not
7085: guaranteed to work on all standard systems, but on any decent system it
7086: will work.}
7087:
7088: doc-postpone
7089: doc-[compile]
7090:
7091: Compiling words like @code{compile-+} are usually immediate (or similar)
7092: so you do not have to switch to interpret state to execute them;
7093: mopifying the last example accordingly produces:
7094:
7095: @example
7096: : [compile-+] ( compilation: --; interpretation: -- )
7097: \ compiled code: ( n1 n2 -- n )
7098: POSTPONE + ; immediate
7099:
7100: : foo ( n1 n2 -- n )
7101: [compile-+] ;
7102: 1 2 foo .
7103: @end example
7104:
7105: Immediate compiling words are similar to macros in other languages (in
7106: particular, Lisp). The important differences to macros in, e.g., C are:
7107:
7108: @itemize @bullet
7109:
7110: @item
7111: You use the same language for defining and processing macros, not a
7112: separate preprocessing language and processor.
7113:
7114: @item
7115: Consequently, the full power of Forth is available in macro definitions.
7116: E.g., you can perform arbitrarily complex computations, or generate
7117: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7118: Tutorial}). This power is very useful when writing a parser generators
7119: or other code-generating software.
7120:
7121: @item
7122: Macros defined using @code{postpone} etc. deal with the language at a
7123: higher level than strings; name binding happens at macro definition
7124: time, so you can avoid the pitfalls of name collisions that can happen
7125: in C macros. Of course, Forth is a liberal language and also allows to
7126: shoot yourself in the foot with text-interpreted macros like
7127:
7128: @example
7129: : [compile-+] s" +" evaluate ; immediate
7130: @end example
7131:
7132: Apart from binding the name at macro use time, using @code{evaluate}
7133: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7134: @end itemize
7135:
7136: You may want the macro to compile a number into a word. The word to do
7137: it is @code{literal}, but you have to @code{postpone} it, so its
7138: compilation semantics take effect when the macro is executed, not when
7139: it is compiled:
7140:
7141: @example
7142: : [compile-5] ( -- ) \ compiled code: ( -- n )
7143: 5 POSTPONE literal ; immediate
7144:
7145: : foo [compile-5] ;
7146: foo .
7147: @end example
7148:
7149: You may want to pass parameters to a macro, that the macro should
7150: compile into the current definition. If the parameter is a number, then
7151: you can use @code{postpone literal} (similar for other values).
7152:
7153: If you want to pass a word that is to be compiled, the usual way is to
7154: pass an execution token and @code{compile,} it:
7155:
7156: @example
7157: : twice1 ( xt -- ) \ compiled code: ... -- ...
7158: dup compile, compile, ;
7159:
7160: : 2+ ( n1 -- n2 )
7161: [ ' 1+ twice1 ] ;
7162: @end example
7163:
7164: doc-compile,
7165:
7166: An alternative available in Gforth, that allows you to pass compile-only
7167: words as parameters is to use the compilation token (@pxref{Compilation
7168: token}). The same example in this technique:
7169:
7170: @example
7171: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7172: 2dup 2>r execute 2r> execute ;
7173:
7174: : 2+ ( n1 -- n2 )
7175: [ comp' 1+ twice ] ;
7176: @end example
7177:
7178: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7179: works even if the executed compilation semantics has an effect on the
7180: data stack.
7181:
7182: You can also define complete definitions with these words; this provides
7183: an alternative to using @code{does>} (@pxref{User-defined Defining
7184: Words}). E.g., instead of
7185:
7186: @example
7187: : curry+ ( n1 "name" -- )
7188: CREATE ,
7189: DOES> ( n2 -- n1+n2 )
7190: @@ + ;
7191: @end example
7192:
7193: you could define
7194:
7195: @example
7196: : curry+ ( n1 "name" -- )
7197: \ name execution: ( n2 -- n1+n2 )
7198: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7199:
1.82 anton 7200: -3 curry+ 3-
7201: see 3-
7202: @end example
1.81 anton 7203:
1.82 anton 7204: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7205: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7206:
1.82 anton 7207: This way of writing defining words is sometimes more, sometimes less
7208: convenient than using @code{does>} (@pxref{Advanced does> usage
7209: example}). One advantage of this method is that it can be optimized
7210: better, because the compiler knows that the value compiled with
7211: @code{literal} is fixed, whereas the data associated with a
7212: @code{create}d word can be changed.
1.47 crook 7213:
1.26 crook 7214: @c ----------------------------------------------------------
1.111 anton 7215: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7216: @section The Text Interpreter
7217: @cindex interpreter - outer
7218: @cindex text interpreter
7219: @cindex outer interpreter
1.1 anton 7220:
1.34 anton 7221: @c Should we really describe all these ugly details? IMO the text
7222: @c interpreter should be much cleaner, but that may not be possible within
7223: @c ANS Forth. - anton
1.44 crook 7224: @c nac-> I wanted to explain how it works to show how you can exploit
7225: @c it in your own programs. When I was writing a cross-compiler, figuring out
7226: @c some of these gory details was very helpful to me. None of the textbooks
7227: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7228: @c seems to positively avoid going into too much detail for some of
7229: @c the internals.
1.34 anton 7230:
1.71 anton 7231: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7232: @c it is; for the ugly details, I would prefer another place. I wonder
7233: @c whether we should have a chapter before "Words" that describes some
7234: @c basic concepts referred to in words, and a chapter after "Words" that
7235: @c describes implementation details.
7236:
1.29 crook 7237: The text interpreter@footnote{This is an expanded version of the
7238: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7239: that processes input from the current input device. It is also called
7240: the outer interpreter, in contrast to the inner interpreter
7241: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7242: implementations.
1.27 crook 7243:
1.29 crook 7244: @cindex interpret state
7245: @cindex compile state
7246: The text interpreter operates in one of two states: @dfn{interpret
7247: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7248: aptly-named variable @code{state}.
1.29 crook 7249:
7250: This section starts by describing how the text interpreter behaves when
7251: it is in interpret state, processing input from the user input device --
7252: the keyboard. This is the mode that a Forth system is in after it starts
7253: up.
7254:
7255: @cindex input buffer
7256: @cindex terminal input buffer
7257: The text interpreter works from an area of memory called the @dfn{input
7258: buffer}@footnote{When the text interpreter is processing input from the
7259: keyboard, this area of memory is called the @dfn{terminal input buffer}
7260: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7261: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7262: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7263: leading spaces (called @dfn{delimiters}) then parses a string (a
7264: sequence of non-space characters) until it reaches either a space
7265: character or the end of the buffer. Having parsed a string, it makes two
7266: attempts to process it:
1.27 crook 7267:
1.29 crook 7268: @cindex dictionary
1.27 crook 7269: @itemize @bullet
7270: @item
1.29 crook 7271: It looks for the string in a @dfn{dictionary} of definitions. If the
7272: string is found, the string names a @dfn{definition} (also known as a
7273: @dfn{word}) and the dictionary search returns information that allows
7274: the text interpreter to perform the word's @dfn{interpretation
7275: semantics}. In most cases, this simply means that the word will be
7276: executed.
1.27 crook 7277: @item
7278: If the string is not found in the dictionary, the text interpreter
1.29 crook 7279: attempts to treat it as a number, using the rules described in
7280: @ref{Number Conversion}. If the string represents a legal number in the
7281: current radix, the number is pushed onto a parameter stack (the data
7282: stack for integers, the floating-point stack for floating-point
7283: numbers).
7284: @end itemize
7285:
7286: If both attempts fail, or if the word is found in the dictionary but has
7287: no interpretation semantics@footnote{This happens if the word was
7288: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7289: remainder of the input buffer, issues an error message and waits for
7290: more input. If one of the attempts succeeds, the text interpreter
7291: repeats the parsing process until the whole of the input buffer has been
7292: processed, at which point it prints the status message ``@code{ ok}''
7293: and waits for more input.
7294:
1.71 anton 7295: @c anton: this should be in the input stream subsection (or below it)
7296:
1.29 crook 7297: @cindex parse area
7298: The text interpreter keeps track of its position in the input buffer by
7299: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7300: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7301: of the input buffer. The region from offset @code{>IN @@} to the end of
7302: the input buffer is called the @dfn{parse area}@footnote{In other words,
7303: the text interpreter processes the contents of the input buffer by
7304: parsing strings from the parse area until the parse area is empty.}.
7305: This example shows how @code{>IN} changes as the text interpreter parses
7306: the input buffer:
7307:
7308: @example
7309: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7310: CR ." ->" TYPE ." <-" ; IMMEDIATE
7311:
7312: 1 2 3 remaining + remaining .
7313:
7314: : foo 1 2 3 remaining SWAP remaining ;
7315: @end example
7316:
7317: @noindent
7318: The result is:
7319:
7320: @example
7321: ->+ remaining .<-
7322: ->.<-5 ok
7323:
7324: ->SWAP remaining ;-<
7325: ->;<- ok
7326: @end example
7327:
7328: @cindex parsing words
7329: The value of @code{>IN} can also be modified by a word in the input
7330: buffer that is executed by the text interpreter. This means that a word
7331: can ``trick'' the text interpreter into either skipping a section of the
7332: input buffer@footnote{This is how parsing words work.} or into parsing a
7333: section twice. For example:
1.27 crook 7334:
1.29 crook 7335: @example
1.71 anton 7336: : lat ." <<foo>>" ;
7337: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7338: @end example
7339:
7340: @noindent
7341: When @code{flat} is executed, this output is produced@footnote{Exercise
7342: for the reader: what would happen if the @code{3} were replaced with
7343: @code{4}?}:
7344:
7345: @example
1.71 anton 7346: <<bar>><<foo>>
1.29 crook 7347: @end example
7348:
1.71 anton 7349: This technique can be used to work around some of the interoperability
7350: problems of parsing words. Of course, it's better to avoid parsing
7351: words where possible.
7352:
1.29 crook 7353: @noindent
7354: Two important notes about the behaviour of the text interpreter:
1.27 crook 7355:
7356: @itemize @bullet
7357: @item
7358: It processes each input string to completion before parsing additional
1.29 crook 7359: characters from the input buffer.
7360: @item
7361: It treats the input buffer as a read-only region (and so must your code).
7362: @end itemize
7363:
7364: @noindent
7365: When the text interpreter is in compile state, its behaviour changes in
7366: these ways:
7367:
7368: @itemize @bullet
7369: @item
7370: If a parsed string is found in the dictionary, the text interpreter will
7371: perform the word's @dfn{compilation semantics}. In most cases, this
7372: simply means that the execution semantics of the word will be appended
7373: to the current definition.
1.27 crook 7374: @item
1.29 crook 7375: When a number is encountered, it is compiled into the current definition
7376: (as a literal) rather than being pushed onto a parameter stack.
7377: @item
7378: If an error occurs, @code{state} is modified to put the text interpreter
7379: back into interpret state.
7380: @item
7381: Each time a line is entered from the keyboard, Gforth prints
7382: ``@code{ compiled}'' rather than `` @code{ok}''.
7383: @end itemize
7384:
7385: @cindex text interpreter - input sources
7386: When the text interpreter is using an input device other than the
7387: keyboard, its behaviour changes in these ways:
7388:
7389: @itemize @bullet
7390: @item
7391: When the parse area is empty, the text interpreter attempts to refill
7392: the input buffer from the input source. When the input source is
1.71 anton 7393: exhausted, the input source is set back to the previous input source.
1.29 crook 7394: @item
7395: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7396: time the parse area is emptied.
7397: @item
7398: If an error occurs, the input source is set back to the user input
7399: device.
1.27 crook 7400: @end itemize
1.21 crook 7401:
1.49 anton 7402: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7403:
1.26 crook 7404: doc->in
1.27 crook 7405: doc-source
7406:
1.26 crook 7407: doc-tib
7408: doc-#tib
1.1 anton 7409:
1.44 crook 7410:
1.26 crook 7411: @menu
1.67 anton 7412: * Input Sources::
7413: * Number Conversion::
7414: * Interpret/Compile states::
7415: * Interpreter Directives::
1.26 crook 7416: @end menu
1.1 anton 7417:
1.29 crook 7418: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7419: @subsection Input Sources
7420: @cindex input sources
7421: @cindex text interpreter - input sources
7422:
1.44 crook 7423: By default, the text interpreter processes input from the user input
1.29 crook 7424: device (the keyboard) when Forth starts up. The text interpreter can
7425: process input from any of these sources:
7426:
7427: @itemize @bullet
7428: @item
7429: The user input device -- the keyboard.
7430: @item
7431: A file, using the words described in @ref{Forth source files}.
7432: @item
7433: A block, using the words described in @ref{Blocks}.
7434: @item
7435: A text string, using @code{evaluate}.
7436: @end itemize
7437:
7438: A program can identify the current input device from the values of
7439: @code{source-id} and @code{blk}.
7440:
1.44 crook 7441:
1.29 crook 7442: doc-source-id
7443: doc-blk
7444:
7445: doc-save-input
7446: doc-restore-input
7447:
7448: doc-evaluate
1.111 anton 7449: doc-query
1.1 anton 7450:
1.29 crook 7451:
1.44 crook 7452:
1.29 crook 7453: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7454: @subsection Number Conversion
7455: @cindex number conversion
7456: @cindex double-cell numbers, input format
7457: @cindex input format for double-cell numbers
7458: @cindex single-cell numbers, input format
7459: @cindex input format for single-cell numbers
7460: @cindex floating-point numbers, input format
7461: @cindex input format for floating-point numbers
1.1 anton 7462:
1.29 crook 7463: This section describes the rules that the text interpreter uses when it
7464: tries to convert a string into a number.
1.1 anton 7465:
1.26 crook 7466: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7467: number base@footnote{For example, 0-9 when the number base is decimal or
7468: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7469:
1.26 crook 7470: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7471:
1.29 crook 7472: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7473: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7474:
1.26 crook 7475: Let * represent any number of instances of the previous character
7476: (including none).
1.1 anton 7477:
1.26 crook 7478: Let any other character represent itself.
1.1 anton 7479:
1.29 crook 7480: @noindent
1.26 crook 7481: Now, the conversion rules are:
1.21 crook 7482:
1.26 crook 7483: @itemize @bullet
7484: @item
7485: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7486: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7487: @item
7488: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7489: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7490: arithmetic. Examples are -45 -5681 -0
7491: @item
7492: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7493: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7494: (all three of these represent the same number).
1.26 crook 7495: @item
7496: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7497: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7498: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7499: -34.65 (all three of these represent the same number).
1.26 crook 7500: @item
1.29 crook 7501: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7502: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7503: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7504: number) +12.E-4
1.26 crook 7505: @end itemize
1.1 anton 7506:
1.26 crook 7507: By default, the number base used for integer number conversion is given
1.35 anton 7508: by the contents of the variable @code{base}. Note that a lot of
7509: confusion can result from unexpected values of @code{base}. If you
7510: change @code{base} anywhere, make sure to save the old value and restore
7511: it afterwards. In general I recommend keeping @code{base} decimal, and
7512: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7513:
1.29 crook 7514: doc-dpl
1.26 crook 7515: doc-base
7516: doc-hex
7517: doc-decimal
1.1 anton 7518:
1.44 crook 7519:
1.26 crook 7520: @cindex '-prefix for character strings
7521: @cindex &-prefix for decimal numbers
7522: @cindex %-prefix for binary numbers
7523: @cindex $-prefix for hexadecimal numbers
1.35 anton 7524: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7525: prefix@footnote{Some Forth implementations provide a similar scheme by
7526: implementing @code{$} etc. as parsing words that process the subsequent
7527: number in the input stream and push it onto the stack. For example, see
7528: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7529: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7530: is required between the prefix and the number.} before the first digit
7531: of an (integer) number. Four prefixes are supported:
1.1 anton 7532:
1.26 crook 7533: @itemize @bullet
7534: @item
1.35 anton 7535: @code{&} -- decimal
1.26 crook 7536: @item
1.35 anton 7537: @code{%} -- binary
1.26 crook 7538: @item
1.35 anton 7539: @code{$} -- hexadecimal
1.26 crook 7540: @item
1.35 anton 7541: @code{'} -- base @code{max-char+1}
1.26 crook 7542: @end itemize
1.1 anton 7543:
1.26 crook 7544: Here are some examples, with the equivalent decimal number shown after
7545: in braces:
1.1 anton 7546:
1.26 crook 7547: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7548: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7549: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7550: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7551:
1.26 crook 7552: @cindex number conversion - traps for the unwary
1.29 crook 7553: @noindent
1.26 crook 7554: Number conversion has a number of traps for the unwary:
1.1 anton 7555:
1.26 crook 7556: @itemize @bullet
7557: @item
7558: You cannot determine the current number base using the code sequence
1.35 anton 7559: @code{base @@ .} -- the number base is always 10 in the current number
7560: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7561: @item
7562: If the number base is set to a value greater than 14 (for example,
7563: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7564: it to be intepreted as either a single-precision integer or a
7565: floating-point number (Gforth treats it as an integer). The ambiguity
7566: can be resolved by explicitly stating the sign of the mantissa and/or
7567: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7568: ambiguity arises; either representation will be treated as a
7569: floating-point number.
7570: @item
1.29 crook 7571: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7572: It is used to specify file types.
7573: @item
1.72 anton 7574: ANS Forth requires the @code{.} of a double-precision number to be the
7575: final character in the string. Gforth allows the @code{.} to be
7576: anywhere after the first digit.
1.26 crook 7577: @item
7578: The number conversion process does not check for overflow.
7579: @item
1.72 anton 7580: In an ANS Forth program @code{base} is required to be decimal when
7581: converting floating-point numbers. In Gforth, number conversion to
7582: floating-point numbers always uses base &10, irrespective of the value
7583: of @code{base}.
1.26 crook 7584: @end itemize
1.1 anton 7585:
1.49 anton 7586: You can read numbers into your programs with the words described in
7587: @ref{Input}.
1.1 anton 7588:
1.82 anton 7589: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7590: @subsection Interpret/Compile states
7591: @cindex Interpret/Compile states
1.1 anton 7592:
1.29 crook 7593: A standard program is not permitted to change @code{state}
7594: explicitly. However, it can change @code{state} implicitly, using the
7595: words @code{[} and @code{]}. When @code{[} is executed it switches
7596: @code{state} to interpret state, and therefore the text interpreter
7597: starts interpreting. When @code{]} is executed it switches @code{state}
7598: to compile state and therefore the text interpreter starts
1.44 crook 7599: compiling. The most common usage for these words is for switching into
7600: interpret state and back from within a colon definition; this technique
1.49 anton 7601: can be used to compile a literal (for an example, @pxref{Literals}) or
7602: for conditional compilation (for an example, @pxref{Interpreter
7603: Directives}).
1.44 crook 7604:
1.35 anton 7605:
7606: @c This is a bad example: It's non-standard, and it's not necessary.
7607: @c However, I can't think of a good example for switching into compile
7608: @c state when there is no current word (@code{state}-smart words are not a
7609: @c good reason). So maybe we should use an example for switching into
7610: @c interpret @code{state} in a colon def. - anton
1.44 crook 7611: @c nac-> I agree. I started out by putting in the example, then realised
7612: @c that it was non-ANS, so wrote more words around it. I hope this
7613: @c re-written version is acceptable to you. I do want to keep the example
7614: @c as it is helpful for showing what is and what is not portable, particularly
7615: @c where it outlaws a style in common use.
7616:
1.72 anton 7617: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7618: @c that, we can also show what's not. In any case, I have written a
7619: @c section Compiling Words which also deals with [ ].
1.35 anton 7620:
1.95 anton 7621: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7622:
1.95 anton 7623: @c @code{[} and @code{]} also give you the ability to switch into compile
7624: @c state and back, but we cannot think of any useful Standard application
7625: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7626:
7627: @c @example
7628: @c : AA ." this is A" ;
7629: @c : BB ." this is B" ;
7630: @c : CC ." this is C" ;
7631:
7632: @c create table ] aa bb cc [
7633:
7634: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7635: @c cells table + @@ execute ;
7636: @c @end example
7637:
7638: @c This example builds a jump table; @code{0 go} will display ``@code{this
7639: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7640: @c defining @code{table} like this:
7641:
7642: @c @example
7643: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7644: @c @end example
7645:
7646: @c The problem with this code is that the definition of @code{table} is not
7647: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7648: @c @i{may} work on systems where code space and data space co-incide, the
7649: @c Standard only allows data space to be assigned for a @code{CREATE}d
7650: @c word. In addition, the Standard only allows @code{@@} to access data
7651: @c space, whilst this example is using it to access code space. The only
7652: @c portable, Standard way to build this table is to build it in data space,
7653: @c like this:
7654:
7655: @c @example
7656: @c create table ' aa , ' bb , ' cc ,
7657: @c @end example
1.29 crook 7658:
1.95 anton 7659: @c doc-state
1.44 crook 7660:
1.29 crook 7661:
1.82 anton 7662: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7663: @subsection Interpreter Directives
7664: @cindex interpreter directives
1.72 anton 7665: @cindex conditional compilation
1.1 anton 7666:
1.29 crook 7667: These words are usually used in interpret state; typically to control
7668: which parts of a source file are processed by the text
1.26 crook 7669: interpreter. There are only a few ANS Forth Standard words, but Gforth
7670: supplements these with a rich set of immediate control structure words
7671: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7672: used in compile state (@pxref{Control Structures}). Typical usages:
7673:
7674: @example
1.72 anton 7675: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7676: .
7677: .
1.72 anton 7678: HAVE-ASSEMBLER [IF]
1.29 crook 7679: : ASSEMBLER-FEATURE
7680: ...
7681: ;
7682: [ENDIF]
7683: .
7684: .
7685: : SEE
7686: ... \ general-purpose SEE code
1.72 anton 7687: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7688: ... \ assembler-specific SEE code
7689: [ [ENDIF] ]
7690: ;
7691: @end example
1.1 anton 7692:
1.44 crook 7693:
1.26 crook 7694: doc-[IF]
7695: doc-[ELSE]
7696: doc-[THEN]
7697: doc-[ENDIF]
1.1 anton 7698:
1.26 crook 7699: doc-[IFDEF]
7700: doc-[IFUNDEF]
1.1 anton 7701:
1.26 crook 7702: doc-[?DO]
7703: doc-[DO]
7704: doc-[FOR]
7705: doc-[LOOP]
7706: doc-[+LOOP]
7707: doc-[NEXT]
1.1 anton 7708:
1.26 crook 7709: doc-[BEGIN]
7710: doc-[UNTIL]
7711: doc-[AGAIN]
7712: doc-[WHILE]
7713: doc-[REPEAT]
1.1 anton 7714:
1.27 crook 7715:
1.26 crook 7716: @c -------------------------------------------------------------
1.111 anton 7717: @node The Input Stream, Word Lists, The Text Interpreter, Words
7718: @section The Input Stream
7719: @cindex input stream
7720:
7721: @c !! integrate this better with the "Text Interpreter" section
7722: The text interpreter reads from the input stream, which can come from
7723: several sources (@pxref{Input Sources}). Some words, in particular
7724: defining words, but also words like @code{'}, read parameters from the
7725: input stream instead of from the stack.
7726:
7727: Such words are called parsing words, because they parse the input
7728: stream. Parsing words are hard to use in other words, because it is
7729: hard to pass program-generated parameters through the input stream.
7730: They also usually have an unintuitive combination of interpretation and
7731: compilation semantics when implemented naively, leading to various
7732: approaches that try to produce a more intuitive behaviour
7733: (@pxref{Combined words}).
7734:
7735: It should be obvious by now that parsing words are a bad idea. If you
7736: want to implement a parsing word for convenience, also provide a factor
7737: of the word that does not parse, but takes the parameters on the stack.
7738: To implement the parsing word on top if it, you can use the following
7739: words:
7740:
7741: @c anton: these belong in the input stream section
7742: doc-parse
7743: doc-parse-word
7744: doc-name
7745: doc-word
7746: doc-\"-parse
7747: doc-refill
7748:
7749: Conversely, if you have the bad luck (or lack of foresight) to have to
7750: deal with parsing words without having such factors, how do you pass a
7751: string that is not in the input stream to it?
7752:
7753: doc-execute-parsing
7754:
7755: If you want to run a parsing word on a file, the following word should
7756: help:
7757:
7758: doc-execute-parsing-file
7759:
7760: @c -------------------------------------------------------------
7761: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7762: @section Word Lists
7763: @cindex word lists
1.32 anton 7764: @cindex header space
1.1 anton 7765:
1.36 anton 7766: A wordlist is a list of named words; you can add new words and look up
7767: words by name (and you can remove words in a restricted way with
7768: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7769:
7770: @cindex search order stack
7771: The text interpreter searches the wordlists present in the search order
7772: (a stack of wordlists), from the top to the bottom. Within each
7773: wordlist, the search starts conceptually at the newest word; i.e., if
7774: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7775:
1.26 crook 7776: @cindex compilation word list
1.36 anton 7777: New words are added to the @dfn{compilation wordlist} (aka current
7778: wordlist).
1.1 anton 7779:
1.36 anton 7780: @cindex wid
7781: A word list is identified by a cell-sized word list identifier (@i{wid})
7782: in much the same way as a file is identified by a file handle. The
7783: numerical value of the wid has no (portable) meaning, and might change
7784: from session to session.
1.1 anton 7785:
1.29 crook 7786: The ANS Forth ``Search order'' word set is intended to provide a set of
7787: low-level tools that allow various different schemes to be
1.74 anton 7788: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7789: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7790: Forth.
1.1 anton 7791:
1.27 crook 7792: @comment TODO: locals section refers to here, saying that every word list (aka
7793: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7794: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7795:
1.45 crook 7796: @comment TODO: document markers, reveal, tables, mappedwordlist
7797:
7798: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7799: @comment word from the source files, rather than some alias.
1.44 crook 7800:
1.26 crook 7801: doc-forth-wordlist
7802: doc-definitions
7803: doc-get-current
7804: doc-set-current
7805: doc-get-order
1.45 crook 7806: doc---gforthman-set-order
1.26 crook 7807: doc-wordlist
1.30 anton 7808: doc-table
1.79 anton 7809: doc->order
1.36 anton 7810: doc-previous
1.26 crook 7811: doc-also
1.45 crook 7812: doc---gforthman-forth
1.26 crook 7813: doc-only
1.45 crook 7814: doc---gforthman-order
1.15 anton 7815:
1.26 crook 7816: doc-find
7817: doc-search-wordlist
1.15 anton 7818:
1.26 crook 7819: doc-words
7820: doc-vlist
1.44 crook 7821: @c doc-words-deferred
1.1 anton 7822:
1.74 anton 7823: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7824: doc-root
7825: doc-vocabulary
7826: doc-seal
7827: doc-vocs
7828: doc-current
7829: doc-context
1.1 anton 7830:
1.44 crook 7831:
1.26 crook 7832: @menu
1.75 anton 7833: * Vocabularies::
1.67 anton 7834: * Why use word lists?::
1.75 anton 7835: * Word list example::
1.26 crook 7836: @end menu
7837:
1.75 anton 7838: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7839: @subsection Vocabularies
7840: @cindex Vocabularies, detailed explanation
7841:
7842: Here is an example of creating and using a new wordlist using ANS
7843: Forth words:
7844:
7845: @example
7846: wordlist constant my-new-words-wordlist
7847: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7848:
7849: \ add it to the search order
7850: also my-new-words
7851:
7852: \ alternatively, add it to the search order and make it
7853: \ the compilation word list
7854: also my-new-words definitions
7855: \ type "order" to see the problem
7856: @end example
7857:
7858: The problem with this example is that @code{order} has no way to
7859: associate the name @code{my-new-words} with the wid of the word list (in
7860: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7861: that has no associated name). There is no Standard way of associating a
7862: name with a wid.
7863:
7864: In Gforth, this example can be re-coded using @code{vocabulary}, which
7865: associates a name with a wid:
7866:
7867: @example
7868: vocabulary my-new-words
7869:
7870: \ add it to the search order
7871: also my-new-words
7872:
7873: \ alternatively, add it to the search order and make it
7874: \ the compilation word list
7875: my-new-words definitions
7876: \ type "order" to see that the problem is solved
7877: @end example
7878:
7879:
7880: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7881: @subsection Why use word lists?
7882: @cindex word lists - why use them?
7883:
1.74 anton 7884: Here are some reasons why people use wordlists:
1.26 crook 7885:
7886: @itemize @bullet
1.74 anton 7887:
7888: @c anton: Gforth's hashing implementation makes the search speed
7889: @c independent from the number of words. But it is linear with the number
7890: @c of wordlists that have to be searched, so in effect using more wordlists
7891: @c actually slows down compilation.
7892:
7893: @c @item
7894: @c To improve compilation speed by reducing the number of header space
7895: @c entries that must be searched. This is achieved by creating a new
7896: @c word list that contains all of the definitions that are used in the
7897: @c definition of a Forth system but which would not usually be used by
7898: @c programs running on that system. That word list would be on the search
7899: @c list when the Forth system was compiled but would be removed from the
7900: @c search list for normal operation. This can be a useful technique for
7901: @c low-performance systems (for example, 8-bit processors in embedded
7902: @c systems) but is unlikely to be necessary in high-performance desktop
7903: @c systems.
7904:
1.26 crook 7905: @item
7906: To prevent a set of words from being used outside the context in which
7907: they are valid. Two classic examples of this are an integrated editor
7908: (all of the edit commands are defined in a separate word list; the
7909: search order is set to the editor word list when the editor is invoked;
7910: the old search order is restored when the editor is terminated) and an
7911: integrated assembler (the op-codes for the machine are defined in a
7912: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 7913:
7914: @item
7915: To organize the words of an application or library into a user-visible
7916: set (in @code{forth-wordlist} or some other common wordlist) and a set
7917: of helper words used just for the implementation (hidden in a separate
1.75 anton 7918: wordlist). This keeps @code{words}' output smaller, separates
7919: implementation and interface, and reduces the chance of name conflicts
7920: within the common wordlist.
1.74 anton 7921:
1.26 crook 7922: @item
7923: To prevent a name-space clash between multiple definitions with the same
7924: name. For example, when building a cross-compiler you might have a word
7925: @code{IF} that generates conditional code for your target system. By
7926: placing this definition in a different word list you can control whether
7927: the host system's @code{IF} or the target system's @code{IF} get used in
7928: any particular context by controlling the order of the word lists on the
7929: search order stack.
1.74 anton 7930:
1.26 crook 7931: @end itemize
1.1 anton 7932:
1.74 anton 7933: The downsides of using wordlists are:
7934:
7935: @itemize
7936:
7937: @item
7938: Debugging becomes more cumbersome.
7939:
7940: @item
7941: Name conflicts worked around with wordlists are still there, and you
7942: have to arrange the search order carefully to get the desired results;
7943: if you forget to do that, you get hard-to-find errors (as in any case
7944: where you read the code differently from the compiler; @code{see} can
1.75 anton 7945: help seeing which of several possible words the name resolves to in such
7946: cases). @code{See} displays just the name of the words, not what
7947: wordlist they belong to, so it might be misleading. Using unique names
7948: is a better approach to avoid name conflicts.
1.74 anton 7949:
7950: @item
7951: You have to explicitly undo any changes to the search order. In many
7952: cases it would be more convenient if this happened implicitly. Gforth
7953: currently does not provide such a feature, but it may do so in the
7954: future.
7955: @end itemize
7956:
7957:
1.75 anton 7958: @node Word list example, , Why use word lists?, Word Lists
7959: @subsection Word list example
7960: @cindex word lists - example
1.1 anton 7961:
1.74 anton 7962: The following example is from the
7963: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
7964: garbage collector} and uses wordlists to separate public words from
7965: helper words:
7966:
7967: @example
7968: get-current ( wid )
7969: vocabulary garbage-collector also garbage-collector definitions
7970: ... \ define helper words
7971: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
7972: ... \ define the public (i.e., API) words
7973: \ they can refer to the helper words
7974: previous \ restore original search order (helper words become invisible)
7975: @end example
7976:
1.26 crook 7977: @c -------------------------------------------------------------
7978: @node Environmental Queries, Files, Word Lists, Words
7979: @section Environmental Queries
7980: @cindex environmental queries
1.21 crook 7981:
1.26 crook 7982: ANS Forth introduced the idea of ``environmental queries'' as a way
7983: for a program running on a system to determine certain characteristics of the system.
7984: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 7985:
1.32 anton 7986: The Standard requires that the header space used for environmental queries
7987: be distinct from the header space used for definitions.
1.21 crook 7988:
1.26 crook 7989: Typically, environmental queries are supported by creating a set of
1.29 crook 7990: definitions in a word list that is @i{only} used during environmental
1.26 crook 7991: queries; that is what Gforth does. There is no Standard way of adding
7992: definitions to the set of recognised environmental queries, but any
7993: implementation that supports the loading of optional word sets must have
7994: some mechanism for doing this (after loading the word set, the
7995: associated environmental query string must return @code{true}). In
7996: Gforth, the word list used to honour environmental queries can be
7997: manipulated just like any other word list.
1.21 crook 7998:
1.44 crook 7999:
1.26 crook 8000: doc-environment?
8001: doc-environment-wordlist
1.21 crook 8002:
1.26 crook 8003: doc-gforth
8004: doc-os-class
1.21 crook 8005:
1.44 crook 8006:
1.26 crook 8007: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8008: returning two items on the stack, querying it using @code{environment?}
8009: will return an additional item; the @code{true} flag that shows that the
8010: string was recognised.
1.21 crook 8011:
1.26 crook 8012: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8013:
1.26 crook 8014: Here are some examples of using environmental queries:
1.21 crook 8015:
1.26 crook 8016: @example
8017: s" address-unit-bits" environment? 0=
8018: [IF]
8019: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8020: [ELSE]
8021: drop \ ensure balanced stack effect
1.26 crook 8022: [THEN]
1.21 crook 8023:
1.75 anton 8024: \ this might occur in the prelude of a standard program that uses THROW
8025: s" exception" environment? [IF]
8026: 0= [IF]
8027: : throw abort" exception thrown" ;
8028: [THEN]
8029: [ELSE] \ we don't know, so make sure
8030: : throw abort" exception thrown" ;
8031: [THEN]
1.21 crook 8032:
1.26 crook 8033: s" gforth" environment? [IF] .( Gforth version ) TYPE
8034: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8035:
8036: \ a program using v*
8037: s" gforth" environment? [IF]
8038: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8039: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8040: >r swap 2swap swap 0e r> 0 ?DO
8041: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8042: LOOP
8043: 2drop 2drop ;
8044: [THEN]
8045: [ELSE] \
8046: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8047: ...
8048: [THEN]
1.26 crook 8049: @end example
1.21 crook 8050:
1.26 crook 8051: Here is an example of adding a definition to the environment word list:
1.21 crook 8052:
1.26 crook 8053: @example
8054: get-current environment-wordlist set-current
8055: true constant block
8056: true constant block-ext
8057: set-current
8058: @end example
1.21 crook 8059:
1.26 crook 8060: You can see what definitions are in the environment word list like this:
1.21 crook 8061:
1.26 crook 8062: @example
1.79 anton 8063: environment-wordlist >order words previous
1.26 crook 8064: @end example
1.21 crook 8065:
8066:
1.26 crook 8067: @c -------------------------------------------------------------
8068: @node Files, Blocks, Environmental Queries, Words
8069: @section Files
1.28 crook 8070: @cindex files
8071: @cindex I/O - file-handling
1.21 crook 8072:
1.26 crook 8073: Gforth provides facilities for accessing files that are stored in the
8074: host operating system's file-system. Files that are processed by Gforth
8075: can be divided into two categories:
1.21 crook 8076:
1.23 crook 8077: @itemize @bullet
8078: @item
1.29 crook 8079: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8080: @item
1.29 crook 8081: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8082: @end itemize
8083:
8084: @menu
1.48 anton 8085: * Forth source files::
8086: * General files::
8087: * Search Paths::
1.26 crook 8088: @end menu
8089:
8090: @c -------------------------------------------------------------
8091: @node Forth source files, General files, Files, Files
8092: @subsection Forth source files
8093: @cindex including files
8094: @cindex Forth source files
1.21 crook 8095:
1.26 crook 8096: The simplest way to interpret the contents of a file is to use one of
8097: these two formats:
1.21 crook 8098:
1.26 crook 8099: @example
8100: include mysource.fs
8101: s" mysource.fs" included
8102: @end example
1.21 crook 8103:
1.75 anton 8104: You usually want to include a file only if it is not included already
1.26 crook 8105: (by, say, another source file). In that case, you can use one of these
1.45 crook 8106: three formats:
1.21 crook 8107:
1.26 crook 8108: @example
8109: require mysource.fs
8110: needs mysource.fs
8111: s" mysource.fs" required
8112: @end example
1.21 crook 8113:
1.26 crook 8114: @cindex stack effect of included files
8115: @cindex including files, stack effect
1.45 crook 8116: It is good practice to write your source files such that interpreting them
8117: does not change the stack. Source files designed in this way can be used with
1.26 crook 8118: @code{required} and friends without complications. For example:
1.21 crook 8119:
1.26 crook 8120: @example
1.75 anton 8121: 1024 require foo.fs drop
1.26 crook 8122: @end example
1.21 crook 8123:
1.75 anton 8124: Here you want to pass the argument 1024 (e.g., a buffer size) to
8125: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8126: ), which allows its use with @code{require}. Of course with such
8127: parameters to required files, you have to ensure that the first
8128: @code{require} fits for all uses (i.e., @code{require} it early in the
8129: master load file).
1.44 crook 8130:
1.26 crook 8131: doc-include-file
8132: doc-included
1.28 crook 8133: doc-included?
1.26 crook 8134: doc-include
8135: doc-required
8136: doc-require
8137: doc-needs
1.75 anton 8138: @c doc-init-included-files @c internal
8139: doc-sourcefilename
8140: doc-sourceline#
1.44 crook 8141:
1.26 crook 8142: A definition in ANS Forth for @code{required} is provided in
8143: @file{compat/required.fs}.
1.21 crook 8144:
1.26 crook 8145: @c -------------------------------------------------------------
8146: @node General files, Search Paths, Forth source files, Files
8147: @subsection General files
8148: @cindex general files
8149: @cindex file-handling
1.21 crook 8150:
1.75 anton 8151: Files are opened/created by name and type. The following file access
8152: methods (FAMs) are recognised:
1.44 crook 8153:
1.75 anton 8154: @cindex fam (file access method)
1.26 crook 8155: doc-r/o
8156: doc-r/w
8157: doc-w/o
8158: doc-bin
1.1 anton 8159:
1.44 crook 8160:
1.26 crook 8161: When a file is opened/created, it returns a file identifier,
1.29 crook 8162: @i{wfileid} that is used for all other file commands. All file
8163: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8164: successful operation and an implementation-defined non-zero value in the
8165: case of an error.
1.21 crook 8166:
1.44 crook 8167:
1.26 crook 8168: doc-open-file
8169: doc-create-file
1.21 crook 8170:
1.26 crook 8171: doc-close-file
8172: doc-delete-file
8173: doc-rename-file
8174: doc-read-file
8175: doc-read-line
8176: doc-write-file
8177: doc-write-line
8178: doc-emit-file
8179: doc-flush-file
1.21 crook 8180:
1.26 crook 8181: doc-file-status
8182: doc-file-position
8183: doc-reposition-file
8184: doc-file-size
8185: doc-resize-file
1.21 crook 8186:
1.93 anton 8187: doc-slurp-file
8188: doc-slurp-fid
1.112 anton 8189: doc-stdin
8190: doc-stdout
8191: doc-stderr
1.44 crook 8192:
1.26 crook 8193: @c ---------------------------------------------------------
1.48 anton 8194: @node Search Paths, , General files, Files
1.26 crook 8195: @subsection Search Paths
8196: @cindex path for @code{included}
8197: @cindex file search path
8198: @cindex @code{include} search path
8199: @cindex search path for files
1.21 crook 8200:
1.26 crook 8201: If you specify an absolute filename (i.e., a filename starting with
8202: @file{/} or @file{~}, or with @file{:} in the second position (as in
8203: @samp{C:...})) for @code{included} and friends, that file is included
8204: just as you would expect.
1.21 crook 8205:
1.75 anton 8206: If the filename starts with @file{./}, this refers to the directory that
8207: the present file was @code{included} from. This allows files to include
8208: other files relative to their own position (irrespective of the current
8209: working directory or the absolute position). This feature is essential
8210: for libraries consisting of several files, where a file may include
8211: other files from the library. It corresponds to @code{#include "..."}
8212: in C. If the current input source is not a file, @file{.} refers to the
8213: directory of the innermost file being included, or, if there is no file
8214: being included, to the current working directory.
8215:
8216: For relative filenames (not starting with @file{./}), Gforth uses a
8217: search path similar to Forth's search order (@pxref{Word Lists}). It
8218: tries to find the given filename in the directories present in the path,
8219: and includes the first one it finds. There are separate search paths for
8220: Forth source files and general files. If the search path contains the
8221: directory @file{.}, this refers to the directory of the current file, or
8222: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8223:
1.26 crook 8224: Use @file{~+} to refer to the current working directory (as in the
8225: @code{bash}).
1.1 anton 8226:
1.75 anton 8227: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8228:
1.48 anton 8229: @menu
1.75 anton 8230: * Source Search Paths::
1.48 anton 8231: * General Search Paths::
8232: @end menu
8233:
1.26 crook 8234: @c ---------------------------------------------------------
1.75 anton 8235: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8236: @subsubsection Source Search Paths
8237: @cindex search path control, source files
1.5 anton 8238:
1.26 crook 8239: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8240: Gforth}). You can display it and change it using @code{fpath} in
8241: combination with the general path handling words.
1.5 anton 8242:
1.75 anton 8243: doc-fpath
8244: @c the functionality of the following words is easily available through
8245: @c fpath and the general path words. The may go away.
8246: @c doc-.fpath
8247: @c doc-fpath+
8248: @c doc-fpath=
8249: @c doc-open-fpath-file
1.44 crook 8250:
8251: @noindent
1.26 crook 8252: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8253:
1.26 crook 8254: @example
1.75 anton 8255: fpath path= /usr/lib/forth/|./
1.26 crook 8256: require timer.fs
8257: @end example
1.5 anton 8258:
1.75 anton 8259:
1.26 crook 8260: @c ---------------------------------------------------------
1.75 anton 8261: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8262: @subsubsection General Search Paths
1.75 anton 8263: @cindex search path control, source files
1.5 anton 8264:
1.26 crook 8265: Your application may need to search files in several directories, like
8266: @code{included} does. To facilitate this, Gforth allows you to define
8267: and use your own search paths, by providing generic equivalents of the
8268: Forth search path words:
1.5 anton 8269:
1.75 anton 8270: doc-open-path-file
8271: doc-path-allot
8272: doc-clear-path
8273: doc-also-path
1.26 crook 8274: doc-.path
8275: doc-path+
8276: doc-path=
1.5 anton 8277:
1.75 anton 8278: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8279:
1.75 anton 8280: Here's an example of creating an empty search path:
8281: @c
1.26 crook 8282: @example
1.75 anton 8283: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8284: @end example
1.5 anton 8285:
1.26 crook 8286: @c -------------------------------------------------------------
8287: @node Blocks, Other I/O, Files, Words
8288: @section Blocks
1.28 crook 8289: @cindex I/O - blocks
8290: @cindex blocks
8291:
8292: When you run Gforth on a modern desk-top computer, it runs under the
8293: control of an operating system which provides certain services. One of
8294: these services is @var{file services}, which allows Forth source code
8295: and data to be stored in files and read into Gforth (@pxref{Files}).
8296:
8297: Traditionally, Forth has been an important programming language on
8298: systems where it has interfaced directly to the underlying hardware with
8299: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8300: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8301:
8302: A block is a 1024-byte data area, which can be used to hold data or
8303: Forth source code. No structure is imposed on the contents of the
8304: block. A block is identified by its number; blocks are numbered
8305: contiguously from 1 to an implementation-defined maximum.
8306:
8307: A typical system that used blocks but no operating system might use a
8308: single floppy-disk drive for mass storage, with the disks formatted to
8309: provide 256-byte sectors. Blocks would be implemented by assigning the
8310: first four sectors of the disk to block 1, the second four sectors to
8311: block 2 and so on, up to the limit of the capacity of the disk. The disk
8312: would not contain any file system information, just the set of blocks.
8313:
1.29 crook 8314: @cindex blocks file
1.28 crook 8315: On systems that do provide file services, blocks are typically
1.29 crook 8316: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8317: file}. The size of the blocks file will be an exact multiple of 1024
8318: bytes, corresponding to the number of blocks it contains. This is the
8319: mechanism that Gforth uses.
8320:
1.29 crook 8321: @cindex @file{blocks.fb}
1.75 anton 8322: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8323: having specified a blocks file, Gforth defaults to the blocks file
8324: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8325: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8326:
1.29 crook 8327: @cindex block buffers
1.28 crook 8328: When you read and write blocks under program control, Gforth uses a
1.29 crook 8329: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8330: not used when you use @code{load} to interpret the contents of a block.
8331:
1.75 anton 8332: The behaviour of the block buffers is analagous to that of a cache.
8333: Each block buffer has three states:
1.28 crook 8334:
8335: @itemize @bullet
8336: @item
8337: Unassigned
8338: @item
8339: Assigned-clean
8340: @item
8341: Assigned-dirty
8342: @end itemize
8343:
1.29 crook 8344: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8345: block, the block (specified by its block number) must be assigned to a
8346: block buffer.
8347:
8348: The assignment of a block to a block buffer is performed by @code{block}
8349: or @code{buffer}. Use @code{block} when you wish to modify the existing
8350: contents of a block. Use @code{buffer} when you don't care about the
8351: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8352: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8353: with the particular block is already stored in a block buffer due to an
8354: earlier @code{block} command, @code{buffer} will return that block
8355: buffer and the existing contents of the block will be
8356: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8357: block buffer for the block.}.
1.28 crook 8358:
1.47 crook 8359: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8360: @code{buffer}, that block buffer becomes the @i{current block
8361: buffer}. Data may only be manipulated (read or written) within the
8362: current block buffer.
1.47 crook 8363:
8364: When the contents of the current block buffer has been modified it is
1.48 anton 8365: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8366: either abandon the changes (by doing nothing) or mark the block as
8367: changed (assigned-dirty), using @code{update}. Using @code{update} does
8368: not change the blocks file; it simply changes a block buffer's state to
8369: @i{assigned-dirty}. The block will be written implicitly when it's
8370: buffer is needed for another block, or explicitly by @code{flush} or
8371: @code{save-buffers}.
8372:
8373: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8374: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8375: @code{flush}.
1.28 crook 8376:
1.29 crook 8377: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8378: algorithm to assign a block buffer to a block. That means that any
8379: particular block can only be assigned to one specific block buffer,
1.29 crook 8380: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8381: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8382: the new block immediately. If it is @i{assigned-dirty} its current
8383: contents are written back to the blocks file on disk before it is
1.28 crook 8384: allocated to the new block.
8385:
8386: Although no structure is imposed on the contents of a block, it is
8387: traditional to display the contents as 16 lines each of 64 characters. A
8388: block provides a single, continuous stream of input (for example, it
8389: acts as a single parse area) -- there are no end-of-line characters
8390: within a block, and no end-of-file character at the end of a
8391: block. There are two consequences of this:
1.26 crook 8392:
1.28 crook 8393: @itemize @bullet
8394: @item
8395: The last character of one line wraps straight into the first character
8396: of the following line
8397: @item
8398: The word @code{\} -- comment to end of line -- requires special
8399: treatment; in the context of a block it causes all characters until the
8400: end of the current 64-character ``line'' to be ignored.
8401: @end itemize
8402:
8403: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8404: the current blocks file will be extended to the appropriate size and the
1.28 crook 8405: block buffer will be initialised with spaces.
8406:
1.47 crook 8407: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8408: for details) but doesn't encourage the use of blocks; the mechanism is
8409: only provided for backward compatibility -- ANS Forth requires blocks to
8410: be available when files are.
1.28 crook 8411:
8412: Common techniques that are used when working with blocks include:
8413:
8414: @itemize @bullet
8415: @item
8416: A screen editor that allows you to edit blocks without leaving the Forth
8417: environment.
8418: @item
8419: Shadow screens; where every code block has an associated block
8420: containing comments (for example: code in odd block numbers, comments in
8421: even block numbers). Typically, the block editor provides a convenient
8422: mechanism to toggle between code and comments.
8423: @item
8424: Load blocks; a single block (typically block 1) contains a number of
8425: @code{thru} commands which @code{load} the whole of the application.
8426: @end itemize
1.26 crook 8427:
1.29 crook 8428: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8429: integrated into a Forth programming environment.
1.26 crook 8430:
8431: @comment TODO what about errors on open-blocks?
1.44 crook 8432:
1.26 crook 8433: doc-open-blocks
8434: doc-use
1.75 anton 8435: doc-block-offset
1.26 crook 8436: doc-get-block-fid
8437: doc-block-position
1.28 crook 8438:
1.75 anton 8439: doc-list
1.28 crook 8440: doc-scr
8441:
1.45 crook 8442: doc---gforthman-block
1.28 crook 8443: doc-buffer
8444:
1.75 anton 8445: doc-empty-buffers
8446: doc-empty-buffer
1.26 crook 8447: doc-update
1.28 crook 8448: doc-updated?
1.26 crook 8449: doc-save-buffers
1.75 anton 8450: doc-save-buffer
1.26 crook 8451: doc-flush
1.28 crook 8452:
1.26 crook 8453: doc-load
8454: doc-thru
8455: doc-+load
8456: doc-+thru
1.45 crook 8457: doc---gforthman--->
1.26 crook 8458: doc-block-included
8459:
1.44 crook 8460:
1.26 crook 8461: @c -------------------------------------------------------------
1.78 anton 8462: @node Other I/O, Locals, Blocks, Words
1.26 crook 8463: @section Other I/O
1.28 crook 8464: @cindex I/O - keyboard and display
1.26 crook 8465:
8466: @menu
8467: * Simple numeric output:: Predefined formats
8468: * Formatted numeric output:: Formatted (pictured) output
8469: * String Formats:: How Forth stores strings in memory
1.67 anton 8470: * Displaying characters and strings:: Other stuff
1.26 crook 8471: * Input:: Input
1.112 anton 8472: * Pipes:: How to create your own pipes
1.26 crook 8473: @end menu
8474:
8475: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8476: @subsection Simple numeric output
1.28 crook 8477: @cindex numeric output - simple/free-format
1.5 anton 8478:
1.26 crook 8479: The simplest output functions are those that display numbers from the
8480: data or floating-point stacks. Floating-point output is always displayed
8481: using base 10. Numbers displayed from the data stack use the value stored
8482: in @code{base}.
1.5 anton 8483:
1.44 crook 8484:
1.26 crook 8485: doc-.
8486: doc-dec.
8487: doc-hex.
8488: doc-u.
8489: doc-.r
8490: doc-u.r
8491: doc-d.
8492: doc-ud.
8493: doc-d.r
8494: doc-ud.r
8495: doc-f.
8496: doc-fe.
8497: doc-fs.
1.111 anton 8498: doc-f.rdp
1.44 crook 8499:
1.26 crook 8500: Examples of printing the number 1234.5678E23 in the different floating-point output
8501: formats are shown below:
1.5 anton 8502:
8503: @example
1.26 crook 8504: f. 123456779999999000000000000.
8505: fe. 123.456779999999E24
8506: fs. 1.23456779999999E26
1.5 anton 8507: @end example
8508:
8509:
1.26 crook 8510: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8511: @subsection Formatted numeric output
1.28 crook 8512: @cindex formatted numeric output
1.26 crook 8513: @cindex pictured numeric output
1.28 crook 8514: @cindex numeric output - formatted
1.26 crook 8515:
1.29 crook 8516: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8517: output} for formatted printing of integers. In this technique, digits
8518: are extracted from the number (using the current output radix defined by
8519: @code{base}), converted to ASCII codes and appended to a string that is
8520: built in a scratch-pad area of memory (@pxref{core-idef,
8521: Implementation-defined options, Implementation-defined
8522: options}). Arbitrary characters can be appended to the string during the
8523: extraction process. The completed string is specified by an address
8524: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8525: under program control.
1.5 anton 8526:
1.75 anton 8527: All of the integer output words described in the previous section
8528: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8529: numeric output.
1.5 anton 8530:
1.47 crook 8531: Three important things to remember about pictured numeric output:
1.5 anton 8532:
1.26 crook 8533: @itemize @bullet
8534: @item
1.28 crook 8535: It always operates on double-precision numbers; to display a
1.49 anton 8536: single-precision number, convert it first (for ways of doing this
8537: @pxref{Double precision}).
1.26 crook 8538: @item
1.28 crook 8539: It always treats the double-precision number as though it were
8540: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8541: @item
8542: The string is built up from right to left; least significant digit first.
8543: @end itemize
1.5 anton 8544:
1.44 crook 8545:
1.26 crook 8546: doc-<#
1.47 crook 8547: doc-<<#
1.26 crook 8548: doc-#
8549: doc-#s
8550: doc-hold
8551: doc-sign
8552: doc-#>
1.47 crook 8553: doc-#>>
1.5 anton 8554:
1.26 crook 8555: doc-represent
1.111 anton 8556: doc-f>str-rdp
8557: doc-f>buf-rdp
1.5 anton 8558:
1.44 crook 8559:
8560: @noindent
1.26 crook 8561: Here are some examples of using pictured numeric output:
1.5 anton 8562:
8563: @example
1.26 crook 8564: : my-u. ( u -- )
8565: \ Simplest use of pns.. behaves like Standard u.
8566: 0 \ convert to unsigned double
1.75 anton 8567: <<# \ start conversion
1.26 crook 8568: #s \ convert all digits
8569: #> \ complete conversion
1.75 anton 8570: TYPE SPACE \ display, with trailing space
8571: #>> ; \ release hold area
1.5 anton 8572:
1.26 crook 8573: : cents-only ( u -- )
8574: 0 \ convert to unsigned double
1.75 anton 8575: <<# \ start conversion
1.26 crook 8576: # # \ convert two least-significant digits
8577: #> \ complete conversion, discard other digits
1.75 anton 8578: TYPE SPACE \ display, with trailing space
8579: #>> ; \ release hold area
1.5 anton 8580:
1.26 crook 8581: : dollars-and-cents ( u -- )
8582: 0 \ convert to unsigned double
1.75 anton 8583: <<# \ start conversion
1.26 crook 8584: # # \ convert two least-significant digits
8585: [char] . hold \ insert decimal point
8586: #s \ convert remaining digits
8587: [char] $ hold \ append currency symbol
8588: #> \ complete conversion
1.75 anton 8589: TYPE SPACE \ display, with trailing space
8590: #>> ; \ release hold area
1.5 anton 8591:
1.26 crook 8592: : my-. ( n -- )
8593: \ handling negatives.. behaves like Standard .
8594: s>d \ convert to signed double
8595: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8596: <<# \ start conversion
1.26 crook 8597: #s \ convert all digits
8598: rot sign \ get at sign byte, append "-" if needed
8599: #> \ complete conversion
1.75 anton 8600: TYPE SPACE \ display, with trailing space
8601: #>> ; \ release hold area
1.5 anton 8602:
1.26 crook 8603: : account. ( n -- )
1.75 anton 8604: \ accountants don't like minus signs, they use parentheses
1.26 crook 8605: \ for negative numbers
8606: s>d \ convert to signed double
8607: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8608: <<# \ start conversion
1.26 crook 8609: 2 pick \ get copy of sign byte
8610: 0< IF [char] ) hold THEN \ right-most character of output
8611: #s \ convert all digits
8612: rot \ get at sign byte
8613: 0< IF [char] ( hold THEN
8614: #> \ complete conversion
1.75 anton 8615: TYPE SPACE \ display, with trailing space
8616: #>> ; \ release hold area
8617:
1.5 anton 8618: @end example
8619:
1.26 crook 8620: Here are some examples of using these words:
1.5 anton 8621:
8622: @example
1.26 crook 8623: 1 my-u. 1
8624: hex -1 my-u. decimal FFFFFFFF
8625: 1 cents-only 01
8626: 1234 cents-only 34
8627: 2 dollars-and-cents $0.02
8628: 1234 dollars-and-cents $12.34
8629: 123 my-. 123
8630: -123 my. -123
8631: 123 account. 123
8632: -456 account. (456)
1.5 anton 8633: @end example
8634:
8635:
1.26 crook 8636: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8637: @subsection String Formats
1.27 crook 8638: @cindex strings - see character strings
8639: @cindex character strings - formats
1.28 crook 8640: @cindex I/O - see character strings
1.75 anton 8641: @cindex counted strings
8642:
8643: @c anton: this does not really belong here; maybe the memory section,
8644: @c or the principles chapter
1.26 crook 8645:
1.27 crook 8646: Forth commonly uses two different methods for representing character
8647: strings:
1.26 crook 8648:
8649: @itemize @bullet
8650: @item
8651: @cindex address of counted string
1.45 crook 8652: @cindex counted string
1.29 crook 8653: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8654: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8655: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8656: memory.
8657: @item
1.29 crook 8658: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8659: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8660: first byte of the string.
8661: @end itemize
8662:
8663: ANS Forth encourages the use of the second format when representing
1.75 anton 8664: strings.
1.26 crook 8665:
1.44 crook 8666:
1.26 crook 8667: doc-count
8668:
1.44 crook 8669:
1.49 anton 8670: For words that move, copy and search for strings see @ref{Memory
8671: Blocks}. For words that display characters and strings see
8672: @ref{Displaying characters and strings}.
1.26 crook 8673:
8674: @node Displaying characters and strings, Input, String Formats, Other I/O
8675: @subsection Displaying characters and strings
1.27 crook 8676: @cindex characters - compiling and displaying
8677: @cindex character strings - compiling and displaying
1.26 crook 8678:
8679: This section starts with a glossary of Forth words and ends with a set
8680: of examples.
8681:
1.44 crook 8682:
1.26 crook 8683: doc-bl
8684: doc-space
8685: doc-spaces
8686: doc-emit
8687: doc-toupper
8688: doc-."
8689: doc-.(
1.98 anton 8690: doc-.\"
1.26 crook 8691: doc-type
1.44 crook 8692: doc-typewhite
1.26 crook 8693: doc-cr
1.27 crook 8694: @cindex cursor control
1.26 crook 8695: doc-at-xy
8696: doc-page
8697: doc-s"
1.98 anton 8698: doc-s\"
1.26 crook 8699: doc-c"
8700: doc-char
8701: doc-[char]
8702:
1.44 crook 8703:
8704: @noindent
1.26 crook 8705: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8706:
8707: @example
1.26 crook 8708: .( text-1)
8709: : my-word
8710: ." text-2" cr
8711: .( text-3)
8712: ;
8713:
8714: ." text-4"
8715:
8716: : my-char
8717: [char] ALPHABET emit
8718: char emit
8719: ;
1.5 anton 8720: @end example
8721:
1.26 crook 8722: When you load this code into Gforth, the following output is generated:
1.5 anton 8723:
1.26 crook 8724: @example
1.30 anton 8725: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8726: @end example
1.5 anton 8727:
1.26 crook 8728: @itemize @bullet
8729: @item
8730: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8731: is an immediate word; it behaves in the same way whether it is used inside
8732: or outside a colon definition.
8733: @item
8734: Message @code{text-4} is displayed because of Gforth's added interpretation
8735: semantics for @code{."}.
8736: @item
1.29 crook 8737: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8738: performs the compilation semantics for @code{."} within the definition of
8739: @code{my-word}.
8740: @end itemize
1.5 anton 8741:
1.26 crook 8742: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8743:
1.26 crook 8744: @example
1.30 anton 8745: @kbd{my-word @key{RET}} text-2
1.26 crook 8746: ok
1.30 anton 8747: @kbd{my-char fred @key{RET}} Af ok
8748: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8749: @end example
1.5 anton 8750:
8751: @itemize @bullet
8752: @item
1.26 crook 8753: Message @code{text-2} is displayed because of the run-time behaviour of
8754: @code{."}.
8755: @item
8756: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8757: on the stack at run-time. @code{emit} always displays the character
8758: when @code{my-char} is executed.
8759: @item
8760: @code{char} parses a string at run-time and the second @code{emit} displays
8761: the first character of the string.
1.5 anton 8762: @item
1.26 crook 8763: If you type @code{see my-char} you can see that @code{[char]} discarded
8764: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8765: definition of @code{my-char}.
1.5 anton 8766: @end itemize
8767:
8768:
8769:
1.112 anton 8770: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8771: @subsection Input
8772: @cindex input
1.28 crook 8773: @cindex I/O - see input
8774: @cindex parsing a string
1.5 anton 8775:
1.49 anton 8776: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8777:
1.27 crook 8778: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8779: @comment then index them
1.27 crook 8780:
1.44 crook 8781:
1.27 crook 8782: doc-key
8783: doc-key?
1.45 crook 8784: doc-ekey
8785: doc-ekey?
8786: doc-ekey>char
1.26 crook 8787: doc->number
8788: doc->float
8789: doc-accept
1.109 anton 8790: doc-edit-line
1.27 crook 8791: doc-pad
8792: @comment obsolescent words..
8793: doc-convert
1.26 crook 8794: doc-expect
1.27 crook 8795: doc-span
1.5 anton 8796:
8797:
1.112 anton 8798: @node Pipes, , Input, Other I/O
8799: @subsection Pipes
8800: @cindex pipes, creating your own
8801:
8802: In addition to using Gforth in pipes created by other processes
8803: (@pxref{Gforth in pipes}), you can create your own pipe with
8804: @code{open-pipe}, and read from or write to it.
8805:
8806: doc-open-pipe
8807: doc-close-pipe
8808:
8809: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8810: you don't catch this exception, Gforth will catch it and exit, usually
8811: silently (@pxref{Gforth in pipes}). Since you probably do not want
8812: this, you should wrap a @code{catch} or @code{try} block around the code
8813: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8814: problem yourself, and then return to regular processing.
8815:
8816: doc-broken-pipe-error
8817:
8818:
1.78 anton 8819: @c -------------------------------------------------------------
8820: @node Locals, Structures, Other I/O, Words
8821: @section Locals
8822: @cindex locals
8823:
8824: Local variables can make Forth programming more enjoyable and Forth
8825: programs easier to read. Unfortunately, the locals of ANS Forth are
8826: laden with restrictions. Therefore, we provide not only the ANS Forth
8827: locals wordset, but also our own, more powerful locals wordset (we
8828: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 8829:
1.78 anton 8830: The ideas in this section have also been published in M. Anton Ertl,
8831: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
8832: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 8833:
8834: @menu
1.78 anton 8835: * Gforth locals::
8836: * ANS Forth locals::
1.5 anton 8837: @end menu
8838:
1.78 anton 8839: @node Gforth locals, ANS Forth locals, Locals, Locals
8840: @subsection Gforth locals
8841: @cindex Gforth locals
8842: @cindex locals, Gforth style
1.5 anton 8843:
1.78 anton 8844: Locals can be defined with
1.44 crook 8845:
1.78 anton 8846: @example
8847: @{ local1 local2 ... -- comment @}
8848: @end example
8849: or
8850: @example
8851: @{ local1 local2 ... @}
8852: @end example
1.5 anton 8853:
1.78 anton 8854: E.g.,
8855: @example
8856: : max @{ n1 n2 -- n3 @}
8857: n1 n2 > if
8858: n1
8859: else
8860: n2
8861: endif ;
8862: @end example
1.44 crook 8863:
1.78 anton 8864: The similarity of locals definitions with stack comments is intended. A
8865: locals definition often replaces the stack comment of a word. The order
8866: of the locals corresponds to the order in a stack comment and everything
8867: after the @code{--} is really a comment.
1.77 anton 8868:
1.78 anton 8869: This similarity has one disadvantage: It is too easy to confuse locals
8870: declarations with stack comments, causing bugs and making them hard to
8871: find. However, this problem can be avoided by appropriate coding
8872: conventions: Do not use both notations in the same program. If you do,
8873: they should be distinguished using additional means, e.g. by position.
1.77 anton 8874:
1.78 anton 8875: @cindex types of locals
8876: @cindex locals types
8877: The name of the local may be preceded by a type specifier, e.g.,
8878: @code{F:} for a floating point value:
1.5 anton 8879:
1.78 anton 8880: @example
8881: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
8882: \ complex multiplication
8883: Ar Br f* Ai Bi f* f-
8884: Ar Bi f* Ai Br f* f+ ;
8885: @end example
1.44 crook 8886:
1.78 anton 8887: @cindex flavours of locals
8888: @cindex locals flavours
8889: @cindex value-flavoured locals
8890: @cindex variable-flavoured locals
8891: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
8892: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
8893: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
8894: with @code{W:}, @code{D:} etc.) produces its value and can be changed
8895: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
8896: produces its address (which becomes invalid when the variable's scope is
8897: left). E.g., the standard word @code{emit} can be defined in terms of
8898: @code{type} like this:
1.5 anton 8899:
1.78 anton 8900: @example
8901: : emit @{ C^ char* -- @}
8902: char* 1 type ;
8903: @end example
1.5 anton 8904:
1.78 anton 8905: @cindex default type of locals
8906: @cindex locals, default type
8907: A local without type specifier is a @code{W:} local. Both flavours of
8908: locals are initialized with values from the data or FP stack.
1.44 crook 8909:
1.78 anton 8910: Currently there is no way to define locals with user-defined data
8911: structures, but we are working on it.
1.5 anton 8912:
1.78 anton 8913: Gforth allows defining locals everywhere in a colon definition. This
8914: poses the following questions:
1.5 anton 8915:
1.78 anton 8916: @menu
8917: * Where are locals visible by name?::
8918: * How long do locals live?::
8919: * Locals programming style::
8920: * Locals implementation::
8921: @end menu
1.44 crook 8922:
1.78 anton 8923: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
8924: @subsubsection Where are locals visible by name?
8925: @cindex locals visibility
8926: @cindex visibility of locals
8927: @cindex scope of locals
1.5 anton 8928:
1.78 anton 8929: Basically, the answer is that locals are visible where you would expect
8930: it in block-structured languages, and sometimes a little longer. If you
8931: want to restrict the scope of a local, enclose its definition in
8932: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 8933:
8934:
1.78 anton 8935: doc-scope
8936: doc-endscope
1.5 anton 8937:
8938:
1.78 anton 8939: These words behave like control structure words, so you can use them
8940: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
8941: arbitrary ways.
1.77 anton 8942:
1.78 anton 8943: If you want a more exact answer to the visibility question, here's the
8944: basic principle: A local is visible in all places that can only be
8945: reached through the definition of the local@footnote{In compiler
8946: construction terminology, all places dominated by the definition of the
8947: local.}. In other words, it is not visible in places that can be reached
8948: without going through the definition of the local. E.g., locals defined
8949: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
8950: defined in @code{BEGIN}...@code{UNTIL} are visible after the
8951: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 8952:
1.78 anton 8953: The reasoning behind this solution is: We want to have the locals
8954: visible as long as it is meaningful. The user can always make the
8955: visibility shorter by using explicit scoping. In a place that can
8956: only be reached through the definition of a local, the meaning of a
8957: local name is clear. In other places it is not: How is the local
8958: initialized at the control flow path that does not contain the
8959: definition? Which local is meant, if the same name is defined twice in
8960: two independent control flow paths?
1.77 anton 8961:
1.78 anton 8962: This should be enough detail for nearly all users, so you can skip the
8963: rest of this section. If you really must know all the gory details and
8964: options, read on.
1.77 anton 8965:
1.78 anton 8966: In order to implement this rule, the compiler has to know which places
8967: are unreachable. It knows this automatically after @code{AHEAD},
8968: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
8969: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
8970: compiler that the control flow never reaches that place. If
8971: @code{UNREACHABLE} is not used where it could, the only consequence is
8972: that the visibility of some locals is more limited than the rule above
8973: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
8974: lie to the compiler), buggy code will be produced.
1.77 anton 8975:
1.5 anton 8976:
1.78 anton 8977: doc-unreachable
1.5 anton 8978:
1.23 crook 8979:
1.78 anton 8980: Another problem with this rule is that at @code{BEGIN}, the compiler
8981: does not know which locals will be visible on the incoming
8982: back-edge. All problems discussed in the following are due to this
8983: ignorance of the compiler (we discuss the problems using @code{BEGIN}
8984: loops as examples; the discussion also applies to @code{?DO} and other
8985: loops). Perhaps the most insidious example is:
1.26 crook 8986: @example
1.78 anton 8987: AHEAD
8988: BEGIN
8989: x
8990: [ 1 CS-ROLL ] THEN
8991: @{ x @}
8992: ...
8993: UNTIL
1.26 crook 8994: @end example
1.23 crook 8995:
1.78 anton 8996: This should be legal according to the visibility rule. The use of
8997: @code{x} can only be reached through the definition; but that appears
8998: textually below the use.
8999:
9000: From this example it is clear that the visibility rules cannot be fully
9001: implemented without major headaches. Our implementation treats common
9002: cases as advertised and the exceptions are treated in a safe way: The
9003: compiler makes a reasonable guess about the locals visible after a
9004: @code{BEGIN}; if it is too pessimistic, the
9005: user will get a spurious error about the local not being defined; if the
9006: compiler is too optimistic, it will notice this later and issue a
9007: warning. In the case above the compiler would complain about @code{x}
9008: being undefined at its use. You can see from the obscure examples in
9009: this section that it takes quite unusual control structures to get the
9010: compiler into trouble, and even then it will often do fine.
1.23 crook 9011:
1.78 anton 9012: If the @code{BEGIN} is reachable from above, the most optimistic guess
9013: is that all locals visible before the @code{BEGIN} will also be
9014: visible after the @code{BEGIN}. This guess is valid for all loops that
9015: are entered only through the @code{BEGIN}, in particular, for normal
9016: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9017: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9018: compiler. When the branch to the @code{BEGIN} is finally generated by
9019: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9020: warns the user if it was too optimistic:
1.26 crook 9021: @example
1.78 anton 9022: IF
9023: @{ x @}
9024: BEGIN
9025: \ x ?
9026: [ 1 cs-roll ] THEN
9027: ...
9028: UNTIL
1.26 crook 9029: @end example
1.23 crook 9030:
1.78 anton 9031: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9032: optimistically assumes that it lives until the @code{THEN}. It notices
9033: this difference when it compiles the @code{UNTIL} and issues a
9034: warning. The user can avoid the warning, and make sure that @code{x}
9035: is not used in the wrong area by using explicit scoping:
9036: @example
9037: IF
9038: SCOPE
9039: @{ x @}
9040: ENDSCOPE
9041: BEGIN
9042: [ 1 cs-roll ] THEN
9043: ...
9044: UNTIL
9045: @end example
1.23 crook 9046:
1.78 anton 9047: Since the guess is optimistic, there will be no spurious error messages
9048: about undefined locals.
1.44 crook 9049:
1.78 anton 9050: If the @code{BEGIN} is not reachable from above (e.g., after
9051: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9052: optimistic guess, as the locals visible after the @code{BEGIN} may be
9053: defined later. Therefore, the compiler assumes that no locals are
9054: visible after the @code{BEGIN}. However, the user can use
9055: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9056: visible at the BEGIN as at the point where the top control-flow stack
9057: item was created.
1.23 crook 9058:
1.44 crook 9059:
1.78 anton 9060: doc-assume-live
1.26 crook 9061:
1.23 crook 9062:
1.78 anton 9063: @noindent
9064: E.g.,
9065: @example
9066: @{ x @}
9067: AHEAD
9068: ASSUME-LIVE
9069: BEGIN
9070: x
9071: [ 1 CS-ROLL ] THEN
9072: ...
9073: UNTIL
9074: @end example
1.44 crook 9075:
1.78 anton 9076: Other cases where the locals are defined before the @code{BEGIN} can be
9077: handled by inserting an appropriate @code{CS-ROLL} before the
9078: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9079: behind the @code{ASSUME-LIVE}).
1.23 crook 9080:
1.78 anton 9081: Cases where locals are defined after the @code{BEGIN} (but should be
9082: visible immediately after the @code{BEGIN}) can only be handled by
9083: rearranging the loop. E.g., the ``most insidious'' example above can be
9084: arranged into:
9085: @example
9086: BEGIN
9087: @{ x @}
9088: ... 0=
9089: WHILE
9090: x
9091: REPEAT
9092: @end example
1.44 crook 9093:
1.78 anton 9094: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9095: @subsubsection How long do locals live?
9096: @cindex locals lifetime
9097: @cindex lifetime of locals
1.23 crook 9098:
1.78 anton 9099: The right answer for the lifetime question would be: A local lives at
9100: least as long as it can be accessed. For a value-flavoured local this
9101: means: until the end of its visibility. However, a variable-flavoured
9102: local could be accessed through its address far beyond its visibility
9103: scope. Ultimately, this would mean that such locals would have to be
9104: garbage collected. Since this entails un-Forth-like implementation
9105: complexities, I adopted the same cowardly solution as some other
9106: languages (e.g., C): The local lives only as long as it is visible;
9107: afterwards its address is invalid (and programs that access it
9108: afterwards are erroneous).
1.23 crook 9109:
1.78 anton 9110: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9111: @subsubsection Locals programming style
9112: @cindex locals programming style
9113: @cindex programming style, locals
1.23 crook 9114:
1.78 anton 9115: The freedom to define locals anywhere has the potential to change
9116: programming styles dramatically. In particular, the need to use the
9117: return stack for intermediate storage vanishes. Moreover, all stack
9118: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9119: determined arguments) can be eliminated: If the stack items are in the
9120: wrong order, just write a locals definition for all of them; then
9121: write the items in the order you want.
1.23 crook 9122:
1.78 anton 9123: This seems a little far-fetched and eliminating stack manipulations is
9124: unlikely to become a conscious programming objective. Still, the number
9125: of stack manipulations will be reduced dramatically if local variables
9126: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9127: a traditional implementation of @code{max}).
1.23 crook 9128:
1.78 anton 9129: This shows one potential benefit of locals: making Forth programs more
9130: readable. Of course, this benefit will only be realized if the
9131: programmers continue to honour the principle of factoring instead of
9132: using the added latitude to make the words longer.
1.23 crook 9133:
1.78 anton 9134: @cindex single-assignment style for locals
9135: Using @code{TO} can and should be avoided. Without @code{TO},
9136: every value-flavoured local has only a single assignment and many
9137: advantages of functional languages apply to Forth. I.e., programs are
9138: easier to analyse, to optimize and to read: It is clear from the
9139: definition what the local stands for, it does not turn into something
9140: different later.
1.23 crook 9141:
1.78 anton 9142: E.g., a definition using @code{TO} might look like this:
9143: @example
9144: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9145: u1 u2 min 0
9146: ?do
9147: addr1 c@@ addr2 c@@ -
9148: ?dup-if
9149: unloop exit
9150: then
9151: addr1 char+ TO addr1
9152: addr2 char+ TO addr2
9153: loop
9154: u1 u2 - ;
1.26 crook 9155: @end example
1.78 anton 9156: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9157: every loop iteration. @code{strcmp} is a typical example of the
9158: readability problems of using @code{TO}. When you start reading
9159: @code{strcmp}, you think that @code{addr1} refers to the start of the
9160: string. Only near the end of the loop you realize that it is something
9161: else.
1.23 crook 9162:
1.78 anton 9163: This can be avoided by defining two locals at the start of the loop that
9164: are initialized with the right value for the current iteration.
9165: @example
9166: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9167: addr1 addr2
9168: u1 u2 min 0
9169: ?do @{ s1 s2 @}
9170: s1 c@@ s2 c@@ -
9171: ?dup-if
9172: unloop exit
9173: then
9174: s1 char+ s2 char+
9175: loop
9176: 2drop
9177: u1 u2 - ;
9178: @end example
9179: Here it is clear from the start that @code{s1} has a different value
9180: in every loop iteration.
1.23 crook 9181:
1.78 anton 9182: @node Locals implementation, , Locals programming style, Gforth locals
9183: @subsubsection Locals implementation
9184: @cindex locals implementation
9185: @cindex implementation of locals
1.23 crook 9186:
1.78 anton 9187: @cindex locals stack
9188: Gforth uses an extra locals stack. The most compelling reason for
9189: this is that the return stack is not float-aligned; using an extra stack
9190: also eliminates the problems and restrictions of using the return stack
9191: as locals stack. Like the other stacks, the locals stack grows toward
9192: lower addresses. A few primitives allow an efficient implementation:
9193:
9194:
9195: doc-@local#
9196: doc-f@local#
9197: doc-laddr#
9198: doc-lp+!#
9199: doc-lp!
9200: doc->l
9201: doc-f>l
9202:
9203:
9204: In addition to these primitives, some specializations of these
9205: primitives for commonly occurring inline arguments are provided for
9206: efficiency reasons, e.g., @code{@@local0} as specialization of
9207: @code{@@local#} for the inline argument 0. The following compiling words
9208: compile the right specialized version, or the general version, as
9209: appropriate:
1.23 crook 9210:
1.5 anton 9211:
1.107 dvdkhlng 9212: @c doc-compile-@local
9213: @c doc-compile-f@local
1.78 anton 9214: doc-compile-lp+!
1.5 anton 9215:
9216:
1.78 anton 9217: Combinations of conditional branches and @code{lp+!#} like
9218: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9219: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9220:
1.78 anton 9221: A special area in the dictionary space is reserved for keeping the
9222: local variable names. @code{@{} switches the dictionary pointer to this
9223: area and @code{@}} switches it back and generates the locals
9224: initializing code. @code{W:} etc.@ are normal defining words. This
9225: special area is cleared at the start of every colon definition.
1.5 anton 9226:
1.78 anton 9227: @cindex word list for defining locals
9228: A special feature of Gforth's dictionary is used to implement the
9229: definition of locals without type specifiers: every word list (aka
9230: vocabulary) has its own methods for searching
9231: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9232: with a special search method: When it is searched for a word, it
9233: actually creates that word using @code{W:}. @code{@{} changes the search
9234: order to first search the word list containing @code{@}}, @code{W:} etc.,
9235: and then the word list for defining locals without type specifiers.
1.5 anton 9236:
1.78 anton 9237: The lifetime rules support a stack discipline within a colon
9238: definition: The lifetime of a local is either nested with other locals
9239: lifetimes or it does not overlap them.
1.23 crook 9240:
1.78 anton 9241: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9242: pointer manipulation is generated. Between control structure words
9243: locals definitions can push locals onto the locals stack. @code{AGAIN}
9244: is the simplest of the other three control flow words. It has to
9245: restore the locals stack depth of the corresponding @code{BEGIN}
9246: before branching. The code looks like this:
9247: @format
9248: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9249: @code{branch} <begin>
9250: @end format
1.26 crook 9251:
1.78 anton 9252: @code{UNTIL} is a little more complicated: If it branches back, it
9253: must adjust the stack just like @code{AGAIN}. But if it falls through,
9254: the locals stack must not be changed. The compiler generates the
9255: following code:
9256: @format
9257: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9258: @end format
9259: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9260:
1.78 anton 9261: @code{THEN} can produce somewhat inefficient code:
9262: @format
9263: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9264: <orig target>:
9265: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9266: @end format
9267: The second @code{lp+!#} adjusts the locals stack pointer from the
9268: level at the @i{orig} point to the level after the @code{THEN}. The
9269: first @code{lp+!#} adjusts the locals stack pointer from the current
9270: level to the level at the orig point, so the complete effect is an
9271: adjustment from the current level to the right level after the
9272: @code{THEN}.
1.26 crook 9273:
1.78 anton 9274: @cindex locals information on the control-flow stack
9275: @cindex control-flow stack items, locals information
9276: In a conventional Forth implementation a dest control-flow stack entry
9277: is just the target address and an orig entry is just the address to be
9278: patched. Our locals implementation adds a word list to every orig or dest
9279: item. It is the list of locals visible (or assumed visible) at the point
9280: described by the entry. Our implementation also adds a tag to identify
9281: the kind of entry, in particular to differentiate between live and dead
9282: (reachable and unreachable) orig entries.
1.26 crook 9283:
1.78 anton 9284: A few unusual operations have to be performed on locals word lists:
1.44 crook 9285:
1.5 anton 9286:
1.78 anton 9287: doc-common-list
9288: doc-sub-list?
9289: doc-list-size
1.52 anton 9290:
9291:
1.78 anton 9292: Several features of our locals word list implementation make these
9293: operations easy to implement: The locals word lists are organised as
9294: linked lists; the tails of these lists are shared, if the lists
9295: contain some of the same locals; and the address of a name is greater
9296: than the address of the names behind it in the list.
1.5 anton 9297:
1.78 anton 9298: Another important implementation detail is the variable
9299: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9300: determine if they can be reached directly or only through the branch
9301: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9302: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9303: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9304:
1.78 anton 9305: Counted loops are similar to other loops in most respects, but
9306: @code{LEAVE} requires special attention: It performs basically the same
9307: service as @code{AHEAD}, but it does not create a control-flow stack
9308: entry. Therefore the information has to be stored elsewhere;
9309: traditionally, the information was stored in the target fields of the
9310: branches created by the @code{LEAVE}s, by organizing these fields into a
9311: linked list. Unfortunately, this clever trick does not provide enough
9312: space for storing our extended control flow information. Therefore, we
9313: introduce another stack, the leave stack. It contains the control-flow
9314: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9315:
1.78 anton 9316: Local names are kept until the end of the colon definition, even if
9317: they are no longer visible in any control-flow path. In a few cases
9318: this may lead to increased space needs for the locals name area, but
9319: usually less than reclaiming this space would cost in code size.
1.5 anton 9320:
1.44 crook 9321:
1.78 anton 9322: @node ANS Forth locals, , Gforth locals, Locals
9323: @subsection ANS Forth locals
9324: @cindex locals, ANS Forth style
1.5 anton 9325:
1.78 anton 9326: The ANS Forth locals wordset does not define a syntax for locals, but
9327: words that make it possible to define various syntaxes. One of the
9328: possible syntaxes is a subset of the syntax we used in the Gforth locals
9329: wordset, i.e.:
1.29 crook 9330:
9331: @example
1.78 anton 9332: @{ local1 local2 ... -- comment @}
9333: @end example
9334: @noindent
9335: or
9336: @example
9337: @{ local1 local2 ... @}
1.29 crook 9338: @end example
9339:
1.78 anton 9340: The order of the locals corresponds to the order in a stack comment. The
9341: restrictions are:
1.5 anton 9342:
1.78 anton 9343: @itemize @bullet
9344: @item
9345: Locals can only be cell-sized values (no type specifiers are allowed).
9346: @item
9347: Locals can be defined only outside control structures.
9348: @item
9349: Locals can interfere with explicit usage of the return stack. For the
9350: exact (and long) rules, see the standard. If you don't use return stack
9351: accessing words in a definition using locals, you will be all right. The
9352: purpose of this rule is to make locals implementation on the return
9353: stack easier.
9354: @item
9355: The whole definition must be in one line.
9356: @end itemize
1.5 anton 9357:
1.78 anton 9358: Locals defined in ANS Forth behave like @code{VALUE}s
9359: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9360: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9361:
1.78 anton 9362: Since the syntax above is supported by Gforth directly, you need not do
9363: anything to use it. If you want to port a program using this syntax to
9364: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9365: syntax on the other system.
1.5 anton 9366:
1.78 anton 9367: Note that a syntax shown in the standard, section A.13 looks
9368: similar, but is quite different in having the order of locals
9369: reversed. Beware!
1.5 anton 9370:
1.78 anton 9371: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9372:
1.78 anton 9373: doc-(local)
1.5 anton 9374:
1.78 anton 9375: The ANS Forth locals extension wordset defines a syntax using
9376: @code{locals|}, but it is so awful that we strongly recommend not to use
9377: it. We have implemented this syntax to make porting to Gforth easy, but
9378: do not document it here. The problem with this syntax is that the locals
9379: are defined in an order reversed with respect to the standard stack
9380: comment notation, making programs harder to read, and easier to misread
9381: and miswrite. The only merit of this syntax is that it is easy to
9382: implement using the ANS Forth locals wordset.
1.53 anton 9383:
9384:
1.78 anton 9385: @c ----------------------------------------------------------
9386: @node Structures, Object-oriented Forth, Locals, Words
9387: @section Structures
9388: @cindex structures
9389: @cindex records
1.53 anton 9390:
1.78 anton 9391: This section presents the structure package that comes with Gforth. A
9392: version of the package implemented in ANS Forth is available in
9393: @file{compat/struct.fs}. This package was inspired by a posting on
9394: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9395: possibly John Hayes). A version of this section has been published in
9396: M. Anton Ertl,
9397: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9398: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9399: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9400:
1.78 anton 9401: @menu
9402: * Why explicit structure support?::
9403: * Structure Usage::
9404: * Structure Naming Convention::
9405: * Structure Implementation::
9406: * Structure Glossary::
9407: @end menu
1.55 anton 9408:
1.78 anton 9409: @node Why explicit structure support?, Structure Usage, Structures, Structures
9410: @subsection Why explicit structure support?
1.53 anton 9411:
1.78 anton 9412: @cindex address arithmetic for structures
9413: @cindex structures using address arithmetic
9414: If we want to use a structure containing several fields, we could simply
9415: reserve memory for it, and access the fields using address arithmetic
9416: (@pxref{Address arithmetic}). As an example, consider a structure with
9417: the following fields
1.57 anton 9418:
1.78 anton 9419: @table @code
9420: @item a
9421: is a float
9422: @item b
9423: is a cell
9424: @item c
9425: is a float
9426: @end table
1.57 anton 9427:
1.78 anton 9428: Given the (float-aligned) base address of the structure we get the
9429: address of the field
1.52 anton 9430:
1.78 anton 9431: @table @code
9432: @item a
9433: without doing anything further.
9434: @item b
9435: with @code{float+}
9436: @item c
9437: with @code{float+ cell+ faligned}
9438: @end table
1.52 anton 9439:
1.78 anton 9440: It is easy to see that this can become quite tiring.
1.52 anton 9441:
1.78 anton 9442: Moreover, it is not very readable, because seeing a
9443: @code{cell+} tells us neither which kind of structure is
9444: accessed nor what field is accessed; we have to somehow infer the kind
9445: of structure, and then look up in the documentation, which field of
9446: that structure corresponds to that offset.
1.53 anton 9447:
1.78 anton 9448: Finally, this kind of address arithmetic also causes maintenance
9449: troubles: If you add or delete a field somewhere in the middle of the
9450: structure, you have to find and change all computations for the fields
9451: afterwards.
1.52 anton 9452:
1.78 anton 9453: So, instead of using @code{cell+} and friends directly, how
9454: about storing the offsets in constants:
1.52 anton 9455:
1.78 anton 9456: @example
9457: 0 constant a-offset
9458: 0 float+ constant b-offset
9459: 0 float+ cell+ faligned c-offset
9460: @end example
1.64 pazsan 9461:
1.78 anton 9462: Now we can get the address of field @code{x} with @code{x-offset
9463: +}. This is much better in all respects. Of course, you still
9464: have to change all later offset definitions if you add a field. You can
9465: fix this by declaring the offsets in the following way:
1.57 anton 9466:
1.78 anton 9467: @example
9468: 0 constant a-offset
9469: a-offset float+ constant b-offset
9470: b-offset cell+ faligned constant c-offset
9471: @end example
1.57 anton 9472:
1.78 anton 9473: Since we always use the offsets with @code{+}, we could use a defining
9474: word @code{cfield} that includes the @code{+} in the action of the
9475: defined word:
1.64 pazsan 9476:
1.78 anton 9477: @example
9478: : cfield ( n "name" -- )
9479: create ,
9480: does> ( name execution: addr1 -- addr2 )
9481: @@ + ;
1.64 pazsan 9482:
1.78 anton 9483: 0 cfield a
9484: 0 a float+ cfield b
9485: 0 b cell+ faligned cfield c
9486: @end example
1.64 pazsan 9487:
1.78 anton 9488: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9489:
1.78 anton 9490: The structure field words now can be used quite nicely. However,
9491: their definition is still a bit cumbersome: We have to repeat the
9492: name, the information about size and alignment is distributed before
9493: and after the field definitions etc. The structure package presented
9494: here addresses these problems.
1.64 pazsan 9495:
1.78 anton 9496: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9497: @subsection Structure Usage
9498: @cindex structure usage
1.57 anton 9499:
1.78 anton 9500: @cindex @code{field} usage
9501: @cindex @code{struct} usage
9502: @cindex @code{end-struct} usage
9503: You can define a structure for a (data-less) linked list with:
1.57 anton 9504: @example
1.78 anton 9505: struct
9506: cell% field list-next
9507: end-struct list%
1.57 anton 9508: @end example
9509:
1.78 anton 9510: With the address of the list node on the stack, you can compute the
9511: address of the field that contains the address of the next node with
9512: @code{list-next}. E.g., you can determine the length of a list
9513: with:
1.57 anton 9514:
9515: @example
1.78 anton 9516: : list-length ( list -- n )
9517: \ "list" is a pointer to the first element of a linked list
9518: \ "n" is the length of the list
9519: 0 BEGIN ( list1 n1 )
9520: over
9521: WHILE ( list1 n1 )
9522: 1+ swap list-next @@ swap
9523: REPEAT
9524: nip ;
1.57 anton 9525: @end example
9526:
1.78 anton 9527: You can reserve memory for a list node in the dictionary with
9528: @code{list% %allot}, which leaves the address of the list node on the
9529: stack. For the equivalent allocation on the heap you can use @code{list%
9530: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9531: use @code{list% %allocate}). You can get the the size of a list
9532: node with @code{list% %size} and its alignment with @code{list%
9533: %alignment}.
9534:
9535: Note that in ANS Forth the body of a @code{create}d word is
9536: @code{aligned} but not necessarily @code{faligned};
9537: therefore, if you do a:
1.57 anton 9538:
9539: @example
1.78 anton 9540: create @emph{name} foo% %allot drop
1.57 anton 9541: @end example
9542:
1.78 anton 9543: @noindent
9544: then the memory alloted for @code{foo%} is guaranteed to start at the
9545: body of @code{@emph{name}} only if @code{foo%} contains only character,
9546: cell and double fields. Therefore, if your structure contains floats,
9547: better use
1.57 anton 9548:
9549: @example
1.78 anton 9550: foo% %allot constant @emph{name}
1.57 anton 9551: @end example
9552:
1.78 anton 9553: @cindex structures containing structures
9554: You can include a structure @code{foo%} as a field of
9555: another structure, like this:
1.65 anton 9556: @example
1.78 anton 9557: struct
9558: ...
9559: foo% field ...
9560: ...
9561: end-struct ...
1.65 anton 9562: @end example
1.52 anton 9563:
1.78 anton 9564: @cindex structure extension
9565: @cindex extended records
9566: Instead of starting with an empty structure, you can extend an
9567: existing structure. E.g., a plain linked list without data, as defined
9568: above, is hardly useful; You can extend it to a linked list of integers,
9569: like this:@footnote{This feature is also known as @emph{extended
9570: records}. It is the main innovation in the Oberon language; in other
9571: words, adding this feature to Modula-2 led Wirth to create a new
9572: language, write a new compiler etc. Adding this feature to Forth just
9573: required a few lines of code.}
1.52 anton 9574:
1.78 anton 9575: @example
9576: list%
9577: cell% field intlist-int
9578: end-struct intlist%
9579: @end example
1.55 anton 9580:
1.78 anton 9581: @code{intlist%} is a structure with two fields:
9582: @code{list-next} and @code{intlist-int}.
1.55 anton 9583:
1.78 anton 9584: @cindex structures containing arrays
9585: You can specify an array type containing @emph{n} elements of
9586: type @code{foo%} like this:
1.55 anton 9587:
9588: @example
1.78 anton 9589: foo% @emph{n} *
1.56 anton 9590: @end example
1.55 anton 9591:
1.78 anton 9592: You can use this array type in any place where you can use a normal
9593: type, e.g., when defining a @code{field}, or with
9594: @code{%allot}.
9595:
9596: @cindex first field optimization
9597: The first field is at the base address of a structure and the word for
9598: this field (e.g., @code{list-next}) actually does not change the address
9599: on the stack. You may be tempted to leave it away in the interest of
9600: run-time and space efficiency. This is not necessary, because the
9601: structure package optimizes this case: If you compile a first-field
9602: words, no code is generated. So, in the interest of readability and
9603: maintainability you should include the word for the field when accessing
9604: the field.
1.52 anton 9605:
9606:
1.78 anton 9607: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9608: @subsection Structure Naming Convention
9609: @cindex structure naming convention
1.52 anton 9610:
1.78 anton 9611: The field names that come to (my) mind are often quite generic, and,
9612: if used, would cause frequent name clashes. E.g., many structures
9613: probably contain a @code{counter} field. The structure names
9614: that come to (my) mind are often also the logical choice for the names
9615: of words that create such a structure.
1.52 anton 9616:
1.78 anton 9617: Therefore, I have adopted the following naming conventions:
1.52 anton 9618:
1.78 anton 9619: @itemize @bullet
9620: @cindex field naming convention
9621: @item
9622: The names of fields are of the form
9623: @code{@emph{struct}-@emph{field}}, where
9624: @code{@emph{struct}} is the basic name of the structure, and
9625: @code{@emph{field}} is the basic name of the field. You can
9626: think of field words as converting the (address of the)
9627: structure into the (address of the) field.
1.52 anton 9628:
1.78 anton 9629: @cindex structure naming convention
9630: @item
9631: The names of structures are of the form
9632: @code{@emph{struct}%}, where
9633: @code{@emph{struct}} is the basic name of the structure.
9634: @end itemize
1.52 anton 9635:
1.78 anton 9636: This naming convention does not work that well for fields of extended
9637: structures; e.g., the integer list structure has a field
9638: @code{intlist-int}, but has @code{list-next}, not
9639: @code{intlist-next}.
1.53 anton 9640:
1.78 anton 9641: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9642: @subsection Structure Implementation
9643: @cindex structure implementation
9644: @cindex implementation of structures
1.52 anton 9645:
1.78 anton 9646: The central idea in the implementation is to pass the data about the
9647: structure being built on the stack, not in some global
9648: variable. Everything else falls into place naturally once this design
9649: decision is made.
1.53 anton 9650:
1.78 anton 9651: The type description on the stack is of the form @emph{align
9652: size}. Keeping the size on the top-of-stack makes dealing with arrays
9653: very simple.
1.53 anton 9654:
1.78 anton 9655: @code{field} is a defining word that uses @code{Create}
9656: and @code{DOES>}. The body of the field contains the offset
9657: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9658:
9659: @example
1.78 anton 9660: @@ +
1.53 anton 9661: @end example
9662:
1.78 anton 9663: @noindent
9664: i.e., add the offset to the address, giving the stack effect
9665: @i{addr1 -- addr2} for a field.
9666:
9667: @cindex first field optimization, implementation
9668: This simple structure is slightly complicated by the optimization
9669: for fields with offset 0, which requires a different
9670: @code{DOES>}-part (because we cannot rely on there being
9671: something on the stack if such a field is invoked during
9672: compilation). Therefore, we put the different @code{DOES>}-parts
9673: in separate words, and decide which one to invoke based on the
9674: offset. For a zero offset, the field is basically a noop; it is
9675: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9676:
1.78 anton 9677: @node Structure Glossary, , Structure Implementation, Structures
9678: @subsection Structure Glossary
9679: @cindex structure glossary
1.53 anton 9680:
1.5 anton 9681:
1.78 anton 9682: doc-%align
9683: doc-%alignment
9684: doc-%alloc
9685: doc-%allocate
9686: doc-%allot
9687: doc-cell%
9688: doc-char%
9689: doc-dfloat%
9690: doc-double%
9691: doc-end-struct
9692: doc-field
9693: doc-float%
9694: doc-naligned
9695: doc-sfloat%
9696: doc-%size
9697: doc-struct
1.54 anton 9698:
9699:
1.26 crook 9700: @c -------------------------------------------------------------
1.78 anton 9701: @node Object-oriented Forth, Programming Tools, Structures, Words
9702: @section Object-oriented Forth
9703:
9704: Gforth comes with three packages for object-oriented programming:
9705: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9706: is preloaded, so you have to @code{include} them before use. The most
9707: important differences between these packages (and others) are discussed
9708: in @ref{Comparison with other object models}. All packages are written
9709: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9710:
1.78 anton 9711: @menu
9712: * Why object-oriented programming?::
9713: * Object-Oriented Terminology::
9714: * Objects::
9715: * OOF::
9716: * Mini-OOF::
9717: * Comparison with other object models::
9718: @end menu
1.5 anton 9719:
1.78 anton 9720: @c ----------------------------------------------------------------
9721: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9722: @subsection Why object-oriented programming?
9723: @cindex object-oriented programming motivation
9724: @cindex motivation for object-oriented programming
1.44 crook 9725:
1.78 anton 9726: Often we have to deal with several data structures (@emph{objects}),
9727: that have to be treated similarly in some respects, but differently in
9728: others. Graphical objects are the textbook example: circles, triangles,
9729: dinosaurs, icons, and others, and we may want to add more during program
9730: development. We want to apply some operations to any graphical object,
9731: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9732: has to do something different for every kind of object.
9733: @comment TODO add some other operations eg perimeter, area
9734: @comment and tie in to concrete examples later..
1.5 anton 9735:
1.78 anton 9736: We could implement @code{draw} as a big @code{CASE}
9737: control structure that executes the appropriate code depending on the
9738: kind of object to be drawn. This would be not be very elegant, and,
9739: moreover, we would have to change @code{draw} every time we add
9740: a new kind of graphical object (say, a spaceship).
1.44 crook 9741:
1.78 anton 9742: What we would rather do is: When defining spaceships, we would tell
9743: the system: ``Here's how you @code{draw} a spaceship; you figure
9744: out the rest''.
1.5 anton 9745:
1.78 anton 9746: This is the problem that all systems solve that (rightfully) call
9747: themselves object-oriented; the object-oriented packages presented here
9748: solve this problem (and not much else).
9749: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9750:
1.78 anton 9751: @c ------------------------------------------------------------------------
9752: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9753: @subsection Object-Oriented Terminology
9754: @cindex object-oriented terminology
9755: @cindex terminology for object-oriented programming
1.5 anton 9756:
1.78 anton 9757: This section is mainly for reference, so you don't have to understand
9758: all of it right away. The terminology is mainly Smalltalk-inspired. In
9759: short:
1.44 crook 9760:
1.78 anton 9761: @table @emph
9762: @cindex class
9763: @item class
9764: a data structure definition with some extras.
1.5 anton 9765:
1.78 anton 9766: @cindex object
9767: @item object
9768: an instance of the data structure described by the class definition.
1.5 anton 9769:
1.78 anton 9770: @cindex instance variables
9771: @item instance variables
9772: fields of the data structure.
1.5 anton 9773:
1.78 anton 9774: @cindex selector
9775: @cindex method selector
9776: @cindex virtual function
9777: @item selector
9778: (or @emph{method selector}) a word (e.g.,
9779: @code{draw}) that performs an operation on a variety of data
9780: structures (classes). A selector describes @emph{what} operation to
9781: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 9782:
1.78 anton 9783: @cindex method
9784: @item method
9785: the concrete definition that performs the operation
9786: described by the selector for a specific class. A method specifies
9787: @emph{how} the operation is performed for a specific class.
1.5 anton 9788:
1.78 anton 9789: @cindex selector invocation
9790: @cindex message send
9791: @cindex invoking a selector
9792: @item selector invocation
9793: a call of a selector. One argument of the call (the TOS (top-of-stack))
9794: is used for determining which method is used. In Smalltalk terminology:
9795: a message (consisting of the selector and the other arguments) is sent
9796: to the object.
1.5 anton 9797:
1.78 anton 9798: @cindex receiving object
9799: @item receiving object
9800: the object used for determining the method executed by a selector
9801: invocation. In the @file{objects.fs} model, it is the object that is on
9802: the TOS when the selector is invoked. (@emph{Receiving} comes from
9803: the Smalltalk @emph{message} terminology.)
1.5 anton 9804:
1.78 anton 9805: @cindex child class
9806: @cindex parent class
9807: @cindex inheritance
9808: @item child class
9809: a class that has (@emph{inherits}) all properties (instance variables,
9810: selectors, methods) from a @emph{parent class}. In Smalltalk
9811: terminology: The subclass inherits from the superclass. In C++
9812: terminology: The derived class inherits from the base class.
1.5 anton 9813:
1.78 anton 9814: @end table
1.5 anton 9815:
1.78 anton 9816: @c If you wonder about the message sending terminology, it comes from
9817: @c a time when each object had it's own task and objects communicated via
9818: @c message passing; eventually the Smalltalk developers realized that
9819: @c they can do most things through simple (indirect) calls. They kept the
9820: @c terminology.
1.5 anton 9821:
1.78 anton 9822: @c --------------------------------------------------------------
9823: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
9824: @subsection The @file{objects.fs} model
9825: @cindex objects
9826: @cindex object-oriented programming
1.26 crook 9827:
1.78 anton 9828: @cindex @file{objects.fs}
9829: @cindex @file{oof.fs}
1.26 crook 9830:
1.78 anton 9831: This section describes the @file{objects.fs} package. This material also
9832: has been published in M. Anton Ertl,
9833: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
9834: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
9835: 37--43.
9836: @c McKewan's and Zsoter's packages
1.26 crook 9837:
1.78 anton 9838: This section assumes that you have read @ref{Structures}.
1.5 anton 9839:
1.78 anton 9840: The techniques on which this model is based have been used to implement
9841: the parser generator, Gray, and have also been used in Gforth for
9842: implementing the various flavours of word lists (hashed or not,
9843: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 9844:
9845:
1.26 crook 9846: @menu
1.78 anton 9847: * Properties of the Objects model::
9848: * Basic Objects Usage::
9849: * The Objects base class::
9850: * Creating objects::
9851: * Object-Oriented Programming Style::
9852: * Class Binding::
9853: * Method conveniences::
9854: * Classes and Scoping::
9855: * Dividing classes::
9856: * Object Interfaces::
9857: * Objects Implementation::
9858: * Objects Glossary::
1.26 crook 9859: @end menu
1.5 anton 9860:
1.78 anton 9861: Marcel Hendrix provided helpful comments on this section.
1.5 anton 9862:
1.78 anton 9863: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
9864: @subsubsection Properties of the @file{objects.fs} model
9865: @cindex @file{objects.fs} properties
1.5 anton 9866:
1.78 anton 9867: @itemize @bullet
9868: @item
9869: It is straightforward to pass objects on the stack. Passing
9870: selectors on the stack is a little less convenient, but possible.
1.44 crook 9871:
1.78 anton 9872: @item
9873: Objects are just data structures in memory, and are referenced by their
9874: address. You can create words for objects with normal defining words
9875: like @code{constant}. Likewise, there is no difference between instance
9876: variables that contain objects and those that contain other data.
1.5 anton 9877:
1.78 anton 9878: @item
9879: Late binding is efficient and easy to use.
1.44 crook 9880:
1.78 anton 9881: @item
9882: It avoids parsing, and thus avoids problems with state-smartness
9883: and reduced extensibility; for convenience there are a few parsing
9884: words, but they have non-parsing counterparts. There are also a few
9885: defining words that parse. This is hard to avoid, because all standard
9886: defining words parse (except @code{:noname}); however, such
9887: words are not as bad as many other parsing words, because they are not
9888: state-smart.
1.5 anton 9889:
1.78 anton 9890: @item
9891: It does not try to incorporate everything. It does a few things and does
9892: them well (IMO). In particular, this model was not designed to support
9893: information hiding (although it has features that may help); you can use
9894: a separate package for achieving this.
1.5 anton 9895:
1.78 anton 9896: @item
9897: It is layered; you don't have to learn and use all features to use this
9898: model. Only a few features are necessary (@pxref{Basic Objects Usage},
9899: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
9900: are optional and independent of each other.
1.5 anton 9901:
1.78 anton 9902: @item
9903: An implementation in ANS Forth is available.
1.5 anton 9904:
1.78 anton 9905: @end itemize
1.5 anton 9906:
1.44 crook 9907:
1.78 anton 9908: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
9909: @subsubsection Basic @file{objects.fs} Usage
9910: @cindex basic objects usage
9911: @cindex objects, basic usage
1.5 anton 9912:
1.78 anton 9913: You can define a class for graphical objects like this:
1.44 crook 9914:
1.78 anton 9915: @cindex @code{class} usage
9916: @cindex @code{end-class} usage
9917: @cindex @code{selector} usage
1.5 anton 9918: @example
1.78 anton 9919: object class \ "object" is the parent class
9920: selector draw ( x y graphical -- )
9921: end-class graphical
9922: @end example
9923:
9924: This code defines a class @code{graphical} with an
9925: operation @code{draw}. We can perform the operation
9926: @code{draw} on any @code{graphical} object, e.g.:
9927:
9928: @example
9929: 100 100 t-rex draw
1.26 crook 9930: @end example
1.5 anton 9931:
1.78 anton 9932: @noindent
9933: where @code{t-rex} is a word (say, a constant) that produces a
9934: graphical object.
9935:
9936: @comment TODO add a 2nd operation eg perimeter.. and use for
9937: @comment a concrete example
1.5 anton 9938:
1.78 anton 9939: @cindex abstract class
9940: How do we create a graphical object? With the present definitions,
9941: we cannot create a useful graphical object. The class
9942: @code{graphical} describes graphical objects in general, but not
9943: any concrete graphical object type (C++ users would call it an
9944: @emph{abstract class}); e.g., there is no method for the selector
9945: @code{draw} in the class @code{graphical}.
1.5 anton 9946:
1.78 anton 9947: For concrete graphical objects, we define child classes of the
9948: class @code{graphical}, e.g.:
1.5 anton 9949:
1.78 anton 9950: @cindex @code{overrides} usage
9951: @cindex @code{field} usage in class definition
1.26 crook 9952: @example
1.78 anton 9953: graphical class \ "graphical" is the parent class
9954: cell% field circle-radius
1.5 anton 9955:
1.78 anton 9956: :noname ( x y circle -- )
9957: circle-radius @@ draw-circle ;
9958: overrides draw
1.5 anton 9959:
1.78 anton 9960: :noname ( n-radius circle -- )
9961: circle-radius ! ;
9962: overrides construct
1.5 anton 9963:
1.78 anton 9964: end-class circle
9965: @end example
1.44 crook 9966:
1.78 anton 9967: Here we define a class @code{circle} as a child of @code{graphical},
9968: with field @code{circle-radius} (which behaves just like a field
9969: (@pxref{Structures}); it defines (using @code{overrides}) new methods
9970: for the selectors @code{draw} and @code{construct} (@code{construct} is
9971: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 9972:
1.78 anton 9973: Now we can create a circle on the heap (i.e.,
9974: @code{allocate}d memory) with:
1.44 crook 9975:
1.78 anton 9976: @cindex @code{heap-new} usage
1.5 anton 9977: @example
1.78 anton 9978: 50 circle heap-new constant my-circle
1.5 anton 9979: @end example
9980:
1.78 anton 9981: @noindent
9982: @code{heap-new} invokes @code{construct}, thus
9983: initializing the field @code{circle-radius} with 50. We can draw
9984: this new circle at (100,100) with:
1.5 anton 9985:
9986: @example
1.78 anton 9987: 100 100 my-circle draw
1.5 anton 9988: @end example
9989:
1.78 anton 9990: @cindex selector invocation, restrictions
9991: @cindex class definition, restrictions
9992: Note: You can only invoke a selector if the object on the TOS
9993: (the receiving object) belongs to the class where the selector was
9994: defined or one of its descendents; e.g., you can invoke
9995: @code{draw} only for objects belonging to @code{graphical}
9996: or its descendents (e.g., @code{circle}). Immediately before
9997: @code{end-class}, the search order has to be the same as
9998: immediately after @code{class}.
9999:
10000: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10001: @subsubsection The @file{object.fs} base class
10002: @cindex @code{object} class
10003:
10004: When you define a class, you have to specify a parent class. So how do
10005: you start defining classes? There is one class available from the start:
10006: @code{object}. It is ancestor for all classes and so is the
10007: only class that has no parent. It has two selectors: @code{construct}
10008: and @code{print}.
10009:
10010: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10011: @subsubsection Creating objects
10012: @cindex creating objects
10013: @cindex object creation
10014: @cindex object allocation options
10015:
10016: @cindex @code{heap-new} discussion
10017: @cindex @code{dict-new} discussion
10018: @cindex @code{construct} discussion
10019: You can create and initialize an object of a class on the heap with
10020: @code{heap-new} ( ... class -- object ) and in the dictionary
10021: (allocation with @code{allot}) with @code{dict-new} (
10022: ... class -- object ). Both words invoke @code{construct}, which
10023: consumes the stack items indicated by "..." above.
10024:
10025: @cindex @code{init-object} discussion
10026: @cindex @code{class-inst-size} discussion
10027: If you want to allocate memory for an object yourself, you can get its
10028: alignment and size with @code{class-inst-size 2@@} ( class --
10029: align size ). Once you have memory for an object, you can initialize
10030: it with @code{init-object} ( ... class object -- );
10031: @code{construct} does only a part of the necessary work.
10032:
10033: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10034: @subsubsection Object-Oriented Programming Style
10035: @cindex object-oriented programming style
10036: @cindex programming style, object-oriented
1.5 anton 10037:
1.78 anton 10038: This section is not exhaustive.
1.5 anton 10039:
1.78 anton 10040: @cindex stack effects of selectors
10041: @cindex selectors and stack effects
10042: In general, it is a good idea to ensure that all methods for the
10043: same selector have the same stack effect: when you invoke a selector,
10044: you often have no idea which method will be invoked, so, unless all
10045: methods have the same stack effect, you will not know the stack effect
10046: of the selector invocation.
1.5 anton 10047:
1.78 anton 10048: One exception to this rule is methods for the selector
10049: @code{construct}. We know which method is invoked, because we
10050: specify the class to be constructed at the same place. Actually, I
10051: defined @code{construct} as a selector only to give the users a
10052: convenient way to specify initialization. The way it is used, a
10053: mechanism different from selector invocation would be more natural
10054: (but probably would take more code and more space to explain).
1.5 anton 10055:
1.78 anton 10056: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10057: @subsubsection Class Binding
10058: @cindex class binding
10059: @cindex early binding
1.5 anton 10060:
1.78 anton 10061: @cindex late binding
10062: Normal selector invocations determine the method at run-time depending
10063: on the class of the receiving object. This run-time selection is called
10064: @i{late binding}.
1.5 anton 10065:
1.78 anton 10066: Sometimes it's preferable to invoke a different method. For example,
10067: you might want to use the simple method for @code{print}ing
10068: @code{object}s instead of the possibly long-winded @code{print} method
10069: of the receiver class. You can achieve this by replacing the invocation
10070: of @code{print} with:
1.5 anton 10071:
1.78 anton 10072: @cindex @code{[bind]} usage
1.5 anton 10073: @example
1.78 anton 10074: [bind] object print
1.5 anton 10075: @end example
10076:
1.78 anton 10077: @noindent
10078: in compiled code or:
10079:
10080: @cindex @code{bind} usage
1.5 anton 10081: @example
1.78 anton 10082: bind object print
1.5 anton 10083: @end example
10084:
1.78 anton 10085: @cindex class binding, alternative to
10086: @noindent
10087: in interpreted code. Alternatively, you can define the method with a
10088: name (e.g., @code{print-object}), and then invoke it through the
10089: name. Class binding is just a (often more convenient) way to achieve
10090: the same effect; it avoids name clutter and allows you to invoke
10091: methods directly without naming them first.
1.5 anton 10092:
1.78 anton 10093: @cindex superclass binding
10094: @cindex parent class binding
10095: A frequent use of class binding is this: When we define a method
10096: for a selector, we often want the method to do what the selector does
10097: in the parent class, and a little more. There is a special word for
10098: this purpose: @code{[parent]}; @code{[parent]
10099: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10100: selector}}, where @code{@emph{parent}} is the parent
10101: class of the current class. E.g., a method definition might look like:
1.44 crook 10102:
1.78 anton 10103: @cindex @code{[parent]} usage
10104: @example
10105: :noname
10106: dup [parent] foo \ do parent's foo on the receiving object
10107: ... \ do some more
10108: ; overrides foo
10109: @end example
1.6 pazsan 10110:
1.78 anton 10111: @cindex class binding as optimization
10112: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10113: March 1997), Andrew McKewan presents class binding as an optimization
10114: technique. I recommend not using it for this purpose unless you are in
10115: an emergency. Late binding is pretty fast with this model anyway, so the
10116: benefit of using class binding is small; the cost of using class binding
10117: where it is not appropriate is reduced maintainability.
1.44 crook 10118:
1.78 anton 10119: While we are at programming style questions: You should bind
10120: selectors only to ancestor classes of the receiving object. E.g., say,
10121: you know that the receiving object is of class @code{foo} or its
10122: descendents; then you should bind only to @code{foo} and its
10123: ancestors.
1.12 anton 10124:
1.78 anton 10125: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10126: @subsubsection Method conveniences
10127: @cindex method conveniences
1.44 crook 10128:
1.78 anton 10129: In a method you usually access the receiving object pretty often. If
10130: you define the method as a plain colon definition (e.g., with
10131: @code{:noname}), you may have to do a lot of stack
10132: gymnastics. To avoid this, you can define the method with @code{m:
10133: ... ;m}. E.g., you could define the method for
10134: @code{draw}ing a @code{circle} with
1.6 pazsan 10135:
1.78 anton 10136: @cindex @code{this} usage
10137: @cindex @code{m:} usage
10138: @cindex @code{;m} usage
10139: @example
10140: m: ( x y circle -- )
10141: ( x y ) this circle-radius @@ draw-circle ;m
10142: @end example
1.6 pazsan 10143:
1.78 anton 10144: @cindex @code{exit} in @code{m: ... ;m}
10145: @cindex @code{exitm} discussion
10146: @cindex @code{catch} in @code{m: ... ;m}
10147: When this method is executed, the receiver object is removed from the
10148: stack; you can access it with @code{this} (admittedly, in this
10149: example the use of @code{m: ... ;m} offers no advantage). Note
10150: that I specify the stack effect for the whole method (i.e. including
10151: the receiver object), not just for the code between @code{m:}
10152: and @code{;m}. You cannot use @code{exit} in
10153: @code{m:...;m}; instead, use
10154: @code{exitm}.@footnote{Moreover, for any word that calls
10155: @code{catch} and was defined before loading
10156: @code{objects.fs}, you have to redefine it like I redefined
10157: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10158:
1.78 anton 10159: @cindex @code{inst-var} usage
10160: You will frequently use sequences of the form @code{this
10161: @emph{field}} (in the example above: @code{this
10162: circle-radius}). If you use the field only in this way, you can
10163: define it with @code{inst-var} and eliminate the
10164: @code{this} before the field name. E.g., the @code{circle}
10165: class above could also be defined with:
1.6 pazsan 10166:
1.78 anton 10167: @example
10168: graphical class
10169: cell% inst-var radius
1.6 pazsan 10170:
1.78 anton 10171: m: ( x y circle -- )
10172: radius @@ draw-circle ;m
10173: overrides draw
1.6 pazsan 10174:
1.78 anton 10175: m: ( n-radius circle -- )
10176: radius ! ;m
10177: overrides construct
1.6 pazsan 10178:
1.78 anton 10179: end-class circle
10180: @end example
1.6 pazsan 10181:
1.78 anton 10182: @code{radius} can only be used in @code{circle} and its
10183: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10184:
1.78 anton 10185: @cindex @code{inst-value} usage
10186: You can also define fields with @code{inst-value}, which is
10187: to @code{inst-var} what @code{value} is to
10188: @code{variable}. You can change the value of such a field with
10189: @code{[to-inst]}. E.g., we could also define the class
10190: @code{circle} like this:
1.44 crook 10191:
1.78 anton 10192: @example
10193: graphical class
10194: inst-value radius
1.6 pazsan 10195:
1.78 anton 10196: m: ( x y circle -- )
10197: radius draw-circle ;m
10198: overrides draw
1.44 crook 10199:
1.78 anton 10200: m: ( n-radius circle -- )
10201: [to-inst] radius ;m
10202: overrides construct
1.6 pazsan 10203:
1.78 anton 10204: end-class circle
10205: @end example
1.6 pazsan 10206:
1.78 anton 10207: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10208:
1.78 anton 10209: @c Finally, you can define named methods with @code{:m}. One use of this
10210: @c feature is the definition of words that occur only in one class and are
10211: @c not intended to be overridden, but which still need method context
10212: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10213: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10214:
10215:
1.78 anton 10216: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10217: @subsubsection Classes and Scoping
10218: @cindex classes and scoping
10219: @cindex scoping and classes
1.6 pazsan 10220:
1.78 anton 10221: Inheritance is frequent, unlike structure extension. This exacerbates
10222: the problem with the field name convention (@pxref{Structure Naming
10223: Convention}): One always has to remember in which class the field was
10224: originally defined; changing a part of the class structure would require
10225: changes for renaming in otherwise unaffected code.
1.6 pazsan 10226:
1.78 anton 10227: @cindex @code{inst-var} visibility
10228: @cindex @code{inst-value} visibility
10229: To solve this problem, I added a scoping mechanism (which was not in my
10230: original charter): A field defined with @code{inst-var} (or
10231: @code{inst-value}) is visible only in the class where it is defined and in
10232: the descendent classes of this class. Using such fields only makes
10233: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10234:
1.78 anton 10235: This scoping mechanism allows us to use the unadorned field name,
10236: because name clashes with unrelated words become much less likely.
1.6 pazsan 10237:
1.78 anton 10238: @cindex @code{protected} discussion
10239: @cindex @code{private} discussion
10240: Once we have this mechanism, we can also use it for controlling the
10241: visibility of other words: All words defined after
10242: @code{protected} are visible only in the current class and its
10243: descendents. @code{public} restores the compilation
10244: (i.e. @code{current}) word list that was in effect before. If you
10245: have several @code{protected}s without an intervening
10246: @code{public} or @code{set-current}, @code{public}
10247: will restore the compilation word list in effect before the first of
10248: these @code{protected}s.
1.6 pazsan 10249:
1.78 anton 10250: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10251: @subsubsection Dividing classes
10252: @cindex Dividing classes
10253: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10254:
1.78 anton 10255: You may want to do the definition of methods separate from the
10256: definition of the class, its selectors, fields, and instance variables,
10257: i.e., separate the implementation from the definition. You can do this
10258: in the following way:
1.6 pazsan 10259:
1.78 anton 10260: @example
10261: graphical class
10262: inst-value radius
10263: end-class circle
1.6 pazsan 10264:
1.78 anton 10265: ... \ do some other stuff
1.6 pazsan 10266:
1.78 anton 10267: circle methods \ now we are ready
1.44 crook 10268:
1.78 anton 10269: m: ( x y circle -- )
10270: radius draw-circle ;m
10271: overrides draw
1.6 pazsan 10272:
1.78 anton 10273: m: ( n-radius circle -- )
10274: [to-inst] radius ;m
10275: overrides construct
1.44 crook 10276:
1.78 anton 10277: end-methods
10278: @end example
1.7 pazsan 10279:
1.78 anton 10280: You can use several @code{methods}...@code{end-methods} sections. The
10281: only things you can do to the class in these sections are: defining
10282: methods, and overriding the class's selectors. You must not define new
10283: selectors or fields.
1.7 pazsan 10284:
1.78 anton 10285: Note that you often have to override a selector before using it. In
10286: particular, you usually have to override @code{construct} with a new
10287: method before you can invoke @code{heap-new} and friends. E.g., you
10288: must not create a circle before the @code{overrides construct} sequence
10289: in the example above.
1.7 pazsan 10290:
1.78 anton 10291: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10292: @subsubsection Object Interfaces
10293: @cindex object interfaces
10294: @cindex interfaces for objects
1.7 pazsan 10295:
1.78 anton 10296: In this model you can only call selectors defined in the class of the
10297: receiving objects or in one of its ancestors. If you call a selector
10298: with a receiving object that is not in one of these classes, the
10299: result is undefined; if you are lucky, the program crashes
10300: immediately.
1.7 pazsan 10301:
1.78 anton 10302: @cindex selectors common to hardly-related classes
10303: Now consider the case when you want to have a selector (or several)
10304: available in two classes: You would have to add the selector to a
10305: common ancestor class, in the worst case to @code{object}. You
10306: may not want to do this, e.g., because someone else is responsible for
10307: this ancestor class.
1.7 pazsan 10308:
1.78 anton 10309: The solution for this problem is interfaces. An interface is a
10310: collection of selectors. If a class implements an interface, the
10311: selectors become available to the class and its descendents. A class
10312: can implement an unlimited number of interfaces. For the problem
10313: discussed above, we would define an interface for the selector(s), and
10314: both classes would implement the interface.
1.7 pazsan 10315:
1.78 anton 10316: As an example, consider an interface @code{storage} for
10317: writing objects to disk and getting them back, and a class
10318: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10319:
1.78 anton 10320: @cindex @code{interface} usage
10321: @cindex @code{end-interface} usage
10322: @cindex @code{implementation} usage
10323: @example
10324: interface
10325: selector write ( file object -- )
10326: selector read1 ( file object -- )
10327: end-interface storage
1.13 pazsan 10328:
1.78 anton 10329: bar class
10330: storage implementation
1.13 pazsan 10331:
1.78 anton 10332: ... overrides write
10333: ... overrides read1
10334: ...
10335: end-class foo
10336: @end example
1.13 pazsan 10337:
1.78 anton 10338: @noindent
10339: (I would add a word @code{read} @i{( file -- object )} that uses
10340: @code{read1} internally, but that's beyond the point illustrated
10341: here.)
1.13 pazsan 10342:
1.78 anton 10343: Note that you cannot use @code{protected} in an interface; and
10344: of course you cannot define fields.
1.13 pazsan 10345:
1.78 anton 10346: In the Neon model, all selectors are available for all classes;
10347: therefore it does not need interfaces. The price you pay in this model
10348: is slower late binding, and therefore, added complexity to avoid late
10349: binding.
1.13 pazsan 10350:
1.78 anton 10351: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10352: @subsubsection @file{objects.fs} Implementation
10353: @cindex @file{objects.fs} implementation
1.13 pazsan 10354:
1.78 anton 10355: @cindex @code{object-map} discussion
10356: An object is a piece of memory, like one of the data structures
10357: described with @code{struct...end-struct}. It has a field
10358: @code{object-map} that points to the method map for the object's
10359: class.
1.13 pazsan 10360:
1.78 anton 10361: @cindex method map
10362: @cindex virtual function table
10363: The @emph{method map}@footnote{This is Self terminology; in C++
10364: terminology: virtual function table.} is an array that contains the
10365: execution tokens (@i{xt}s) of the methods for the object's class. Each
10366: selector contains an offset into a method map.
1.13 pazsan 10367:
1.78 anton 10368: @cindex @code{selector} implementation, class
10369: @code{selector} is a defining word that uses
10370: @code{CREATE} and @code{DOES>}. The body of the
10371: selector contains the offset; the @code{DOES>} action for a
10372: class selector is, basically:
1.8 pazsan 10373:
10374: @example
1.78 anton 10375: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10376: @end example
10377:
1.78 anton 10378: Since @code{object-map} is the first field of the object, it
10379: does not generate any code. As you can see, calling a selector has a
10380: small, constant cost.
1.26 crook 10381:
1.78 anton 10382: @cindex @code{current-interface} discussion
10383: @cindex class implementation and representation
10384: A class is basically a @code{struct} combined with a method
10385: map. During the class definition the alignment and size of the class
10386: are passed on the stack, just as with @code{struct}s, so
10387: @code{field} can also be used for defining class
10388: fields. However, passing more items on the stack would be
10389: inconvenient, so @code{class} builds a data structure in memory,
10390: which is accessed through the variable
10391: @code{current-interface}. After its definition is complete, the
10392: class is represented on the stack by a pointer (e.g., as parameter for
10393: a child class definition).
1.26 crook 10394:
1.78 anton 10395: A new class starts off with the alignment and size of its parent,
10396: and a copy of the parent's method map. Defining new fields extends the
10397: size and alignment; likewise, defining new selectors extends the
10398: method map. @code{overrides} just stores a new @i{xt} in the method
10399: map at the offset given by the selector.
1.13 pazsan 10400:
1.78 anton 10401: @cindex class binding, implementation
10402: Class binding just gets the @i{xt} at the offset given by the selector
10403: from the class's method map and @code{compile,}s (in the case of
10404: @code{[bind]}) it.
1.13 pazsan 10405:
1.78 anton 10406: @cindex @code{this} implementation
10407: @cindex @code{catch} and @code{this}
10408: @cindex @code{this} and @code{catch}
10409: I implemented @code{this} as a @code{value}. At the
10410: start of an @code{m:...;m} method the old @code{this} is
10411: stored to the return stack and restored at the end; and the object on
10412: the TOS is stored @code{TO this}. This technique has one
10413: disadvantage: If the user does not leave the method via
10414: @code{;m}, but via @code{throw} or @code{exit},
10415: @code{this} is not restored (and @code{exit} may
10416: crash). To deal with the @code{throw} problem, I have redefined
10417: @code{catch} to save and restore @code{this}; the same
10418: should be done with any word that can catch an exception. As for
10419: @code{exit}, I simply forbid it (as a replacement, there is
10420: @code{exitm}).
1.13 pazsan 10421:
1.78 anton 10422: @cindex @code{inst-var} implementation
10423: @code{inst-var} is just the same as @code{field}, with
10424: a different @code{DOES>} action:
1.13 pazsan 10425: @example
1.78 anton 10426: @@ this +
1.8 pazsan 10427: @end example
1.78 anton 10428: Similar for @code{inst-value}.
1.8 pazsan 10429:
1.78 anton 10430: @cindex class scoping implementation
10431: Each class also has a word list that contains the words defined with
10432: @code{inst-var} and @code{inst-value}, and its protected
10433: words. It also has a pointer to its parent. @code{class} pushes
10434: the word lists of the class and all its ancestors onto the search order stack,
10435: and @code{end-class} drops them.
1.20 pazsan 10436:
1.78 anton 10437: @cindex interface implementation
10438: An interface is like a class without fields, parent and protected
10439: words; i.e., it just has a method map. If a class implements an
10440: interface, its method map contains a pointer to the method map of the
10441: interface. The positive offsets in the map are reserved for class
10442: methods, therefore interface map pointers have negative
10443: offsets. Interfaces have offsets that are unique throughout the
10444: system, unlike class selectors, whose offsets are only unique for the
10445: classes where the selector is available (invokable).
1.20 pazsan 10446:
1.78 anton 10447: This structure means that interface selectors have to perform one
10448: indirection more than class selectors to find their method. Their body
10449: contains the interface map pointer offset in the class method map, and
10450: the method offset in the interface method map. The
10451: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10452:
10453: @example
1.78 anton 10454: ( object selector-body )
10455: 2dup selector-interface @@ ( object selector-body object interface-offset )
10456: swap object-map @@ + @@ ( object selector-body map )
10457: swap selector-offset @@ + @@ execute
1.20 pazsan 10458: @end example
10459:
1.78 anton 10460: where @code{object-map} and @code{selector-offset} are
10461: first fields and generate no code.
1.20 pazsan 10462:
1.78 anton 10463: As a concrete example, consider the following code:
1.20 pazsan 10464:
10465: @example
1.78 anton 10466: interface
10467: selector if1sel1
10468: selector if1sel2
10469: end-interface if1
1.20 pazsan 10470:
1.78 anton 10471: object class
10472: if1 implementation
10473: selector cl1sel1
10474: cell% inst-var cl1iv1
1.20 pazsan 10475:
1.78 anton 10476: ' m1 overrides construct
10477: ' m2 overrides if1sel1
10478: ' m3 overrides if1sel2
10479: ' m4 overrides cl1sel2
10480: end-class cl1
1.20 pazsan 10481:
1.78 anton 10482: create obj1 object dict-new drop
10483: create obj2 cl1 dict-new drop
10484: @end example
1.20 pazsan 10485:
1.78 anton 10486: The data structure created by this code (including the data structure
10487: for @code{object}) is shown in the
10488: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10489: @comment TODO add this diagram..
1.20 pazsan 10490:
1.78 anton 10491: @node Objects Glossary, , Objects Implementation, Objects
10492: @subsubsection @file{objects.fs} Glossary
10493: @cindex @file{objects.fs} Glossary
1.20 pazsan 10494:
10495:
1.78 anton 10496: doc---objects-bind
10497: doc---objects-<bind>
10498: doc---objects-bind'
10499: doc---objects-[bind]
10500: doc---objects-class
10501: doc---objects-class->map
10502: doc---objects-class-inst-size
10503: doc---objects-class-override!
1.79 anton 10504: doc---objects-class-previous
10505: doc---objects-class>order
1.78 anton 10506: doc---objects-construct
10507: doc---objects-current'
10508: doc---objects-[current]
10509: doc---objects-current-interface
10510: doc---objects-dict-new
10511: doc---objects-end-class
10512: doc---objects-end-class-noname
10513: doc---objects-end-interface
10514: doc---objects-end-interface-noname
10515: doc---objects-end-methods
10516: doc---objects-exitm
10517: doc---objects-heap-new
10518: doc---objects-implementation
10519: doc---objects-init-object
10520: doc---objects-inst-value
10521: doc---objects-inst-var
10522: doc---objects-interface
10523: doc---objects-m:
10524: doc---objects-:m
10525: doc---objects-;m
10526: doc---objects-method
10527: doc---objects-methods
10528: doc---objects-object
10529: doc---objects-overrides
10530: doc---objects-[parent]
10531: doc---objects-print
10532: doc---objects-protected
10533: doc---objects-public
10534: doc---objects-selector
10535: doc---objects-this
10536: doc---objects-<to-inst>
10537: doc---objects-[to-inst]
10538: doc---objects-to-this
10539: doc---objects-xt-new
1.20 pazsan 10540:
10541:
1.78 anton 10542: @c -------------------------------------------------------------
10543: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10544: @subsection The @file{oof.fs} model
10545: @cindex oof
10546: @cindex object-oriented programming
1.20 pazsan 10547:
1.78 anton 10548: @cindex @file{objects.fs}
10549: @cindex @file{oof.fs}
1.20 pazsan 10550:
1.78 anton 10551: This section describes the @file{oof.fs} package.
1.20 pazsan 10552:
1.78 anton 10553: The package described in this section has been used in bigFORTH since 1991, and
10554: used for two large applications: a chromatographic system used to
10555: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10556:
1.78 anton 10557: You can find a description (in German) of @file{oof.fs} in @cite{Object
10558: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10559: 10(2), 1994.
1.20 pazsan 10560:
1.78 anton 10561: @menu
10562: * Properties of the OOF model::
10563: * Basic OOF Usage::
10564: * The OOF base class::
10565: * Class Declaration::
10566: * Class Implementation::
10567: @end menu
1.20 pazsan 10568:
1.78 anton 10569: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10570: @subsubsection Properties of the @file{oof.fs} model
10571: @cindex @file{oof.fs} properties
1.20 pazsan 10572:
1.78 anton 10573: @itemize @bullet
10574: @item
10575: This model combines object oriented programming with information
10576: hiding. It helps you writing large application, where scoping is
10577: necessary, because it provides class-oriented scoping.
1.20 pazsan 10578:
1.78 anton 10579: @item
10580: Named objects, object pointers, and object arrays can be created,
10581: selector invocation uses the ``object selector'' syntax. Selector invocation
10582: to objects and/or selectors on the stack is a bit less convenient, but
10583: possible.
1.44 crook 10584:
1.78 anton 10585: @item
10586: Selector invocation and instance variable usage of the active object is
10587: straightforward, since both make use of the active object.
1.44 crook 10588:
1.78 anton 10589: @item
10590: Late binding is efficient and easy to use.
1.20 pazsan 10591:
1.78 anton 10592: @item
10593: State-smart objects parse selectors. However, extensibility is provided
10594: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10595:
1.78 anton 10596: @item
10597: An implementation in ANS Forth is available.
1.20 pazsan 10598:
1.78 anton 10599: @end itemize
1.23 crook 10600:
10601:
1.78 anton 10602: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10603: @subsubsection Basic @file{oof.fs} Usage
10604: @cindex @file{oof.fs} usage
1.23 crook 10605:
1.78 anton 10606: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10607:
1.78 anton 10608: You can define a class for graphical objects like this:
1.23 crook 10609:
1.78 anton 10610: @cindex @code{class} usage
10611: @cindex @code{class;} usage
10612: @cindex @code{method} usage
10613: @example
10614: object class graphical \ "object" is the parent class
10615: method draw ( x y graphical -- )
10616: class;
10617: @end example
1.23 crook 10618:
1.78 anton 10619: This code defines a class @code{graphical} with an
10620: operation @code{draw}. We can perform the operation
10621: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10622:
1.78 anton 10623: @example
10624: 100 100 t-rex draw
10625: @end example
1.23 crook 10626:
1.78 anton 10627: @noindent
10628: where @code{t-rex} is an object or object pointer, created with e.g.
10629: @code{graphical : t-rex}.
1.23 crook 10630:
1.78 anton 10631: @cindex abstract class
10632: How do we create a graphical object? With the present definitions,
10633: we cannot create a useful graphical object. The class
10634: @code{graphical} describes graphical objects in general, but not
10635: any concrete graphical object type (C++ users would call it an
10636: @emph{abstract class}); e.g., there is no method for the selector
10637: @code{draw} in the class @code{graphical}.
1.23 crook 10638:
1.78 anton 10639: For concrete graphical objects, we define child classes of the
10640: class @code{graphical}, e.g.:
1.23 crook 10641:
1.78 anton 10642: @example
10643: graphical class circle \ "graphical" is the parent class
10644: cell var circle-radius
10645: how:
10646: : draw ( x y -- )
10647: circle-radius @@ draw-circle ;
1.23 crook 10648:
1.78 anton 10649: : init ( n-radius -- (
10650: circle-radius ! ;
10651: class;
10652: @end example
1.1 anton 10653:
1.78 anton 10654: Here we define a class @code{circle} as a child of @code{graphical},
10655: with a field @code{circle-radius}; it defines new methods for the
10656: selectors @code{draw} and @code{init} (@code{init} is defined in
10657: @code{object}, the parent class of @code{graphical}).
1.1 anton 10658:
1.78 anton 10659: Now we can create a circle in the dictionary with:
1.1 anton 10660:
1.78 anton 10661: @example
10662: 50 circle : my-circle
10663: @end example
1.21 crook 10664:
1.78 anton 10665: @noindent
10666: @code{:} invokes @code{init}, thus initializing the field
10667: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10668: with:
1.1 anton 10669:
1.78 anton 10670: @example
10671: 100 100 my-circle draw
10672: @end example
1.1 anton 10673:
1.78 anton 10674: @cindex selector invocation, restrictions
10675: @cindex class definition, restrictions
10676: Note: You can only invoke a selector if the receiving object belongs to
10677: the class where the selector was defined or one of its descendents;
10678: e.g., you can invoke @code{draw} only for objects belonging to
10679: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10680: mechanism will check if you try to invoke a selector that is not
10681: defined in this class hierarchy, so you'll get an error at compilation
10682: time.
1.1 anton 10683:
10684:
1.78 anton 10685: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10686: @subsubsection The @file{oof.fs} base class
10687: @cindex @file{oof.fs} base class
1.1 anton 10688:
1.78 anton 10689: When you define a class, you have to specify a parent class. So how do
10690: you start defining classes? There is one class available from the start:
10691: @code{object}. You have to use it as ancestor for all classes. It is the
10692: only class that has no parent. Classes are also objects, except that
10693: they don't have instance variables; class manipulation such as
10694: inheritance or changing definitions of a class is handled through
10695: selectors of the class @code{object}.
1.1 anton 10696:
1.78 anton 10697: @code{object} provides a number of selectors:
1.1 anton 10698:
1.78 anton 10699: @itemize @bullet
10700: @item
10701: @code{class} for subclassing, @code{definitions} to add definitions
10702: later on, and @code{class?} to get type informations (is the class a
10703: subclass of the class passed on the stack?).
1.1 anton 10704:
1.78 anton 10705: doc---object-class
10706: doc---object-definitions
10707: doc---object-class?
1.1 anton 10708:
10709:
1.26 crook 10710: @item
1.78 anton 10711: @code{init} and @code{dispose} as constructor and destructor of the
10712: object. @code{init} is invocated after the object's memory is allocated,
10713: while @code{dispose} also handles deallocation. Thus if you redefine
10714: @code{dispose}, you have to call the parent's dispose with @code{super
10715: dispose}, too.
10716:
10717: doc---object-init
10718: doc---object-dispose
10719:
1.1 anton 10720:
1.26 crook 10721: @item
1.78 anton 10722: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10723: @code{[]} to create named and unnamed objects and object arrays or
10724: object pointers.
10725:
10726: doc---object-new
10727: doc---object-new[]
10728: doc---object-:
10729: doc---object-ptr
10730: doc---object-asptr
10731: doc---object-[]
10732:
1.1 anton 10733:
1.26 crook 10734: @item
1.78 anton 10735: @code{::} and @code{super} for explicit scoping. You should use explicit
10736: scoping only for super classes or classes with the same set of instance
10737: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10738:
1.78 anton 10739: doc---object-::
10740: doc---object-super
1.21 crook 10741:
10742:
1.26 crook 10743: @item
1.78 anton 10744: @code{self} to get the address of the object
1.21 crook 10745:
1.78 anton 10746: doc---object-self
1.21 crook 10747:
10748:
1.78 anton 10749: @item
10750: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10751: pointers and instance defers.
1.21 crook 10752:
1.78 anton 10753: doc---object-bind
10754: doc---object-bound
10755: doc---object-link
10756: doc---object-is
1.21 crook 10757:
10758:
1.78 anton 10759: @item
10760: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10761: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10762:
1.78 anton 10763: doc---object-'
10764: doc---object-postpone
1.21 crook 10765:
10766:
1.78 anton 10767: @item
10768: @code{with} and @code{endwith} to select the active object from the
10769: stack, and enable its scope. Using @code{with} and @code{endwith}
10770: also allows you to create code using selector @code{postpone} without being
10771: trapped by the state-smart objects.
1.21 crook 10772:
1.78 anton 10773: doc---object-with
10774: doc---object-endwith
1.21 crook 10775:
10776:
1.78 anton 10777: @end itemize
1.21 crook 10778:
1.78 anton 10779: @node Class Declaration, Class Implementation, The OOF base class, OOF
10780: @subsubsection Class Declaration
10781: @cindex class declaration
1.21 crook 10782:
1.78 anton 10783: @itemize @bullet
10784: @item
10785: Instance variables
1.21 crook 10786:
1.78 anton 10787: doc---oof-var
1.21 crook 10788:
10789:
1.78 anton 10790: @item
10791: Object pointers
1.21 crook 10792:
1.78 anton 10793: doc---oof-ptr
10794: doc---oof-asptr
1.21 crook 10795:
10796:
1.78 anton 10797: @item
10798: Instance defers
1.21 crook 10799:
1.78 anton 10800: doc---oof-defer
1.21 crook 10801:
10802:
1.78 anton 10803: @item
10804: Method selectors
1.21 crook 10805:
1.78 anton 10806: doc---oof-early
10807: doc---oof-method
1.21 crook 10808:
10809:
1.78 anton 10810: @item
10811: Class-wide variables
1.21 crook 10812:
1.78 anton 10813: doc---oof-static
1.21 crook 10814:
10815:
1.78 anton 10816: @item
10817: End declaration
1.1 anton 10818:
1.78 anton 10819: doc---oof-how:
10820: doc---oof-class;
1.21 crook 10821:
10822:
1.78 anton 10823: @end itemize
1.21 crook 10824:
1.78 anton 10825: @c -------------------------------------------------------------
10826: @node Class Implementation, , Class Declaration, OOF
10827: @subsubsection Class Implementation
10828: @cindex class implementation
1.21 crook 10829:
1.78 anton 10830: @c -------------------------------------------------------------
10831: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10832: @subsection The @file{mini-oof.fs} model
10833: @cindex mini-oof
1.21 crook 10834:
1.78 anton 10835: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 10836: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 10837: and reduces to the bare minimum of features. This is based on a posting
10838: of Bernd Paysan in comp.lang.forth.
1.21 crook 10839:
1.78 anton 10840: @menu
10841: * Basic Mini-OOF Usage::
10842: * Mini-OOF Example::
10843: * Mini-OOF Implementation::
10844: @end menu
1.21 crook 10845:
1.78 anton 10846: @c -------------------------------------------------------------
10847: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10848: @subsubsection Basic @file{mini-oof.fs} Usage
10849: @cindex mini-oof usage
1.21 crook 10850:
1.78 anton 10851: There is a base class (@code{class}, which allocates one cell for the
10852: object pointer) plus seven other words: to define a method, a variable,
10853: a class; to end a class, to resolve binding, to allocate an object and
10854: to compile a class method.
10855: @comment TODO better description of the last one
1.26 crook 10856:
1.21 crook 10857:
1.78 anton 10858: doc-object
10859: doc-method
10860: doc-var
10861: doc-class
10862: doc-end-class
10863: doc-defines
10864: doc-new
10865: doc-::
1.21 crook 10866:
10867:
10868:
1.78 anton 10869: @c -------------------------------------------------------------
10870: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
10871: @subsubsection Mini-OOF Example
10872: @cindex mini-oof example
1.1 anton 10873:
1.78 anton 10874: A short example shows how to use this package. This example, in slightly
10875: extended form, is supplied as @file{moof-exm.fs}
10876: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 10877:
1.26 crook 10878: @example
1.78 anton 10879: object class
10880: method init
10881: method draw
10882: end-class graphical
1.26 crook 10883: @end example
1.20 pazsan 10884:
1.78 anton 10885: This code defines a class @code{graphical} with an
10886: operation @code{draw}. We can perform the operation
10887: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 10888:
1.26 crook 10889: @example
1.78 anton 10890: 100 100 t-rex draw
1.26 crook 10891: @end example
1.12 anton 10892:
1.78 anton 10893: where @code{t-rex} is an object or object pointer, created with e.g.
10894: @code{graphical new Constant t-rex}.
1.12 anton 10895:
1.78 anton 10896: For concrete graphical objects, we define child classes of the
10897: class @code{graphical}, e.g.:
1.12 anton 10898:
1.26 crook 10899: @example
10900: graphical class
1.78 anton 10901: cell var circle-radius
10902: end-class circle \ "graphical" is the parent class
1.12 anton 10903:
1.78 anton 10904: :noname ( x y -- )
10905: circle-radius @@ draw-circle ; circle defines draw
10906: :noname ( r -- )
10907: circle-radius ! ; circle defines init
10908: @end example
1.12 anton 10909:
1.78 anton 10910: There is no implicit init method, so we have to define one. The creation
10911: code of the object now has to call init explicitely.
1.21 crook 10912:
1.78 anton 10913: @example
10914: circle new Constant my-circle
10915: 50 my-circle init
1.12 anton 10916: @end example
10917:
1.78 anton 10918: It is also possible to add a function to create named objects with
10919: automatic call of @code{init}, given that all objects have @code{init}
10920: on the same place:
1.38 anton 10921:
1.78 anton 10922: @example
10923: : new: ( .. o "name" -- )
10924: new dup Constant init ;
10925: 80 circle new: large-circle
10926: @end example
1.12 anton 10927:
1.78 anton 10928: We can draw this new circle at (100,100) with:
1.12 anton 10929:
1.78 anton 10930: @example
10931: 100 100 my-circle draw
10932: @end example
1.12 anton 10933:
1.78 anton 10934: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
10935: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 10936:
1.78 anton 10937: Object-oriented systems with late binding typically use a
10938: ``vtable''-approach: the first variable in each object is a pointer to a
10939: table, which contains the methods as function pointers. The vtable
10940: may also contain other information.
1.12 anton 10941:
1.79 anton 10942: So first, let's declare selectors:
1.37 anton 10943:
10944: @example
1.79 anton 10945: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 10946: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
10947: @end example
1.37 anton 10948:
1.79 anton 10949: During selector declaration, the number of selectors and instance
10950: variables is on the stack (in address units). @code{method} creates one
10951: selector and increments the selector number. To execute a selector, it
1.78 anton 10952: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 10953: executes the method @i{xt} stored there. Each selector takes the object
10954: it is invoked with as top of stack parameter; it passes the parameters
10955: (including the object) unchanged to the appropriate method which should
1.78 anton 10956: consume that object.
1.37 anton 10957:
1.78 anton 10958: Now, we also have to declare instance variables
1.37 anton 10959:
1.78 anton 10960: @example
1.79 anton 10961: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 10962: DOES> ( o -- addr ) @@ + ;
1.37 anton 10963: @end example
10964:
1.78 anton 10965: As before, a word is created with the current offset. Instance
10966: variables can have different sizes (cells, floats, doubles, chars), so
10967: all we do is take the size and add it to the offset. If your machine
10968: has alignment restrictions, put the proper @code{aligned} or
10969: @code{faligned} before the variable, to adjust the variable
10970: offset. That's why it is on the top of stack.
1.37 anton 10971:
1.78 anton 10972: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 10973:
1.78 anton 10974: @example
10975: Create object 1 cells , 2 cells ,
1.79 anton 10976: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 10977: @end example
1.12 anton 10978:
1.78 anton 10979: For inheritance, the vtable of the parent object has to be
10980: copied when a new, derived class is declared. This gives all the
10981: methods of the parent class, which can be overridden, though.
1.12 anton 10982:
1.78 anton 10983: @example
1.79 anton 10984: : end-class ( class selectors vars "name" -- )
1.78 anton 10985: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
10986: cell+ dup cell+ r> rot @@ 2 cells /string move ;
10987: @end example
1.12 anton 10988:
1.78 anton 10989: The first line creates the vtable, initialized with
10990: @code{noop}s. The second line is the inheritance mechanism, it
10991: copies the xts from the parent vtable.
1.12 anton 10992:
1.78 anton 10993: We still have no way to define new methods, let's do that now:
1.12 anton 10994:
1.26 crook 10995: @example
1.79 anton 10996: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 10997: @end example
1.12 anton 10998:
1.78 anton 10999: To allocate a new object, we need a word, too:
1.12 anton 11000:
1.78 anton 11001: @example
11002: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11003: @end example
11004:
1.78 anton 11005: Sometimes derived classes want to access the method of the
11006: parent object. There are two ways to achieve this with Mini-OOF:
11007: first, you could use named words, and second, you could look up the
11008: vtable of the parent object.
1.12 anton 11009:
1.78 anton 11010: @example
11011: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11012: @end example
1.12 anton 11013:
11014:
1.78 anton 11015: Nothing can be more confusing than a good example, so here is
11016: one. First let's declare a text object (called
11017: @code{button}), that stores text and position:
1.12 anton 11018:
1.78 anton 11019: @example
11020: object class
11021: cell var text
11022: cell var len
11023: cell var x
11024: cell var y
11025: method init
11026: method draw
11027: end-class button
11028: @end example
1.12 anton 11029:
1.78 anton 11030: @noindent
11031: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11032:
1.26 crook 11033: @example
1.78 anton 11034: :noname ( o -- )
11035: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11036: button defines draw
11037: :noname ( addr u o -- )
11038: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11039: button defines init
1.26 crook 11040: @end example
1.12 anton 11041:
1.78 anton 11042: @noindent
11043: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11044: new data and no new selectors:
1.78 anton 11045:
11046: @example
11047: button class
11048: end-class bold-button
1.12 anton 11049:
1.78 anton 11050: : bold 27 emit ." [1m" ;
11051: : normal 27 emit ." [0m" ;
11052: @end example
1.1 anton 11053:
1.78 anton 11054: @noindent
11055: The class @code{bold-button} has a different draw method to
11056: @code{button}, but the new method is defined in terms of the draw method
11057: for @code{button}:
1.20 pazsan 11058:
1.78 anton 11059: @example
11060: :noname bold [ button :: draw ] normal ; bold-button defines draw
11061: @end example
1.21 crook 11062:
1.78 anton 11063: @noindent
1.79 anton 11064: Finally, create two objects and apply selectors:
1.21 crook 11065:
1.26 crook 11066: @example
1.78 anton 11067: button new Constant foo
11068: s" thin foo" foo init
11069: page
11070: foo draw
11071: bold-button new Constant bar
11072: s" fat bar" bar init
11073: 1 bar y !
11074: bar draw
1.26 crook 11075: @end example
1.21 crook 11076:
11077:
1.78 anton 11078: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11079: @subsection Comparison with other object models
11080: @cindex comparison of object models
11081: @cindex object models, comparison
11082:
11083: Many object-oriented Forth extensions have been proposed (@cite{A survey
11084: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11085: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11086: relation of the object models described here to two well-known and two
11087: closely-related (by the use of method maps) models. Andras Zsoter
11088: helped us with this section.
11089:
11090: @cindex Neon model
11091: The most popular model currently seems to be the Neon model (see
11092: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11093: 1997) by Andrew McKewan) but this model has a number of limitations
11094: @footnote{A longer version of this critique can be
11095: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11096: Dimensions, May 1997) by Anton Ertl.}:
11097:
11098: @itemize @bullet
11099: @item
11100: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11101: to pass objects on the stack.
1.21 crook 11102:
1.78 anton 11103: @item
11104: It requires that the selector parses the input stream (at
1.79 anton 11105: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11106: hard to find.
1.21 crook 11107:
1.78 anton 11108: @item
1.79 anton 11109: It allows using every selector on every object; this eliminates the
11110: need for interfaces, but makes it harder to create efficient
11111: implementations.
1.78 anton 11112: @end itemize
1.21 crook 11113:
1.78 anton 11114: @cindex Pountain's object-oriented model
11115: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11116: Press, London, 1987) by Dick Pountain. However, it is not really about
11117: object-oriented programming, because it hardly deals with late
11118: binding. Instead, it focuses on features like information hiding and
11119: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11120:
1.78 anton 11121: @cindex Zsoter's object-oriented model
1.79 anton 11122: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11123: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11124: describes a model that makes heavy use of an active object (like
11125: @code{this} in @file{objects.fs}): The active object is not only used
11126: for accessing all fields, but also specifies the receiving object of
11127: every selector invocation; you have to change the active object
11128: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11129: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11130: the method entry point is unnecessary with Zsoter's model, because the
11131: receiving object is the active object already. On the other hand, the
11132: explicit change is absolutely necessary in that model, because otherwise
11133: no one could ever change the active object. An ANS Forth implementation
11134: of this model is available through
11135: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11136:
1.78 anton 11137: @cindex @file{oof.fs}, differences to other models
11138: The @file{oof.fs} model combines information hiding and overloading
11139: resolution (by keeping names in various word lists) with object-oriented
11140: programming. It sets the active object implicitly on method entry, but
11141: also allows explicit changing (with @code{>o...o>} or with
11142: @code{with...endwith}). It uses parsing and state-smart objects and
11143: classes for resolving overloading and for early binding: the object or
11144: class parses the selector and determines the method from this. If the
11145: selector is not parsed by an object or class, it performs a call to the
11146: selector for the active object (late binding), like Zsoter's model.
11147: Fields are always accessed through the active object. The big
11148: disadvantage of this model is the parsing and the state-smartness, which
11149: reduces extensibility and increases the opportunities for subtle bugs;
11150: essentially, you are only safe if you never tick or @code{postpone} an
11151: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11152:
1.78 anton 11153: @cindex @file{mini-oof.fs}, differences to other models
11154: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11155: version of the @file{objects.fs} model, but syntactically it is a
11156: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11157:
11158:
1.78 anton 11159: @c -------------------------------------------------------------
11160: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11161: @section Programming Tools
11162: @cindex programming tools
1.21 crook 11163:
1.78 anton 11164: @c !! move this and assembler down below OO stuff.
1.21 crook 11165:
1.78 anton 11166: @menu
11167: * Examining::
11168: * Forgetting words::
11169: * Debugging:: Simple and quick.
11170: * Assertions:: Making your programs self-checking.
11171: * Singlestep Debugger:: Executing your program word by word.
11172: @end menu
1.21 crook 11173:
1.78 anton 11174: @node Examining, Forgetting words, Programming Tools, Programming Tools
11175: @subsection Examining data and code
11176: @cindex examining data and code
11177: @cindex data examination
11178: @cindex code examination
1.44 crook 11179:
1.78 anton 11180: The following words inspect the stack non-destructively:
1.21 crook 11181:
1.78 anton 11182: doc-.s
11183: doc-f.s
1.44 crook 11184:
1.78 anton 11185: There is a word @code{.r} but it does @i{not} display the return stack!
11186: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11187:
1.78 anton 11188: doc-depth
11189: doc-fdepth
11190: doc-clearstack
1.21 crook 11191:
1.78 anton 11192: The following words inspect memory.
1.21 crook 11193:
1.78 anton 11194: doc-?
11195: doc-dump
1.21 crook 11196:
1.78 anton 11197: And finally, @code{see} allows to inspect code:
1.21 crook 11198:
1.78 anton 11199: doc-see
11200: doc-xt-see
1.111 anton 11201: doc-simple-see
11202: doc-simple-see-range
1.21 crook 11203:
1.78 anton 11204: @node Forgetting words, Debugging, Examining, Programming Tools
11205: @subsection Forgetting words
11206: @cindex words, forgetting
11207: @cindex forgeting words
1.21 crook 11208:
1.78 anton 11209: @c anton: other, maybe better places for this subsection: Defining Words;
11210: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11211:
1.78 anton 11212: Forth allows you to forget words (and everything that was alloted in the
11213: dictonary after them) in a LIFO manner.
1.21 crook 11214:
1.78 anton 11215: doc-marker
1.21 crook 11216:
1.78 anton 11217: The most common use of this feature is during progam development: when
11218: you change a source file, forget all the words it defined and load it
11219: again (since you also forget everything defined after the source file
11220: was loaded, you have to reload that, too). Note that effects like
11221: storing to variables and destroyed system words are not undone when you
11222: forget words. With a system like Gforth, that is fast enough at
11223: starting up and compiling, I find it more convenient to exit and restart
11224: Gforth, as this gives me a clean slate.
1.21 crook 11225:
1.78 anton 11226: Here's an example of using @code{marker} at the start of a source file
11227: that you are debugging; it ensures that you only ever have one copy of
11228: the file's definitions compiled at any time:
1.21 crook 11229:
1.78 anton 11230: @example
11231: [IFDEF] my-code
11232: my-code
11233: [ENDIF]
1.26 crook 11234:
1.78 anton 11235: marker my-code
11236: init-included-files
1.21 crook 11237:
1.78 anton 11238: \ .. definitions start here
11239: \ .
11240: \ .
11241: \ end
11242: @end example
1.21 crook 11243:
1.26 crook 11244:
1.78 anton 11245: @node Debugging, Assertions, Forgetting words, Programming Tools
11246: @subsection Debugging
11247: @cindex debugging
1.21 crook 11248:
1.78 anton 11249: Languages with a slow edit/compile/link/test development loop tend to
11250: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11251:
1.78 anton 11252: A much better (faster) way in fast-compiling languages is to add
11253: printing code at well-selected places, let the program run, look at
11254: the output, see where things went wrong, add more printing code, etc.,
11255: until the bug is found.
1.21 crook 11256:
1.78 anton 11257: The simple debugging aids provided in @file{debugs.fs}
11258: are meant to support this style of debugging.
1.21 crook 11259:
1.78 anton 11260: The word @code{~~} prints debugging information (by default the source
11261: location and the stack contents). It is easy to insert. If you use Emacs
11262: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11263: query-replace them with nothing). The deferred words
1.101 anton 11264: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11265: @code{~~}. The default source location output format works well with
11266: Emacs' compilation mode, so you can step through the program at the
11267: source level using @kbd{C-x `} (the advantage over a stepping debugger
11268: is that you can step in any direction and you know where the crash has
11269: happened or where the strange data has occurred).
1.21 crook 11270:
1.78 anton 11271: doc-~~
11272: doc-printdebugdata
1.101 anton 11273: doc-.debugline
1.21 crook 11274:
1.106 anton 11275: @cindex filenames in @code{~~} output
11276: @code{~~} (and assertions) will usually print the wrong file name if a
11277: marker is executed in the same file after their occurance. They will
11278: print @samp{*somewhere*} as file name if a marker is executed in the
11279: same file before their occurance.
11280:
11281:
1.78 anton 11282: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11283: @subsection Assertions
11284: @cindex assertions
1.21 crook 11285:
1.78 anton 11286: It is a good idea to make your programs self-checking, especially if you
11287: make an assumption that may become invalid during maintenance (for
11288: example, that a certain field of a data structure is never zero). Gforth
11289: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11290:
11291: @example
1.78 anton 11292: assert( @i{flag} )
1.26 crook 11293: @end example
11294:
1.78 anton 11295: The code between @code{assert(} and @code{)} should compute a flag, that
11296: should be true if everything is alright and false otherwise. It should
11297: not change anything else on the stack. The overall stack effect of the
11298: assertion is @code{( -- )}. E.g.
1.21 crook 11299:
1.26 crook 11300: @example
1.78 anton 11301: assert( 1 1 + 2 = ) \ what we learn in school
11302: assert( dup 0<> ) \ assert that the top of stack is not zero
11303: assert( false ) \ this code should not be reached
1.21 crook 11304: @end example
11305:
1.78 anton 11306: The need for assertions is different at different times. During
11307: debugging, we want more checking, in production we sometimes care more
11308: for speed. Therefore, assertions can be turned off, i.e., the assertion
11309: becomes a comment. Depending on the importance of an assertion and the
11310: time it takes to check it, you may want to turn off some assertions and
11311: keep others turned on. Gforth provides several levels of assertions for
11312: this purpose:
11313:
11314:
11315: doc-assert0(
11316: doc-assert1(
11317: doc-assert2(
11318: doc-assert3(
11319: doc-assert(
11320: doc-)
1.21 crook 11321:
11322:
1.78 anton 11323: The variable @code{assert-level} specifies the highest assertions that
11324: are turned on. I.e., at the default @code{assert-level} of one,
11325: @code{assert0(} and @code{assert1(} assertions perform checking, while
11326: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11327:
1.78 anton 11328: The value of @code{assert-level} is evaluated at compile-time, not at
11329: run-time. Therefore you cannot turn assertions on or off at run-time;
11330: you have to set the @code{assert-level} appropriately before compiling a
11331: piece of code. You can compile different pieces of code at different
11332: @code{assert-level}s (e.g., a trusted library at level 1 and
11333: newly-written code at level 3).
1.26 crook 11334:
11335:
1.78 anton 11336: doc-assert-level
1.26 crook 11337:
11338:
1.78 anton 11339: If an assertion fails, a message compatible with Emacs' compilation mode
11340: is produced and the execution is aborted (currently with @code{ABORT"}.
11341: If there is interest, we will introduce a special throw code. But if you
11342: intend to @code{catch} a specific condition, using @code{throw} is
11343: probably more appropriate than an assertion).
1.106 anton 11344:
11345: @cindex filenames in assertion output
11346: Assertions (and @code{~~}) will usually print the wrong file name if a
11347: marker is executed in the same file after their occurance. They will
11348: print @samp{*somewhere*} as file name if a marker is executed in the
11349: same file before their occurance.
1.44 crook 11350:
1.78 anton 11351: Definitions in ANS Forth for these assertion words are provided
11352: in @file{compat/assert.fs}.
1.26 crook 11353:
1.44 crook 11354:
1.78 anton 11355: @node Singlestep Debugger, , Assertions, Programming Tools
11356: @subsection Singlestep Debugger
11357: @cindex singlestep Debugger
11358: @cindex debugging Singlestep
1.44 crook 11359:
1.112 anton 11360: The singlestep debugger does not work in this release.
11361:
1.78 anton 11362: When you create a new word there's often the need to check whether it
11363: behaves correctly or not. You can do this by typing @code{dbg
11364: badword}. A debug session might look like this:
1.26 crook 11365:
1.78 anton 11366: @example
11367: : badword 0 DO i . LOOP ; ok
11368: 2 dbg badword
11369: : badword
11370: Scanning code...
1.44 crook 11371:
1.78 anton 11372: Nesting debugger ready!
1.44 crook 11373:
1.78 anton 11374: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11375: 400D4740 8049F68 DO -> [ 0 ]
11376: 400D4744 804A0C8 i -> [ 1 ] 00000
11377: 400D4748 400C5E60 . -> 0 [ 0 ]
11378: 400D474C 8049D0C LOOP -> [ 0 ]
11379: 400D4744 804A0C8 i -> [ 1 ] 00001
11380: 400D4748 400C5E60 . -> 1 [ 0 ]
11381: 400D474C 8049D0C LOOP -> [ 0 ]
11382: 400D4758 804B384 ; -> ok
11383: @end example
1.21 crook 11384:
1.78 anton 11385: Each line displayed is one step. You always have to hit return to
11386: execute the next word that is displayed. If you don't want to execute
11387: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11388: an overview what keys are available:
1.44 crook 11389:
1.78 anton 11390: @table @i
1.44 crook 11391:
1.78 anton 11392: @item @key{RET}
11393: Next; Execute the next word.
1.21 crook 11394:
1.78 anton 11395: @item n
11396: Nest; Single step through next word.
1.44 crook 11397:
1.78 anton 11398: @item u
11399: Unnest; Stop debugging and execute rest of word. If we got to this word
11400: with nest, continue debugging with the calling word.
1.44 crook 11401:
1.78 anton 11402: @item d
11403: Done; Stop debugging and execute rest.
1.21 crook 11404:
1.78 anton 11405: @item s
11406: Stop; Abort immediately.
1.44 crook 11407:
1.78 anton 11408: @end table
1.44 crook 11409:
1.78 anton 11410: Debugging large application with this mechanism is very difficult, because
11411: you have to nest very deeply into the program before the interesting part
11412: begins. This takes a lot of time.
1.26 crook 11413:
1.78 anton 11414: To do it more directly put a @code{BREAK:} command into your source code.
11415: When program execution reaches @code{BREAK:} the single step debugger is
11416: invoked and you have all the features described above.
1.44 crook 11417:
1.78 anton 11418: If you have more than one part to debug it is useful to know where the
11419: program has stopped at the moment. You can do this by the
11420: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11421: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11422:
1.26 crook 11423:
1.78 anton 11424: doc-dbg
11425: doc-break:
11426: doc-break"
1.44 crook 11427:
11428:
1.26 crook 11429:
1.78 anton 11430: @c -------------------------------------------------------------
11431: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11432: @section Assembler and Code Words
11433: @cindex assembler
11434: @cindex code words
1.44 crook 11435:
1.78 anton 11436: @menu
11437: * Code and ;code::
11438: * Common Assembler:: Assembler Syntax
11439: * Common Disassembler::
11440: * 386 Assembler:: Deviations and special cases
11441: * Alpha Assembler:: Deviations and special cases
11442: * MIPS assembler:: Deviations and special cases
11443: * Other assemblers:: How to write them
11444: @end menu
1.21 crook 11445:
1.78 anton 11446: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11447: @subsection @code{Code} and @code{;code}
1.26 crook 11448:
1.78 anton 11449: Gforth provides some words for defining primitives (words written in
11450: machine code), and for defining the machine-code equivalent of
11451: @code{DOES>}-based defining words. However, the machine-independent
11452: nature of Gforth poses a few problems: First of all, Gforth runs on
11453: several architectures, so it can provide no standard assembler. What's
11454: worse is that the register allocation not only depends on the processor,
11455: but also on the @code{gcc} version and options used.
1.44 crook 11456:
1.78 anton 11457: The words that Gforth offers encapsulate some system dependences (e.g.,
11458: the header structure), so a system-independent assembler may be used in
11459: Gforth. If you do not have an assembler, you can compile machine code
11460: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11461: because these words emit stuff in @i{data} space; it works because
11462: Gforth has unified code/data spaces. Assembler isn't likely to be
11463: portable anyway.}.
1.21 crook 11464:
1.44 crook 11465:
1.78 anton 11466: doc-assembler
11467: doc-init-asm
11468: doc-code
11469: doc-end-code
11470: doc-;code
11471: doc-flush-icache
1.44 crook 11472:
1.21 crook 11473:
1.78 anton 11474: If @code{flush-icache} does not work correctly, @code{code} words
11475: etc. will not work (reliably), either.
1.44 crook 11476:
1.78 anton 11477: The typical usage of these @code{code} words can be shown most easily by
11478: analogy to the equivalent high-level defining words:
1.44 crook 11479:
1.78 anton 11480: @example
11481: : foo code foo
11482: <high-level Forth words> <assembler>
11483: ; end-code
11484:
11485: : bar : bar
11486: <high-level Forth words> <high-level Forth words>
11487: CREATE CREATE
11488: <high-level Forth words> <high-level Forth words>
11489: DOES> ;code
11490: <high-level Forth words> <assembler>
11491: ; end-code
11492: @end example
1.21 crook 11493:
1.78 anton 11494: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11495:
1.78 anton 11496: @cindex registers of the inner interpreter
11497: In the assembly code you will want to refer to the inner interpreter's
11498: registers (e.g., the data stack pointer) and you may want to use other
11499: registers for temporary storage. Unfortunately, the register allocation
11500: is installation-dependent.
1.44 crook 11501:
1.78 anton 11502: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11503: (return stack pointer) may be in different places in @code{gforth} and
11504: @code{gforth-fast}, or different installations. This means that you
11505: cannot write a @code{NEXT} routine that works reliably on both versions
11506: or different installations; so for doing @code{NEXT}, I recommend
11507: jumping to @code{' noop >code-address}, which contains nothing but a
11508: @code{NEXT}.
1.21 crook 11509:
1.78 anton 11510: For general accesses to the inner interpreter's registers, the easiest
11511: solution is to use explicit register declarations (@pxref{Explicit Reg
11512: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11513: all of the inner interpreter's registers: You have to compile Gforth
11514: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11515: the appropriate declarations must be present in the @code{machine.h}
11516: file (see @code{mips.h} for an example; you can find a full list of all
11517: declarable register symbols with @code{grep register engine.c}). If you
11518: give explicit registers to all variables that are declared at the
11519: beginning of @code{engine()}, you should be able to use the other
11520: caller-saved registers for temporary storage. Alternatively, you can use
11521: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11522: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11523: reserve a register (however, this restriction on register allocation may
11524: slow Gforth significantly).
1.44 crook 11525:
1.78 anton 11526: If this solution is not viable (e.g., because @code{gcc} does not allow
11527: you to explicitly declare all the registers you need), you have to find
11528: out by looking at the code where the inner interpreter's registers
11529: reside and which registers can be used for temporary storage. You can
11530: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11531:
1.78 anton 11532: In any case, it is good practice to abstract your assembly code from the
11533: actual register allocation. E.g., if the data stack pointer resides in
11534: register @code{$17}, create an alias for this register called @code{sp},
11535: and use that in your assembly code.
1.21 crook 11536:
1.78 anton 11537: @cindex code words, portable
11538: Another option for implementing normal and defining words efficiently
11539: is to add the desired functionality to the source of Gforth. For normal
11540: words you just have to edit @file{primitives} (@pxref{Automatic
11541: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11542: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11543: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11544:
1.78 anton 11545: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11546: @subsection Common Assembler
1.44 crook 11547:
1.78 anton 11548: The assemblers in Gforth generally use a postfix syntax, i.e., the
11549: instruction name follows the operands.
1.21 crook 11550:
1.78 anton 11551: The operands are passed in the usual order (the same that is used in the
11552: manual of the architecture). Since they all are Forth words, they have
11553: to be separated by spaces; you can also use Forth words to compute the
11554: operands.
1.44 crook 11555:
1.78 anton 11556: The instruction names usually end with a @code{,}. This makes it easier
11557: to visually separate instructions if you put several of them on one
11558: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11559:
1.78 anton 11560: Registers are usually specified by number; e.g., (decimal) @code{11}
11561: specifies registers R11 and F11 on the Alpha architecture (which one,
11562: depends on the instruction). The usual names are also available, e.g.,
11563: @code{s2} for R11 on Alpha.
1.21 crook 11564:
1.78 anton 11565: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11566: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11567: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11568: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11569: conditions are specified in a way specific to each assembler.
1.1 anton 11570:
1.78 anton 11571: Note that the register assignments of the Gforth engine can change
11572: between Gforth versions, or even between different compilations of the
11573: same Gforth version (e.g., if you use a different GCC version). So if
11574: you want to refer to Gforth's registers (e.g., the stack pointer or
11575: TOS), I recommend defining your own words for refering to these
11576: registers, and using them later on; then you can easily adapt to a
11577: changed register assignment. The stability of the register assignment
11578: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11579:
1.100 anton 11580: The most common use of these registers is to dispatch to the next word
11581: (the @code{next} routine). A portable way to do this is to jump to
11582: @code{' noop >code-address} (of course, this is less efficient than
11583: integrating the @code{next} code and scheduling it well).
1.1 anton 11584:
1.96 anton 11585: Another difference between Gforth version is that the top of stack is
11586: kept in memory in @code{gforth} and, on most platforms, in a register in
11587: @code{gforth-fast}.
11588:
1.78 anton 11589: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11590: @subsection Common Disassembler
1.1 anton 11591:
1.78 anton 11592: You can disassemble a @code{code} word with @code{see}
11593: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11594:
1.78 anton 11595: doc-disasm
1.44 crook 11596:
1.78 anton 11597: The disassembler generally produces output that can be fed into the
11598: assembler (i.e., same syntax, etc.). It also includes additional
11599: information in comments. In particular, the address of the instruction
11600: is given in a comment before the instruction.
1.1 anton 11601:
1.78 anton 11602: @code{See} may display more or less than the actual code of the word,
11603: because the recognition of the end of the code is unreliable. You can
11604: use @code{disasm} if it did not display enough. It may display more, if
11605: the code word is not immediately followed by a named word. If you have
11606: something else there, you can follow the word with @code{align last @ ,}
11607: to ensure that the end is recognized.
1.21 crook 11608:
1.78 anton 11609: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11610: @subsection 386 Assembler
1.44 crook 11611:
1.78 anton 11612: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11613: available under GPL, and originally part of bigFORTH.
1.21 crook 11614:
1.78 anton 11615: The 386 disassembler included in Gforth was written by Andrew McKewan
11616: and is in the public domain.
1.21 crook 11617:
1.91 anton 11618: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11619:
1.78 anton 11620: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11621:
1.78 anton 11622: The assembler includes all instruction of the Athlon, i.e. 486 core
11623: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11624: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11625: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11626:
1.78 anton 11627: There are several prefixes to switch between different operation sizes,
11628: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11629: double-word accesses. Addressing modes can be switched with @code{.wa}
11630: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11631: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11632:
1.78 anton 11633: For floating point operations, the prefixes are @code{.fs} (IEEE
11634: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11635: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11636:
1.78 anton 11637: The MMX opcodes don't have size prefixes, they are spelled out like in
11638: the Intel assembler. Instead of move from and to memory, there are
11639: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11640:
1.78 anton 11641: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11642: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11643: e.g., @code{3 #}. Here are some examples of addressing modes in various
11644: syntaxes:
1.21 crook 11645:
1.26 crook 11646: @example
1.91 anton 11647: Gforth Intel (NASM) AT&T (gas) Name
11648: .w ax ax %ax register (16 bit)
11649: ax eax %eax register (32 bit)
11650: 3 # offset 3 $3 immediate
11651: 1000 #) byte ptr 1000 1000 displacement
11652: bx ) [ebx] (%ebx) base
11653: 100 di d) 100[edi] 100(%edi) base+displacement
11654: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11655: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11656: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11657: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11658: @end example
11659:
11660: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11661: @code{DI)} to enforce 32-bit displacement fields (useful for
11662: later patching).
1.21 crook 11663:
1.78 anton 11664: Some example of instructions are:
1.1 anton 11665:
11666: @example
1.78 anton 11667: ax bx mov \ move ebx,eax
11668: 3 # ax mov \ mov eax,3
11669: 100 di ) ax mov \ mov eax,100[edi]
11670: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11671: .w ax bx mov \ mov bx,ax
1.1 anton 11672: @end example
11673:
1.78 anton 11674: The following forms are supported for binary instructions:
1.1 anton 11675:
11676: @example
1.78 anton 11677: <reg> <reg> <inst>
11678: <n> # <reg> <inst>
11679: <mem> <reg> <inst>
11680: <reg> <mem> <inst>
1.1 anton 11681: @end example
11682:
1.78 anton 11683: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 11684:
1.26 crook 11685: @example
1.78 anton 11686: <reg/mem> 1 # shl \ shortens to shift without immediate
11687: <reg/mem> 4 # shl
11688: <reg/mem> cl shl
1.26 crook 11689: @end example
1.1 anton 11690:
1.78 anton 11691: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11692: the byte version.
1.1 anton 11693:
1.78 anton 11694: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11695: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11696: pc < >= <= >}. (Note that most of these words shadow some Forth words
11697: when @code{assembler} is in front of @code{forth} in the search path,
11698: e.g., in @code{code} words). Currently the control structure words use
11699: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11700: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11701:
1.78 anton 11702: Here is an example of a @code{code} word (assumes that the stack pointer
11703: is in esi and the TOS is in ebx):
1.21 crook 11704:
1.26 crook 11705: @example
1.78 anton 11706: code my+ ( n1 n2 -- n )
11707: 4 si D) bx add
11708: 4 # si add
11709: Next
11710: end-code
1.26 crook 11711: @end example
1.21 crook 11712:
1.78 anton 11713: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11714: @subsection Alpha Assembler
1.21 crook 11715:
1.78 anton 11716: The Alpha assembler and disassembler were originally written by Bernd
11717: Thallner.
1.26 crook 11718:
1.78 anton 11719: The register names @code{a0}--@code{a5} are not available to avoid
11720: shadowing hex numbers.
1.2 jwilke 11721:
1.78 anton 11722: Immediate forms of arithmetic instructions are distinguished by a
11723: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11724: does not count as arithmetic instruction).
1.2 jwilke 11725:
1.78 anton 11726: You have to specify all operands to an instruction, even those that
11727: other assemblers consider optional, e.g., the destination register for
11728: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11729:
1.78 anton 11730: You can specify conditions for @code{if,} by removing the first @code{b}
11731: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11732:
1.26 crook 11733: @example
1.78 anton 11734: 11 fgt if, \ if F11>0e
11735: ...
11736: endif,
1.26 crook 11737: @end example
1.2 jwilke 11738:
1.78 anton 11739: @code{fbgt,} gives @code{fgt}.
11740:
11741: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11742: @subsection MIPS assembler
1.2 jwilke 11743:
1.78 anton 11744: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11745:
1.78 anton 11746: Currently the assembler and disassembler only cover the MIPS-I
11747: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11748:
1.78 anton 11749: The register names @code{$a0}--@code{$a3} are not available to avoid
11750: shadowing hex numbers.
1.2 jwilke 11751:
1.78 anton 11752: Because there is no way to distinguish registers from immediate values,
11753: you have to explicitly use the immediate forms of instructions, i.e.,
11754: @code{addiu,}, not just @code{addu,} (@command{as} does this
11755: implicitly).
1.2 jwilke 11756:
1.78 anton 11757: If the architecture manual specifies several formats for the instruction
11758: (e.g., for @code{jalr,}), you usually have to use the one with more
11759: arguments (i.e., two for @code{jalr,}). When in doubt, see
11760: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 11761:
1.78 anton 11762: Branches and jumps in the MIPS architecture have a delay slot. You have
11763: to fill it yourself (the simplest way is to use @code{nop,}), the
11764: assembler does not do it for you (unlike @command{as}). Even
11765: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11766: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11767: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 11768:
1.78 anton 11769: Note that you must not put branches, jumps, or @code{li,} into the delay
11770: slot: @code{li,} may expand to several instructions, and control flow
11771: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 11772:
1.78 anton 11773: For branches the argument specifying the target is a relative address;
11774: You have to add the address of the delay slot to get the absolute
11775: address.
1.1 anton 11776:
1.78 anton 11777: The MIPS architecture also has load delay slots and restrictions on
11778: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11779: yourself to satisfy these restrictions, the assembler does not do it for
11780: you.
1.1 anton 11781:
1.78 anton 11782: You can specify the conditions for @code{if,} etc. by taking a
11783: conditional branch and leaving away the @code{b} at the start and the
11784: @code{,} at the end. E.g.,
1.1 anton 11785:
1.26 crook 11786: @example
1.78 anton 11787: 4 5 eq if,
11788: ... \ do something if $4 equals $5
11789: then,
1.26 crook 11790: @end example
1.1 anton 11791:
1.78 anton 11792: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11793: @subsection Other assemblers
11794:
11795: If you want to contribute another assembler/disassembler, please contact
1.103 anton 11796: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11797: an assembler already. If you are writing them from scratch, please use
11798: a similar syntax style as the one we use (i.e., postfix, commas at the
11799: end of the instruction names, @pxref{Common Assembler}); make the output
11800: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 11801: similar to the style we used.
11802:
11803: Hints on implementation: The most important part is to have a good test
11804: suite that contains all instructions. Once you have that, the rest is
11805: easy. For actual coding you can take a look at
11806: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11807: the assembler and disassembler, avoiding redundancy and some potential
11808: bugs. You can also look at that file (and @pxref{Advanced does> usage
11809: example}) to get ideas how to factor a disassembler.
11810:
11811: Start with the disassembler, because it's easier to reuse data from the
11812: disassembler for the assembler than the other way round.
1.1 anton 11813:
1.78 anton 11814: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11815: how simple it can be.
1.1 anton 11816:
1.78 anton 11817: @c -------------------------------------------------------------
11818: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11819: @section Threading Words
11820: @cindex threading words
1.1 anton 11821:
1.78 anton 11822: @cindex code address
11823: These words provide access to code addresses and other threading stuff
11824: in Gforth (and, possibly, other interpretive Forths). It more or less
11825: abstracts away the differences between direct and indirect threading
11826: (and, for direct threading, the machine dependences). However, at
11827: present this wordset is still incomplete. It is also pretty low-level;
11828: some day it will hopefully be made unnecessary by an internals wordset
11829: that abstracts implementation details away completely.
1.1 anton 11830:
1.78 anton 11831: The terminology used here stems from indirect threaded Forth systems; in
11832: such a system, the XT of a word is represented by the CFA (code field
11833: address) of a word; the CFA points to a cell that contains the code
11834: address. The code address is the address of some machine code that
11835: performs the run-time action of invoking the word (e.g., the
11836: @code{dovar:} routine pushes the address of the body of the word (a
11837: variable) on the stack
11838: ).
1.1 anton 11839:
1.78 anton 11840: @cindex code address
11841: @cindex code field address
11842: In an indirect threaded Forth, you can get the code address of @i{name}
11843: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
11844: >code-address}, independent of the threading method.
1.1 anton 11845:
1.78 anton 11846: doc-threading-method
11847: doc->code-address
11848: doc-code-address!
1.1 anton 11849:
1.78 anton 11850: @cindex @code{does>}-handler
11851: @cindex @code{does>}-code
11852: For a word defined with @code{DOES>}, the code address usually points to
11853: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
11854: routine (in Gforth on some platforms, it can also point to the dodoes
11855: routine itself). What you are typically interested in, though, is
11856: whether a word is a @code{DOES>}-defined word, and what Forth code it
11857: executes; @code{>does-code} tells you that.
1.1 anton 11858:
1.78 anton 11859: doc->does-code
1.1 anton 11860:
1.78 anton 11861: To create a @code{DOES>}-defined word with the following basic words,
11862: you have to set up a @code{DOES>}-handler with @code{does-handler!};
11863: @code{/does-handler} aus behind you have to place your executable Forth
11864: code. Finally you have to create a word and modify its behaviour with
11865: @code{does-handler!}.
1.1 anton 11866:
1.78 anton 11867: doc-does-code!
11868: doc-does-handler!
11869: doc-/does-handler
1.1 anton 11870:
1.78 anton 11871: The code addresses produced by various defining words are produced by
11872: the following words:
1.1 anton 11873:
1.78 anton 11874: doc-docol:
11875: doc-docon:
11876: doc-dovar:
11877: doc-douser:
11878: doc-dodefer:
11879: doc-dofield:
1.1 anton 11880:
1.99 anton 11881: @cindex definer
11882: The following two words generalize @code{>code-address},
11883: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
11884:
11885: doc->definer
11886: doc-definer!
11887:
1.26 crook 11888: @c -------------------------------------------------------------
1.78 anton 11889: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 11890: @section Passing Commands to the Operating System
11891: @cindex operating system - passing commands
11892: @cindex shell commands
11893:
11894: Gforth allows you to pass an arbitrary string to the host operating
11895: system shell (if such a thing exists) for execution.
11896:
1.44 crook 11897:
1.21 crook 11898: doc-sh
11899: doc-system
11900: doc-$?
1.23 crook 11901: doc-getenv
1.21 crook 11902:
1.44 crook 11903:
1.26 crook 11904: @c -------------------------------------------------------------
1.47 crook 11905: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11906: @section Keeping track of Time
11907: @cindex time-related words
11908:
11909: doc-ms
11910: doc-time&date
1.79 anton 11911: doc-utime
11912: doc-cputime
1.47 crook 11913:
11914:
11915: @c -------------------------------------------------------------
11916: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 11917: @section Miscellaneous Words
11918: @cindex miscellaneous words
11919:
1.29 crook 11920: @comment TODO find homes for these
11921:
1.26 crook 11922: These section lists the ANS Forth words that are not documented
1.21 crook 11923: elsewhere in this manual. Ultimately, they all need proper homes.
11924:
1.68 anton 11925: doc-quit
1.44 crook 11926:
1.26 crook 11927: The following ANS Forth words are not currently supported by Gforth
1.27 crook 11928: (@pxref{ANS conformance}):
1.21 crook 11929:
11930: @code{EDITOR}
11931: @code{EMIT?}
11932: @code{FORGET}
11933:
1.24 anton 11934: @c ******************************************************************
11935: @node Error messages, Tools, Words, Top
11936: @chapter Error messages
11937: @cindex error messages
11938: @cindex backtrace
11939:
11940: A typical Gforth error message looks like this:
11941:
11942: @example
1.86 anton 11943: in file included from \evaluated string/:-1
1.24 anton 11944: in file included from ./yyy.fs:1
11945: ./xxx.fs:4: Invalid memory address
11946: bar
11947: ^^^
1.79 anton 11948: Backtrace:
1.25 anton 11949: $400E664C @@
11950: $400E6664 foo
1.24 anton 11951: @end example
11952:
11953: The message identifying the error is @code{Invalid memory address}. The
11954: error happened when text-interpreting line 4 of the file
11955: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
11956: word on the line where the error happened, is pointed out (with
11957: @code{^^^}).
11958:
11959: The file containing the error was included in line 1 of @file{./yyy.fs},
11960: and @file{yyy.fs} was included from a non-file (in this case, by giving
11961: @file{yyy.fs} as command-line parameter to Gforth).
11962:
11963: At the end of the error message you find a return stack dump that can be
11964: interpreted as a backtrace (possibly empty). On top you find the top of
11965: the return stack when the @code{throw} happened, and at the bottom you
11966: find the return stack entry just above the return stack of the topmost
11967: text interpreter.
11968:
11969: To the right of most return stack entries you see a guess for the word
11970: that pushed that return stack entry as its return address. This gives a
11971: backtrace. In our case we see that @code{bar} called @code{foo}, and
11972: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
11973: address} exception).
11974:
11975: Note that the backtrace is not perfect: We don't know which return stack
11976: entries are return addresses (so we may get false positives); and in
11977: some cases (e.g., for @code{abort"}) we cannot determine from the return
11978: address the word that pushed the return address, so for some return
11979: addresses you see no names in the return stack dump.
1.25 anton 11980:
11981: @cindex @code{catch} and backtraces
11982: The return stack dump represents the return stack at the time when a
11983: specific @code{throw} was executed. In programs that make use of
11984: @code{catch}, it is not necessarily clear which @code{throw} should be
11985: used for the return stack dump (e.g., consider one @code{throw} that
11986: indicates an error, which is caught, and during recovery another error
1.42 anton 11987: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 11988: presents the return stack dump for the first @code{throw} after the last
11989: executed (not returned-to) @code{catch}; this works well in the usual
11990: case.
11991:
11992: @cindex @code{gforth-fast} and backtraces
11993: @cindex @code{gforth-fast}, difference from @code{gforth}
11994: @cindex backtraces with @code{gforth-fast}
11995: @cindex return stack dump with @code{gforth-fast}
1.79 anton 11996: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 11997: from primitives (e.g., invalid memory address, stack empty etc.);
11998: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 11999: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12000: exception caused by a primitive in @code{gforth-fast}, you will
12001: typically see no return stack dump at all; however, if the exception is
12002: caught by @code{catch} (e.g., for restoring some state), and then
12003: @code{throw}n again, the return stack dump will be for the first such
12004: @code{throw}.
1.2 jwilke 12005:
1.5 anton 12006: @c ******************************************************************
1.24 anton 12007: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12008: @chapter Tools
12009:
12010: @menu
12011: * ANS Report:: Report the words used, sorted by wordset.
12012: @end menu
12013:
12014: See also @ref{Emacs and Gforth}.
12015:
12016: @node ANS Report, , Tools, Tools
12017: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12018: @cindex @file{ans-report.fs}
12019: @cindex report the words used in your program
12020: @cindex words used in your program
12021:
12022: If you want to label a Forth program as ANS Forth Program, you must
12023: document which wordsets the program uses; for extension wordsets, it is
12024: helpful to list the words the program requires from these wordsets
12025: (because Forth systems are allowed to provide only some words of them).
12026:
12027: The @file{ans-report.fs} tool makes it easy for you to determine which
12028: words from which wordset and which non-ANS words your application
12029: uses. You simply have to include @file{ans-report.fs} before loading the
12030: program you want to check. After loading your program, you can get the
12031: report with @code{print-ans-report}. A typical use is to run this as
12032: batch job like this:
12033: @example
12034: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12035: @end example
12036:
12037: The output looks like this (for @file{compat/control.fs}):
12038: @example
12039: The program uses the following words
12040: from CORE :
12041: : POSTPONE THEN ; immediate ?dup IF 0=
12042: from BLOCK-EXT :
12043: \
12044: from FILE :
12045: (
12046: @end example
12047:
12048: @subsection Caveats
12049:
12050: Note that @file{ans-report.fs} just checks which words are used, not whether
12051: they are used in an ANS Forth conforming way!
12052:
12053: Some words are defined in several wordsets in the
12054: standard. @file{ans-report.fs} reports them for only one of the
12055: wordsets, and not necessarily the one you expect. It depends on usage
12056: which wordset is the right one to specify. E.g., if you only use the
12057: compilation semantics of @code{S"}, it is a Core word; if you also use
12058: its interpretation semantics, it is a File word.
12059:
12060: @c ******************************************************************
1.65 anton 12061: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12062: @chapter ANS conformance
12063: @cindex ANS conformance of Gforth
12064:
12065: To the best of our knowledge, Gforth is an
12066:
12067: ANS Forth System
12068: @itemize @bullet
12069: @item providing the Core Extensions word set
12070: @item providing the Block word set
12071: @item providing the Block Extensions word set
12072: @item providing the Double-Number word set
12073: @item providing the Double-Number Extensions word set
12074: @item providing the Exception word set
12075: @item providing the Exception Extensions word set
12076: @item providing the Facility word set
1.40 anton 12077: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12078: @item providing the File Access word set
12079: @item providing the File Access Extensions word set
12080: @item providing the Floating-Point word set
12081: @item providing the Floating-Point Extensions word set
12082: @item providing the Locals word set
12083: @item providing the Locals Extensions word set
12084: @item providing the Memory-Allocation word set
12085: @item providing the Memory-Allocation Extensions word set (that one's easy)
12086: @item providing the Programming-Tools word set
12087: @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
12088: @item providing the Search-Order word set
12089: @item providing the Search-Order Extensions word set
12090: @item providing the String word set
12091: @item providing the String Extensions word set (another easy one)
12092: @end itemize
12093:
12094: @cindex system documentation
12095: In addition, ANS Forth systems are required to document certain
12096: implementation choices. This chapter tries to meet these
12097: requirements. In many cases it gives a way to ask the system for the
12098: information instead of providing the information directly, in
12099: particular, if the information depends on the processor, the operating
12100: system or the installation options chosen, or if they are likely to
12101: change during the maintenance of Gforth.
12102:
12103: @comment The framework for the rest has been taken from pfe.
12104:
12105: @menu
12106: * The Core Words::
12107: * The optional Block word set::
12108: * The optional Double Number word set::
12109: * The optional Exception word set::
12110: * The optional Facility word set::
12111: * The optional File-Access word set::
12112: * The optional Floating-Point word set::
12113: * The optional Locals word set::
12114: * The optional Memory-Allocation word set::
12115: * The optional Programming-Tools word set::
12116: * The optional Search-Order word set::
12117: @end menu
12118:
12119:
12120: @c =====================================================================
12121: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12122: @comment node-name, next, previous, up
12123: @section The Core Words
12124: @c =====================================================================
12125: @cindex core words, system documentation
12126: @cindex system documentation, core words
12127:
12128: @menu
12129: * core-idef:: Implementation Defined Options
12130: * core-ambcond:: Ambiguous Conditions
12131: * core-other:: Other System Documentation
12132: @end menu
12133:
12134: @c ---------------------------------------------------------------------
12135: @node core-idef, core-ambcond, The Core Words, The Core Words
12136: @subsection Implementation Defined Options
12137: @c ---------------------------------------------------------------------
12138: @cindex core words, implementation-defined options
12139: @cindex implementation-defined options, core words
12140:
12141:
12142: @table @i
12143: @item (Cell) aligned addresses:
12144: @cindex cell-aligned addresses
12145: @cindex aligned addresses
12146: processor-dependent. Gforth's alignment words perform natural alignment
12147: (e.g., an address aligned for a datum of size 8 is divisible by
12148: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12149:
12150: @item @code{EMIT} and non-graphic characters:
12151: @cindex @code{EMIT} and non-graphic characters
12152: @cindex non-graphic characters and @code{EMIT}
12153: The character is output using the C library function (actually, macro)
12154: @code{putc}.
12155:
12156: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12157: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12158: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12159: @cindex @code{ACCEPT}, editing
12160: @cindex @code{EXPECT}, editing
12161: This is modeled on the GNU readline library (@pxref{Readline
12162: Interaction, , Command Line Editing, readline, The GNU Readline
12163: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12164: producing a full word completion every time you type it (instead of
1.28 crook 12165: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12166:
12167: @item character set:
12168: @cindex character set
12169: The character set of your computer and display device. Gforth is
12170: 8-bit-clean (but some other component in your system may make trouble).
12171:
12172: @item Character-aligned address requirements:
12173: @cindex character-aligned address requirements
12174: installation-dependent. Currently a character is represented by a C
12175: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12176: (Comments on that requested).
12177:
12178: @item character-set extensions and matching of names:
12179: @cindex character-set extensions and matching of names
1.26 crook 12180: @cindex case-sensitivity for name lookup
12181: @cindex name lookup, case-sensitivity
12182: @cindex locale and case-sensitivity
1.21 crook 12183: Any character except the ASCII NUL character can be used in a
1.1 anton 12184: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12185: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12186: function is probably influenced by the locale. E.g., the @code{C} locale
12187: does not know about accents and umlauts, so they are matched
12188: case-sensitively in that locale. For portability reasons it is best to
12189: write programs such that they work in the @code{C} locale. Then one can
12190: use libraries written by a Polish programmer (who might use words
12191: containing ISO Latin-2 encoded characters) and by a French programmer
12192: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12193: funny results for some of the words (which ones, depends on the font you
12194: are using)). Also, the locale you prefer may not be available in other
12195: operating systems. Hopefully, Unicode will solve these problems one day.
12196:
12197: @item conditions under which control characters match a space delimiter:
12198: @cindex space delimiters
12199: @cindex control characters as delimiters
12200: If @code{WORD} is called with the space character as a delimiter, all
12201: white-space characters (as identified by the C macro @code{isspace()})
12202: are delimiters. @code{PARSE}, on the other hand, treats space like other
1.44 crook 12203: delimiters. @code{SWORD} treats space like @code{WORD}, but behaves
1.79 anton 12204: like @code{PARSE} otherwise. @code{Name}, which is used by the outer
1.1 anton 12205: interpreter (aka text interpreter) by default, treats all white-space
12206: characters as delimiters.
12207:
1.26 crook 12208: @item format of the control-flow stack:
12209: @cindex control-flow stack, format
12210: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12211: stack item in cells is given by the constant @code{cs-item-size}. At the
12212: time of this writing, an item consists of a (pointer to a) locals list
12213: (third), an address in the code (second), and a tag for identifying the
12214: item (TOS). The following tags are used: @code{defstart},
12215: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12216: @code{scopestart}.
12217:
12218: @item conversion of digits > 35
12219: @cindex digits > 35
12220: The characters @code{[\]^_'} are the digits with the decimal value
12221: 36@minus{}41. There is no way to input many of the larger digits.
12222:
12223: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12224: @cindex @code{EXPECT}, display after end of input
12225: @cindex @code{ACCEPT}, display after end of input
12226: The cursor is moved to the end of the entered string. If the input is
12227: terminated using the @kbd{Return} key, a space is typed.
12228:
12229: @item exception abort sequence of @code{ABORT"}:
12230: @cindex exception abort sequence of @code{ABORT"}
12231: @cindex @code{ABORT"}, exception abort sequence
12232: The error string is stored into the variable @code{"error} and a
12233: @code{-2 throw} is performed.
12234:
12235: @item input line terminator:
12236: @cindex input line terminator
12237: @cindex line terminator on input
1.26 crook 12238: @cindex newline character on input
1.1 anton 12239: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12240: lines. One of these characters is typically produced when you type the
12241: @kbd{Enter} or @kbd{Return} key.
12242:
12243: @item maximum size of a counted string:
12244: @cindex maximum size of a counted string
12245: @cindex counted string, maximum size
12246: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12247: on all platforms, but this may change.
1.1 anton 12248:
12249: @item maximum size of a parsed string:
12250: @cindex maximum size of a parsed string
12251: @cindex parsed string, maximum size
12252: Given by the constant @code{/line}. Currently 255 characters.
12253:
12254: @item maximum size of a definition name, in characters:
12255: @cindex maximum size of a definition name, in characters
12256: @cindex name, maximum length
1.113 ! anton 12257: MAXU/8
1.1 anton 12258:
12259: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12260: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12261: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 ! anton 12262: MAXU/8
1.1 anton 12263:
12264: @item method of selecting the user input device:
12265: @cindex user input device, method of selecting
12266: The user input device is the standard input. There is currently no way to
12267: change it from within Gforth. However, the input can typically be
12268: redirected in the command line that starts Gforth.
12269:
12270: @item method of selecting the user output device:
12271: @cindex user output device, method of selecting
12272: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12273: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12274: output when the user output device is a terminal, otherwise the output
12275: is buffered.
1.1 anton 12276:
12277: @item methods of dictionary compilation:
12278: What are we expected to document here?
12279:
12280: @item number of bits in one address unit:
12281: @cindex number of bits in one address unit
12282: @cindex address unit, size in bits
12283: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12284: platforms.
1.1 anton 12285:
12286: @item number representation and arithmetic:
12287: @cindex number representation and arithmetic
1.79 anton 12288: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12289:
12290: @item ranges for integer types:
12291: @cindex ranges for integer types
12292: @cindex integer types, ranges
12293: Installation-dependent. Make environmental queries for @code{MAX-N},
12294: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12295: unsigned (and positive) types is 0. The lower bound for signed types on
12296: two's complement and one's complement machines machines can be computed
12297: by adding 1 to the upper bound.
12298:
12299: @item read-only data space regions:
12300: @cindex read-only data space regions
12301: @cindex data-space, read-only regions
12302: The whole Forth data space is writable.
12303:
12304: @item size of buffer at @code{WORD}:
12305: @cindex size of buffer at @code{WORD}
12306: @cindex @code{WORD} buffer size
12307: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12308: shared with the pictured numeric output string. If overwriting
12309: @code{PAD} is acceptable, it is as large as the remaining dictionary
12310: space, although only as much can be sensibly used as fits in a counted
12311: string.
12312:
12313: @item size of one cell in address units:
12314: @cindex cell size
12315: @code{1 cells .}.
12316:
12317: @item size of one character in address units:
12318: @cindex char size
1.79 anton 12319: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12320:
12321: @item size of the keyboard terminal buffer:
12322: @cindex size of the keyboard terminal buffer
12323: @cindex terminal buffer, size
12324: Varies. You can determine the size at a specific time using @code{lp@@
12325: tib - .}. It is shared with the locals stack and TIBs of files that
12326: include the current file. You can change the amount of space for TIBs
12327: and locals stack at Gforth startup with the command line option
12328: @code{-l}.
12329:
12330: @item size of the pictured numeric output buffer:
12331: @cindex size of the pictured numeric output buffer
12332: @cindex pictured numeric output buffer, size
12333: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12334: shared with @code{WORD}.
12335:
12336: @item size of the scratch area returned by @code{PAD}:
12337: @cindex size of the scratch area returned by @code{PAD}
12338: @cindex @code{PAD} size
12339: The remainder of dictionary space. @code{unused pad here - - .}.
12340:
12341: @item system case-sensitivity characteristics:
12342: @cindex case-sensitivity characteristics
1.26 crook 12343: Dictionary searches are case-insensitive (except in
1.1 anton 12344: @code{TABLE}s). However, as explained above under @i{character-set
12345: extensions}, the matching for non-ASCII characters is determined by the
12346: locale you are using. In the default @code{C} locale all non-ASCII
12347: characters are matched case-sensitively.
12348:
12349: @item system prompt:
12350: @cindex system prompt
12351: @cindex prompt
12352: @code{ ok} in interpret state, @code{ compiled} in compile state.
12353:
12354: @item division rounding:
12355: @cindex division rounding
12356: installation dependent. @code{s" floored" environment? drop .}. We leave
12357: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12358: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12359:
12360: @item values of @code{STATE} when true:
12361: @cindex @code{STATE} values
12362: -1.
12363:
12364: @item values returned after arithmetic overflow:
12365: On two's complement machines, arithmetic is performed modulo
12366: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12367: arithmetic (with appropriate mapping for signed types). Division by zero
12368: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12369: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12370:
12371: @item whether the current definition can be found after @t{DOES>}:
12372: @cindex @t{DOES>}, visibility of current definition
12373: No.
12374:
12375: @end table
12376:
12377: @c ---------------------------------------------------------------------
12378: @node core-ambcond, core-other, core-idef, The Core Words
12379: @subsection Ambiguous conditions
12380: @c ---------------------------------------------------------------------
12381: @cindex core words, ambiguous conditions
12382: @cindex ambiguous conditions, core words
12383:
12384: @table @i
12385:
12386: @item a name is neither a word nor a number:
12387: @cindex name not found
1.26 crook 12388: @cindex undefined word
1.80 anton 12389: @code{-13 throw} (Undefined word).
1.1 anton 12390:
12391: @item a definition name exceeds the maximum length allowed:
1.26 crook 12392: @cindex word name too long
1.1 anton 12393: @code{-19 throw} (Word name too long)
12394:
12395: @item addressing a region not inside the various data spaces of the forth system:
12396: @cindex Invalid memory address
1.32 anton 12397: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12398: typically readable. Accessing other addresses gives results dependent on
12399: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12400: address).
12401:
12402: @item argument type incompatible with parameter:
1.26 crook 12403: @cindex argument type mismatch
1.1 anton 12404: This is usually not caught. Some words perform checks, e.g., the control
12405: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12406: mismatch).
12407:
12408: @item attempting to obtain the execution token of a word with undefined execution semantics:
12409: @cindex Interpreting a compile-only word, for @code{'} etc.
12410: @cindex execution token of words with undefined execution semantics
12411: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12412: get an execution token for @code{compile-only-error} (which performs a
12413: @code{-14 throw} when executed).
12414:
12415: @item dividing by zero:
12416: @cindex dividing by zero
12417: @cindex floating point unidentified fault, integer division
1.80 anton 12418: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12419: zero); on other systems, this typically results in a @code{-55 throw}
12420: (Floating-point unidentified fault).
1.1 anton 12421:
12422: @item insufficient data stack or return stack space:
12423: @cindex insufficient data stack or return stack space
12424: @cindex stack overflow
1.26 crook 12425: @cindex address alignment exception, stack overflow
1.1 anton 12426: @cindex Invalid memory address, stack overflow
12427: Depending on the operating system, the installation, and the invocation
12428: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12429: it is not checked. If it is checked, you typically get a @code{-3 throw}
12430: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12431: throw} (Invalid memory address) (depending on the platform and how you
12432: achieved the overflow) as soon as the overflow happens. If it is not
12433: checked, overflows typically result in mysterious illegal memory
12434: accesses, producing @code{-9 throw} (Invalid memory address) or
12435: @code{-23 throw} (Address alignment exception); they might also destroy
12436: the internal data structure of @code{ALLOCATE} and friends, resulting in
12437: various errors in these words.
1.1 anton 12438:
12439: @item insufficient space for loop control parameters:
12440: @cindex insufficient space for loop control parameters
1.80 anton 12441: Like other return stack overflows.
1.1 anton 12442:
12443: @item insufficient space in the dictionary:
12444: @cindex insufficient space in the dictionary
12445: @cindex dictionary overflow
1.12 anton 12446: If you try to allot (either directly with @code{allot}, or indirectly
12447: with @code{,}, @code{create} etc.) more memory than available in the
12448: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12449: to access memory beyond the end of the dictionary, the results are
12450: similar to stack overflows.
1.1 anton 12451:
12452: @item interpreting a word with undefined interpretation semantics:
12453: @cindex interpreting a word with undefined interpretation semantics
12454: @cindex Interpreting a compile-only word
12455: For some words, we have defined interpretation semantics. For the
12456: others: @code{-14 throw} (Interpreting a compile-only word).
12457:
12458: @item modifying the contents of the input buffer or a string literal:
12459: @cindex modifying the contents of the input buffer or a string literal
12460: These are located in writable memory and can be modified.
12461:
12462: @item overflow of the pictured numeric output string:
12463: @cindex overflow of the pictured numeric output string
12464: @cindex pictured numeric output string, overflow
1.24 anton 12465: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12466:
12467: @item parsed string overflow:
12468: @cindex parsed string overflow
12469: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12470:
12471: @item producing a result out of range:
12472: @cindex result out of range
12473: On two's complement machines, arithmetic is performed modulo
12474: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12475: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12476: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12477: throw} (floating point unidentified fault). @code{convert} and
12478: @code{>number} currently overflow silently.
1.1 anton 12479:
12480: @item reading from an empty data or return stack:
12481: @cindex stack empty
12482: @cindex stack underflow
1.24 anton 12483: @cindex return stack underflow
1.1 anton 12484: The data stack is checked by the outer (aka text) interpreter after
12485: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12486: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12487: depending on operating system, installation, and invocation. If they are
12488: caught by a check, they typically result in @code{-4 throw} (Stack
12489: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12490: (Invalid memory address), depending on the platform and which stack
12491: underflows and by how much. Note that even if the system uses checking
12492: (through the MMU), your program may have to underflow by a significant
12493: number of stack items to trigger the reaction (the reason for this is
12494: that the MMU, and therefore the checking, works with a page-size
12495: granularity). If there is no checking, the symptoms resulting from an
12496: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12497: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12498: (Invalid memory address) and Illegal Instruction (typically @code{-260
12499: throw}).
1.1 anton 12500:
12501: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12502: @cindex unexpected end of the input buffer
12503: @cindex zero-length string as a name
12504: @cindex Attempt to use zero-length string as a name
12505: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12506: use zero-length string as a name). Words like @code{'} probably will not
12507: find what they search. Note that it is possible to create zero-length
12508: names with @code{nextname} (should it not?).
12509:
12510: @item @code{>IN} greater than input buffer:
12511: @cindex @code{>IN} greater than input buffer
12512: The next invocation of a parsing word returns a string with length 0.
12513:
12514: @item @code{RECURSE} appears after @code{DOES>}:
12515: @cindex @code{RECURSE} appears after @code{DOES>}
12516: Compiles a recursive call to the defining word, not to the defined word.
12517:
12518: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12519: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12520: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12521: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12522: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12523: the end of the file was reached), its source-id may be
12524: reused. Therefore, restoring an input source specification referencing a
12525: closed file may lead to unpredictable results instead of a @code{-12
12526: THROW}.
12527:
12528: In the future, Gforth may be able to restore input source specifications
12529: from other than the current input source.
12530:
12531: @item data space containing definitions gets de-allocated:
12532: @cindex data space containing definitions gets de-allocated
12533: Deallocation with @code{allot} is not checked. This typically results in
12534: memory access faults or execution of illegal instructions.
12535:
12536: @item data space read/write with incorrect alignment:
12537: @cindex data space read/write with incorrect alignment
12538: @cindex alignment faults
1.26 crook 12539: @cindex address alignment exception
1.1 anton 12540: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12541: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12542: alignment turned on, incorrect alignment results in a @code{-9 throw}
12543: (Invalid memory address). There are reportedly some processors with
1.12 anton 12544: alignment restrictions that do not report violations.
1.1 anton 12545:
12546: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12547: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12548: Like other alignment errors.
12549:
12550: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12551: Like other stack underflows.
12552:
12553: @item loop control parameters not available:
12554: @cindex loop control parameters not available
12555: Not checked. The counted loop words simply assume that the top of return
12556: stack items are loop control parameters and behave accordingly.
12557:
12558: @item most recent definition does not have a name (@code{IMMEDIATE}):
12559: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12560: @cindex last word was headerless
12561: @code{abort" last word was headerless"}.
12562:
12563: @item name not defined by @code{VALUE} used by @code{TO}:
12564: @cindex name not defined by @code{VALUE} used by @code{TO}
12565: @cindex @code{TO} on non-@code{VALUE}s
12566: @cindex Invalid name argument, @code{TO}
12567: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12568: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12569:
12570: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12571: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12572: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12573: @code{-13 throw} (Undefined word)
12574:
12575: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12576: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12577: Gforth behaves as if they were of the same type. I.e., you can predict
12578: the behaviour by interpreting all parameters as, e.g., signed.
12579:
12580: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12581: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12582: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12583: compilation semantics of @code{TO}.
12584:
12585: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12586: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12587: @cindex @code{WORD}, string overflow
12588: Not checked. The string will be ok, but the count will, of course,
12589: contain only the least significant bits of the length.
12590:
12591: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12592: @cindex @code{LSHIFT}, large shift counts
12593: @cindex @code{RSHIFT}, large shift counts
12594: Processor-dependent. Typical behaviours are returning 0 and using only
12595: the low bits of the shift count.
12596:
12597: @item word not defined via @code{CREATE}:
12598: @cindex @code{>BODY} of non-@code{CREATE}d words
12599: @code{>BODY} produces the PFA of the word no matter how it was defined.
12600:
12601: @cindex @code{DOES>} of non-@code{CREATE}d words
12602: @code{DOES>} changes the execution semantics of the last defined word no
12603: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12604: @code{CREATE , DOES>}.
12605:
12606: @item words improperly used outside @code{<#} and @code{#>}:
12607: Not checked. As usual, you can expect memory faults.
12608:
12609: @end table
12610:
12611:
12612: @c ---------------------------------------------------------------------
12613: @node core-other, , core-ambcond, The Core Words
12614: @subsection Other system documentation
12615: @c ---------------------------------------------------------------------
12616: @cindex other system documentation, core words
12617: @cindex core words, other system documentation
12618:
12619: @table @i
12620: @item nonstandard words using @code{PAD}:
12621: @cindex @code{PAD} use by nonstandard words
12622: None.
12623:
12624: @item operator's terminal facilities available:
12625: @cindex operator's terminal facilities available
1.80 anton 12626: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12627: and you can give commands to Gforth interactively. The actual facilities
12628: available depend on how you invoke Gforth.
12629:
12630: @item program data space available:
12631: @cindex program data space available
12632: @cindex data space available
12633: @code{UNUSED .} gives the remaining dictionary space. The total
12634: dictionary space can be specified with the @code{-m} switch
12635: (@pxref{Invoking Gforth}) when Gforth starts up.
12636:
12637: @item return stack space available:
12638: @cindex return stack space available
12639: You can compute the total return stack space in cells with
12640: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12641: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12642:
12643: @item stack space available:
12644: @cindex stack space available
12645: You can compute the total data stack space in cells with
12646: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12647: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12648:
12649: @item system dictionary space required, in address units:
12650: @cindex system dictionary space required, in address units
12651: Type @code{here forthstart - .} after startup. At the time of this
12652: writing, this gives 80080 (bytes) on a 32-bit system.
12653: @end table
12654:
12655:
12656: @c =====================================================================
12657: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12658: @section The optional Block word set
12659: @c =====================================================================
12660: @cindex system documentation, block words
12661: @cindex block words, system documentation
12662:
12663: @menu
12664: * block-idef:: Implementation Defined Options
12665: * block-ambcond:: Ambiguous Conditions
12666: * block-other:: Other System Documentation
12667: @end menu
12668:
12669:
12670: @c ---------------------------------------------------------------------
12671: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12672: @subsection Implementation Defined Options
12673: @c ---------------------------------------------------------------------
12674: @cindex implementation-defined options, block words
12675: @cindex block words, implementation-defined options
12676:
12677: @table @i
12678: @item the format for display by @code{LIST}:
12679: @cindex @code{LIST} display format
12680: First the screen number is displayed, then 16 lines of 64 characters,
12681: each line preceded by the line number.
12682:
12683: @item the length of a line affected by @code{\}:
12684: @cindex length of a line affected by @code{\}
12685: @cindex @code{\}, line length in blocks
12686: 64 characters.
12687: @end table
12688:
12689:
12690: @c ---------------------------------------------------------------------
12691: @node block-ambcond, block-other, block-idef, The optional Block word set
12692: @subsection Ambiguous conditions
12693: @c ---------------------------------------------------------------------
12694: @cindex block words, ambiguous conditions
12695: @cindex ambiguous conditions, block words
12696:
12697: @table @i
12698: @item correct block read was not possible:
12699: @cindex block read not possible
12700: Typically results in a @code{throw} of some OS-derived value (between
12701: -512 and -2048). If the blocks file was just not long enough, blanks are
12702: supplied for the missing portion.
12703:
12704: @item I/O exception in block transfer:
12705: @cindex I/O exception in block transfer
12706: @cindex block transfer, I/O exception
12707: Typically results in a @code{throw} of some OS-derived value (between
12708: -512 and -2048).
12709:
12710: @item invalid block number:
12711: @cindex invalid block number
12712: @cindex block number invalid
12713: @code{-35 throw} (Invalid block number)
12714:
12715: @item a program directly alters the contents of @code{BLK}:
12716: @cindex @code{BLK}, altering @code{BLK}
12717: The input stream is switched to that other block, at the same
12718: position. If the storing to @code{BLK} happens when interpreting
12719: non-block input, the system will get quite confused when the block ends.
12720:
12721: @item no current block buffer for @code{UPDATE}:
12722: @cindex @code{UPDATE}, no current block buffer
12723: @code{UPDATE} has no effect.
12724:
12725: @end table
12726:
12727: @c ---------------------------------------------------------------------
12728: @node block-other, , block-ambcond, The optional Block word set
12729: @subsection Other system documentation
12730: @c ---------------------------------------------------------------------
12731: @cindex other system documentation, block words
12732: @cindex block words, other system documentation
12733:
12734: @table @i
12735: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12736: No restrictions (yet).
12737:
12738: @item the number of blocks available for source and data:
12739: depends on your disk space.
12740:
12741: @end table
12742:
12743:
12744: @c =====================================================================
12745: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12746: @section The optional Double Number word set
12747: @c =====================================================================
12748: @cindex system documentation, double words
12749: @cindex double words, system documentation
12750:
12751: @menu
12752: * double-ambcond:: Ambiguous Conditions
12753: @end menu
12754:
12755:
12756: @c ---------------------------------------------------------------------
12757: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12758: @subsection Ambiguous conditions
12759: @c ---------------------------------------------------------------------
12760: @cindex double words, ambiguous conditions
12761: @cindex ambiguous conditions, double words
12762:
12763: @table @i
1.29 crook 12764: @item @i{d} outside of range of @i{n} in @code{D>S}:
12765: @cindex @code{D>S}, @i{d} out of range of @i{n}
12766: The least significant cell of @i{d} is produced.
1.1 anton 12767:
12768: @end table
12769:
12770:
12771: @c =====================================================================
12772: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12773: @section The optional Exception word set
12774: @c =====================================================================
12775: @cindex system documentation, exception words
12776: @cindex exception words, system documentation
12777:
12778: @menu
12779: * exception-idef:: Implementation Defined Options
12780: @end menu
12781:
12782:
12783: @c ---------------------------------------------------------------------
12784: @node exception-idef, , The optional Exception word set, The optional Exception word set
12785: @subsection Implementation Defined Options
12786: @c ---------------------------------------------------------------------
12787: @cindex implementation-defined options, exception words
12788: @cindex exception words, implementation-defined options
12789:
12790: @table @i
12791: @item @code{THROW}-codes used in the system:
12792: @cindex @code{THROW}-codes used in the system
12793: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 12794: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 12795: codes -512@minus{}-2047 are used for OS errors (for file and memory
12796: allocation operations). The mapping from OS error numbers to throw codes
12797: is -512@minus{}@code{errno}. One side effect of this mapping is that
12798: undefined OS errors produce a message with a strange number; e.g.,
12799: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12800: @end table
12801:
12802: @c =====================================================================
12803: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12804: @section The optional Facility word set
12805: @c =====================================================================
12806: @cindex system documentation, facility words
12807: @cindex facility words, system documentation
12808:
12809: @menu
12810: * facility-idef:: Implementation Defined Options
12811: * facility-ambcond:: Ambiguous Conditions
12812: @end menu
12813:
12814:
12815: @c ---------------------------------------------------------------------
12816: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12817: @subsection Implementation Defined Options
12818: @c ---------------------------------------------------------------------
12819: @cindex implementation-defined options, facility words
12820: @cindex facility words, implementation-defined options
12821:
12822: @table @i
12823: @item encoding of keyboard events (@code{EKEY}):
12824: @cindex keyboard events, encoding in @code{EKEY}
12825: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 12826: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 12827: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12828: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12829: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12830: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 12831:
1.1 anton 12832:
12833: @item duration of a system clock tick:
12834: @cindex duration of a system clock tick
12835: @cindex clock tick duration
12836: System dependent. With respect to @code{MS}, the time is specified in
12837: microseconds. How well the OS and the hardware implement this, is
12838: another question.
12839:
12840: @item repeatability to be expected from the execution of @code{MS}:
12841: @cindex repeatability to be expected from the execution of @code{MS}
12842: @cindex @code{MS}, repeatability to be expected
12843: System dependent. On Unix, a lot depends on load. If the system is
12844: lightly loaded, and the delay is short enough that Gforth does not get
12845: swapped out, the performance should be acceptable. Under MS-DOS and
12846: other single-tasking systems, it should be good.
12847:
12848: @end table
12849:
12850:
12851: @c ---------------------------------------------------------------------
12852: @node facility-ambcond, , facility-idef, The optional Facility word set
12853: @subsection Ambiguous conditions
12854: @c ---------------------------------------------------------------------
12855: @cindex facility words, ambiguous conditions
12856: @cindex ambiguous conditions, facility words
12857:
12858: @table @i
12859: @item @code{AT-XY} can't be performed on user output device:
12860: @cindex @code{AT-XY} can't be performed on user output device
12861: Largely terminal dependent. No range checks are done on the arguments.
12862: No errors are reported. You may see some garbage appearing, you may see
12863: simply nothing happen.
12864:
12865: @end table
12866:
12867:
12868: @c =====================================================================
12869: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12870: @section The optional File-Access word set
12871: @c =====================================================================
12872: @cindex system documentation, file words
12873: @cindex file words, system documentation
12874:
12875: @menu
12876: * file-idef:: Implementation Defined Options
12877: * file-ambcond:: Ambiguous Conditions
12878: @end menu
12879:
12880: @c ---------------------------------------------------------------------
12881: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12882: @subsection Implementation Defined Options
12883: @c ---------------------------------------------------------------------
12884: @cindex implementation-defined options, file words
12885: @cindex file words, implementation-defined options
12886:
12887: @table @i
12888: @item file access methods used:
12889: @cindex file access methods used
12890: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12891: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12892: @code{wb}): The file is cleared, if it exists, and created, if it does
12893: not (with both @code{open-file} and @code{create-file}). Under Unix
12894: @code{create-file} creates a file with 666 permissions modified by your
12895: umask.
12896:
12897: @item file exceptions:
12898: @cindex file exceptions
12899: The file words do not raise exceptions (except, perhaps, memory access
12900: faults when you pass illegal addresses or file-ids).
12901:
12902: @item file line terminator:
12903: @cindex file line terminator
12904: System-dependent. Gforth uses C's newline character as line
12905: terminator. What the actual character code(s) of this are is
12906: system-dependent.
12907:
12908: @item file name format:
12909: @cindex file name format
12910: System dependent. Gforth just uses the file name format of your OS.
12911:
12912: @item information returned by @code{FILE-STATUS}:
12913: @cindex @code{FILE-STATUS}, returned information
12914: @code{FILE-STATUS} returns the most powerful file access mode allowed
12915: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12916: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12917: along with the returned mode.
12918:
12919: @item input file state after an exception when including source:
12920: @cindex exception when including source
12921: All files that are left via the exception are closed.
12922:
1.29 crook 12923: @item @i{ior} values and meaning:
12924: @cindex @i{ior} values and meaning
1.68 anton 12925: @cindex @i{wior} values and meaning
1.29 crook 12926: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 12927: intended as throw codes. They typically are in the range
12928: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 12929: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 12930:
12931: @item maximum depth of file input nesting:
12932: @cindex maximum depth of file input nesting
12933: @cindex file input nesting, maximum depth
12934: limited by the amount of return stack, locals/TIB stack, and the number
12935: of open files available. This should not give you troubles.
12936:
12937: @item maximum size of input line:
12938: @cindex maximum size of input line
12939: @cindex input line size, maximum
12940: @code{/line}. Currently 255.
12941:
12942: @item methods of mapping block ranges to files:
12943: @cindex mapping block ranges to files
12944: @cindex files containing blocks
12945: @cindex blocks in files
12946: By default, blocks are accessed in the file @file{blocks.fb} in the
12947: current working directory. The file can be switched with @code{USE}.
12948:
12949: @item number of string buffers provided by @code{S"}:
12950: @cindex @code{S"}, number of string buffers
12951: 1
12952:
12953: @item size of string buffer used by @code{S"}:
12954: @cindex @code{S"}, size of string buffer
12955: @code{/line}. currently 255.
12956:
12957: @end table
12958:
12959: @c ---------------------------------------------------------------------
12960: @node file-ambcond, , file-idef, The optional File-Access word set
12961: @subsection Ambiguous conditions
12962: @c ---------------------------------------------------------------------
12963: @cindex file words, ambiguous conditions
12964: @cindex ambiguous conditions, file words
12965:
12966: @table @i
12967: @item attempting to position a file outside its boundaries:
12968: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
12969: @code{REPOSITION-FILE} is performed as usual: Afterwards,
12970: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
12971:
12972: @item attempting to read from file positions not yet written:
12973: @cindex reading from file positions not yet written
12974: End-of-file, i.e., zero characters are read and no error is reported.
12975:
1.29 crook 12976: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
12977: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 12978: An appropriate exception may be thrown, but a memory fault or other
12979: problem is more probable.
12980:
1.29 crook 12981: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
12982: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
12983: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
12984: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 12985: thrown.
12986:
12987: @item named file cannot be opened (@code{INCLUDED}):
12988: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 12989: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 12990:
12991: @item requesting an unmapped block number:
12992: @cindex unmapped block numbers
12993: There are no unmapped legal block numbers. On some operating systems,
12994: writing a block with a large number may overflow the file system and
12995: have an error message as consequence.
12996:
12997: @item using @code{source-id} when @code{blk} is non-zero:
12998: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
12999: @code{source-id} performs its function. Typically it will give the id of
13000: the source which loaded the block. (Better ideas?)
13001:
13002: @end table
13003:
13004:
13005: @c =====================================================================
13006: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13007: @section The optional Floating-Point word set
13008: @c =====================================================================
13009: @cindex system documentation, floating-point words
13010: @cindex floating-point words, system documentation
13011:
13012: @menu
13013: * floating-idef:: Implementation Defined Options
13014: * floating-ambcond:: Ambiguous Conditions
13015: @end menu
13016:
13017:
13018: @c ---------------------------------------------------------------------
13019: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13020: @subsection Implementation Defined Options
13021: @c ---------------------------------------------------------------------
13022: @cindex implementation-defined options, floating-point words
13023: @cindex floating-point words, implementation-defined options
13024:
13025: @table @i
13026: @item format and range of floating point numbers:
13027: @cindex format and range of floating point numbers
13028: @cindex floating point numbers, format and range
13029: System-dependent; the @code{double} type of C.
13030:
1.29 crook 13031: @item results of @code{REPRESENT} when @i{float} is out of range:
13032: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13033: System dependent; @code{REPRESENT} is implemented using the C library
13034: function @code{ecvt()} and inherits its behaviour in this respect.
13035:
13036: @item rounding or truncation of floating-point numbers:
13037: @cindex rounding of floating-point numbers
13038: @cindex truncation of floating-point numbers
13039: @cindex floating-point numbers, rounding or truncation
13040: System dependent; the rounding behaviour is inherited from the hosting C
13041: compiler. IEEE-FP-based (i.e., most) systems by default round to
13042: nearest, and break ties by rounding to even (i.e., such that the last
13043: bit of the mantissa is 0).
13044:
13045: @item size of floating-point stack:
13046: @cindex floating-point stack size
13047: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13048: the floating-point stack (in floats). You can specify this on startup
13049: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13050:
13051: @item width of floating-point stack:
13052: @cindex floating-point stack width
13053: @code{1 floats}.
13054:
13055: @end table
13056:
13057:
13058: @c ---------------------------------------------------------------------
13059: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13060: @subsection Ambiguous conditions
13061: @c ---------------------------------------------------------------------
13062: @cindex floating-point words, ambiguous conditions
13063: @cindex ambiguous conditions, floating-point words
13064:
13065: @table @i
13066: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13067: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13068: System-dependent. Typically results in a @code{-23 THROW} like other
13069: alignment violations.
13070:
13071: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13072: @cindex @code{f@@} used with an address that is not float aligned
13073: @cindex @code{f!} used with an address that is not float aligned
13074: System-dependent. Typically results in a @code{-23 THROW} like other
13075: alignment violations.
13076:
13077: @item floating-point result out of range:
13078: @cindex floating-point result out of range
1.80 anton 13079: System-dependent. Can result in a @code{-43 throw} (floating point
13080: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13081: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13082: unidentified fault), or can produce a special value representing, e.g.,
13083: Infinity.
13084:
13085: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13086: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13087: System-dependent. Typically results in an alignment fault like other
13088: alignment violations.
13089:
1.35 anton 13090: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13091: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13092: The floating-point number is converted into decimal nonetheless.
13093:
13094: @item Both arguments are equal to zero (@code{FATAN2}):
13095: @cindex @code{FATAN2}, both arguments are equal to zero
13096: System-dependent. @code{FATAN2} is implemented using the C library
13097: function @code{atan2()}.
13098:
1.29 crook 13099: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13100: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13101: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13102: because of small errors and the tan will be a very large (or very small)
13103: but finite number.
13104:
1.29 crook 13105: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13106: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13107: The result is rounded to the nearest float.
13108:
13109: @item dividing by zero:
13110: @cindex dividing by zero, floating-point
13111: @cindex floating-point dividing by zero
13112: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13113: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13114: (floating point divide by zero) or @code{-55 throw} (Floating-point
13115: unidentified fault).
1.1 anton 13116:
13117: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13118: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13119: System dependent. On IEEE-FP based systems the number is converted into
13120: an infinity.
13121:
1.29 crook 13122: @item @i{float}<1 (@code{FACOSH}):
13123: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13124: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13125: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13126:
1.29 crook 13127: @item @i{float}=<-1 (@code{FLNP1}):
13128: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13129: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13130: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13131: negative infinity for @i{float}=-1).
1.1 anton 13132:
1.29 crook 13133: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13134: @cindex @code{FLN}, @i{float}=<0
13135: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13136: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13137: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13138: negative infinity for @i{float}=0).
1.1 anton 13139:
1.29 crook 13140: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13141: @cindex @code{FASINH}, @i{float}<0
13142: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13143: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13144: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13145: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13146: C library?).
1.1 anton 13147:
1.29 crook 13148: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13149: @cindex @code{FACOS}, |@i{float}|>1
13150: @cindex @code{FASIN}, |@i{float}|>1
13151: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13152: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13153: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13154:
1.29 crook 13155: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13156: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13157: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13158: Platform-dependent; typically, some double number is produced and no
13159: error is reported.
1.1 anton 13160:
13161: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13162: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13163: @code{Precision} characters of the numeric output area are used. If
13164: @code{precision} is too high, these words will smash the data or code
13165: close to @code{here}.
1.1 anton 13166: @end table
13167:
13168: @c =====================================================================
13169: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13170: @section The optional Locals word set
13171: @c =====================================================================
13172: @cindex system documentation, locals words
13173: @cindex locals words, system documentation
13174:
13175: @menu
13176: * locals-idef:: Implementation Defined Options
13177: * locals-ambcond:: Ambiguous Conditions
13178: @end menu
13179:
13180:
13181: @c ---------------------------------------------------------------------
13182: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13183: @subsection Implementation Defined Options
13184: @c ---------------------------------------------------------------------
13185: @cindex implementation-defined options, locals words
13186: @cindex locals words, implementation-defined options
13187:
13188: @table @i
13189: @item maximum number of locals in a definition:
13190: @cindex maximum number of locals in a definition
13191: @cindex locals, maximum number in a definition
13192: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13193: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13194: characters. The number of locals in a definition is bounded by the size
13195: of locals-buffer, which contains the names of the locals.
13196:
13197: @end table
13198:
13199:
13200: @c ---------------------------------------------------------------------
13201: @node locals-ambcond, , locals-idef, The optional Locals word set
13202: @subsection Ambiguous conditions
13203: @c ---------------------------------------------------------------------
13204: @cindex locals words, ambiguous conditions
13205: @cindex ambiguous conditions, locals words
13206:
13207: @table @i
13208: @item executing a named local in interpretation state:
13209: @cindex local in interpretation state
13210: @cindex Interpreting a compile-only word, for a local
13211: Locals have no interpretation semantics. If you try to perform the
13212: interpretation semantics, you will get a @code{-14 throw} somewhere
13213: (Interpreting a compile-only word). If you perform the compilation
13214: semantics, the locals access will be compiled (irrespective of state).
13215:
1.29 crook 13216: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13217: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13218: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13219: @cindex Invalid name argument, @code{TO}
13220: @code{-32 throw} (Invalid name argument)
13221:
13222: @end table
13223:
13224:
13225: @c =====================================================================
13226: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13227: @section The optional Memory-Allocation word set
13228: @c =====================================================================
13229: @cindex system documentation, memory-allocation words
13230: @cindex memory-allocation words, system documentation
13231:
13232: @menu
13233: * memory-idef:: Implementation Defined Options
13234: @end menu
13235:
13236:
13237: @c ---------------------------------------------------------------------
13238: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13239: @subsection Implementation Defined Options
13240: @c ---------------------------------------------------------------------
13241: @cindex implementation-defined options, memory-allocation words
13242: @cindex memory-allocation words, implementation-defined options
13243:
13244: @table @i
1.29 crook 13245: @item values and meaning of @i{ior}:
13246: @cindex @i{ior} values and meaning
13247: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13248: intended as throw codes. They typically are in the range
13249: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13250: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13251:
13252: @end table
13253:
13254: @c =====================================================================
13255: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13256: @section The optional Programming-Tools word set
13257: @c =====================================================================
13258: @cindex system documentation, programming-tools words
13259: @cindex programming-tools words, system documentation
13260:
13261: @menu
13262: * programming-idef:: Implementation Defined Options
13263: * programming-ambcond:: Ambiguous Conditions
13264: @end menu
13265:
13266:
13267: @c ---------------------------------------------------------------------
13268: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13269: @subsection Implementation Defined Options
13270: @c ---------------------------------------------------------------------
13271: @cindex implementation-defined options, programming-tools words
13272: @cindex programming-tools words, implementation-defined options
13273:
13274: @table @i
13275: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13276: @cindex @code{;CODE} ending sequence
13277: @cindex @code{CODE} ending sequence
13278: @code{END-CODE}
13279:
13280: @item manner of processing input following @code{;CODE} and @code{CODE}:
13281: @cindex @code{;CODE}, processing input
13282: @cindex @code{CODE}, processing input
13283: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13284: the input is processed by the text interpreter, (starting) in interpret
13285: state.
13286:
13287: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13288: @cindex @code{ASSEMBLER}, search order capability
13289: The ANS Forth search order word set.
13290:
13291: @item source and format of display by @code{SEE}:
13292: @cindex @code{SEE}, source and format of output
1.80 anton 13293: The source for @code{see} is the executable code used by the inner
1.1 anton 13294: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13295: (and on some platforms, assembly code for primitives) as well as
13296: possible.
1.1 anton 13297:
13298: @end table
13299:
13300: @c ---------------------------------------------------------------------
13301: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13302: @subsection Ambiguous conditions
13303: @c ---------------------------------------------------------------------
13304: @cindex programming-tools words, ambiguous conditions
13305: @cindex ambiguous conditions, programming-tools words
13306:
13307: @table @i
13308:
1.21 crook 13309: @item deleting the compilation word list (@code{FORGET}):
13310: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13311: Not implemented (yet).
13312:
1.29 crook 13313: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13314: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13315: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13316: @cindex control-flow stack underflow
13317: This typically results in an @code{abort"} with a descriptive error
13318: message (may change into a @code{-22 throw} (Control structure mismatch)
13319: in the future). You may also get a memory access error. If you are
13320: unlucky, this ambiguous condition is not caught.
13321:
1.29 crook 13322: @item @i{name} can't be found (@code{FORGET}):
13323: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13324: Not implemented (yet).
13325:
1.29 crook 13326: @item @i{name} not defined via @code{CREATE}:
13327: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13328: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13329: the execution semantics of the last defined word no matter how it was
13330: defined.
13331:
13332: @item @code{POSTPONE} applied to @code{[IF]}:
13333: @cindex @code{POSTPONE} applied to @code{[IF]}
13334: @cindex @code{[IF]} and @code{POSTPONE}
13335: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13336: equivalent to @code{[IF]}.
13337:
13338: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13339: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13340: Continue in the same state of conditional compilation in the next outer
13341: input source. Currently there is no warning to the user about this.
13342:
13343: @item removing a needed definition (@code{FORGET}):
13344: @cindex @code{FORGET}, removing a needed definition
13345: Not implemented (yet).
13346:
13347: @end table
13348:
13349:
13350: @c =====================================================================
13351: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13352: @section The optional Search-Order word set
13353: @c =====================================================================
13354: @cindex system documentation, search-order words
13355: @cindex search-order words, system documentation
13356:
13357: @menu
13358: * search-idef:: Implementation Defined Options
13359: * search-ambcond:: Ambiguous Conditions
13360: @end menu
13361:
13362:
13363: @c ---------------------------------------------------------------------
13364: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13365: @subsection Implementation Defined Options
13366: @c ---------------------------------------------------------------------
13367: @cindex implementation-defined options, search-order words
13368: @cindex search-order words, implementation-defined options
13369:
13370: @table @i
13371: @item maximum number of word lists in search order:
13372: @cindex maximum number of word lists in search order
13373: @cindex search order, maximum depth
13374: @code{s" wordlists" environment? drop .}. Currently 16.
13375:
13376: @item minimum search order:
13377: @cindex minimum search order
13378: @cindex search order, minimum
13379: @code{root root}.
13380:
13381: @end table
13382:
13383: @c ---------------------------------------------------------------------
13384: @node search-ambcond, , search-idef, The optional Search-Order word set
13385: @subsection Ambiguous conditions
13386: @c ---------------------------------------------------------------------
13387: @cindex search-order words, ambiguous conditions
13388: @cindex ambiguous conditions, search-order words
13389:
13390: @table @i
1.21 crook 13391: @item changing the compilation word list (during compilation):
13392: @cindex changing the compilation word list (during compilation)
13393: @cindex compilation word list, change before definition ends
13394: The word is entered into the word list that was the compilation word list
1.1 anton 13395: at the start of the definition. Any changes to the name field (e.g.,
13396: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
13397: are applied to the latest defined word (as reported by @code{last} or
1.21 crook 13398: @code{lastxt}), if possible, irrespective of the compilation word list.
1.1 anton 13399:
13400: @item search order empty (@code{previous}):
13401: @cindex @code{previous}, search order empty
1.26 crook 13402: @cindex vocstack empty, @code{previous}
1.1 anton 13403: @code{abort" Vocstack empty"}.
13404:
13405: @item too many word lists in search order (@code{also}):
13406: @cindex @code{also}, too many word lists in search order
1.26 crook 13407: @cindex vocstack full, @code{also}
1.1 anton 13408: @code{abort" Vocstack full"}.
13409:
13410: @end table
13411:
13412: @c ***************************************************************
1.65 anton 13413: @node Standard vs Extensions, Model, ANS conformance, Top
13414: @chapter Should I use Gforth extensions?
13415: @cindex Gforth extensions
13416:
13417: As you read through the rest of this manual, you will see documentation
13418: for @i{Standard} words, and documentation for some appealing Gforth
13419: @i{extensions}. You might ask yourself the question: @i{``Should I
13420: restrict myself to the standard, or should I use the extensions?''}
13421:
13422: The answer depends on the goals you have for the program you are working
13423: on:
13424:
13425: @itemize @bullet
13426:
13427: @item Is it just for yourself or do you want to share it with others?
13428:
13429: @item
13430: If you want to share it, do the others all use Gforth?
13431:
13432: @item
13433: If it is just for yourself, do you want to restrict yourself to Gforth?
13434:
13435: @end itemize
13436:
13437: If restricting the program to Gforth is ok, then there is no reason not
13438: to use extensions. It is still a good idea to keep to the standard
13439: where it is easy, in case you want to reuse these parts in another
13440: program that you want to be portable.
13441:
13442: If you want to be able to port the program to other Forth systems, there
13443: are the following points to consider:
13444:
13445: @itemize @bullet
13446:
13447: @item
13448: Most Forth systems that are being maintained support the ANS Forth
13449: standard. So if your program complies with the standard, it will be
13450: portable among many systems.
13451:
13452: @item
13453: A number of the Gforth extensions can be implemented in ANS Forth using
13454: public-domain files provided in the @file{compat/} directory. These are
13455: mentioned in the text in passing. There is no reason not to use these
13456: extensions, your program will still be ANS Forth compliant; just include
13457: the appropriate compat files with your program.
13458:
13459: @item
13460: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13461: analyse your program and determine what non-Standard words it relies
13462: upon. However, it does not check whether you use standard words in a
13463: non-standard way.
13464:
13465: @item
13466: Some techniques are not standardized by ANS Forth, and are hard or
13467: impossible to implement in a standard way, but can be implemented in
13468: most Forth systems easily, and usually in similar ways (e.g., accessing
13469: word headers). Forth has a rich historical precedent for programmers
13470: taking advantage of implementation-dependent features of their tools
13471: (for example, relying on a knowledge of the dictionary
13472: structure). Sometimes these techniques are necessary to extract every
13473: last bit of performance from the hardware, sometimes they are just a
13474: programming shorthand.
13475:
13476: @item
13477: Does using a Gforth extension save more work than the porting this part
13478: to other Forth systems (if any) will cost?
13479:
13480: @item
13481: Is the additional functionality worth the reduction in portability and
13482: the additional porting problems?
13483:
13484: @end itemize
13485:
13486: In order to perform these consideratios, you need to know what's
13487: standard and what's not. This manual generally states if something is
1.81 anton 13488: non-standard, but the authoritative source is the
13489: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13490: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13491: into the thought processes of the technical committee.
13492:
13493: Note also that portability between Forth systems is not the only
13494: portability issue; there is also the issue of portability between
13495: different platforms (processor/OS combinations).
13496:
13497: @c ***************************************************************
13498: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13499: @chapter Model
13500:
13501: This chapter has yet to be written. It will contain information, on
13502: which internal structures you can rely.
13503:
13504: @c ***************************************************************
13505: @node Integrating Gforth, Emacs and Gforth, Model, Top
13506: @chapter Integrating Gforth into C programs
13507:
13508: This is not yet implemented.
13509:
13510: Several people like to use Forth as scripting language for applications
13511: that are otherwise written in C, C++, or some other language.
13512:
13513: The Forth system ATLAST provides facilities for embedding it into
13514: applications; unfortunately it has several disadvantages: most
13515: importantly, it is not based on ANS Forth, and it is apparently dead
13516: (i.e., not developed further and not supported). The facilities
1.21 crook 13517: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13518: making the switch should not be hard.
13519:
13520: We also tried to design the interface such that it can easily be
13521: implemented by other Forth systems, so that we may one day arrive at a
13522: standardized interface. Such a standard interface would allow you to
13523: replace the Forth system without having to rewrite C code.
13524:
13525: You embed the Gforth interpreter by linking with the library
13526: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13527: global symbols in this library that belong to the interface, have the
13528: prefix @code{forth_}. (Global symbols that are used internally have the
13529: prefix @code{gforth_}).
13530:
13531: You can include the declarations of Forth types and the functions and
13532: variables of the interface with @code{#include <forth.h>}.
13533:
13534: Types.
13535:
13536: Variables.
13537:
13538: Data and FP Stack pointer. Area sizes.
13539:
13540: functions.
13541:
13542: forth_init(imagefile)
13543: forth_evaluate(string) exceptions?
13544: forth_goto(address) (or forth_execute(xt)?)
13545: forth_continue() (a corountining mechanism)
13546:
13547: Adding primitives.
13548:
13549: No checking.
13550:
13551: Signals?
13552:
13553: Accessing the Stacks
13554:
1.26 crook 13555: @c ******************************************************************
1.1 anton 13556: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13557: @chapter Emacs and Gforth
13558: @cindex Emacs and Gforth
13559:
13560: @cindex @file{gforth.el}
13561: @cindex @file{forth.el}
13562: @cindex Rydqvist, Goran
1.107 dvdkhlng 13563: @cindex Kuehling, David
1.1 anton 13564: @cindex comment editing commands
13565: @cindex @code{\}, editing with Emacs
13566: @cindex debug tracer editing commands
13567: @cindex @code{~~}, removal with Emacs
13568: @cindex Forth mode in Emacs
1.107 dvdkhlng 13569:
1.1 anton 13570: Gforth comes with @file{gforth.el}, an improved version of
13571: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13572: improvements are:
13573:
13574: @itemize @bullet
13575: @item
1.107 dvdkhlng 13576: A better handling of indentation.
13577: @item
13578: A custom hilighting engine for Forth-code.
1.26 crook 13579: @item
13580: Comment paragraph filling (@kbd{M-q})
13581: @item
13582: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13583: @item
13584: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13585: @item
13586: Support of the @code{info-lookup} feature for looking up the
13587: documentation of a word.
1.107 dvdkhlng 13588: @item
13589: Support for reading and writing blocks files.
1.26 crook 13590: @end itemize
13591:
1.107 dvdkhlng 13592: To get a basic description of these features, enter Forth mode and
13593: type @kbd{C-h m}.
1.1 anton 13594:
13595: @cindex source location of error or debugging output in Emacs
13596: @cindex error output, finding the source location in Emacs
13597: @cindex debugging output, finding the source location in Emacs
13598: In addition, Gforth supports Emacs quite well: The source code locations
13599: given in error messages, debugging output (from @code{~~}) and failed
13600: assertion messages are in the right format for Emacs' compilation mode
13601: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13602: Manual}) so the source location corresponding to an error or other
13603: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13604: @kbd{C-c C-c} for the error under the cursor).
13605:
1.107 dvdkhlng 13606: @cindex viewing the documentation of a word in Emacs
13607: @cindex context-sensitive help
13608: Moreover, for words documented in this manual, you can look up the
13609: glossary entry quickly by using @kbd{C-h TAB}
13610: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13611: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13612: later and does not work for words containing @code{:}.
13613:
13614: @menu
13615: * Installing gforth.el:: Making Emacs aware of Forth.
13616: * Emacs Tags:: Viewing the source of a word in Emacs.
13617: * Hilighting:: Making Forth code look prettier.
13618: * Auto-Indentation:: Customizing auto-indentation.
13619: * Blocks Files:: Reading and writing blocks files.
13620: @end menu
13621:
13622: @c ----------------------------------
1.109 anton 13623: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13624: @section Installing gforth.el
13625: @cindex @file{.emacs}
13626: @cindex @file{gforth.el}, installation
13627: To make the features from @file{gforth.el} available in Emacs, add
13628: the following lines to your @file{.emacs} file:
13629:
13630: @example
13631: (autoload 'forth-mode "gforth.el")
13632: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13633: auto-mode-alist))
13634: (autoload 'forth-block-mode "gforth.el")
13635: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13636: auto-mode-alist))
13637: (add-hook 'forth-mode-hook (function (lambda ()
13638: ;; customize variables here:
13639: (setq forth-indent-level 4)
13640: (setq forth-minor-indent-level 2)
13641: (setq forth-hilight-level 3)
13642: ;;; ...
13643: )))
13644: @end example
13645:
13646: @c ----------------------------------
13647: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13648: @section Emacs Tags
1.1 anton 13649: @cindex @file{TAGS} file
13650: @cindex @file{etags.fs}
13651: @cindex viewing the source of a word in Emacs
1.43 anton 13652: @cindex @code{require}, placement in files
13653: @cindex @code{include}, placement in files
1.107 dvdkhlng 13654: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13655: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13656: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13657: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13658: several tags files at the same time (e.g., one for the Gforth sources
13659: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13660: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13661: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13662: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13663: with @file{etags.fs}, you should avoid putting definitions both before
13664: and after @code{require} etc., otherwise you will see the same file
13665: visited several times by commands like @code{tags-search}.
1.1 anton 13666:
1.107 dvdkhlng 13667: @c ----------------------------------
13668: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13669: @section Hilighting
13670: @cindex hilighting Forth code in Emacs
13671: @cindex highlighting Forth code in Emacs
13672: @file{gforth.el} comes with a custom source hilighting engine. When
13673: you open a file in @code{forth-mode}, it will be completely parsed,
13674: assigning faces to keywords, comments, strings etc. While you edit
13675: the file, modified regions get parsed and updated on-the-fly.
13676:
13677: Use the variable `forth-hilight-level' to change the level of
13678: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13679: you set the hilighting level to 0, the parser will still work in the
13680: background, collecting information about whether regions of text are
13681: ``compiled'' or ``interpreted''. Those information are required for
13682: auto-indentation to work properly. Set `forth-disable-parser' to
13683: non-nil if your computer is too slow to handle parsing. This will
13684: have an impact on the smartness of the auto-indentation engine,
13685: though.
13686:
13687: Sometimes Forth sources define new features that should be hilighted,
13688: new control structures, defining-words etc. You can use the variable
13689: `forth-custom-words' to make @code{forth-mode} hilight additional
13690: words and constructs. See the docstring of `forth-words' for details
13691: (in Emacs, type @kbd{C-h v forth-words}).
13692:
13693: `forth-custom-words' is meant to be customized in your
13694: @file{.emacs} file. To customize hilighing in a file-specific manner,
13695: set `forth-local-words' in a local-variables section at the end of
13696: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13697:
13698: Example:
13699: @example
13700: 0 [IF]
13701: Local Variables:
13702: forth-local-words:
13703: ((("t:") definition-starter (font-lock-keyword-face . 1)
13704: "[ \t\n]" t name (font-lock-function-name-face . 3))
13705: ((";t") definition-ender (font-lock-keyword-face . 1)))
13706: End:
13707: [THEN]
13708: @end example
13709:
13710: @c ----------------------------------
13711: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13712: @section Auto-Indentation
13713: @cindex auto-indentation of Forth code in Emacs
13714: @cindex indentation of Forth code in Emacs
13715: @code{forth-mode} automatically tries to indent lines in a smart way,
13716: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13717:
13718: Simple customization can be achieved by setting
13719: `forth-indent-level' and `forth-minor-indent-level' in your
13720: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13721: per default by multiples of 4 columns. To use the more traditional
13722: 3-column indentation, add the following lines to your @file{.emacs}:
13723:
13724: @example
13725: (add-hook 'forth-mode-hook (function (lambda ()
13726: ;; customize variables here:
13727: (setq forth-indent-level 3)
13728: (setq forth-minor-indent-level 1)
13729: )))
13730: @end example
13731:
13732: If you want indentation to recognize non-default words, customize it
13733: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
13734: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13735: v forth-indent-words}).
13736:
13737: To customize indentation in a file-specific manner, set
13738: `forth-local-indent-words' in a local-variables section at the end of
13739: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13740: Emacs Manual}).
13741:
13742: Example:
13743: @example
13744: 0 [IF]
13745: Local Variables:
13746: forth-local-indent-words:
13747: ((("t:") (0 . 2) (0 . 2))
13748: ((";t") (-2 . 0) (0 . -2)))
13749: End:
13750: [THEN]
13751: @end example
13752:
13753: @c ----------------------------------
1.109 anton 13754: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 13755: @section Blocks Files
13756: @cindex blocks files, use with Emacs
13757: @code{forth-mode} Autodetects blocks files by checking whether the
13758: length of the first line exceeds 1023 characters. It then tries to
13759: convert the file into normal text format. When you save the file, it
13760: will be written to disk as normal stream-source file.
13761:
13762: If you want to write blocks files, use @code{forth-blocks-mode}. It
13763: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 13764:
1.107 dvdkhlng 13765: @itemize @bullet
13766: @item
13767: Files are written to disk in blocks file format.
13768: @item
13769: Screen numbers are displayed in the mode line (enumerated beginning
13770: with the value of `forth-block-base')
13771: @item
13772: Warnings are displayed when lines exceed 64 characters.
13773: @item
13774: The beginning of the currently edited block is marked with an
13775: overlay-arrow.
13776: @end itemize
1.41 anton 13777:
1.107 dvdkhlng 13778: There are some restrictions you should be aware of. When you open a
13779: blocks file that contains tabulator or newline characters, these
13780: characters will be translated into spaces when the file is written
13781: back to disk. If tabs or newlines are encountered during blocks file
13782: reading, an error is output to the echo area. So have a look at the
13783: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 13784:
1.107 dvdkhlng 13785: Please consult the docstring of @code{forth-blocks-mode} for more
13786: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 13787:
1.26 crook 13788: @c ******************************************************************
1.1 anton 13789: @node Image Files, Engine, Emacs and Gforth, Top
13790: @chapter Image Files
1.26 crook 13791: @cindex image file
13792: @cindex @file{.fi} files
1.1 anton 13793: @cindex precompiled Forth code
13794: @cindex dictionary in persistent form
13795: @cindex persistent form of dictionary
13796:
13797: An image file is a file containing an image of the Forth dictionary,
13798: i.e., compiled Forth code and data residing in the dictionary. By
13799: convention, we use the extension @code{.fi} for image files.
13800:
13801: @menu
1.18 anton 13802: * Image Licensing Issues:: Distribution terms for images.
13803: * Image File Background:: Why have image files?
1.67 anton 13804: * Non-Relocatable Image Files:: don't always work.
1.18 anton 13805: * Data-Relocatable Image Files:: are better.
1.67 anton 13806: * Fully Relocatable Image Files:: better yet.
1.18 anton 13807: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 13808: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 13809: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 13810: @end menu
13811:
1.18 anton 13812: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13813: @section Image Licensing Issues
13814: @cindex license for images
13815: @cindex image license
13816:
13817: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13818: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13819: original image; i.e., according to copyright law it is a derived work of
13820: the original image.
13821:
13822: Since Gforth is distributed under the GNU GPL, the newly created image
13823: falls under the GNU GPL, too. In particular, this means that if you
13824: distribute the image, you have to make all of the sources for the image
1.113 ! anton 13825: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 13826: GNU General Public License (Section 3)}.
13827:
13828: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13829: contains only code compiled from the sources you gave it; if none of
13830: these sources is under the GPL, the terms discussed above do not apply
13831: to the image. However, if your image needs an engine (a gforth binary)
13832: that is under the GPL, you should make sure that you distribute both in
13833: a way that is at most a @emph{mere aggregation}, if you don't want the
13834: terms of the GPL to apply to the image.
13835:
13836: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 13837: @section Image File Background
13838: @cindex image file background
13839:
1.80 anton 13840: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 13841: definitions written in Forth. Since the Forth compiler itself belongs to
13842: those definitions, it is not possible to start the system with the
1.80 anton 13843: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 13844: code as an image file in nearly executable form. When Gforth starts up,
13845: a C routine loads the image file into memory, optionally relocates the
13846: addresses, then sets up the memory (stacks etc.) according to
13847: information in the image file, and (finally) starts executing Forth
13848: code.
1.1 anton 13849:
13850: The image file variants represent different compromises between the
13851: goals of making it easy to generate image files and making them
13852: portable.
13853:
13854: @cindex relocation at run-time
1.26 crook 13855: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 13856: run-time. This avoids many of the complications discussed below (image
13857: files are data relocatable without further ado), but costs performance
13858: (one addition per memory access).
13859:
13860: @cindex relocation at load-time
1.26 crook 13861: By contrast, the Gforth loader performs relocation at image load time. The
13862: loader also has to replace tokens that represent primitive calls with the
1.1 anton 13863: appropriate code-field addresses (or code addresses in the case of
13864: direct threading).
13865:
13866: There are three kinds of image files, with different degrees of
13867: relocatability: non-relocatable, data-relocatable, and fully relocatable
13868: image files.
13869:
13870: @cindex image file loader
13871: @cindex relocating loader
13872: @cindex loader for image files
13873: These image file variants have several restrictions in common; they are
13874: caused by the design of the image file loader:
13875:
13876: @itemize @bullet
13877: @item
13878: There is only one segment; in particular, this means, that an image file
13879: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 13880: them). The contents of the stacks are not represented, either.
1.1 anton 13881:
13882: @item
13883: The only kinds of relocation supported are: adding the same offset to
13884: all cells that represent data addresses; and replacing special tokens
13885: with code addresses or with pieces of machine code.
13886:
13887: If any complex computations involving addresses are performed, the
13888: results cannot be represented in the image file. Several applications that
13889: use such computations come to mind:
13890: @itemize @minus
13891: @item
13892: Hashing addresses (or data structures which contain addresses) for table
13893: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13894: purpose, you will have no problem, because the hash tables are
13895: recomputed automatically when the system is started. If you use your own
13896: hash tables, you will have to do something similar.
13897:
13898: @item
13899: There's a cute implementation of doubly-linked lists that uses
13900: @code{XOR}ed addresses. You could represent such lists as singly-linked
13901: in the image file, and restore the doubly-linked representation on
13902: startup.@footnote{In my opinion, though, you should think thrice before
13903: using a doubly-linked list (whatever implementation).}
13904:
13905: @item
13906: The code addresses of run-time routines like @code{docol:} cannot be
13907: represented in the image file (because their tokens would be replaced by
13908: machine code in direct threaded implementations). As a workaround,
13909: compute these addresses at run-time with @code{>code-address} from the
13910: executions tokens of appropriate words (see the definitions of
1.80 anton 13911: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 13912:
13913: @item
13914: On many architectures addresses are represented in machine code in some
13915: shifted or mangled form. You cannot put @code{CODE} words that contain
13916: absolute addresses in this form in a relocatable image file. Workarounds
13917: are representing the address in some relative form (e.g., relative to
13918: the CFA, which is present in some register), or loading the address from
13919: a place where it is stored in a non-mangled form.
13920: @end itemize
13921: @end itemize
13922:
13923: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13924: @section Non-Relocatable Image Files
13925: @cindex non-relocatable image files
1.26 crook 13926: @cindex image file, non-relocatable
1.1 anton 13927:
13928: These files are simple memory dumps of the dictionary. They are specific
13929: to the executable (i.e., @file{gforth} file) they were created
13930: with. What's worse, they are specific to the place on which the
13931: dictionary resided when the image was created. Now, there is no
13932: guarantee that the dictionary will reside at the same place the next
13933: time you start Gforth, so there's no guarantee that a non-relocatable
13934: image will work the next time (Gforth will complain instead of crashing,
13935: though).
13936:
13937: You can create a non-relocatable image file with
13938:
1.44 crook 13939:
1.1 anton 13940: doc-savesystem
13941:
1.44 crook 13942:
1.1 anton 13943: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13944: @section Data-Relocatable Image Files
13945: @cindex data-relocatable image files
1.26 crook 13946: @cindex image file, data-relocatable
1.1 anton 13947:
13948: These files contain relocatable data addresses, but fixed code addresses
13949: (instead of tokens). They are specific to the executable (i.e.,
13950: @file{gforth} file) they were created with. For direct threading on some
13951: architectures (e.g., the i386), data-relocatable images do not work. You
13952: get a data-relocatable image, if you use @file{gforthmi} with a
13953: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13954: Relocatable Image Files}).
13955:
13956: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13957: @section Fully Relocatable Image Files
13958: @cindex fully relocatable image files
1.26 crook 13959: @cindex image file, fully relocatable
1.1 anton 13960:
13961: @cindex @file{kern*.fi}, relocatability
13962: @cindex @file{gforth.fi}, relocatability
13963: These image files have relocatable data addresses, and tokens for code
13964: addresses. They can be used with different binaries (e.g., with and
13965: without debugging) on the same machine, and even across machines with
13966: the same data formats (byte order, cell size, floating point
13967: format). However, they are usually specific to the version of Gforth
13968: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13969: are fully relocatable.
13970:
13971: There are two ways to create a fully relocatable image file:
13972:
13973: @menu
1.29 crook 13974: * gforthmi:: The normal way
1.1 anton 13975: * cross.fs:: The hard way
13976: @end menu
13977:
13978: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
13979: @subsection @file{gforthmi}
13980: @cindex @file{comp-i.fs}
13981: @cindex @file{gforthmi}
13982:
13983: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 13984: image @i{file} that contains everything you would load by invoking
13985: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 13986: @example
1.29 crook 13987: gforthmi @i{file} @i{options}
1.1 anton 13988: @end example
13989:
13990: E.g., if you want to create an image @file{asm.fi} that has the file
13991: @file{asm.fs} loaded in addition to the usual stuff, you could do it
13992: like this:
13993:
13994: @example
13995: gforthmi asm.fi asm.fs
13996: @end example
13997:
1.27 crook 13998: @file{gforthmi} is implemented as a sh script and works like this: It
13999: produces two non-relocatable images for different addresses and then
14000: compares them. Its output reflects this: first you see the output (if
1.62 crook 14001: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14002: files, then you see the output of the comparing program: It displays the
14003: offset used for data addresses and the offset used for code addresses;
1.1 anton 14004: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14005: image files, it displays a line like this:
1.1 anton 14006:
14007: @example
14008: 78DC BFFFFA50 BFFFFA40
14009: @end example
14010:
14011: This means that at offset $78dc from @code{forthstart}, one input image
14012: contains $bffffa50, and the other contains $bffffa40. Since these cells
14013: cannot be represented correctly in the output image, you should examine
14014: these places in the dictionary and verify that these cells are dead
14015: (i.e., not read before they are written).
1.39 anton 14016:
14017: @cindex --application, @code{gforthmi} option
14018: If you insert the option @code{--application} in front of the image file
14019: name, you will get an image that uses the @code{--appl-image} option
14020: instead of the @code{--image-file} option (@pxref{Invoking
14021: Gforth}). When you execute such an image on Unix (by typing the image
14022: name as command), the Gforth engine will pass all options to the image
14023: instead of trying to interpret them as engine options.
1.1 anton 14024:
1.27 crook 14025: If you type @file{gforthmi} with no arguments, it prints some usage
14026: instructions.
14027:
1.1 anton 14028: @cindex @code{savesystem} during @file{gforthmi}
14029: @cindex @code{bye} during @file{gforthmi}
14030: @cindex doubly indirect threaded code
1.44 crook 14031: @cindex environment variables
14032: @cindex @code{GFORTHD} -- environment variable
14033: @cindex @code{GFORTH} -- environment variable
1.1 anton 14034: @cindex @code{gforth-ditc}
1.29 crook 14035: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14036: words @code{savesystem} and @code{bye} must be visible. A special doubly
14037: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14038: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14039: this executable through the environment variable @code{GFORTHD}
14040: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14041: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14042: data-relocatable image (because there is no code address offset). The
14043: normal @file{gforth} executable is used for creating the relocatable
14044: image; you can pass the exact filename of this executable through the
14045: environment variable @code{GFORTH}.
1.1 anton 14046:
14047: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14048: @subsection @file{cross.fs}
14049: @cindex @file{cross.fs}
14050: @cindex cross-compiler
14051: @cindex metacompiler
1.47 crook 14052: @cindex target compiler
1.1 anton 14053:
14054: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14055: programming language (@pxref{Cross Compiler}).
1.1 anton 14056:
1.47 crook 14057: @code{cross} allows you to create image files for machines with
1.1 anton 14058: different data sizes and data formats than the one used for generating
14059: the image file. You can also use it to create an application image that
14060: does not contain a Forth compiler. These features are bought with
14061: restrictions and inconveniences in programming. E.g., addresses have to
14062: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14063: order to make the code relocatable.
14064:
14065:
14066: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14067: @section Stack and Dictionary Sizes
14068: @cindex image file, stack and dictionary sizes
14069: @cindex dictionary size default
14070: @cindex stack size default
14071:
14072: If you invoke Gforth with a command line flag for the size
14073: (@pxref{Invoking Gforth}), the size you specify is stored in the
14074: dictionary. If you save the dictionary with @code{savesystem} or create
14075: an image with @file{gforthmi}, this size will become the default
14076: for the resulting image file. E.g., the following will create a
1.21 crook 14077: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14078:
14079: @example
14080: gforthmi gforth.fi -m 1M
14081: @end example
14082:
14083: In other words, if you want to set the default size for the dictionary
14084: and the stacks of an image, just invoke @file{gforthmi} with the
14085: appropriate options when creating the image.
14086:
14087: @cindex stack size, cache-friendly
14088: Note: For cache-friendly behaviour (i.e., good performance), you should
14089: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14090: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14091: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14092:
14093: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14094: @section Running Image Files
14095: @cindex running image files
14096: @cindex invoking image files
14097: @cindex image file invocation
14098:
14099: @cindex -i, invoke image file
14100: @cindex --image file, invoke image file
1.29 crook 14101: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14102: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14103: @example
1.29 crook 14104: gforth -i @i{image}
1.1 anton 14105: @end example
14106:
14107: @cindex executable image file
1.26 crook 14108: @cindex image file, executable
1.1 anton 14109: If your operating system supports starting scripts with a line of the
14110: form @code{#! ...}, you just have to type the image file name to start
14111: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14112: just a convention). I.e., to run Gforth with the image file @i{image},
14113: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14114: This works because every @code{.fi} file starts with a line of this
14115: format:
14116:
14117: @example
14118: #! /usr/local/bin/gforth-0.4.0 -i
14119: @end example
14120:
14121: The file and pathname for the Gforth engine specified on this line is
14122: the specific Gforth executable that it was built against; i.e. the value
14123: of the environment variable @code{GFORTH} at the time that
14124: @file{gforthmi} was executed.
1.1 anton 14125:
1.27 crook 14126: You can make use of the same shell capability to make a Forth source
14127: file into an executable. For example, if you place this text in a file:
1.26 crook 14128:
14129: @example
14130: #! /usr/local/bin/gforth
14131:
14132: ." Hello, world" CR
14133: bye
14134: @end example
14135:
14136: @noindent
1.27 crook 14137: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14138: directly from the command line. The sequence @code{#!} is used in two
14139: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14140: system@footnote{The Unix kernel actually recognises two types of files:
14141: executable files and files of data, where the data is processed by an
14142: interpreter that is specified on the ``interpreter line'' -- the first
14143: line of the file, starting with the sequence #!. There may be a small
14144: limit (e.g., 32) on the number of characters that may be specified on
14145: the interpreter line.} secondly it is treated as a comment character by
14146: Gforth. Because of the second usage, a space is required between
1.80 anton 14147: @code{#!} and the path to the executable (moreover, some Unixes
14148: require the sequence @code{#! /}).
1.27 crook 14149:
14150: The disadvantage of this latter technique, compared with using
1.80 anton 14151: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14152: compiled on-the-fly, each time the program is invoked.
1.26 crook 14153:
1.1 anton 14154: doc-#!
14155:
1.44 crook 14156:
1.1 anton 14157: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14158: @section Modifying the Startup Sequence
14159: @cindex startup sequence for image file
14160: @cindex image file initialization sequence
14161: @cindex initialization sequence of image file
14162:
14163: You can add your own initialization to the startup sequence through the
1.26 crook 14164: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80 anton 14165: image-specific command line processing (i.e., loading files and
1.26 crook 14166: evaluating (@code{-e}) strings) starts.
1.1 anton 14167:
14168: A sequence for adding your initialization usually looks like this:
14169:
14170: @example
14171: :noname
14172: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14173: ... \ your stuff
14174: ; IS 'cold
14175: @end example
14176:
14177: @cindex turnkey image files
1.26 crook 14178: @cindex image file, turnkey applications
1.1 anton 14179: You can make a turnkey image by letting @code{'cold} execute a word
14180: (your turnkey application) that never returns; instead, it exits Gforth
14181: via @code{bye} or @code{throw}.
14182:
14183: @cindex command-line arguments, access
14184: @cindex arguments on the command line, access
14185: You can access the (image-specific) command-line arguments through the
1.26 crook 14186: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 14187: access to @code{argv}.
14188:
1.26 crook 14189: If @code{'cold} exits normally, Gforth processes the command-line
14190: arguments as files to be loaded and strings to be evaluated. Therefore,
14191: @code{'cold} should remove the arguments it has used in this case.
14192:
1.44 crook 14193:
14194:
1.26 crook 14195: doc-'cold
1.1 anton 14196: doc-argc
14197: doc-argv
14198: doc-arg
14199:
14200:
1.44 crook 14201:
1.1 anton 14202: @c ******************************************************************
1.113 ! anton 14203: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14204: @chapter Engine
14205: @cindex engine
14206: @cindex virtual machine
14207:
1.26 crook 14208: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14209: may be helpful for finding your way in the Gforth sources.
14210:
1.109 anton 14211: The ideas in this section have also been published in the following
14212: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14213: Forth-Tagung '93; M. Anton Ertl,
14214: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14215: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14216: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14217: Threaded code variations and optimizations (extended version)}},
14218: Forth-Tagung '02.
1.1 anton 14219:
14220: @menu
14221: * Portability::
14222: * Threading::
14223: * Primitives::
14224: * Performance::
14225: @end menu
14226:
14227: @node Portability, Threading, Engine, Engine
14228: @section Portability
14229: @cindex engine portability
14230:
1.26 crook 14231: An important goal of the Gforth Project is availability across a wide
14232: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14233: achieved this goal by manually coding the engine in assembly language
14234: for several then-popular processors. This approach is very
14235: labor-intensive and the results are short-lived due to progress in
14236: computer architecture.
1.1 anton 14237:
14238: @cindex C, using C for the engine
14239: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14240: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14241: particularly popular for UNIX-based Forths due to the large variety of
14242: architectures of UNIX machines. Unfortunately an implementation in C
14243: does not mix well with the goals of efficiency and with using
14244: traditional techniques: Indirect or direct threading cannot be expressed
14245: in C, and switch threading, the fastest technique available in C, is
14246: significantly slower. Another problem with C is that it is very
14247: cumbersome to express double integer arithmetic.
14248:
14249: @cindex GNU C for the engine
14250: @cindex long long
14251: Fortunately, there is a portable language that does not have these
14252: limitations: GNU C, the version of C processed by the GNU C compiler
14253: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14254: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14255: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14256: threading possible, its @code{long long} type (@pxref{Long Long, ,
14257: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14258: double numbers on many systems. GNU C is freely available on all
1.1 anton 14259: important (and many unimportant) UNIX machines, VMS, 80386s running
14260: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14261: on all these machines.
14262:
14263: Writing in a portable language has the reputation of producing code that
14264: is slower than assembly. For our Forth engine we repeatedly looked at
14265: the code produced by the compiler and eliminated most compiler-induced
14266: inefficiencies by appropriate changes in the source code.
14267:
14268: @cindex explicit register declarations
14269: @cindex --enable-force-reg, configuration flag
14270: @cindex -DFORCE_REG
14271: However, register allocation cannot be portably influenced by the
14272: programmer, leading to some inefficiencies on register-starved
14273: machines. We use explicit register declarations (@pxref{Explicit Reg
14274: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14275: improve the speed on some machines. They are turned on by using the
14276: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14277: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14278: machine, but also on the compiler version: On some machines some
14279: compiler versions produce incorrect code when certain explicit register
14280: declarations are used. So by default @code{-DFORCE_REG} is not used.
14281:
14282: @node Threading, Primitives, Portability, Engine
14283: @section Threading
14284: @cindex inner interpreter implementation
14285: @cindex threaded code implementation
14286:
14287: @cindex labels as values
14288: GNU C's labels as values extension (available since @code{gcc-2.0},
14289: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14290: makes it possible to take the address of @i{label} by writing
14291: @code{&&@i{label}}. This address can then be used in a statement like
14292: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14293: @code{goto x}.
14294:
1.26 crook 14295: @cindex @code{NEXT}, indirect threaded
1.1 anton 14296: @cindex indirect threaded inner interpreter
14297: @cindex inner interpreter, indirect threaded
1.26 crook 14298: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14299: @example
14300: cfa = *ip++;
14301: ca = *cfa;
14302: goto *ca;
14303: @end example
14304: @cindex instruction pointer
14305: For those unfamiliar with the names: @code{ip} is the Forth instruction
14306: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14307: execution token and points to the code field of the next word to be
14308: executed; The @code{ca} (code address) fetched from there points to some
14309: executable code, e.g., a primitive or the colon definition handler
14310: @code{docol}.
14311:
1.26 crook 14312: @cindex @code{NEXT}, direct threaded
1.1 anton 14313: @cindex direct threaded inner interpreter
14314: @cindex inner interpreter, direct threaded
14315: Direct threading is even simpler:
14316: @example
14317: ca = *ip++;
14318: goto *ca;
14319: @end example
14320:
14321: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14322: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14323:
14324: @menu
14325: * Scheduling::
14326: * Direct or Indirect Threaded?::
1.109 anton 14327: * Dynamic Superinstructions::
1.1 anton 14328: * DOES>::
14329: @end menu
14330:
14331: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14332: @subsection Scheduling
14333: @cindex inner interpreter optimization
14334:
14335: There is a little complication: Pipelined and superscalar processors,
14336: i.e., RISC and some modern CISC machines can process independent
14337: instructions while waiting for the results of an instruction. The
14338: compiler usually reorders (schedules) the instructions in a way that
14339: achieves good usage of these delay slots. However, on our first tries
14340: the compiler did not do well on scheduling primitives. E.g., for
14341: @code{+} implemented as
14342: @example
14343: n=sp[0]+sp[1];
14344: sp++;
14345: sp[0]=n;
14346: NEXT;
14347: @end example
1.81 anton 14348: the @code{NEXT} comes strictly after the other code, i.e., there is
14349: nearly no scheduling. After a little thought the problem becomes clear:
14350: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14351: addresses (and the version of @code{gcc} we used would not know it even
14352: if it was possible), so it could not move the load of the cfa above the
14353: store to the TOS. Indeed the pointers could be the same, if code on or
14354: very near the top of stack were executed. In the interest of speed we
14355: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14356: in scheduling: @code{NEXT} is divided into several parts:
14357: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14358: like:
1.1 anton 14359: @example
1.81 anton 14360: NEXT_P0;
1.1 anton 14361: n=sp[0]+sp[1];
14362: sp++;
14363: NEXT_P1;
14364: sp[0]=n;
14365: NEXT_P2;
14366: @end example
14367:
1.81 anton 14368: There are various schemes that distribute the different operations of
14369: NEXT between these parts in several ways; in general, different schemes
14370: perform best on different processors. We use a scheme for most
14371: architectures that performs well for most processors of this
1.109 anton 14372: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14373: the scheme on installation time.
14374:
1.1 anton 14375:
1.109 anton 14376: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14377: @subsection Direct or Indirect Threaded?
14378: @cindex threading, direct or indirect?
14379:
1.109 anton 14380: Threaded forth code consists of references to primitives (simple machine
14381: code routines like @code{+}) and to non-primitives (e.g., colon
14382: definitions, variables, constants); for a specific class of
14383: non-primitives (e.g., variables) there is one code routine (e.g.,
14384: @code{dovar}), but each variable needs a separate reference to its data.
14385:
14386: Traditionally Forth has been implemented as indirect threaded code,
14387: because this allows to use only one cell to reference a non-primitive
14388: (basically you point to the data, and find the code address there).
14389:
14390: @cindex primitive-centric threaded code
14391: However, threaded code in Gforth (since 0.6.0) uses two cells for
14392: non-primitives, one for the code address, and one for the data address;
14393: the data pointer is an immediate argument for the virtual machine
14394: instruction represented by the code address. We call this
14395: @emph{primitive-centric} threaded code, because all code addresses point
14396: to simple primitives. E.g., for a variable, the code address is for
14397: @code{lit} (also used for integer literals like @code{99}).
14398:
14399: Primitive-centric threaded code allows us to use (faster) direct
14400: threading as dispatch method, completely portably (direct threaded code
14401: in Gforth before 0.6.0 required architecture-specific code). It also
14402: eliminates the performance problems related to I-cache consistency that
14403: 386 implementations have with direct threaded code, and allows
14404: additional optimizations.
14405:
14406: @cindex hybrid direct/indirect threaded code
14407: There is a catch, however: the @var{xt} parameter of @code{execute} can
14408: occupy only one cell, so how do we pass non-primitives with their code
14409: @emph{and} data addresses to them? Our answer is to use indirect
14410: threaded dispatch for @code{execute} and other words that use a
14411: single-cell xt. So, normal threaded code in colon definitions uses
14412: direct threading, and @code{execute} and similar words, which dispatch
14413: to xts on the data stack, use indirect threaded code. We call this
14414: @emph{hybrid direct/indirect} threaded code.
14415:
14416: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14417: @cindex gforth engine
14418: @cindex gforth-fast engine
14419: The engines @command{gforth} and @command{gforth-fast} use hybrid
14420: direct/indirect threaded code. This means that with these engines you
14421: cannot use @code{,} to compile an xt. Instead, you have to use
14422: @code{compile,}.
14423:
14424: @cindex gforth-itc engine
14425: If you want to compile xts with @code{,}, use @command{gforth-itc}. This
14426: engine uses plain old indirect threaded code. It still compiles in a
14427: primitive-centric style, so you cannot use @code{compile,} instead of
14428: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
14429: ... [}. If you want to do that, you have to use @command{gforth-itc}
14430: and execute @code{' , is compile,}. Your program can check if it is
14431: running on a hybrid direct/indirect threaded engine or a pure indirect
14432: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14433:
14434:
14435: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14436: @subsection Dynamic Superinstructions
14437: @cindex Dynamic superinstructions with replication
14438: @cindex Superinstructions
14439: @cindex Replication
14440:
14441: The engines @command{gforth} and @command{gforth-fast} use another
14442: optimization: Dynamic superinstructions with replication. As an
14443: example, consider the following colon definition:
14444:
14445: @example
14446: : squared ( n1 -- n2 )
14447: dup * ;
14448: @end example
14449:
14450: Gforth compiles this into the threaded code sequence
14451:
14452: @example
14453: dup
14454: *
14455: ;s
14456: @end example
14457:
14458: In normal direct threaded code there is a code address occupying one
14459: cell for each of these primitives. Each code address points to a
14460: machine code routine, and the interpreter jumps to this machine code in
14461: order to execute the primitive. The routines for these three
14462: primitives are (in @command{gforth-fast} on the 386):
14463:
14464: @example
14465: Code dup
14466: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14467: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14468: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14469: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14470: end-code
14471: Code *
14472: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14473: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14474: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14475: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14476: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14477: end-code
14478: Code ;s
14479: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14480: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14481: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14482: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14483: end-code
14484: @end example
14485:
14486: With dynamic superinstructions and replication the compiler does not
14487: just lay down the threaded code, but also copies the machine code
14488: fragments, usually without the jump at the end.
14489:
14490: @example
14491: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14492: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14493: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14494: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14495: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14496: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14497: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14498: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14499: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14500: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14501: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14502: @end example
14503:
14504: Only when a threaded-code control-flow change happens (e.g., in
14505: @code{;s}), the jump is appended. This optimization eliminates many of
14506: these jumps and makes the rest much more predictable. The speedup
14507: depends on the processor and the application; on the Athlon and Pentium
14508: III this optimization typically produces a speedup by a factor of 2.
14509:
14510: The code addresses in the direct-threaded code are set to point to the
14511: appropriate points in the copied machine code, in this example like
14512: this:
1.1 anton 14513:
1.109 anton 14514: @example
14515: primitive code address
14516: dup $4057D27D
14517: * $4057D286
14518: ;s $4057D292
14519: @end example
14520:
14521: Thus there can be threaded-code jumps to any place in this piece of
14522: code. This also simplifies decompilation quite a bit.
14523:
14524: @cindex --no-dynamic command-line option
14525: @cindex --no-super command-line option
14526: You can disable this optimization with @option{--no-dynamic}. You can
14527: use the copying without eliminating the jumps (i.e., dynamic
14528: replication, but without superinstructions) with @option{--no-super};
14529: this gives the branch prediction benefit alone; the effect on
1.110 anton 14530: performance depends on the CPU; on the Athlon and Pentium III the
14531: speedup is a little less than for dynamic superinstructions with
14532: replication.
14533:
14534: @cindex patching threaded code
14535: One use of these options is if you want to patch the threaded code.
14536: With superinstructions, many of the dispatch jumps are eliminated, so
14537: patching often has no effect. These options preserve all the dispatch
14538: jumps.
1.109 anton 14539:
14540: @cindex --dynamic command-line option
1.110 anton 14541: On some machines dynamic superinstructions are disabled by default,
14542: because it is unsafe on these machines. However, if you feel
14543: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14544:
14545: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14546: @subsection DOES>
14547: @cindex @code{DOES>} implementation
14548:
1.26 crook 14549: @cindex @code{dodoes} routine
14550: @cindex @code{DOES>}-code
1.1 anton 14551: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14552: the chunk of code executed by every word defined by a
1.109 anton 14553: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14554: this is only needed if the xt of the word is @code{execute}d. The main
14555: problem here is: How to find the Forth code to be executed, i.e. the
14556: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14557: solutions:
1.1 anton 14558:
1.21 crook 14559: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14560: @code{DOES>}-code address is stored in the cell after the code address
14561: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14562: illegal in the Forth-79 and all later standards, because in fig-Forth
14563: this address lies in the body (which is illegal in these
14564: standards). However, by making the code field larger for all words this
14565: solution becomes legal again. We use this approach. Leaving a cell
14566: unused in most words is a bit wasteful, but on the machines we are
14567: targeting this is hardly a problem.
14568:
1.1 anton 14569:
14570: @node Primitives, Performance, Threading, Engine
14571: @section Primitives
14572: @cindex primitives, implementation
14573: @cindex virtual machine instructions, implementation
14574:
14575: @menu
14576: * Automatic Generation::
14577: * TOS Optimization::
14578: * Produced code::
14579: @end menu
14580:
14581: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14582: @subsection Automatic Generation
14583: @cindex primitives, automatic generation
14584:
14585: @cindex @file{prims2x.fs}
1.109 anton 14586:
1.1 anton 14587: Since the primitives are implemented in a portable language, there is no
14588: longer any need to minimize the number of primitives. On the contrary,
14589: having many primitives has an advantage: speed. In order to reduce the
14590: number of errors in primitives and to make programming them easier, we
1.109 anton 14591: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14592: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14593: generates most (and sometimes all) of the C code for a primitive from
14594: the stack effect notation. The source for a primitive has the following
14595: form:
1.1 anton 14596:
14597: @cindex primitive source format
14598: @format
1.58 anton 14599: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14600: [@code{""}@i{glossary entry}@code{""}]
14601: @i{C code}
1.1 anton 14602: [@code{:}
1.29 crook 14603: @i{Forth code}]
1.1 anton 14604: @end format
14605:
14606: The items in brackets are optional. The category and glossary fields
14607: are there for generating the documentation, the Forth code is there
14608: for manual implementations on machines without GNU C. E.g., the source
14609: for the primitive @code{+} is:
14610: @example
1.58 anton 14611: + ( n1 n2 -- n ) core plus
1.1 anton 14612: n = n1+n2;
14613: @end example
14614:
14615: This looks like a specification, but in fact @code{n = n1+n2} is C
14616: code. Our primitive generation tool extracts a lot of information from
14617: the stack effect notations@footnote{We use a one-stack notation, even
14618: though we have separate data and floating-point stacks; The separate
14619: notation can be generated easily from the unified notation.}: The number
14620: of items popped from and pushed on the stack, their type, and by what
14621: name they are referred to in the C code. It then generates a C code
14622: prelude and postlude for each primitive. The final C code for @code{+}
14623: looks like this:
14624:
14625: @example
1.46 pazsan 14626: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14627: /* */ /* documentation */
1.81 anton 14628: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14629: @{
14630: DEF_CA /* definition of variable ca (indirect threading) */
14631: Cell n1; /* definitions of variables */
14632: Cell n2;
14633: Cell n;
1.81 anton 14634: NEXT_P0; /* NEXT part 0 */
1.1 anton 14635: n1 = (Cell) sp[1]; /* input */
14636: n2 = (Cell) TOS;
14637: sp += 1; /* stack adjustment */
14638: @{
14639: n = n1+n2; /* C code taken from the source */
14640: @}
14641: NEXT_P1; /* NEXT part 1 */
14642: TOS = (Cell)n; /* output */
14643: NEXT_P2; /* NEXT part 2 */
14644: @}
14645: @end example
14646:
14647: This looks long and inefficient, but the GNU C compiler optimizes quite
14648: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14649: HP RISC machines: Defining the @code{n}s does not produce any code, and
14650: using them as intermediate storage also adds no cost.
14651:
1.26 crook 14652: There are also other optimizations that are not illustrated by this
14653: example: assignments between simple variables are usually for free (copy
1.1 anton 14654: propagation). If one of the stack items is not used by the primitive
14655: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14656: (dead code elimination). On the other hand, there are some things that
14657: the compiler does not do, therefore they are performed by
14658: @file{prims2x.fs}: The compiler does not optimize code away that stores
14659: a stack item to the place where it just came from (e.g., @code{over}).
14660:
14661: While programming a primitive is usually easy, there are a few cases
14662: where the programmer has to take the actions of the generator into
14663: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14664: fall through to @code{NEXT}.
1.109 anton 14665:
14666: For more information
1.1 anton 14667:
14668: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14669: @subsection TOS Optimization
14670: @cindex TOS optimization for primitives
14671: @cindex primitives, keeping the TOS in a register
14672:
14673: An important optimization for stack machine emulators, e.g., Forth
14674: engines, is keeping one or more of the top stack items in
1.29 crook 14675: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14676: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14677: @itemize @bullet
14678: @item
1.29 crook 14679: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14680: due to fewer loads from and stores to the stack.
1.29 crook 14681: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14682: @i{y<n}, due to additional moves between registers.
1.1 anton 14683: @end itemize
14684:
14685: @cindex -DUSE_TOS
14686: @cindex -DUSE_NO_TOS
14687: In particular, keeping one item in a register is never a disadvantage,
14688: if there are enough registers. Keeping two items in registers is a
14689: disadvantage for frequent words like @code{?branch}, constants,
14690: variables, literals and @code{i}. Therefore our generator only produces
14691: code that keeps zero or one items in registers. The generated C code
14692: covers both cases; the selection between these alternatives is made at
14693: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14694: code for @code{+} is just a simple variable name in the one-item case,
14695: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14696: GNU C compiler tries to keep simple variables like @code{TOS} in
14697: registers, and it usually succeeds, if there are enough registers.
14698:
14699: @cindex -DUSE_FTOS
14700: @cindex -DUSE_NO_FTOS
14701: The primitive generator performs the TOS optimization for the
14702: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14703: operations the benefit of this optimization is even larger:
14704: floating-point operations take quite long on most processors, but can be
14705: performed in parallel with other operations as long as their results are
14706: not used. If the FP-TOS is kept in a register, this works. If
14707: it is kept on the stack, i.e., in memory, the store into memory has to
14708: wait for the result of the floating-point operation, lengthening the
14709: execution time of the primitive considerably.
14710:
14711: The TOS optimization makes the automatic generation of primitives a
14712: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14713: @code{TOS} is not sufficient. There are some special cases to
14714: consider:
14715: @itemize @bullet
14716: @item In the case of @code{dup ( w -- w w )} the generator must not
14717: eliminate the store to the original location of the item on the stack,
14718: if the TOS optimization is turned on.
14719: @item Primitives with stack effects of the form @code{--}
1.29 crook 14720: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14721: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14722: must load the TOS from the stack at the end. But for the null stack
14723: effect @code{--} no stores or loads should be generated.
14724: @end itemize
14725:
14726: @node Produced code, , TOS Optimization, Primitives
14727: @subsection Produced code
14728: @cindex primitives, assembly code listing
14729:
14730: @cindex @file{engine.s}
14731: To see what assembly code is produced for the primitives on your machine
14732: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 14733: look at the resulting file @file{engine.s}. Alternatively, you can also
14734: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 14735:
14736: @node Performance, , Primitives, Engine
14737: @section Performance
14738: @cindex performance of some Forth interpreters
14739: @cindex engine performance
14740: @cindex benchmarking Forth systems
14741: @cindex Gforth performance
14742:
14743: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 14744: impossible to write a significantly faster threaded-code engine.
1.1 anton 14745:
14746: On register-starved machines like the 386 architecture processors
14747: improvements are possible, because @code{gcc} does not utilize the
14748: registers as well as a human, even with explicit register declarations;
14749: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14750: and hand-tuned it for the 486; this system is 1.19 times faster on the
14751: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 14752: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14753: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14754: registers fit in real registers (and we can even afford to use the TOS
14755: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 14756: earlier results. And dynamic superinstructions provide another speedup
14757: (but only around a factor 1.2 on the 486).
1.1 anton 14758:
14759: @cindex Win32Forth performance
14760: @cindex NT Forth performance
14761: @cindex eforth performance
14762: @cindex ThisForth performance
14763: @cindex PFE performance
14764: @cindex TILE performance
1.81 anton 14765: The potential advantage of assembly language implementations is not
1.112 anton 14766: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 14767: (direct threaded, compiled with @code{gcc-2.95.1} and
14768: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14769: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14770: (with and without peephole (aka pinhole) optimization of the threaded
14771: code); all these systems were written in assembly language. We also
14772: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14773: with @code{gcc-2.6.3} with the default configuration for Linux:
14774: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14775: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14776: employs peephole optimization of the threaded code) and TILE (compiled
14777: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14778: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14779: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14780: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14781: then extended it to run the benchmarks, added the peephole optimizer,
14782: ran the benchmarks and reported the results.
1.40 anton 14783:
1.1 anton 14784: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14785: matrix multiplication come from the Stanford integer benchmarks and have
14786: been translated into Forth by Martin Fraeman; we used the versions
14787: included in the TILE Forth package, but with bigger data set sizes; and
14788: a recursive Fibonacci number computation for benchmarking calling
14789: performance. The following table shows the time taken for the benchmarks
14790: scaled by the time taken by Gforth (in other words, it shows the speedup
14791: factor that Gforth achieved over the other systems).
14792:
14793: @example
1.112 anton 14794: relative Win32- NT eforth This-
14795: time Gforth Forth Forth eforth +opt PFE Forth TILE
14796: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
14797: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
14798: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
14799: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 14800: @end example
14801:
1.26 crook 14802: You may be quite surprised by the good performance of Gforth when
14803: compared with systems written in assembly language. One important reason
14804: for the disappointing performance of these other systems is probably
14805: that they are not written optimally for the 486 (e.g., they use the
14806: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14807: but costly method for relocating the Forth image: like @code{cforth}, it
14808: computes the actual addresses at run time, resulting in two address
14809: computations per @code{NEXT} (@pxref{Image File Background}).
14810:
1.1 anton 14811: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14812: explained with the self-imposed restriction of the latter systems to
14813: standard C, which makes efficient threading impossible (however, the
1.4 anton 14814: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 14815: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14816: Moreover, current C compilers have a hard time optimizing other aspects
14817: of the ThisForth and the TILE source.
14818:
1.26 crook 14819: The performance of Gforth on 386 architecture processors varies widely
14820: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14821: allocate any of the virtual machine registers into real machine
14822: registers by itself and would not work correctly with explicit register
1.112 anton 14823: declarations, giving a significantly slower engine (on a 486DX2/66
14824: running the Sieve) than the one measured above.
1.1 anton 14825:
1.26 crook 14826: Note that there have been several releases of Win32Forth since the
14827: release presented here, so the results presented above may have little
1.40 anton 14828: predictive value for the performance of Win32Forth today (results for
14829: the current release on an i486DX2/66 are welcome).
1.1 anton 14830:
14831: @cindex @file{Benchres}
1.66 anton 14832: In
14833: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14834: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 14835: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 14836: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14837: several native code systems; that version of Gforth is slower on a 486
1.112 anton 14838: than the version used here. You can find a newer version of these
14839: measurements at
1.47 crook 14840: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 14841: find numbers for Gforth on various machines in @file{Benchres}.
14842:
1.26 crook 14843: @c ******************************************************************
1.113 ! anton 14844: @c @node Binding to System Library, Cross Compiler, Engine, Top
! 14845: @c @chapter Binding to System Library
1.13 pazsan 14846:
1.113 ! anton 14847: @c ****************************************************************
! 14848: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 14849: @chapter Cross Compiler
1.47 crook 14850: @cindex @file{cross.fs}
14851: @cindex cross-compiler
14852: @cindex metacompiler
14853: @cindex target compiler
1.13 pazsan 14854:
1.46 pazsan 14855: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14856: mostly written in Forth, including crucial parts like the outer
14857: interpreter and compiler, it needs compiled Forth code to get
14858: started. The cross compiler allows to create new images for other
14859: architectures, even running under another Forth system.
1.13 pazsan 14860:
14861: @menu
1.67 anton 14862: * Using the Cross Compiler::
14863: * How the Cross Compiler Works::
1.13 pazsan 14864: @end menu
14865:
1.21 crook 14866: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 14867: @section Using the Cross Compiler
1.46 pazsan 14868:
14869: The cross compiler uses a language that resembles Forth, but isn't. The
14870: main difference is that you can execute Forth code after definition,
14871: while you usually can't execute the code compiled by cross, because the
14872: code you are compiling is typically for a different computer than the
14873: one you are compiling on.
14874:
1.81 anton 14875: @c anton: This chapter is somewhat different from waht I would expect: I
14876: @c would expect an explanation of the cross language and how to create an
14877: @c application image with it. The section explains some aspects of
14878: @c creating a Gforth kernel.
14879:
1.46 pazsan 14880: The Makefile is already set up to allow you to create kernels for new
14881: architectures with a simple make command. The generic kernels using the
14882: GCC compiled virtual machine are created in the normal build process
14883: with @code{make}. To create a embedded Gforth executable for e.g. the
14884: 8086 processor (running on a DOS machine), type
14885:
14886: @example
14887: make kernl-8086.fi
14888: @end example
14889:
14890: This will use the machine description from the @file{arch/8086}
14891: directory to create a new kernel. A machine file may look like that:
14892:
14893: @example
14894: \ Parameter for target systems 06oct92py
14895:
14896: 4 Constant cell \ cell size in bytes
14897: 2 Constant cell<< \ cell shift to bytes
14898: 5 Constant cell>bit \ cell shift to bits
14899: 8 Constant bits/char \ bits per character
14900: 8 Constant bits/byte \ bits per byte [default: 8]
14901: 8 Constant float \ bytes per float
14902: 8 Constant /maxalign \ maximum alignment in bytes
14903: false Constant bigendian \ byte order
14904: ( true=big, false=little )
14905:
14906: include machpc.fs \ feature list
14907: @end example
14908:
14909: This part is obligatory for the cross compiler itself, the feature list
14910: is used by the kernel to conditionally compile some features in and out,
14911: depending on whether the target supports these features.
14912:
14913: There are some optional features, if you define your own primitives,
14914: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 14915: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 14916: @code{prims-include} includes primitives, and @code{>boot} prepares for
14917: booting.
14918:
14919: @example
14920: : asm-include ." Include assembler" cr
14921: s" arch/8086/asm.fs" included ;
14922:
14923: : prims-include ." Include primitives" cr
14924: s" arch/8086/prim.fs" included ;
14925:
14926: : >boot ." Prepare booting" cr
14927: s" ' boot >body into-forth 1+ !" evaluate ;
14928: @end example
14929:
14930: These words are used as sort of macro during the cross compilation in
1.81 anton 14931: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 14932: be possible --- but more complicated --- to write a new kernel project
14933: file, too.
14934:
14935: @file{kernel/main.fs} expects the machine description file name on the
14936: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14937: @code{mach-file} leaves a counted string on the stack, or
14938: @code{machine-file} leaves an address, count pair of the filename on the
14939: stack.
14940:
14941: The feature list is typically controlled using @code{SetValue}, generic
14942: files that are used by several projects can use @code{DefaultValue}
14943: instead. Both functions work like @code{Value}, when the value isn't
14944: defined, but @code{SetValue} works like @code{to} if the value is
14945: defined, and @code{DefaultValue} doesn't set anything, if the value is
14946: defined.
14947:
14948: @example
14949: \ generic mach file for pc gforth 03sep97jaw
14950:
14951: true DefaultValue NIL \ relocating
14952:
14953: >ENVIRON
14954:
14955: true DefaultValue file \ controls the presence of the
14956: \ file access wordset
14957: true DefaultValue OS \ flag to indicate a operating system
14958:
14959: true DefaultValue prims \ true: primitives are c-code
14960:
14961: true DefaultValue floating \ floating point wordset is present
14962:
14963: true DefaultValue glocals \ gforth locals are present
14964: \ will be loaded
14965: true DefaultValue dcomps \ double number comparisons
14966:
14967: true DefaultValue hash \ hashing primitives are loaded/present
14968:
14969: true DefaultValue xconds \ used together with glocals,
14970: \ special conditionals supporting gforths'
14971: \ local variables
14972: true DefaultValue header \ save a header information
14973:
14974: true DefaultValue backtrace \ enables backtrace code
14975:
14976: false DefaultValue ec
14977: false DefaultValue crlf
14978:
14979: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14980:
14981: &16 KB DefaultValue stack-size
14982: &15 KB &512 + DefaultValue fstack-size
14983: &15 KB DefaultValue rstack-size
14984: &14 KB &512 + DefaultValue lstack-size
14985: @end example
1.13 pazsan 14986:
1.48 anton 14987: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 14988: @section How the Cross Compiler Works
1.13 pazsan 14989:
14990: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 14991: @appendix Bugs
1.1 anton 14992: @cindex bug reporting
14993:
1.21 crook 14994: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 14995:
1.103 anton 14996: If you find a bug, please submit a bug report through
14997: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 14998:
14999: @itemize @bullet
15000: @item
1.81 anton 15001: A program (or a sequence of keyboard commands) that reproduces the bug.
15002: @item
15003: A description of what you think constitutes the buggy behaviour.
15004: @item
1.21 crook 15005: The Gforth version used (it is announced at the start of an
15006: interactive Gforth session).
15007: @item
15008: The machine and operating system (on Unix
15009: systems @code{uname -a} will report this information).
15010: @item
1.81 anton 15011: The installation options (you can find the configure options at the
15012: start of @file{config.status}) and configuration (@code{configure}
15013: output or @file{config.cache}).
1.21 crook 15014: @item
15015: A complete list of changes (if any) you (or your installer) have made to the
15016: Gforth sources.
15017: @end itemize
1.1 anton 15018:
15019: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15020: to Report Bugs, gcc.info, GNU C Manual}.
15021:
15022:
1.21 crook 15023: @node Origin, Forth-related information, Bugs, Top
15024: @appendix Authors and Ancestors of Gforth
1.1 anton 15025:
15026: @section Authors and Contributors
15027: @cindex authors of Gforth
15028: @cindex contributors to Gforth
15029:
15030: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15031: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15032: lot to the manual. Assemblers and disassemblers were contributed by
15033: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15034: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15035: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15036: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15037: support for calling C libraries. Helpful comments also came from Paul
15038: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 ! anton 15039: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
! 15040: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
! 15041: Gforth-0.2.1 there were also helpful comments from many others; thank
! 15042: you all, sorry for not listing you here (but digging through my mailbox
! 15043: to extract your names is on my to-do list).
1.1 anton 15044:
15045: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15046: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15047: was developed across the Internet, and its authors did not meet
1.20 pazsan 15048: physically for the first 4 years of development.
1.1 anton 15049:
15050: @section Pedigree
1.26 crook 15051: @cindex pedigree of Gforth
1.1 anton 15052:
1.81 anton 15053: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15054: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15055:
1.20 pazsan 15056: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15057: 32 bit native code version of VolksForth for the Atari ST, written
15058: mostly by Dietrich Weineck.
15059:
1.81 anton 15060: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15061: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15062: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15063:
15064: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15065: Forth-83 standard. !! Pedigree? When?
15066:
15067: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15068: 1979. Robert Selzer and Bill Ragsdale developed the original
15069: implementation of fig-Forth for the 6502 based on microForth.
15070:
15071: The principal architect of microForth was Dean Sanderson. microForth was
15072: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15073: the 1802, and subsequently implemented on the 8080, the 6800 and the
15074: Z80.
15075:
15076: All earlier Forth systems were custom-made, usually by Charles Moore,
15077: who discovered (as he puts it) Forth during the late 60s. The first full
15078: Forth existed in 1971.
15079:
1.81 anton 15080: A part of the information in this section comes from
15081: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15082: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15083: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15084: SIGPLAN Notices 28(3), 1993. You can find more historical and
15085: genealogical information about Forth there.
1.1 anton 15086:
1.81 anton 15087: @c ------------------------------------------------------------------
1.113 ! anton 15088: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15089: @appendix Other Forth-related information
15090: @cindex Forth-related information
15091:
1.81 anton 15092: @c anton: I threw most of this stuff out, because it can be found through
15093: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15094:
15095: @cindex comp.lang.forth
15096: @cindex frequently asked questions
1.81 anton 15097: There is an active news group (comp.lang.forth) discussing Forth
15098: (including Gforth) and Forth-related issues. Its
15099: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15100: (frequently asked questions and their answers) contains a lot of
15101: information on Forth. You should read it before posting to
15102: comp.lang.forth.
1.21 crook 15103:
1.81 anton 15104: The ANS Forth standard is most usable in its
15105: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15106:
1.113 ! anton 15107: @c ---------------------------------------------------
! 15108: @node Licenses, Word Index, Forth-related information, Top
! 15109: @appendix Licenses
! 15110:
! 15111: @menu
! 15112: * GNU Free Documentation License:: License for copying this manual.
! 15113: * Copying:: GPL (for copying this software).
! 15114: @end menu
! 15115:
! 15116: @include fdl.texi
! 15117:
! 15118: @include gpl.texi
! 15119:
! 15120:
! 15121:
1.81 anton 15122: @c ------------------------------------------------------------------
1.113 ! anton 15123: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15124: @unnumbered Word Index
15125:
1.26 crook 15126: This index is a list of Forth words that have ``glossary'' entries
15127: within this manual. Each word is listed with its stack effect and
15128: wordset.
1.1 anton 15129:
15130: @printindex fn
15131:
1.81 anton 15132: @c anton: the name index seems superfluous given the word and concept indices.
15133:
15134: @c @node Name Index, Concept Index, Word Index, Top
15135: @c @unnumbered Name Index
1.41 anton 15136:
1.81 anton 15137: @c This index is a list of Forth words that have ``glossary'' entries
15138: @c within this manual.
1.41 anton 15139:
1.81 anton 15140: @c @printindex ky
1.41 anton 15141:
1.113 ! anton 15142: @c -------------------------------------------------------
1.81 anton 15143: @node Concept Index, , Word Index, Top
1.1 anton 15144: @unnumbered Concept and Word Index
15145:
1.26 crook 15146: Not all entries listed in this index are present verbatim in the
15147: text. This index also duplicates, in abbreviated form, all of the words
15148: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15149:
15150: @printindex cp
15151:
15152: @bye
1.81 anton 15153:
15154:
1.1 anton 15155:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>